Example #1
0
        /// <summary>
        /// Save a copy of the log to the users desired location or a default location
        /// if this feature is enabled in options.
        /// </summary>
        /// <param name="destination">
        /// The Destination File Path
        /// </param>
        /// <param name="isPreview">
        /// The is Preview.
        /// </param>
        /// <param name="configuration">
        /// The configuration.
        /// </param>
        public string ProcessLogs(string destination, bool isPreview, HBConfiguration configuration)
        {
            try
            {
                string logDir = DirectoryUtilities.GetLogDirectory();
                string encodeDestinationPath = Path.GetDirectoryName(destination);
                string destinationFile       = Path.GetFileName(destination);
                string encodeLogFile         = destinationFile + " " + DateTime.Now.ToString(CultureInfo.InvariantCulture).Replace("/", "-").Replace(":", "-") + ".txt";
                string logContent            = this.encodeLogService.GetFullLog();

                // Make sure the log directory exists.
                if (!Directory.Exists(logDir))
                {
                    Directory.CreateDirectory(logDir);
                }

                // Copy the Log to HandBrakes log folder in the users applciation data folder.
                this.WriteFile(logContent, Path.Combine(logDir, encodeLogFile));

                // Save a copy of the log file in the same location as the enocde.
                if (this.userSettingService.GetUserSetting <bool>(UserSettingConstants.SaveLogWithVideo))
                {
                    this.WriteFile(logContent, Path.Combine(encodeDestinationPath, encodeLogFile));
                }

                // Save a copy of the log file to a user specified location
                if (Directory.Exists(this.userSettingService.GetUserSetting <string>(UserSettingConstants.SaveLogCopyDirectory)) && this.userSettingService.GetUserSetting <bool>(UserSettingConstants.SaveLogToCopyDirectory))
                {
                    this.WriteFile(logContent, Path.Combine(this.userSettingService.GetUserSetting <string>(UserSettingConstants.SaveLogCopyDirectory), encodeLogFile));
                }

                return(Path.Combine(logDir, encodeLogFile));
            }
            catch (Exception exc)
            {
                Debug.WriteLine(exc); // This exception doesn't warrant user interaction, but it should be logged
            }

            return(null);
        }
Example #2
0
        /// <summary>
        /// Save a copy of the log to the users desired location or a default location
        /// if this feature is enabled in options.
        /// </summary>
        /// <param name="destination">
        /// The Destination File Path
        /// </param>
        /// <param name="configuration">
        /// The configuration.
        /// </param>
        public void ProcessLogs(string destination, HBConfiguration configuration)
        {
            try
            {
                string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
                                "\\HandBrake\\logs";
                string tempLogFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", GeneralUtilities.ProcessId));

                string encodeDestinationPath = Path.GetDirectoryName(destination);
                string destinationFile       = Path.GetFileName(destination);
                string encodeLogFile         = destinationFile + " " +
                                               DateTime.Now.ToString().Replace("/", "-").Replace(":", "-") + ".txt";

                // Make sure the log directory exists.
                if (!Directory.Exists(logDir))
                {
                    Directory.CreateDirectory(logDir);
                }

                // Copy the Log to HandBrakes log folder in the users applciation data folder.
                File.Copy(tempLogFile, Path.Combine(logDir, encodeLogFile));

                // Save a copy of the log file in the same location as the enocde.
                if (configuration.SaveLogWithVideo)
                {
                    File.Copy(tempLogFile, Path.Combine(encodeDestinationPath, encodeLogFile));
                }

                // Save a copy of the log file to a user specified location
                if (Directory.Exists(configuration.SaveLogCopyDirectory) && configuration.SaveLogToCopyDirectory)
                {
                    File.Copy(
                        tempLogFile, Path.Combine(configuration.SaveLogCopyDirectory, encodeLogFile));
                }
            }
            catch (Exception exc)
            {
                Debug.WriteLine(exc); // This exception doesn't warrent user interaction, but it should be logged
            }
        }
Example #3
0
        /// <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);
        }
Example #4
0
        public QueueTask(EncodeTask task, HBConfiguration configuration, string scannedSourcePath, Preset currentPreset, bool isPresetModified)
        {
            this.Task              = task;
            this.Configuration     = configuration;
            this.Status            = QueueItemStatus.Waiting;
            this.ScannedSourcePath = scannedSourcePath;
            if (currentPreset != null)
            {
                this.presetKey = currentPreset.Name;
                if (isPresetModified)
                {
                    this.presetKey = this.presetKey + " (Modified)";
                }
            }
            id      = id + 1;
            this.Id = string.Format("{0}.{1}", GeneralUtilities.ProcessId, id);
            this.SelectedPresetKey = this.presetKey;

            this.Statistics  = new QueueStats();
            this.TaskId      = Guid.NewGuid().ToString();
            this.JobProgress = new QueueProgressStatus();
        }
Example #5
0
        private string GetQueueJson(List <EncodeTask> tasks, HBConfiguration configuration)
        {
            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
            };

            IHbFunctionsProvider provider    = IoC.Get <IHbFunctionsProvider>(); // TODO remove IoC call.
            IHbFunctions         hbFunctions = provider.GetHbFunctionsWrapper();

            List <Task> queueJobs = new List <Task>();

            foreach (var item in tasks)
            {
                Task task = new Task {
                    Job = this.encodeTaskFactory.Create(item, configuration)
                };
                queueJobs.Add(task);
            }

            return(JsonConvert.SerializeObject(queueJobs, Formatting.Indented, settings));
        }
