Example #1
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
            {
                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>
        /// 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 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);
        }
        public static IEncodeInstance GetEncodeInstance(int verbosity, HBConfiguration configuration, ILog logService, IUserSettingService userSettingService, IPortService portService)
        {
            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);
        }
Example #4
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>
        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();
            }
        }
Example #5
0
        /// <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);
        }
Example #6
0
        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.DisableLibDvdNav)
            {
                HandBrakeUtils.SetDvdNav(true); // TODO check this is correct
            }
        }
Example #7
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>
        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()"));
                }
            }
        }
Example #8
0
        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;
            }
        }
Example #9
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
            {
                // 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>
        /// 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);
        }
Example #12
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 #13
0
        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;
            }
        }
Example #14
0
 private void GlobalInitialize()
 {
     HandBrakeUtils.SetDvdNav(Config.EnableLibDvdNav);
 }
Example #15
0
        /// <summary>
        /// Start with a LibHb EncodeJob Object
        /// </summary>
        /// <param name="job">
        /// The job.
        /// </param>
        public void Start(QueueTask job)
        {
            // Setup
            this.startTime   = DateTime.Now;
            this.currentTask = job;

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

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

                this.IsEncoding = true;

                // Enable logging if required.
                try
                {
                    this.SetupLogging(job, true);
                }
                catch (Exception)
                {
                    this.IsEncoding = false;
                    throw;
                }

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

                // We have to scan the source again but only the title so the HandBrake instance is initialised correctly.
                // Since the UI sends the crop params down, we don't have to do all the previews.

                this.instance.ScanCompleted += delegate
                {
                    // Process into internal structures.
                    this.scannedSource = new Source {
                        Titles = LibScan.ConvertTitles(this.instance.Titles, this.instance.FeatureTitle)
                    };                                                                                                                    // TODO work around the bad Internal API.
                    this.ScanCompleted(job, this.instance);
                };

                HandBrakeUtils.SetDvdNav(!job.Configuration.IsDvdNavDisabled);

                ServiceLogMessage("Scanning title for encoding ... ");

                this.instance.StartScan(job.ScannedSourcePath, job.Configuration.PreviewScanCount, TimeSpan.FromSeconds(job.Configuration.MinScanDuration), job.Task.Title);
            }
            catch (Exception exc)
            {
                ServiceLogMessage("Scan Failed ... " + Environment.NewLine + exc);
                this.InvokeEncodeCompleted(new EventArgs.EncodeCompletedEventArgs(false, exc, "An Error has occured.", this.currentTask.Task.Destination));
            }
        }
Example #16
0
        public void StartEncode(EncodeJob job, bool preview, int previewNumber, int previewSeconds, double overallSelectedLengthSeconds, int verbosity, int previewCount, bool useDvdNav)
        {
            CurrentEncoder = this;
            this.callback  = OperationContext.Current.GetCallbackChannel <IHandBrakeEncoderCallback>();

            try
            {
                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);

                this.instance = new HandBrakeInstance();
                this.instance.Initialize(verbosity);

                this.instance.ScanCompleted += (o, e) =>
                {
                    try
                    {
                        Title encodeTitle = this.instance.Titles.FirstOrDefault(title => title.TitleNumber == job.Title);

                        if (encodeTitle != null)
                        {
                            lock (this.encodeLock)
                            {
                                this.instance.StartEncode(job, preview, previewNumber, previewSeconds, overallSelectedLengthSeconds, previewCount);
                                this.callback.OnEncodeStarted();
                                this.state = EncodeState.Encoding;
                            }
                        }
                        else
                        {
                            this.callback.OnEncodeComplete(true);
                            this.CleanUpAndSignalCompletion();
                        }
                    }
                    catch (Exception exception)
                    {
                        this.callback.OnException(exception.ToString());
                        this.CleanUpAndSignalCompletion();
                    }
                };

                this.instance.EncodeProgress += (o, e) =>
                {
                    this.StopOnException(() =>
                    {
                        this.callback.OnEncodeProgress(e.AverageFrameRate, e.CurrentFrameRate, e.EstimatedTimeLeft, e.FractionComplete, e.Pass);
                    });
                };

                this.instance.EncodeCompleted += (o, e) =>
                {
                    this.state = EncodeState.Finished;

                    try
                    {
                        this.callback.OnEncodeComplete(e.Error);
                    }
                    catch (CommunicationException exception)
                    {
                        WorkerLogger.Log("Got exception when reporting completion: " + exception, isError: true);
                    }
                    finally
                    {
                        this.CleanUpAndSignalCompletion();
                    }
                };

                this.instance.StartScan(job.SourcePath, previewCount, job.Title);
                this.state = EncodeState.Scanning;
            }
            catch (Exception exception)
            {
                this.callback.OnException(exception.ToString());
                throw;
            }
        }
Example #17
0
 private void GlobalInitialize()
 {
     HandBrakeUtils.EnsureGlobalInit(initNoHardwareMode: false);
     HandBrakeUtils.SetDvdNav(Config.EnableLibDvdNav);
 }