public void StartScan(string path) { this.Instance = new HandBrakeInstance(); this.Instance.Initialize(this.PassedVerbosity, noHardware: false); this.Instance.ScanProgress += (o, e) => { this.MakeOneWayCallback(c => c.OnScanProgress((float)e.Progress)); }; this.Instance.ScanCompleted += async(o, e) => { try { await this.CallbackInvoker.InvokeAsync(c => c.OnScanComplete(this.Instance.TitlesJson)); } catch (Exception exception) { WorkerErrorLogger.LogError("Got exception when reporting completion: " + exception, isError: true); } finally { this.CleanUpAndSignalCompletion(); } }; this.Instance.StartScan(path, this.PassedPreviewCount, TimeSpan.FromSeconds(this.PassedMinTitleDurationSeconds), 0); }
public void StartScan(string path) { this.instance = new HandBrakeInstance(); this.instance.Initialize(this.passedVerbosity); this.instance.ScanProgress += (o, e) => { this.callback.OnScanProgress((float)e.Progress); }; this.instance.ScanCompleted += (o, e) => { try { this.callback.OnScanComplete(this.instance.TitlesJson); } catch (Exception exception) { WorkerErrorLogger.LogError("Got exception when reporting completion: " + exception, isError: true); } finally { this.CleanUpAndSignalCompletion(); } }; this.instance.StartScan(path, this.passedPreviewCount, TimeSpan.FromSeconds(this.passedMinTitleDurationSeconds), 0); }
// Executes a callback operation and stops the encode when a communication exception occurs. private void StopOnException(Action action) { try { action(); } catch (CommunicationException exception) { WorkerErrorLogger.LogError("Got exception: " + exception, isError: true); this.StopEncodeIfPossible(); } }
// Executes a callback operation and stops the encode when an exception occurs. private async void StopOnException(Func <Task> action) { try { await action(); } catch (Exception exception) { WorkerErrorLogger.LogError("Got exception: " + exception, isError: true); this.StopEncodeIfPossible(); } }
private static async void StartService(HandBrakeWorkerAction action) { try { IPipeServer server; if (action == HandBrakeWorkerAction.Encode) { PipeServerWithCallback <IHandBrakeEncodeWorkerCallback, IHandBrakeEncodeWorker> encodeServer = null; Lazy <IHandBrakeEncodeWorker> lazyEncodeWorker = new Lazy <IHandBrakeEncodeWorker>(() => new HandBrakeEncodeWorker(encodeServer.Invoker)); encodeServer = new PipeServerWithCallback <IHandBrakeEncodeWorkerCallback, IHandBrakeEncodeWorker>(PipeName, () => lazyEncodeWorker.Value); #if DEBUG encodeServer.SetLogger(message => System.Diagnostics.Debug.WriteLine(message)); #endif server = encodeServer; } else if (action == HandBrakeWorkerAction.Scan) { PipeServerWithCallback <IHandBrakeScanWorkerCallback, IHandBrakeScanWorker> scanServer = null; Lazy <IHandBrakeScanWorker> lazyScanWorker = new Lazy <IHandBrakeScanWorker>(() => new HandBrakeScanWorker(scanServer.Invoker)); scanServer = new PipeServerWithCallback <IHandBrakeScanWorkerCallback, IHandBrakeScanWorker>(PipeName, () => lazyScanWorker.Value); #if DEBUG scanServer.SetLogger(message => System.Diagnostics.Debug.WriteLine(message)); #endif server = scanServer; } else { throw new ArgumentException("Unrecognized action: " + action, nameof(action)); } Task connectionTask = server.WaitForConnectionAsync(); // Write a line to let the client know we are ready for connections Console.WriteLine($"Pipe '{PipeName}' is open"); await connectionTask.ConfigureAwait(false); await server.WaitForRemotePipeCloseAsync().ConfigureAwait(false); } catch (Exception exception) { WorkerErrorLogger.LogError("Exception in StartService: " + exception, isError: true); } }
/// <summary> /// Starts an encode. /// </summary> /// <param name="scanPath">The path to scan.</param> /// <param name="titleNumber">The title number to scan.</param> /// <param name="jsonFunc">A function to pick the encode JSON given the scan.</param> private void StartEncodeInternal(string scanPath, int titleNumber, Func <JsonScanObject, string> jsonFunc) { try { this.instance = new HandBrakeInstance(); this.instance.Initialize(this.passedVerbosity); this.instance.ScanCompleted += (o, e) => { try { string encodeJson = jsonFunc(this.instance.Titles); if (encodeJson != null) { lock (this.encodeLock) { this.instance.StartEncode(encodeJson); this.callback.OnEncodeStarted(); this.state = EncodeState.Encoding; } } else { this.callback.OnEncodeComplete(error: true); this.CleanUpAndSignalCompletion(); } } catch (Exception exception) { this.callback.OnException(exception.ToString()); this.CleanUpAndSignalCompletion(); } }; this.instance.EncodeProgress += (o, e) => { this.StopOnException(() => { this.callback.OnEncodeProgress((float)e.AverageFrameRate, (float)e.CurrentFrameRate, e.EstimatedTimeLeft, (float)e.FractionComplete, e.PassId, e.Pass, e.PassCount); }); }; this.instance.EncodeCompleted += (o, e) => { this.state = EncodeState.Finished; try { this.callback.OnEncodeComplete(e.Error); } catch (CommunicationException exception) { WorkerErrorLogger.LogError("Got exception when reporting completion: " + exception, isError: true); } finally { this.CleanUpAndSignalCompletion(); } }; this.instance.StartScan(scanPath, this.passedPreviewCount, TimeSpan.FromSeconds(this.passedMinTitleDurationSeconds), titleNumber); this.state = EncodeState.Scanning; } catch (Exception exception) { this.callback.OnException(exception.ToString()); throw; } }
/// <summary> /// Starts an encode. /// </summary> /// <param name="scanPath">The path to scan.</param> /// <param name="titleNumber">The title number to scan.</param> /// <param name="jsonFunc">A function to pick the encode JSON given the scan.</param> private void StartEncodeInternal(string scanPath, int titleNumber, Func <JsonScanObject, string> jsonFunc) { try { this.Instance = new HandBrakeInstance(); this.Instance.Initialize(this.PassedVerbosity, noHardware: false); this.Instance.ScanCompleted += (o, e) => { try { string encodeJson = jsonFunc(this.Instance.Titles); if (encodeJson != null) { lock (this.encodeLock) { this.Instance.StartEncode(encodeJson); this.MakeOneWayCallback(c => c.OnEncodeStarted()); this.state = EncodeState.Encoding; } } else { this.MakeOneWayCallback(c => c.OnEncodeComplete(true)); this.CleanUpAndSignalCompletion(); } } catch (Exception exception) { this.MakeOneWayCallback(c => c.OnException(exception.ToString())); this.CleanUpAndSignalCompletion(); } }; this.Instance.EncodeProgress += (o, e) => { this.StopOnException(() => { if (e.PassId > this.lastSetAffinityPassId && e.FractionComplete > 0) { this.ApplyCpuThrottling(); this.lastSetAffinityPassId = e.PassId; } this.MakeOneWayCallback(c => c.OnEncodeProgress( (float)e.AverageFrameRate, (float)e.CurrentFrameRate, e.EstimatedTimeLeft, (float)e.FractionComplete, e.PassId, e.Pass, e.PassCount, e.StateCode)); return(Task.CompletedTask); }); }; this.Instance.EncodeCompleted += async(o, e) => { this.state = EncodeState.Finished; try { await this.SendPendingLogMessagesAsync().ConfigureAwait(false); await this.CallbackInvoker.InvokeAsync(c => c.OnEncodeComplete(e.Error)).ConfigureAwait(false); } catch (Exception exception) { WorkerErrorLogger.LogError("Got exception when reporting completion: " + exception, isError: true); } finally { this.CleanUpAndSignalCompletion(); } }; this.Instance.StartScan(scanPath, this.PassedPreviewCount, TimeSpan.FromSeconds(this.PassedMinTitleDurationSeconds), titleNumber); this.state = EncodeState.Scanning; } catch (Exception exception) { this.MakeOneWayCallback(c => c.OnException(exception.ToString())); throw; } }
static async Task Main(string[] args) { try { ////Debugger.Launch(); if (args.Length < 3) { PrintUsage(); return; } int parentProcId; if (!int.TryParse(args[0], out parentProcId)) { PrintUsage(); return; } JsonSettings.SetDefaultSerializationSettings(); PipeName = args[1]; var action = (HandBrakeWorkerAction)Enum.Parse(typeof(HandBrakeWorkerAction), args[2]); parentCheckTimer = new System.Timers.Timer(); parentCheckTimer.Interval = ParentCheckInterval; parentCheckTimer.AutoReset = true; parentCheckTimer.Elapsed += (o, e) => { try { if (!ProcessExists(parentProcId)) { if (action == HandBrakeWorkerAction.Encode && HandBrakeEncodeWorker.CurrentWorker != null && HandBrakeEncodeWorker.CurrentWorker.StopEncodeIfPossible()) { // If we are able to stop the encode, we will do so. Cleanup should // happen with the encode complete callback. Console.WriteLine("Parent no longer exists, stopping encode."); } } } catch (Exception exception) { WorkerErrorLogger.LogError("Exception in parentCheckTimer. Elapsed: " + exception.ToString(), isError: true); throw; } }; parentCheckTimer.Start(); StartService(action); encodeComplete = new SemaphoreSlim(0, 1); await encodeComplete.WaitAsync().ConfigureAwait(false); } catch (Exception exception) { WorkerErrorLogger.LogError("Exception in Main: " + exception, isError: true); throw; } }
static void Main(string[] args) { try { if (args.Length < 2) { PrintUsage(); return; } int parentProcId; if (!int.TryParse(args[0], out parentProcId)) { PrintUsage(); return; } JsonSettings.SetDefaultSerializationSettings(); PipeName = args[1]; parentCheckTimer = new System.Timers.Timer(); parentCheckTimer.Interval = ParentCheckInterval; parentCheckTimer.AutoReset = true; parentCheckTimer.Elapsed += (o, e) => { try { if (!ProcessExists(parentProcId)) { // If we couldn't stop the process, just wait until next tick. May have not started yet or may // already be in the process of closing. if (HandBrakeWorker.CurrentWorker != null && HandBrakeWorker.CurrentWorker.StopEncodeIfPossible()) { // If we are able to stop the encode, we will do so. Cleanup should // happen with the encode complete callback. Console.WriteLine("Parent no longer exists, stopping encode."); } } } catch (Exception exception) { WorkerErrorLogger.LogError("Exception in parentCheckTimer.Elapsed: " + exception.ToString(), isError: true); throw; } }; parentCheckTimer.Start(); ServiceHost host = null; try { host = new ServiceHost(typeof(HandBrakeWorker)); host.AddServiceEndpoint( typeof(IHandBrakeWorker), new NetNamedPipeBinding(), "net.pipe://localhost/" + PipeName); host.Open(); encodeComplete = new ManualResetEventSlim(false); Console.WriteLine("Service state is " + host.State + " on pipe " + PipeName); encodeComplete.Wait(); host.Close(); } catch (CommunicationException exception) { WorkerErrorLogger.LogError("Exception when trying to establish pipe service: " + exception, isError: true); if (host != null) { host.Abort(); } } catch (TimeoutException exception) { WorkerErrorLogger.LogError("Exception when trying to establish pipe service: " + exception, isError: true); if (host != null) { host.Abort(); } } catch (Exception) { if (host != null) { host.Abort(); } throw; } } catch (Exception exception) { WorkerErrorLogger.LogError("Exception in Main: " + exception, isError: true); throw; } }