Example #6
0
        /// <summary>
        /// Get a Preview image for the current job and preview number.
        /// </summary>
        /// <param name="job">
        /// The job.
        /// </param>
        /// <param name="preview">
        /// The preview.
        /// </param>
        /// <param name="configuraiton">
        /// The configuraiton.
        /// </param>
        /// <returns>
        /// The <see cref="BitmapImage"/>.
        /// </returns>
        public BitmapImage GetPreview(EncodeTask job, int preview, HBConfiguration configuraiton)
        {
            if (this.instance == null)
            {
                return(null);
            }

            EncodeJob encodeJob = InteropModelCreator.GetEncodeJob(job, configuraiton);

            BitmapImage bitmapImage = null;

            try
            {
                bitmapImage = this.instance.GetPreview(encodeJob, preview);
            }
            catch (AccessViolationException e)
            {
                Console.WriteLine(e);
            }

            return(bitmapImage);
        }
        /// <summary>
        /// The create.
        /// </summary>
        /// <returns>
        /// The <see cref="HBConfiguration"/>.
        /// </returns>
        public static HBConfiguration Create()
        {
            HBConfiguration config = new HBConfiguration
            {
                IsDvdNavDisabled         = UserSettingService.GetUserSetting <bool>(UserSettingConstants.DisableLibDvdNav),
                ScalingMode              = UserSettingService.GetUserSetting <VideoScaler>(UserSettingConstants.ScalingMode, typeof(int)),
                PreviewScanCount         = UserSettingService.GetUserSetting <int>(UserSettingConstants.PreviewScanCount, typeof(int)),
                Verbosity                = UserSettingService.GetUserSetting <int>(UserSettingConstants.Verbosity, typeof(int)),
                MinScanDuration          = UserSettingService.GetUserSetting <int>(UserSettingConstants.MinScanDuration, typeof(int)),
                SaveLogToCopyDirectory   = UserSettingService.GetUserSetting <bool>(UserSettingConstants.SaveLogToCopyDirectory),
                SaveLogWithVideo         = UserSettingService.GetUserSetting <bool>(UserSettingConstants.SaveLogWithVideo),
                SaveLogCopyDirectory     = UserSettingService.GetUserSetting <string>(UserSettingConstants.SaveLogCopyDirectory),
                RemoteServiceEnabled     = UserSettingService.GetUserSetting <bool>(UserSettingConstants.RemoteServiceEnabled),
                RemoteServicePort        = UserSettingService.GetUserSetting <int>(UserSettingConstants.RemoteServicePort, typeof(int)),
                EnableVceEncoder         = UserSettingService.GetUserSetting <bool>(UserSettingConstants.EnableVceEncoder),
                EnableNvencEncoder       = UserSettingService.GetUserSetting <bool>(UserSettingConstants.EnableNvencEncoder),
                EnableQsvEncoder         = UserSettingService.GetUserSetting <bool>(UserSettingConstants.EnableQuickSyncEncoding),
                EnableQuickSyncDecoding  = UserSettingService.GetUserSetting <bool>(UserSettingConstants.EnableQuickSyncDecoding),
                UseQSVDecodeForNonQSVEnc = UserSettingService.GetUserSetting <bool>(UserSettingConstants.UseQSVDecodeForNonQSVEnc)
            };

            return(config);
        }
Example #8
0
        /// <summary>
        /// Save a copy of the log to the users desired location or a default location
        /// if this feature is enabled in options.
        /// </summary>
        /// <param name="destination">
        /// The Destination File Path
        /// </param>
        /// <param name="isPreview">
        /// The is Preview.
        /// </param>
        /// <param name="configuration">
        /// The configuration.
        /// </param>
        public void ProcessLogs(string destination, bool isPreview, HBConfiguration configuration)
        {
            try
            {
                string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
                string encodeDestinationPath = Path.GetDirectoryName(destination);
                string destinationFile       = Path.GetFileName(destination);
                string encodeLogFile         = destinationFile + " " + DateTime.Now.ToString(CultureInfo.InvariantCulture).Replace("/", "-").Replace(":", "-") + ".txt";
                ILog   log        = LogService.GetLogger();
                string logContent = log.ActivityLog;

                // Make sure the log directory exists.
                if (!Directory.Exists(logDir))
                {
                    Directory.CreateDirectory(logDir);
                }

                // Copy the Log to HandBrakes log folder in the users applciation data folder.
                this.WriteFile(logContent, Path.Combine(logDir, encodeLogFile));

                // Save a copy of the log file in the same location as the enocde.
                if (configuration.SaveLogWithVideo)
                {
                    this.WriteFile(logContent, Path.Combine(encodeDestinationPath, encodeLogFile));
                }

                // Save a copy of the log file to a user specified location
                if (Directory.Exists(configuration.SaveLogCopyDirectory) && configuration.SaveLogToCopyDirectory)
                {
                    this.WriteFile(logContent, Path.Combine(configuration.SaveLogCopyDirectory, encodeLogFile));
                }
            }
            catch (Exception exc)
            {
                Debug.WriteLine(exc); // This exception doesn't warrent user interaction, but it should be logged
            }
        }
Example #9
0
        /// <summary>
        /// Get a Preview image for the current job and preview number.
        /// </summary>
        /// <param name="job">
        /// The job.
        /// </param>
        /// <param name="preview">
        /// The preview.
        /// </param>
        /// <param name="configuraiton">
        /// The configuraiton.
        /// </param>
        /// <returns>
        /// The <see cref="BitmapImage"/>.
        /// </returns>
        public BitmapImage GetPreview(EncodeTask job, int preview, HBConfiguration configuraiton)
        {
            if (this.instance == null)
            {
                return(null);
            }

            BitmapImage bitmapImage = null;

            try
            {
                PreviewSettings settings = new PreviewSettings
                {
                    Cropping          = new Cropping(job.Cropping),
                    MaxWidth          = job.MaxWidth ?? 0,
                    MaxHeight         = job.MaxHeight ?? 0,
                    KeepDisplayAspect = job.KeepDisplayAspect,
                    TitleNumber       = job.Title,
                    Anamorphic        = job.Anamorphic,
                    Modulus           = job.Modulus,
                    Width             = job.Width ?? 0,
                    Height            = job.Height ?? 0,
                    PixelAspectX      = job.PixelAspectX,
                    PixelAspectY      = job.PixelAspectY
                };

                var bitmapData = this.instance.GetPreview(settings, preview, job.DeinterlaceFilter != DeinterlaceFilter.Off);
                bitmapImage = BitmapUtilities.ConvertToBitmapImage(BitmapUtilities.ConvertByteArrayToBitmap(bitmapData));
            }
            catch (AccessViolationException e)
            {
                Debug.WriteLine(e);
            }

            return(bitmapImage);
        }
