private void Initialise(InitCommand command) { if (this.handbrakeInstance == null) { this.handbrakeInstance = new HandBrakeInstance(); } if (this.logHandler == null) { this.logHandler = new LogHandler(command.LogDirectory, command.LogFile, command.EnableDiskLogging); } if (!command.AllowDisconnectedWorker) { ConsoleOutput.WriteLine("Worker: Disconnected worker monitoring enabled!", ConsoleColor.White, true); this.instanceWatcher = new InstanceWatcher(this); this.instanceWatcher.Start(5000); } this.completedState = null; this.handbrakeInstance.Initialize(command.LogVerbosity, !command.EnableHardwareAcceleration); this.handbrakeInstance.EncodeCompleted += this.HandbrakeInstance_EncodeCompleted; if (command.EnableLibDvdNav) { HandBrakeUtils.SetDvdNav(true); } }
public static IEncodeInstance GetEncodeInstance(int verbosity, HBConfiguration configuration, ILog logService, IUserSettingService userSettingService, IPortService portService) { lock (ProcessingLock) { if (!HandBrakeUtils.IsInitialised()) { throw new Exception("Please call Init before Using!"); } IEncodeInstance newInstance; if (userSettingService.GetUserSetting <bool>(UserSettingConstants.ProcessIsolationEnabled) && Portable.IsProcessIsolationEnabled()) { newInstance = new RemoteInstance(logService, userSettingService, portService); } else { if (encodeInstance != null && !encodeInstance.IsRemoteInstance) { encodeInstance.Dispose(); encodeInstance = null; } newInstance = new HandBrakeInstance(); HandBrakeUtils.SetDvdNav( !userSettingService.GetUserSetting <bool>(UserSettingConstants.DisableLibDvdNav)); encodeInstance = newInstance; } newInstance.Initialize(verbosity, noHardware); return(newInstance); } }
/// <summary> /// The get encode instance. /// </summary> /// <param name="verbosity"> /// The verbosity. /// </param> /// <param name="configuration"> /// The configuratio. /// </param> /// <returns> /// The <see cref="IHandBrakeInstance"/>. /// </returns> public static IEncodeInstance GetEncodeInstance(int verbosity, HBConfiguration configuration) { if (!HandBrakeUtils.IsInitialised()) { throw new Exception("Please call Init before Using!"); } if (encodeInstance != null) { encodeInstance.Dispose(); encodeInstance = null; } IEncodeInstance newInstance; if (configuration.RemoteServiceEnabled) { newInstance = new RemoteInstance(configuration.RemoteServicePort); } else { newInstance = new HandBrakeInstance(); } newInstance.Initialize(verbosity, noHardware); encodeInstance = newInstance; HandBrakeUtils.SetDvdNav(!configuration.IsDvdNavDisabled); return(encodeInstance); }
/// <summary> /// The get encode instance. /// </summary> /// <param name="verbosity"> /// The verbosity. /// </param> /// <param name="configuration"> /// The configuratio. /// </param> /// <returns> /// The <see cref="IHandBrakeInstance"/>. /// </returns> public static IEncodeInstance GetEncodeInstance(int verbosity, HBConfiguration configuration) { if (encodeInstance != null) { encodeInstance.Dispose(); encodeInstance = null; } IEncodeInstance newInstance; if (configuration.RemoteServiceEnabled) { newInstance = new RemoteInstance(configuration.RemoteServicePort); } else { newInstance = new HandBrakeInstance(); } newInstance.Initialize(verbosity); encodeInstance = newInstance; HandBrakeUtils.SetDvdNav(!configuration.IsDvdNavDisabled); return(encodeInstance); }
public void SetUpWorker( int verbosity, int previewCount, bool useDvdNav, double minTitleDurationSeconds, double cpuThrottlingFraction, string tempFolder) { #if DEBUG_REMOTE Debugger.Launch(); #endif this.passedVerbosity = verbosity; this.passedPreviewCount = previewCount; this.passedMinTitleDurationSeconds = minTitleDurationSeconds; this.passedCpuThrottlingFraction = cpuThrottlingFraction; CurrentWorker = this; this.callback = OperationContext.Current.GetCallbackChannel <IHandBrakeWorkerCallback>(); this.logger = new WorkerLogger(this.callback); try { if (!string.IsNullOrEmpty(tempFolder)) { Environment.SetEnvironmentVariable("TMP", tempFolder, EnvironmentVariableTarget.Process); } if (this.callback == null) { throw new ArgumentException("Could not get callback channel."); } this.ApplyCpuThrottling(); HandBrakeUtils.MessageLogged += (o, e) => { this.StopOnException(() => { this.callback.OnMessageLogged(e.Message); }); }; HandBrakeUtils.ErrorLogged += (o, e) => { this.StopOnException(() => { this.callback.OnErrorLogged(e.Message); }); }; HandBrakeUtils.SetDvdNav(useDvdNav); } catch (Exception exception) { this.callback.OnException(exception.ToString()); throw; } }
/// <summary> /// Start a scan for a given source path and title /// </summary> /// <param name="sourcePath"> /// Path to the source file /// </param> /// <param name="title"> /// the title number to look at /// </param> /// <param name="previewCount"> /// The preview Count. /// </param> private void ScanSource(object sourcePath, int title, int previewCount) { try { string source = sourcePath.ToString().EndsWith("\\") ? string.Format("\"{0}\\\\\"", sourcePath.ToString().TrimEnd('\\')) : "\"" + sourcePath + "\""; this.currentSourceScanPath = source; this.IsScanning = true; TimeSpan minDuration = TimeSpan.FromSeconds(this.userSettingService.GetUserSetting <int>(UserSettingConstants.MinScanDuration)); HandBrakeUtils.SetDvdNav(!this.userSettingService.GetUserSetting <bool>(UserSettingConstants.DisableLibDvdNav)); this.ServiceLogMessage("Starting Scan ..."); this.instance.StartScan(sourcePath.ToString(), previewCount, minDuration, title != 0 ? title : 0); this.ScanStarted?.Invoke(this, System.EventArgs.Empty); } catch (Exception exc) { this.ServiceLogMessage("Scan Failed ..." + Environment.NewLine + exc); this.Stop(); } }
private void Initialise(InitCommand command) { if (this.handbrakeInstance == null) { this.handbrakeInstance = new HandBrakeInstance(); } if (this.logHandler == null) { this.logHandler = new LogHandler(command.LogDirectory, command.LogFile, command.EnableDiskLogging); } if (!command.AllowDisconnectedWorker) { this.instanceWatcher = new InstanceWatcher(this); this.instanceWatcher.Start(5000); } this.handbrakeInstance.Initialize(command.LogVerbosity, command.EnableHardwareAcceleration); this.handbrakeInstance.EncodeCompleted += this.HandbrakeInstance_EncodeCompleted; if (command.DisableLibDvdNav) { HandBrakeUtils.SetDvdNav(true); // TODO check this is correct } }
/// <summary> /// Start a scan for a given source path and title /// </summary> /// <param name="sourcePath"> /// Path to the source file /// </param> /// <param name="title"> /// the title number to look at /// </param> /// <param name="previewCount"> /// The preview Count. /// </param> /// <param name="configuraiton"> /// The configuraiton. /// </param> private void ScanSource(object sourcePath, int title, int previewCount, HBConfiguration configuraiton) { try { string source = sourcePath.ToString().EndsWith("\\") ? string.Format("\"{0}\\\\\"", sourcePath.ToString().TrimEnd('\\')) : "\"" + sourcePath + "\""; this.currentSourceScanPath = source; this.IsScanning = true; TimeSpan minDuration = TimeSpan.FromSeconds(configuraiton.MinScanDuration); HandBrakeUtils.SetDvdNav(!configuraiton.IsDvdNavDisabled); this.ServiceLogMessage("Starting Scan ..."); this.instance.StartScan(sourcePath.ToString(), previewCount, minDuration, title != 0 ? title : 0); if (this.ScanStarted != null) { this.ScanStarted(this, System.EventArgs.Empty); } } catch (Exception exc) { this.ServiceLogMessage("Scan Failed ..." + Environment.NewLine + exc); this.Stop(); } }
/// <summary> /// Start a scan for a given source path and title /// </summary> /// <param name="sourcePath"> /// Path to the source file /// </param> /// <param name="title"> /// the title number to look at /// </param> /// <param name="previewCount"> /// The preview Count. /// </param> private void ScanSource(object sourcePath, int title, int previewCount) { try { this.logging.Clear(); string source = sourcePath.ToString().EndsWith("\\") ? string.Format("\"{0}\\\\\"", sourcePath.ToString().TrimEnd('\\')) : "\"" + sourcePath + "\""; currentSourceScanPath = source; IsScanning = true; if (this.ScanStared != null) { this.ScanStared(this, new EventArgs()); } TimeSpan minDuration = TimeSpan.FromSeconds( this.userSettingService.GetUserSetting <int>(ASUserSettingConstants.MinScanDuration)); HandBrakeUtils.SetDvdNav(this.userSettingService.GetUserSetting <bool>(ASUserSettingConstants.DisableLibDvdNav)); this.instance.StartScan(sourcePath.ToString(), previewCount, minDuration, title != 0 ? title : 0); } catch (Exception exc) { this.Stop(); if (this.ScanCompleted != null) { this.ScanCompleted(this, new ScanCompletedEventArgs(false, exc, "An Error has occured in ScanService.ScanSource()")); } } }
public static void Init(bool noHardwareMode, IUserSettingService userSettingService) { Thread thread = new Thread(() => { if (userSettingService.GetUserSetting <bool>(UserSettingConstants.ForceDisableHardwareSupport)) { noHardware = true; } else { noHardware = noHardwareMode; } HandBrakeUtils.RegisterLogger(); HandBrakeUtils.EnsureGlobalInit(noHardware); }); thread.Start(); if (!thread.Join(8000)) { // Something is likely handing in a graphics driver. Force disable this feature so we don't probe the hardware next time around. userSettingService.SetUserSetting(UserSettingConstants.ForceDisableHardwareSupport, true); throw new GeneralApplicationException(Resources.Startup_UnableToStart, Resources.Startup_UnableToStartInfo); } }
public void CleanUp() { if (this.instance != null) { this.instance.Dispose(); } HandBrakeUtils.DisposeGlobal(); }
protected async void CleanUpAndSignalCompletion() { this.Instance?.Dispose(); HandBrakeUtils.DisposeGlobal(); await this.SendPendingLogMessagesAsync().ConfigureAwait(false); Program.SignalEncodeComplete(); }
/// <summary> /// Initializes static members of the Converters class. /// </summary> static Converters() { HandBrakeUtils.EnsureGlobalInit(); VideoRates = new Dictionary <double, int>(); foreach (var framerate in Encoders.VideoFramerates) { VideoRates.Add(double.Parse(framerate.Name, CultureInfo.InvariantCulture), framerate.Rate); } }
/// <summary> /// The create geometry. /// </summary> /// <param name="job"> /// The job. /// </param> /// <param name="title"> /// The current title. /// </param> /// <param name="keepWidthOrHeight"> /// Keep Width or Height. (Not Display Aspect) /// </param> /// <returns> /// The <see cref="Geometry"/>. /// </returns> public static Geometry CreateGeometry(EncodeTask job, SourceVideoInfo title, KeepSetting keepWidthOrHeight) // Todo remove the need for these objects. Should use simpler objects. { int settingMode = (int)keepWidthOrHeight + (job.KeepDisplayAspect ? 0x04 : 0); // Sanitize the Geometry First. AnamorphicGeometry anamorphicGeometry = new AnamorphicGeometry { SourceGeometry = new Geometry { Width = title.Resolution.Width, Height = title.Resolution.Height, PAR = new PAR { Num = title.ParVal.Width, Den = title.ParVal.Height } }, DestSettings = new DestSettings { AnamorphicMode = (int)job.Anamorphic, Geometry = { Width = job.Width ?? 0, Height = job.Height ?? 0, PAR = new PAR { Num = job.Anamorphic != Anamorphic.Custom ? title.ParVal.Width : job.PixelAspectX, Den = job.Anamorphic != Anamorphic.Custom ? title.ParVal.Height : job.PixelAspectY, } }, Keep = settingMode, Crop = new List <int> { job.Cropping.Top, job.Cropping.Bottom, job.Cropping.Left, job.Cropping.Right }, Modulus = job.Modulus ?? 16, MaxWidth = job.MaxWidth ?? 0, MaxHeight = job.MaxHeight ?? 0, ItuPAR = false } }; if (job.Anamorphic == Anamorphic.Custom) { anamorphicGeometry.DestSettings.Geometry.PAR = new PAR { Num = job.PixelAspectX, Den = job.PixelAspectY }; } else { anamorphicGeometry.DestSettings.Geometry.PAR = new PAR { Num = title.ParVal.Width, Den = title.ParVal.Height }; } return(HandBrakeUtils.GetAnamorphicSize(anamorphicGeometry)); }
/// <summary> /// Finds output geometry for the given preview settings and title. /// </summary> /// <param name="settings"> /// The preview settings. /// </param> /// <param name="title"> /// Information on the title to consider. /// </param> /// <returns> /// Geometry Information /// </returns> public static Geometry CreateGeometry(PreviewSettings settings, SourceVideoInfo title) { int settingMode = settings.KeepDisplayAspect ? 0x04 : 0; // Sanitize the Geometry First. AnamorphicGeometry anamorphicGeometry = new AnamorphicGeometry { SourceGeometry = new Geometry { Width = title.Resolution.Width, Height = title.Resolution.Height, PAR = new PAR { Num = title.ParVal.Width, Den = title.ParVal.Height } }, DestSettings = new DestSettings { AnamorphicMode = (int)settings.Anamorphic, Geometry = { Width = settings.Width, Height = settings.Height, PAR = new PAR { Num = settings.Anamorphic != Anamorphic.Custom ? title.ParVal.Width : settings.PixelAspectX, Den = settings.Anamorphic != Anamorphic.Custom ? title.ParVal.Height : settings.PixelAspectY, } }, Keep = settingMode, Crop = new List <int> { settings.Cropping.Top, settings.Cropping.Bottom, settings.Cropping.Left, settings.Cropping.Right }, Modulus = settings.Modulus ?? 16, MaxWidth = settings.MaxWidth, MaxHeight = settings.MaxHeight, ItuPAR = false } }; if (settings.Anamorphic == Anamorphic.Custom) { anamorphicGeometry.DestSettings.Geometry.PAR = new PAR { Num = settings.PixelAspectX, Den = settings.PixelAspectY }; } else { anamorphicGeometry.DestSettings.Geometry.PAR = new PAR { Num = title.ParVal.Width, Den = title.ParVal.Height }; } return(HandBrakeUtils.GetAnamorphicSize(anamorphicGeometry)); }
/// <summary> /// The get actualx 264 query. /// </summary> /// <returns> /// The <see cref="string"/>. /// </returns> private string GetActualx264Query() { if (!GeneralUtilities.IsLibHbPresent) { return(string.Empty); // Feature is disabled. } string preset = EnumHelper <x264Preset> .GetDisplay(this.X264Preset).ToLower().Replace(" ", string.Empty); string profile = EnumHelper <x264Profile> .GetDisplay(this.H264Profile).ToLower(); List <string> tunes = new List <string>(); if (X264Tune != x264Tune.None) { tunes.Add(this.X264Tune.ToString().ToLower().Replace(" ", string.Empty)); // TODO tidy this sillyness up. } if (this.FastDecode) { tunes.Add("fastdecode"); } // Get the width or height, default if we don't have it yet so we don't crash. int width = this.Task.Width.HasValue ? this.Task.Width.Value : 720; int height = this.Task.Height.HasValue ? this.Task.Height.Value : 576; if (height == 0) { height = 576; } if (width == 0) { width = 720; } try { return(HandBrakeUtils.CreateX264OptionsString( preset, tunes, this.ExtraArguments, profile, this.H264Level, width, height)); } catch (Exception) { return("Error: Libhb not loaded."); } }
public void SetUpWorker( int verbosity, int previewCount, bool useDvdNav, double minTitleDurationSeconds, double cpuThrottlingFraction, string tempFolder) { #if DEBUG_REMOTE Debugger.Launch(); #endif this.PassedVerbosity = verbosity; this.PassedPreviewCount = previewCount; this.PassedMinTitleDurationSeconds = minTitleDurationSeconds; this.passedCpuThrottlingFraction = cpuThrottlingFraction; this.Logger = new WorkerLogger <TCallback>(this.CallbackInvoker); try { if (!string.IsNullOrEmpty(tempFolder)) { Environment.SetEnvironmentVariable("TMP", tempFolder, EnvironmentVariableTarget.Process); } this.ApplyCpuThrottling(); HandBrakeUtils.MessageLogged += (o, e) => { lock (this.logListLock) { this.logMessageList.Add(e.Message); this.ScheduleMessageSendIfNeeded(); } }; HandBrakeUtils.ErrorLogged += (o, e) => { // If we run into an error, immediately send any pending batch of log messages this.StartSendingPendingLogMessages(); this.CallbackError(e.Message); }; HandBrakeUtils.SetDvdNav(useDvdNav); } catch (Exception exception) { this.CallbackError(exception.ToString()); throw; } }
/// <summary> /// The get actualx 264 query. /// </summary> /// <returns> /// The <see cref="string"/>. /// </returns> private string GetActualx264Query() { if (!GeneralUtilities.IsLibHbPresent) { return(string.Empty); // Feature is disabled. } string preset = this.VideoPreset != null ? this.VideoPreset.ShortName : string.Empty; string profile = this.VideoProfile != null ? this.VideoProfile.ShortName : string.Empty; List <string> tunes = new List <string>(); if (this.VideoTune != null && this.VideoTune.ShortName != "none") { tunes.Add(this.VideoTune.ShortName); } if (this.FastDecode) { tunes.Add("fastdecode"); } // Get the width or height, default if we don't have it yet so we don't crash. int width = this.Task.Width.HasValue ? this.Task.Width.Value : 720; int height = this.Task.Height.HasValue ? this.Task.Height.Value : 576; if (height == 0) { height = 576; } if (width == 0) { width = 720; } try { return(HandBrakeUtils.CreateX264OptionsString( preset, tunes, this.ExtraArguments, profile, this.VideoLevel != null ? this.VideoLevel.ShortName : string.Empty, width, height)); } catch (Exception) { return("Error: Libhb not loaded."); } }
private void HandbrakeInstance_EncodeCompleted(object sender, Interop.Interop.EventArgs.EncodeCompletedEventArgs e) { this.completedState = new JsonState() { WorkDone = new WorkDone() { Error = e.Error } }; this.completedState.State = "WORKDONE"; this.logHandler.ShutdownFileWriter(); this.handbrakeInstance.Dispose(); HandBrakeUtils.DisposeGlobal(); }
/// <summary> /// Start with a LibHb EncodeJob Object /// </summary> /// <param name="task"> /// The task. /// </param> /// <param name="configuration"> /// The configuration. /// </param> public void Start(EncodeTask task, HBConfiguration configuration) { try { // Sanity Checking and Setup if (this.IsEncoding) { throw new GeneralApplicationException("HandBrake is already encoding a file.", "Please stop the current encode. If the problem persists, please restart HandBrake.", null); } // Setup this.startTime = DateTime.Now; this.currentTask = task; this.currentConfiguration = configuration; // Create a new HandBrake instance // Setup the HandBrake Instance this.log.Reset(); // Reset so we have a clean log for the start of the encode. this.ServiceLogMessage("Starting Encode ..."); HandBrakeUtils.SetDvdNav(!configuration.IsDvdNavDisabled); this.instance = task.IsPreviewEncode ? HandBrakeInstanceManager.GetPreviewInstance(configuration.Verbosity) : HandBrakeInstanceManager.GetEncodeInstance(configuration.Verbosity); this.instance.EncodeCompleted += this.InstanceEncodeCompleted; this.instance.EncodeProgress += this.InstanceEncodeProgress; this.IsEncoding = true; this.isPreviewInstance = task.IsPreviewEncode; // Verify the Destination Path Exists, and if not, create it. this.VerifyEncodeDestinationPath(task); // Get an EncodeJob object for the Interop Library this.instance.StartEncode(EncodeFactory.Create(task, configuration)); // Fire the Encode Started Event this.InvokeEncodeStarted(System.EventArgs.Empty); } catch (Exception exc) { this.IsEncoding = false; this.ServiceLogMessage("Failed to start encoding ..." + Environment.NewLine + exc); this.InvokeEncodeCompleted(new EventArgs.EncodeCompletedEventArgs(false, exc, "Unable to start encoding", task.Source)); } }
/// <summary> /// The get encode instance. /// </summary> /// <param name="verbosity"> /// The verbosity. /// </param> /// <param name="configuration"> /// The configuration. /// </param> /// <returns> /// The <see cref="IHandBrakeInstance"/>. /// </returns> public static IHandBrakeInstance GetPreviewInstance(int verbosity, HBConfiguration configuration) { if (previewInstance != null) { previewInstance.Dispose(); previewInstance = null; } HandBrakeInstance newInstance = new HandBrakeInstance(); newInstance.Initialize(verbosity); previewInstance = newInstance; HandBrakeUtils.SetDvdNav(!configuration.IsDvdNavDisabled); return(previewInstance); }
/// <summary> /// Gets the scanInstance. /// </summary> /// <param name="verbosity"> /// The verbosity. /// </param> /// <returns> /// The <see cref="IHandBrakeInstance"/>. /// </returns> public static IHandBrakeInstance GetScanInstance(int verbosity) { if (!HandBrakeUtils.IsInitialised()) { throw new Exception("Please call Init before Using!"); } if (scanInstance != null) { scanInstance.Dispose(); scanInstance = null; } HandBrakeInstance newInstance = new HandBrakeInstance(); newInstance.Initialize(verbosity, noHardware); scanInstance = newInstance; return(scanInstance); }
/// <summary> /// The get encode instance. /// </summary> /// <param name="verbosity"> /// The verbosity. /// </param> /// <param name="configuration"> /// The configuration. /// </param> /// <returns> /// The <see cref="IHandBrakeInstance"/>. /// </returns> public static IHandBrakeInstance GetPreviewInstance(int verbosity, HBConfiguration configuration) { if (!HandBrakeUtils.IsInitialised()) { throw new Exception("Please call Init before Using!"); } if (previewInstance != null) { previewInstance.Dispose(); previewInstance = null; } HandBrakeInstance newInstance = new HandBrakeInstance(); newInstance.Initialize(verbosity, noHardware); previewInstance = newInstance; HandBrakeUtils.SetDvdNav(!configuration.IsDvdNavDisabled); return(previewInstance); }
/// <summary> /// The get encode instance. /// </summary> /// <param name="verbosity"> /// The verbosity. /// </param> /// <param name="userSettingService"> /// The user Setting Service. /// </param> /// <returns> /// The <see cref="IHandBrakeInstance"/>. /// </returns> public static IHandBrakeInstance GetPreviewInstance(int verbosity, IUserSettingService userSettingService) { if (!HandBrakeUtils.IsInitialised()) { throw new Exception("Please call Init before Using!"); } if (previewInstance != null) { previewInstance.Dispose(); previewInstance = null; } HandBrakeInstance newInstance = new HandBrakeInstance(); newInstance.Initialize(verbosity, noHardware); previewInstance = newInstance; HandBrakeUtils.SetDvdNav(!userSettingService.GetUserSetting <bool>(UserSettingConstants.DisableLibDvdNav)); return(previewInstance); }
/// <summary> /// The get picture settings. /// </summary> /// <returns> /// The <see cref="PictureSize.PictureSettingsJob"/>. /// </returns> private PictureSize.PictureSettingsJob GetPictureSettings(ChangedPictureField changedField) { PictureSize.PictureSettingsJob job = new PictureSize.PictureSettingsJob { Width = this.Width, Height = this.Height, ItuPar = false, Modulus = this.SelectedModulus, ParW = this.ParWidth, ParH = this.ParHeight, MaxWidth = this.MaxWidth, MaxHeight = this.MaxHeight, KeepDisplayAspect = this.MaintainAspectRatio, AnamorphicMode = this.SelectedAnamorphicMode, Crop = new Cropping(this.CropTop, this.CropBottom, this.CropLeft, this.CropRight), }; if (this.SelectedAnamorphicMode == Anamorphic.Custom) { if (changedField == ChangedPictureField.DisplayWidth) { var displayWidth = this.DisplayWidth; job.ParW = (int)displayWidth; // num job.ParH = job.Width; // den } } // Reduce the Par W/H if we can. Don't do it while the user is altering the PAR controls through as it will mess with the result. if (changedField != ChangedPictureField.ParH && changedField != ChangedPictureField.ParW) { long x, y; HandBrakeUtils.Reduce(job.ParW, job.ParH, out x, out y); job.ParW = (int)y; job.ParH = (int)x; } return(job); }
/// <summary> /// Update the x264 options string from a UI change. /// </summary> private void UpdateOptionsString() { if (this.AutomaticChange) { return; } List <string> newOptions = new List <string>(); // First add any parts of the options string that don't correspond to the UI if (this.VideoOptions != null) { string[] existingSegments = this.VideoOptions.Split(':'); foreach (string existingSegment in existingSegments) { string optionName = existingSegment; int equalsIndex = existingSegment.IndexOf('='); if (equalsIndex >= 0) { optionName = existingSegment.Substring(0, existingSegment.IndexOf("=", StringComparison.Ordinal)); } if (optionName != string.Empty && !this.uiOptions.Contains(HandBrakeUtils.SanitizeX264OptName(optionName))) { newOptions.Add(existingSegment); } } } // Now add everything from the UI if (!this.ReferenceFrames.IsDefault) { newOptions.Add("ref=" + this.ReferenceFrames.Value); } if (!this.BFrames.IsDefault) { newOptions.Add("bframes=" + this.BFrames.Value); } if (this.BFrames.Value != "0") { if (!this.AdaptiveBFrames.IsDefault) { newOptions.Add("b-adapt=" + this.AdaptiveBFrames.Value); } if (!this.DirectPrediction.IsDefault) { newOptions.Add("direct=" + this.DirectPrediction.Value); } if (this.BFrames.Value != "1" && !this.PyramidalBFrames.IsDefault) { newOptions.Add("b-pyramid=" + this.PyramidalBFrames.Value); } } if (!this.WeightedPFrames) { newOptions.Add("weightp=0"); } if (!this.MotionEstimationMethod.IsDefault) { newOptions.Add("me=" + this.MotionEstimationMethod.Value); } if (!this.SubpixelMotionEstimation.IsDefault) { newOptions.Add("subme=" + this.SubpixelMotionEstimation.Value); } if (this.MotionEstimationRange != 16) { newOptions.Add("merange=" + this.MotionEstimationRange); } if (!this.Analysis.IsDefault) { newOptions.Add("analyse=" + this.Analysis.Value); } if (this.Analysis.Value != "none" && !this.EightByEightDct) { newOptions.Add("8x8dct=0"); } if (!this.CabacEntropyCoding) { newOptions.Add("cabac=0"); } if (!this.Trellis.IsDefault) { newOptions.Add("trellis=" + this.Trellis.Value); } double psTrellis = 0.0; if (this.CabacEntropyCoding && this.Trellis.Value != "0") { psTrellis = this.PsychovisualTrellis; } if (this.AdaptiveQuantizationStrength != 1.0) { newOptions.Add("aq-strength=" + this.AdaptiveQuantizationStrength.ToString("F1", CultureInfo.InvariantCulture)); } if (this.PsychovisualRateDistortion != 1.0 || psTrellis > 0.0) { newOptions.Add("psy-rd=" + this.PsychovisualRateDistortion.ToString("F1", CultureInfo.InvariantCulture) + "," + psTrellis.ToString("F2", CultureInfo.InvariantCulture)); } if (this.NoDctDecimate) { newOptions.Add("no-dct-decimate=1"); } if (!this.DeblockingStrength.IsDefault || !this.DeblockingThreshold.IsDefault) { newOptions.Add("deblock=" + this.DeblockingStrength.Value + "," + this.DeblockingThreshold.Value); } this.VideoOptions = string.Join(":", newOptions); }
/// <summary> /// Recalculate the picture settings when the user changes a particular field defined in the ChangedPictureField enum. /// The properties in this class are dumb. They simply call this method if there is a change. /// It is the job of this method to update all affected private fields and raise change notifications. /// </summary> /// <param name="changedField"> /// The changed field. /// </param> private void RecaulcatePictureSettingsProperties(ChangedPictureField changedField) { // Sanity Check if (this.currentTitle == null) { return; } // Step 1, Update what controls are visible. this.UpdateVisibileControls(); // Step 2, Set sensible defaults if (changedField == ChangedPictureField.Anamorphic && (this.SelectedAnamorphicMode == Anamorphic.None || this.SelectedAnamorphicMode == Anamorphic.Loose)) { this.Task.Width = this.sourceResolution.Width > this.MaxWidth ? this.MaxWidth : this.sourceResolution.Width; this.Task.KeepDisplayAspect = true; } // Choose which setting to keep. PictureSize.KeepSetting setting = PictureSize.KeepSetting.HB_KEEP_WIDTH; switch (changedField) { case ChangedPictureField.Width: setting = PictureSize.KeepSetting.HB_KEEP_WIDTH; break; case ChangedPictureField.Height: setting = PictureSize.KeepSetting.HB_KEEP_HEIGHT; break; } // Step 2, For the changed field, call hb_set_anamorphic_size and process the results. PictureSize.AnamorphicResult result = PictureSize.hb_set_anamorphic_size2(this.GetPictureSettings(changedField), this.GetPictureTitleInfo(), setting); double dispWidth = Math.Round((result.OutputWidth * result.OutputParWidth / result.OutputParHeight), 0); this.Task.Width = result.OutputWidth; this.Task.Height = result.OutputHeight; long x, y; HandBrakeUtils.Reduce((int)Math.Round(result.OutputParWidth, 0), (int)Math.Round(result.OutputParHeight, 0), out x, out y); this.Task.PixelAspectX = (int)Math.Round(result.OutputParWidth, 0); this.Task.PixelAspectY = (int)Math.Round(result.OutputParHeight, 0); this.Task.DisplayWidth = dispWidth; // Step 3, Set the display width label to indicate the output. this.DisplaySize = this.sourceResolution == null || this.sourceResolution.IsEmpty ? string.Empty : string.Format(Resources.PictureSettingsViewModel_StorageDisplayLabel, dispWidth, result.OutputHeight, this.ParWidth, this.ParHeight); // Step 4, Force an update on all the UI elements. this.NotifyOfPropertyChange(() => this.Width); this.NotifyOfPropertyChange(() => this.Height); this.NotifyOfPropertyChange(() => this.DisplayWidth); this.NotifyOfPropertyChange(() => this.ParWidth); this.NotifyOfPropertyChange(() => this.ParHeight); this.NotifyOfPropertyChange(() => this.CropTop); this.NotifyOfPropertyChange(() => this.CropBottom); this.NotifyOfPropertyChange(() => this.CropLeft); this.NotifyOfPropertyChange(() => this.CropRight); this.NotifyOfPropertyChange(() => this.SelectedModulus); this.NotifyOfPropertyChange(() => this.MaintainAspectRatio); // Step 5, Update the Preview if (delayedPreviewprocessor != null && this.Task != null && this.StaticPreviewViewModel != null && this.StaticPreviewViewModel.IsOpen) { delayedPreviewprocessor.PerformTask(() => this.StaticPreviewViewModel.UpdatePreviewFrame(this.Task, this.scannedSource), 800); } }
public void SetUpWorker( int verbosity, int previewCount, bool useDvdNav, double minTitleDurationSeconds, double cpuThrottlingFraction, string tempFolder) { #if DEBUG_REMOTE Debugger.Launch(); #endif this.passedVerbosity = verbosity; this.passedPreviewCount = previewCount; this.passedMinTitleDurationSeconds = minTitleDurationSeconds; CurrentWorker = this; this.callback = OperationContext.Current.GetCallbackChannel <IHandBrakeWorkerCallback>(); Ioc.Container.RegisterInstance <ILogger>(new WorkerLogger(this.callback)); try { if (!string.IsNullOrEmpty(tempFolder)) { Environment.SetEnvironmentVariable("TMP", tempFolder, EnvironmentVariableTarget.Process); } if (cpuThrottlingFraction < 1.0) { int coresToUse = (int)Math.Round(Environment.ProcessorCount * cpuThrottlingFraction); if (coresToUse < 1) { coresToUse = 1; } if (coresToUse > Environment.ProcessorCount) { coresToUse = Environment.ProcessorCount; } Process process = Process.GetCurrentProcess(); long affinityMask = 0x0; for (int i = 0; i < coresToUse; i++) { affinityMask |= (uint)(1 << i); } process.ProcessorAffinity = (IntPtr)affinityMask; } if (this.callback == null) { throw new ArgumentException("Could not get callback channel."); } HandBrakeUtils.MessageLogged += (o, e) => { this.StopOnException(() => { this.callback.OnMessageLogged(e.Message); }); }; HandBrakeUtils.ErrorLogged += (o, e) => { this.StopOnException(() => { this.callback.OnErrorLogged(e.Message); }); }; HandBrakeUtils.SetDvdNav(useDvdNav); } catch (Exception exception) { this.callback.OnException(exception.ToString()); throw; } }
private void CurrentDomain_ProcessExit(object sender, System.EventArgs e) { HandBrakeUtils.DisposeGlobal(); }
/// <summary> /// Initializes static members of the Encoders class. /// </summary> static Encoders() { HandBrakeUtils.EnsureGlobalInit(); }