Example #10
0
        /// <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
            {
                this.logging.Clear();

                string source = sourcePath.ToString().EndsWith("\\") ? string.Format("\"{0}\\\\\"", sourcePath.ToString().TrimEnd('\\'))
                              : "\"" + sourcePath + "\"";
                this.currentSourceScanPath = source;

                this.IsScanning = true;
                if (this.ScanStared != null)
                {
                    this.ScanStared(this, System.EventArgs.Empty);
                }

                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);
            }
            catch (Exception exc)
            {
                this.ServiceLogMessage("Scan Failed ..." + Environment.NewLine + exc);
                this.Stop();

                if (this.ScanCompleted != null)
                {
                    this.ScanCompleted(this, new ScanCompletedEventArgs(false, exc, "An Error has occured in ScanService.ScanSource()"));
                }
            }
        }
Example #11
0
 public FixedTableNineDozensRepository(IOptionsMonitor <HBConfiguration> hbConfiguration)
 {
     _hbConfiguration    = hbConfiguration.CurrentValue;
     _providerConnection = new ProviderConnection(_hbConfiguration.ConnectionString);
 }
Example #12
0
        /// <summary>
        /// Scan a Source Path.
        /// Title 0: scan all
        /// </summary>
        /// <param name="sourcePath">
        /// Path to the file to scan
        /// </param>
        /// <param name="title">
        /// int title number. 0 for scan all
        /// </param>
        /// <param name="postAction">
        /// The post Action.
        /// </param>
        /// <param name="configuraiton">
        /// The configuraiton.
        /// </param>
        public void Scan(string sourcePath, int title, Action <bool, Source> postAction, HBConfiguration configuraiton)
        {
            // Try to cleanup any previous scan instances.
            if (this.instance != null)
            {
                try
                {
                    this.instance.Dispose();
                }
                catch (Exception)
                {
                    // Do Nothing
                }
            }

            this.isCancelled = false;

            // Handle the post scan operation.
            this.postScanOperation = postAction;

            // Create a new HandBrake Instance.
            this.instance = HandBrakeInstanceManager.GetScanInstance(configuraiton.Verbosity);
            this.instance.ScanProgress  += this.InstanceScanProgress;
            this.instance.ScanCompleted += this.InstanceScanCompleted;

            // Start the scan on a back
            this.ScanSource(sourcePath, title, configuraiton.PreviewScanCount, configuraiton);
        }
Example #13
0
        /// <summary>
        /// The create hb preset.
        /// </summary>
        /// <param name="export">
        /// The export.
        /// </param>
        /// <param name="config">HandBrakes current configuration</param>
        /// <returns>
        /// The <see cref="HBPreset"/>.
        /// </returns>
        public static HBPreset CreateHbPreset(Preset export, HBConfiguration config)
        {
            HBPreset preset = new HBPreset();

            // Preset
            preset.PresetDescription = export.Description;
            preset.PresetName        = export.Name;
            preset.Type = export.IsBuildIn ? 0 : 1;
            preset.UsesPictureSettings = (int)export.PictureSettingsMode;
            preset.Default             = export.IsDefault;

            // Audio
            preset.AudioCopyMask        = export.Task.AllowedPassthruOptions.AllowedPassthruOptions.Select(EnumHelper <AudioEncoder> .GetShortName).ToList();
            preset.AudioEncoderFallback = EnumHelper <AudioEncoder> .GetShortName(export.Task.AllowedPassthruOptions.AudioEncoderFallback);

            preset.AudioLanguageList           = LanguageUtilities.GetLanguageCodes(export.AudioTrackBehaviours.SelectedLangauges);
            preset.AudioTrackSelectionBehavior = EnumHelper <AudioBehaviourModes> .GetShortName(export.AudioTrackBehaviours.SelectedBehaviour);

            preset.AudioSecondaryEncoderMode = export.AudioTrackBehaviours.SelectedTrackDefaultBehaviour == AudioTrackDefaultsMode.FirstTrack; // TODO -> We don't support AllTracks yet in other GUIs.
            preset.AudioList = new List <AudioList>();
            foreach (var item in export.AudioTrackBehaviours.BehaviourTracks)
            {
                AudioList track = new AudioList
                {
                    AudioBitrate            = item.Bitrate,
                    AudioCompressionLevel   = 0,    // TODO
                    AudioDitherMethod       = null, // TODO
                    AudioEncoder            = EnumHelper <AudioEncoder> .GetShortName(item.Encoder),
                    AudioMixdown            = item.MixDown != null ? item.MixDown.ShortName : "dpl2",
                    AudioNormalizeMixLevel  = false,                                                                                  // TODO
                    AudioSamplerate         = item.SampleRate == 0 ? "auto" : item.SampleRate.ToString(CultureInfo.InvariantCulture), // TODO check formatting.
                    AudioTrackDRCSlider     = item.DRC,
                    AudioTrackGainSlider    = item.Gain,
                    AudioTrackQuality       = item.Quality ?? 0,
                    AudioTrackQualityEnable = item.Quality.HasValue && item.IsQualityVisible
                };

                preset.AudioList.Add(track);
            }

            // Subtitles
            preset.SubtitleAddCC = export.SubtitleTrackBehaviours.AddClosedCaptions;
            preset.SubtitleAddForeignAudioSearch = export.SubtitleTrackBehaviours.AddForeignAudioScanTrack;
            preset.SubtitleBurnBDSub             = false; // TODO not supported yet.
            preset.SubtitleBurnDVDSub            = false; // TODO not supported yet.
            preset.SubtitleBurnBehavior          = EnumHelper <SubtitleBurnInBehaviourModes> .GetShortName(export.SubtitleTrackBehaviours.SelectedBurnInBehaviour);

            preset.SubtitleLanguageList           = LanguageUtilities.GetLanguageCodes(export.SubtitleTrackBehaviours.SelectedLangauges);
            preset.SubtitleTrackSelectionBehavior = EnumHelper <SubtitleBehaviourModes> .GetShortName(export.SubtitleTrackBehaviours.SelectedBehaviour);

            // Chapters
            preset.ChapterMarkers = export.Task.IncludeChapterMarkers;

            // Output Settings
            preset.FileFormat = EnumHelper <OutputFormat> .GetShortName(export.Task.OutputFormat);

            preset.Mp4HttpOptimize   = export.Task.OptimizeMP4;
            preset.Mp4iPodCompatible = export.Task.IPod5GSupport;

            // Picture Settings
            preset.PictureForceHeight = 0;                                                           // TODO
            preset.PictureForceWidth  = 0;                                                           // TODO
            preset.PictureHeight      = preset.UsesPictureSettings >= 1 ? export.Task.MaxHeight : 0; // TODO; // TODO
            preset.PictureItuPAR      = false;                                                       // TODO Not supported Yet
            preset.PictureKeepRatio   = export.Task.KeepDisplayAspect;
            preset.PictureLeftCrop    = export.Task.Cropping.Left;
            preset.PictureLooseCrop   = false; // TODO Not Supported Yet
            preset.PictureModulus     = export.Task.Modulus ?? 16;
            preset.PicturePAR         = EnumHelper <Anamorphic> .GetShortName(export.Task.Anamorphic);

            preset.PicturePARHeight  = export.Task.PixelAspectY;
            preset.PicturePARWidth   = export.Task.PixelAspectX;
            preset.PictureRightCrop  = export.Task.Cropping.Right;
            preset.PictureRotate     = string.Format("{0}:{1}", export.Task.Rotation, export.Task.FlipVideo ? "1" : "0");
            preset.PictureTopCrop    = export.Task.Cropping.Top;
            preset.PictureWidth      = preset.UsesPictureSettings >= 1 ? export.Task.MaxWidth : 0; // TODO
            preset.PictureDARWidth   = export.Task.DisplayWidth.HasValue ? (int)export.Task.DisplayWidth.Value : 0;
            preset.PictureAutoCrop   = !export.Task.HasCropping;
            preset.PictureBottomCrop = export.Task.Cropping.Bottom;

            // Filters
            preset.PictureDeblock           = export.Task.Deblock;
            preset.PictureDeinterlaceFilter = export.Task.DeinterlaceFilter == DeinterlaceFilter.Decomb
                ? "decomb"
                : export.Task.DeinterlaceFilter == DeinterlaceFilter.Yadif ? "yadif" : "off";
            preset.PictureDeinterlacePreset = export.Task.DeinterlaceFilter == DeinterlaceFilter.Decomb
                ? EnumHelper <Decomb> .GetShortName(export.Task.Decomb)
                : export.Task.DeinterlaceFilter == DeinterlaceFilter.Yadif ? EnumHelper <Deinterlace> .GetShortName(export.Task.Deinterlace) : string.Empty;

            preset.PictureDeinterlaceCustom = export.Task.DeinterlaceFilter == DeinterlaceFilter.Decomb
                ? export.Task.CustomDecomb
                : export.Task.DeinterlaceFilter == DeinterlaceFilter.Yadif ? export.Task.CustomDeinterlace : string.Empty;
            preset.PictureDeinterlaceCustom = export.Task.CustomDeinterlace;
            preset.PictureDenoiseCustom     = export.Task.CustomDenoise;
            preset.PictureDenoiseFilter     = EnumHelper <Denoise> .GetShortName(export.Task.Denoise);

            preset.PictureDenoisePreset = EnumHelper <DenoisePreset> .GetShortName(export.Task.DenoisePreset);

            preset.PictureDenoiseTune = EnumHelper <DenoiseTune> .GetShortName(export.Task.DenoiseTune);

            preset.PictureDetelecine = EnumHelper <Detelecine> .GetShortName(export.Task.Detelecine);

            preset.PictureDetelecineCustom = export.Task.CustomDetelecine;
            preset.PictureCombDetectPreset = EnumHelper <CombDetect> .GetShortName(export.Task.CombDetect);

            preset.PictureCombDetectCustom = export.Task.CustomCombDetect;

            // Video
            preset.VideoEncoder = EnumHelper <VideoEncoder> .GetShortName(export.Task.VideoEncoder);

            preset.VideoFramerate     = export.Task.Framerate.ToString();
            preset.VideoFramerateMode = EnumHelper <FramerateMode> .GetShortName(export.Task.FramerateMode);

            preset.VideoGrayScale     = export.Task.Grayscale;
            preset.VideoLevel         = export.Task.VideoLevel.ShortName;
            preset.VideoOptionExtra   = export.Task.ExtraAdvancedArguments;
            preset.VideoPreset        = export.Task.VideoPreset.ShortName;
            preset.VideoProfile       = export.Task.VideoProfile.ShortName;
            preset.VideoQSVAsyncDepth = 4; // Defaulted to 4 for now.
            preset.VideoQSVDecode     = !config.DisableQuickSyncDecoding;
            preset.VideoQualitySlider = export.Task.Quality.HasValue ? export.Task.Quality.Value : 0;
            preset.VideoQualityType   = (int)export.Task.VideoEncodeRateType;
            preset.VideoScaler        = EnumHelper <VideoScaler> .GetShortName(config.ScalingMode);

            preset.VideoTune            = export.Task.VideoTunes.Aggregate(string.Empty, (current, item) => !string.IsNullOrEmpty(current) ? string.Format("{0}, {1}", current, item.ShortName) : item.ShortName);
            preset.VideoAvgBitrate      = export.Task.VideoBitrate ?? 0;
            preset.VideoColorMatrixCode = 0; // TODO not supported.
            preset.VideoTurboTwoPass    = export.Task.TurboFirstPass;
            preset.VideoTwoPass         = export.Task.TwoPass;

            // Advanced
            preset.x264Option             = export.Task.AdvancedEncoderOptions;
            preset.x264UseAdvancedOptions = export.Task.ShowAdvancedTab;

            // Unknown
            preset.ChildrenArray = new List <object>(); // We don't support nested presets.
            preset.Folder        = false;               // TODO
            preset.FolderOpen    = false;               // TODO

            return(preset);
        }
Example #14
0
        /// <summary>
        /// Export a list of Presets.
        /// </summary>
        /// <param name="exportList">A list of presets to export</param>
        /// <param name="config">HB's configuration</param>
        /// <returns>A list of JSON object presets.</returns>
        public static PresetTransportContainer ExportPresets(IEnumerable <Preset> exportList, HBConfiguration config)
        {
            PresetTransportContainer container = new PresetTransportContainer();

            container.VersionMajor = Constants.PresetVersionMajor;
            container.VersionMinor = Constants.PresetVersionMinor;
            container.VersionMicro = Constants.PresetVersionMicro;

            List <HBPreset> presets = exportList.Select(item => CreateHbPreset(item, config)).ToList();

            container.PresetList = new List <object>();
            container.PresetList.AddRange(presets);

            return(container);
        }
Example #15
0
        /// <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, string basePresetName)
        {
            try
            {
                // Sanity Checking and Setup
                if (this.IsEncoding)
                {
                    throw new GeneralApplicationException(Resources.Queue_AlreadyEncoding, Resources.Queue_AlreadyEncodingSolution, 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.

                if (this.instance != null)
                {
                    // Cleanup
                    try
                    {
                        this.instance.EncodeCompleted -= this.InstanceEncodeCompleted;
                        this.instance.EncodeProgress  -= this.InstanceEncodeProgress;
                        this.instance.Dispose();
                        this.instance = null;
                    }
                    catch (Exception exc)
                    {
                        this.ServiceLogMessage("Failed to cleanup previous instance: " + exc);
                    }
                }

                this.ServiceLogMessage("Starting Encode ...");
                if (!string.IsNullOrEmpty(basePresetName))
                {
                    this.TimedLogMessage(string.Format("base preset: {0}", basePresetName));
                }

                this.instance = task.IsPreviewEncode ? HandBrakeInstanceManager.GetPreviewInstance(configuration.Verbosity, configuration) : HandBrakeInstanceManager.GetEncodeInstance(configuration.Verbosity, configuration);

                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(EncodeTaskFactory.Create(task, configuration, hbFunctionsProvider.GetHbFunctionsWrapper()));

                // 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", this.currentTask.Source, this.currentTask.Destination, null, 0));
            }
        }
Example #16
0
 public HistoryLotoFacilRespository(IOptionsMonitor <HBConfiguration> hbConfiguration)
 {
     _hbConfiguration    = hbConfiguration.CurrentValue;
     _providerConnection = new ProviderConnection(_hbConfiguration.ConnectionString);
 }
        /// <summary>
        /// Get an EncodeJob model for a LibHB Encode.
        /// </summary>
        /// <param name="task">
        /// The task.
        /// </param>
        /// <param name="configuration">
        /// The configuration.
        /// </param>
        /// <returns>
        /// An Interop.EncodeJob model.
        /// </returns>
        public static EncodeJob GetEncodeJob(EncodeTask task, HBConfiguration configuration)
        {
            // The current Job Configuration
            EncodeTask work = task;

            // Which will be converted to this EncodeJob Model.
            EncodeJob job = new EncodeJob();

            // Audio Settings
            job.AudioEncodings = new List <AudioEncoding>();
            foreach (AudioTrack track in work.AudioTracks)
            {
                AudioEncoding newTrack = new AudioEncoding
                {
                    Bitrate        = track.Bitrate,
                    Drc            = track.DRC,
                    Gain           = track.Gain,
                    Encoder        = Converters.GetCliAudioEncoder(track.Encoder),
                    InputNumber    = track.Track.HasValue ? track.Track.Value : 0,
                    Mixdown        = Converters.GetCliMixDown(track.MixDown),
                    SampleRateRaw  = GetSampleRateRaw(track.SampleRate),
                    EncodeRateType = AudioEncodeRateType.Bitrate,
                    Name           = track.TrackName,
                    IsPassthru     = track.IsPassthru,
                };

                job.AudioEncodings.Add(newTrack);
            }

            // Title Settings
            job.OutputPath = work.Destination;
            job.SourcePath = work.Source;
            job.Title      = work.Title;

            // job.SourceType = work.Type;
            switch (work.PointToPointMode)
            {
            case PointToPointMode.Chapters:
                job.RangeType = VideoRangeType.Chapters;
                break;

            case PointToPointMode.Seconds:
                job.RangeType = VideoRangeType.Seconds;
                break;

            case PointToPointMode.Frames:
                job.RangeType = VideoRangeType.Frames;
                break;

            case PointToPointMode.Preview:
                job.RangeType = VideoRangeType.Preview;
                break;
            }

            if (work.PointToPointMode == PointToPointMode.Seconds)
            {
                job.SecondsEnd   = work.EndPoint;
                job.SecondsStart = work.StartPoint;
            }
            if (work.PointToPointMode == PointToPointMode.Chapters)
            {
                job.ChapterStart = work.StartPoint;
                job.ChapterEnd   = work.EndPoint;
            }
            if (work.PointToPointMode == PointToPointMode.Frames)
            {
                job.FramesEnd   = work.EndPoint;
                job.FramesStart = work.StartPoint;
            }

            if (work.PointToPointMode == PointToPointMode.Preview)
            {
                job.StartAtPreview = work.PreviewEncodeStartAt.HasValue ? work.PreviewEncodeStartAt.Value + 1 : 1;
                job.SecondsEnd     = work.PreviewEncodeDuration.HasValue ? work.PreviewEncodeDuration.Value : 30;
                job.SeekPoints     = configuration.PreviewScanCount;
            }

            job.Angle = work.Angle;

            // Output Settings
            job.IPod5GSupport = work.IPod5GSupport;
            job.Optimize      = work.OptimizeMP4;
            switch (work.OutputFormat)
            {
            case OutputFormat.Mp4:
                job.ContainerName = "av_mp4";     // TODO make part of enum.
                break;

            case OutputFormat.Mkv:
                job.ContainerName = "av_mkv";     // TODO make part of enum.
                break;
            }

            // Picture Settings
            job.Anamorphic = work.Anamorphic;
            job.Cropping   = new Cropping {
                Top = work.Cropping.Top, Bottom = work.Cropping.Bottom, Left = work.Cropping.Left, Right = work.Cropping.Right
            };
            job.DisplayWidth      = work.DisplayWidth.HasValue ? int.Parse(Math.Round(work.DisplayWidth.Value, 0).ToString()) : 0;
            job.PixelAspectX      = work.PixelAspectX;
            job.PixelAspectY      = work.PixelAspectY;
            job.Height            = work.Height.HasValue ? work.Height.Value : 0;
            job.KeepDisplayAspect = work.KeepDisplayAspect;
            job.MaxHeight         = work.MaxHeight.HasValue ? work.MaxHeight.Value : 0;
            job.MaxWidth          = work.MaxWidth.HasValue ? work.MaxWidth.Value : 0;
            job.Modulus           = work.Modulus.HasValue ? work.Modulus.Value : 16;
            job.UseDisplayWidth   = true;
            job.Width             = work.Width.HasValue ? work.Width.Value : 0;

            // Filter Settings
            job.CustomDecomb      = work.CustomDecomb;
            job.CustomDeinterlace = work.CustomDeinterlace;
            job.CustomDenoise     = work.CustomDenoise;
            job.DenoisePreset     = work.DenoisePreset.ToString().ToLower().Replace(" ", string.Empty);
            job.DenoiseTune       = work.DenoiseTune.ToString().ToLower().Replace(" ", string.Empty);
            job.CustomDetelecine  = work.CustomDetelecine;
            if (work.Deblock > 4)
            {
                job.Deblock = work.Deblock;
            }
            job.Decomb      = work.Decomb;
            job.Deinterlace = work.Deinterlace;
            job.Denoise     = work.Denoise;
            job.Detelecine  = work.Detelecine;
            job.Grayscale   = work.Grayscale;

            // Video Settings
            job.Framerate           = work.Framerate.HasValue ? work.Framerate.Value : 0;
            job.ConstantFramerate   = work.FramerateMode == FramerateMode.CFR;
            job.PeakFramerate       = work.FramerateMode == FramerateMode.PFR;
            job.Quality             = work.Quality.HasValue ? work.Quality.Value : 0;
            job.VideoBitrate        = work.VideoBitrate.HasValue ? work.VideoBitrate.Value : 0;
            job.VideoEncodeRateType = work.VideoEncodeRateType;
            job.VideoEncoder        = Converters.GetVideoEncoder(work.VideoEncoder);
            job.TwoPass             = work.TwoPass;
            job.TurboFirstPass      = work.TurboFirstPass;

            if (work.VideoEncoder == VideoEncoder.X264 || work.VideoEncoder == VideoEncoder.X265 || work.VideoEncoder == VideoEncoder.QuickSync)
            {
                job.VideoPreset  = work.VideoPreset.ShortName;
                job.VideoProfile = work.VideoProfile.ShortName;
                job.VideoLevel   = work.VideoLevel.ShortName;

                if (work.VideoEncoder != VideoEncoder.QuickSync)
                {
                    job.VideoTunes = new List <string>();
                    foreach (var item in work.VideoTunes)
                    {
                        job.VideoTunes.Add(item.ShortName);
                    }
                }
            }

            // Chapter Markers
            job.IncludeChapterMarkers  = work.IncludeChapterMarkers;
            job.CustomChapterNames     = work.ChapterNames.Select(item => item.ChapterName).ToList();
            job.UseDefaultChapterNames = work.IncludeChapterMarkers;

            // Advanced Settings
            job.VideoOptions = work.ShowAdvancedTab ? work.AdvancedEncoderOptions : work.ExtraAdvancedArguments;

            // Subtitles
            job.Subtitles = new Subtitles {
                SourceSubtitles = new List <SourceSubtitle>(), SrtSubtitles = new List <SrtSubtitle>()
            };
            foreach (SubtitleTrack track in work.SubtitleTracks)
            {
                if (track.IsSrtSubtitle)
                {
                    job.Subtitles.SrtSubtitles.Add(
                        new SrtSubtitle
                    {
                        CharacterCode = track.SrtCharCode,
                        Default       = track.Default,
                        FileName      = track.SrtPath,
                        LanguageCode  = track.SrtLang,
                        Offset        = track.SrtOffset,
                        BurnedIn      = track.Burned
                    });
                }
                else
                {
                    if (track.SourceTrack != null)
                    {
                        job.Subtitles.SourceSubtitles.Add(
                            new SourceSubtitle {
                            BurnedIn = track.Burned, Default = track.Default, Forced = track.Forced, TrackNumber = track.SourceTrack.TrackNumber
                        });
                    }
                }
            }

            return(job);
        }
Example #18
0
        /// <summary>
        /// Export a list of Presets.
        /// </summary>
        /// <param name="exportList">A list of presets to export</param>
        /// <param name="config">HB's configuration</param>
        /// <returns>A list of JSON object presets.</returns>
        public static PresetTransportContainer ExportPresets(IEnumerable <Preset> exportList, HBConfiguration config)
        {
            PresetVersion            presetVersion = HandBrakePresetService.GetCurrentPresetVersion();
            PresetTransportContainer container     = new PresetTransportContainer(presetVersion.Major, presetVersion.Minor, presetVersion.Micro);

            List <HBPreset> presets = exportList.Select(item => CreateHbPreset(item, config)).ToList();

            container.PresetList = new List <object>();
            container.PresetList.AddRange(presets);

            return(container);
        }
        public static HBPresetCategory CreatePresetCategory(PresetDisplayCategory category, HBConfiguration config)
        {
            HBPresetCategory preset = new HBPresetCategory();

            preset.Folder            = true;
            preset.PresetName        = category.Category;
            preset.PresetDescription = string.Empty;
            preset.ChildrenArray     = new List <HBPreset>();

            foreach (Preset singlePreset in category.Presets)
            {
                preset.ChildrenArray.Add(CreateHbPreset(singlePreset, config));
            }

            return(preset);
        }
Example #20
0
        public void ExportCategories(string filename, IList <PresetDisplayCategory> categories, HBConfiguration configuration)
        {
            PresetTransportContainer container = JsonPresetFactory.ExportPresetCategories(categories, configuration);

            HandBrakePresetService.ExportPreset(filename, container);
        }
        /// <summary>
        /// Scan a Source Path.
        /// Title 0: scan all
        /// </summary>
        /// <param name="sourcePath">
        /// Path to the file to scan
        /// </param>
        /// <param name="title">
        /// int title number. 0 for scan all
        /// </param>
        /// <param name="postAction">
        /// The post Action.
        /// </param>
        /// <param name="configuraiton">
        /// The configuraiton.
        /// </param>
        public void Scan(string sourcePath, int title, Action <bool, Source> postAction, HBConfiguration configuraiton)
        {
            // Try to cleanup any previous scan instances.
            if (this.instance != null)
            {
                try
                {
                    lock (LogLock)
                    {
                        this.scanLog.Close();
                        this.scanLog.Dispose();
                        this.scanLog = null;
                    }
                    this.instance.Dispose();
                }
                catch (Exception)
                {
                    // Do Nothing
                }
            }

            // Handle the post scan operation.
            this.postScanOperation = postAction;

            // Clear down the logging
            this.logging.Clear();

            try
            {
                // Make we don't pick up a stale last_scan_log_xyz.txt (and that we have rights to the file)
                if (File.Exists(this.dvdInfoPath))
                {
                    File.Delete(this.dvdInfoPath);
                }
            }
            catch (Exception exc)
            {
                Debug.WriteLine(exc);
            }

            if (!Directory.Exists(Path.GetDirectoryName(this.dvdInfoPath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(this.dvdInfoPath));
            }

            // Create a new scan log.
            this.scanLog = new StreamWriter(this.dvdInfoPath);

            // Create a new HandBrake Instance.
            HandBrakeUtils.MessageLogged += this.HandBrakeInstanceMessageLogged;
            HandBrakeUtils.ErrorLogged   += this.HandBrakeInstanceErrorLogged;
            this.instance = HandBrakeInstanceManager.GetScanInstance(configuraiton.Verbosity);
            this.instance.ScanProgress  += this.InstanceScanProgress;
            this.instance.ScanCompleted += this.InstanceScanCompleted;

            // Start the scan on a back
            this.ScanSource(sourcePath, title, configuraiton.PreviewScanCount, configuraiton);
        }
Example #22
0
 /// <summary>
 /// Copy the log file to the desired destinations
 /// </summary>
 /// <param name="destination">
 /// The destination.
 /// </param>
 /// <param name="configuration">
 /// The configuration.
 /// </param>
 public void ProcessLogs(string destination, HBConfiguration configuration)
 {
     ThreadPool.QueueUserWorkItem(delegate { this.Service.ProcessEncodeLogs(destination, configuration); });
 }
Example #23
0
        /// <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
            {
                // Setup
                this.startTime            = DateTime.Now;
                this.currentTask          = task;
                this.currentConfiguration = configuration;

                // Create a new HandBrake instance
                // Setup the HandBrake Instance
                HandBrakeUtils.MessageLogged += this.HandBrakeInstanceMessageLogged;
                HandBrakeUtils.ErrorLogged   += this.HandBrakeInstanceErrorLogged;
                this.instance = HandBrakeInstanceManager.GetEncodeInstance(configuration.Verbosity);
                this.instance.EncodeCompleted += this.InstanceEncodeCompleted;
                this.instance.EncodeProgress  += this.InstanceEncodeProgress;

                // Sanity Checking and Setup
                if (this.IsEncoding)
                {
                    throw new Exception("HandBrake is already encoding.");
                }

                this.IsEncoding = true;
                this.SetupLogging();

                // Verify the Destination Path Exists, and if not, create it.
                this.VerifyEncodeDestinationPath(task);

                this.ServiceLogMessage("Starting Encode ...");

                // 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);

                // Set the Process Priority
                switch (configuration.ProcessPriority)
                {
                case "Realtime":
                    Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime;
                    break;

                case "High":
                    Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
                    break;

                case "Above Normal":
                    Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.AboveNormal;
                    break;

                case "Normal":
                    Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.Normal;
                    break;

                case "Low":
                    Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.Idle;
                    break;

                default:
                    Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.BelowNormal;
                    break;
                }
            }
            catch (Exception exc)
            {
                this.IsEncoding = false;

                this.ServiceLogMessage("Failed to start encoding ..." + Environment.NewLine + exc);
                this.InvokeEncodeCompleted(new HandBrakeWPF.Services.Encode.EventArgs.EncodeCompletedEventArgs(false, exc, "Unable to start encoding", task.Source));
            }
        }
Example #24
0
 /// <summary>
 /// The process encode logs.
 /// </summary>
 /// <param name="destination">
 /// The destination.
 /// </param>
 /// <param name="configuration">
 /// The configuration.
 /// </param>
 public void ProcessEncodeLogs(string destination, HBConfiguration configuration)
 {
     encodeService.ProcessLogs(destination, configuration);
 }
Example #25
0
        public void Export(string filename, Preset preset, HBConfiguration configuration)
        {
            PresetTransportContainer container = JsonPresetFactory.ExportPreset(preset, configuration);

            HandBrakePresetService.ExportPreset(filename, container);
        }
Example #26
0
        /// <summary>
        /// The create video.
        /// </summary>
        /// <param name="job">
        /// The job.
        /// </param>
        /// <param name="configuration">
        /// The configuration.
        /// </param>
        /// <returns>
        /// The <see cref="Video"/>.
        /// </returns>
        private static Video CreateVideo(EncodeTask job, HBConfiguration configuration)
        {
            Video video = new Video();

            HBVideoEncoder videoEncoder = HandBrakeEncoderHelpers.VideoEncoders.FirstOrDefault(e => e.ShortName == EnumHelper <VideoEncoder> .GetShortName(job.VideoEncoder));

            Validate.NotNull(videoEncoder, "Video encoder " + job.VideoEncoder + " not recognized.");
            if (videoEncoder != null)
            {
                video.Encoder = videoEncoder.ShortName;
            }

            video.Level   = job.VideoLevel?.ShortName;
            video.Preset  = job.VideoPreset?.ShortName;
            video.Profile = job.VideoProfile?.ShortName;

            if (job.VideoTunes != null && job.VideoTunes.Count > 0)
            {
                foreach (var item in job.VideoTunes)
                {
                    video.Tune += string.IsNullOrEmpty(video.Tune) ? item.ShortName : "," + item.ShortName;
                }
            }

            if (job.VideoEncodeRateType == VideoEncodeRateType.ConstantQuality)
            {
                video.Quality = job.Quality;
            }

            if (job.VideoEncodeRateType == VideoEncodeRateType.AverageBitrate)
            {
                video.Bitrate = job.VideoBitrate;
                video.TwoPass = job.TwoPass;
                video.Turbo   = job.TurboFirstPass;
            }

            video.QSV.Decode = SystemInfo.IsQsvAvailable && configuration.EnableQuickSyncDecoding;

            // The use of the QSV decoder is configurable for non QSV encoders.
            if (video.QSV.Decode && job.VideoEncoder != VideoEncoder.QuickSync && job.VideoEncoder != VideoEncoder.QuickSyncH265 && job.VideoEncoder != VideoEncoder.QuickSyncH26510b)
            {
                video.QSV.Decode = configuration.UseQSVDecodeForNonQSVEnc;
            }


            video.Options = job.ExtraAdvancedArguments;

            if (job.VideoEncoder == VideoEncoder.QuickSync || job.VideoEncoder == VideoEncoder.QuickSyncH265 || job.VideoEncoder == VideoEncoder.QuickSyncH26510b)
            {
                if (configuration.EnableQsvLowPower && !video.Options.Contains("lowpower"))
                {
                    video.Options = string.IsNullOrEmpty(video.Options) ? "lowpower=1" : string.Concat(video.Options, ":lowpower=1");
                }
                else if (!configuration.EnableQsvLowPower && !video.Options.Contains("lowpower"))
                {
                    video.Options = string.IsNullOrEmpty(video.Options) ? "lowpower=0" : string.Concat(video.Options, ":lowpower=0");
                }
            }

            return(video);
        }
Example #27
0
        public void Start(EncodeTask task, HBConfiguration configuration, string basePresetName)
        {
            try
            {
                // Sanity Checking and Setup
                if (this.IsEncoding)
                {
                    throw new GeneralApplicationException(Resources.Queue_AlreadyEncoding, Resources.Queue_AlreadyEncodingSolution, null);
                }

                // Setup
                this.startTime         = DateTime.Now;
                this.currentTask       = task;
                this.isPreviewInstance = task.IsPreviewEncode;

                if (this.userSettingService.GetUserSetting <bool>(UserSettingConstants.ProcessIsolationEnabled))
                {
                    this.InitLogging(task.Destination);
                }
                else
                {
                    this.encodeLogService = this.logInstanceManager.ApplicationLogInstance;
                    this.encodeLogService.Reset();
                }

                if (this.instance != null)
                {
                    // Cleanup
                    try
                    {
                        this.instance.EncodeCompleted -= this.InstanceEncodeCompleted;
                        this.instance.EncodeProgress  -= this.InstanceEncodeProgress;
                        this.instance.Dispose();
                        this.instance = null;
                    }
                    catch (Exception exc)
                    {
                        this.ServiceLogMessage("Failed to cleanup previous instance: " + exc);
                    }
                }

                this.ServiceLogMessage("Starting Encode ...");
                if (!string.IsNullOrEmpty(basePresetName))
                {
                    this.TimedLogMessage(string.Format("base preset: {0}", basePresetName));
                }

                int verbosity = this.userSettingService.GetUserSetting <int>(UserSettingConstants.Verbosity);

                // Prevent port stealing if multiple jobs start at the same time.
                lock (this.portLock)
                {
                    this.instance = task.IsPreviewEncode ? HandBrakeInstanceManager.GetPreviewInstance(verbosity, this.userSettingService) : HandBrakeInstanceManager.GetEncodeInstance(verbosity, configuration, this.encodeLogService, this.userSettingService, this.portService);

                    this.instance.EncodeCompleted += this.InstanceEncodeCompleted;
                    this.instance.EncodeProgress  += this.InstanceEncodeProgress;

                    this.IsEncoding = true;

                    // Verify the Destination Path Exists, and if not, create it.
                    this.VerifyEncodeDestinationPath(task);

                    // Get an EncodeJob object for the Interop Library
                    JsonEncodeObject work = this.encodeTaskFactory.Create(task, configuration);

                    this.instance.StartEncode(work);
                }

                // 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", this.currentTask.Source, this.currentTask.Destination, null, 0, 3));
            }
        }
        public static PresetTransportContainer ExportPresetCategories(IList <PresetDisplayCategory> categories, HBConfiguration config)
        {
            PresetVersion            presetVersion = HandBrakePresetService.GetCurrentPresetVersion();
            PresetTransportContainer container     = new PresetTransportContainer(presetVersion.Major, presetVersion.Minor, presetVersion.Micro);

            List <object> presets = new List <object>();

            foreach (var category in categories)
            {
                presets.Add(CreatePresetCategory(category, config));
            }

            container.PresetList = presets;

            return(container);
        }