Пример #1
0
        public void StartScan(string path)
        {
            this.instance = new HandBrakeInstance();
            this.instance.Initialize(this.passedVerbosity);
            this.instance.ScanProgress += (o, e) =>
            {
                this.callback.OnScanProgress((float)e.Progress);
            };
            this.instance.ScanCompleted += (o, e) =>
            {
                try
                {
                    this.callback.OnScanComplete(this.instance.TitlesJson);
                }
                catch (Exception exception)
                {
                    WorkerErrorLogger.LogError("Got exception when reporting completion: " + exception, isError: true);
                }
                finally
                {
                    this.CleanUpAndSignalCompletion();
                }
            };

            this.instance.StartScan(path, this.passedPreviewCount, TimeSpan.FromSeconds(this.passedMinTitleDurationSeconds), 0);
        }
        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);
            }
        }
Пример #3
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.EnableLibDvdNav)
            {
                HandBrakeUtils.SetDvdNav(true);
            }
        }
Пример #4
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);
        }
Пример #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 (!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);
        }
Пример #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)
            {
                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
            }
        }
Пример #7
0
        private void RunJob(string jobName)
        {
            this.resetEvent.Reset();

            EncodeJob job = EncodeJobsPersist.GetJob("Normal");

            if (job.SourceType == SourceType.VideoFolder)
            {
                job.SourcePath = Path.Combine(Environment.CurrentDirectory, Path.GetFileName(job.SourcePath));
            }

            if (job.SourceType == SourceType.File)
            {
                job.SourcePath = Path.Combine(Environment.CurrentDirectory, Path.GetFileName(job.SourcePath));
            }

            string extension;

            if (job.EncodingProfile.OutputFormat == Container.Mkv)
            {
                extension = ".mkv";
            }
            else
            {
                extension = ".mp4";
            }

            job.OutputPath = Path.Combine(OutputVideoDirectory, jobName + extension);

            var instance = new HandBrakeInstance();

            instance.Initialize(0);
            instance.ScanCompleted += (sender, e) =>
            {
                this.resetEvent.Set();
            };

            instance.StartScan(job.SourcePath, 10);
            this.resetEvent.WaitOne();

            this.resetEvent.Reset();
            instance.EncodeCompleted += (sender, e) =>
            {
                Assert.IsFalse(e.Error);
                this.resetEvent.Set();
            };

            instance.StartEncode(job);
            this.resetEvent.WaitOne();

            Assert.IsTrue(File.Exists(job.OutputPath));

            var fileInfo = new FileInfo(job.OutputPath);

            Assert.IsTrue(fileInfo.Length > 1024);
        }
Пример #8
0
        static void Main(string[] args)
        {
            instance = new HandBrakeInstance();

            instance.Initialize(verbosity: 1);
            instance.ScanCompleted += Instance_ScanCompleted;
            instance.StartScan(srcPath, previewCount: 10);

            Console.ReadLine();
        }
Пример #9
0
        public string Initialise(HttpListenerRequest request)
        {
            if (this.handbrakeInstance == null)
            {
                this.handbrakeInstance = new HandBrakeInstance();
            }

            // TODO support verbosity
            this.handbrakeInstance.Initialize(1, true); // TODO enable user setting support for nohardware

            return(null);
        }
Пример #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="LibScan"/> class.
        /// </summary>
        public LibScan()
        {
            logging = new StringBuilder();

            instance = ServiceManager.HandBrakeInstance;
            instance.Initialize(1);
            instance.ScanProgress  += this.InstanceScanProgress;
            instance.ScanCompleted += this.InstanceScanCompleted;

            HandBrakeUtils.MessageLogged += this.HandBrakeInstanceMessageLogged;
            HandBrakeUtils.ErrorLogged   += this.HandBrakeInstanceErrorLogged;
        }
Пример #11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="LibEncode"/> class.
        /// </summary>
        public LibEncode()
        {
            // Setup the HandBrake Instance
            this.instance = ServiceManager.HandBrakeInstance;
            this.instance.EncodeCompleted += this.InstanceEncodeCompleted;
            this.instance.EncodeProgress  += this.InstanceEncodeProgress;

            HandBrakeUtils.MessageLogged += this.HandBrakeInstanceMessageLogged;
            HandBrakeUtils.ErrorLogged   += this.HandBrakeInstanceErrorLogged;

            GrowlCommunicator.Register();
        }
Пример #12
0
        public string Initialise(HttpListenerRequest request)
        {
            if (this.handbrakeInstance == null)
            {
                this.handbrakeInstance = new HandBrakeInstance();
            }

            // TODO support verbosity
            this.handbrakeInstance.Initialize(1);

            return(null);
        }
Пример #13
0
        public void ScanNextJob()
        {
            EncodeJobViewModel jobVM = itemsToScan[currentJobIndex];

            var onDemandInstance = new HandBrakeInstance();

            onDemandInstance.Initialize(Config.LogVerbosity);
            onDemandInstance.ScanProgress += (o, e) =>
            {
                lock (this.currentJobIndexLock)
                {
                    this.currentJobProgress = e.Progress;
                    this.RaisePropertyChanged(() => this.Progress);
                }
            };
            onDemandInstance.ScanCompleted += (o, e) =>
            {
                jobVM.HandBrakeInstance = onDemandInstance;

                if (onDemandInstance.Titles.Count > 0)
                {
                    Title titleToEncode = Utilities.GetFeatureTitle(onDemandInstance.Titles, onDemandInstance.FeatureTitle);

                    jobVM.Job.Title        = titleToEncode.TitleNumber;
                    jobVM.Job.Length       = titleToEncode.Duration;
                    jobVM.Job.ChapterStart = 1;
                    jobVM.Job.ChapterEnd   = titleToEncode.Chapters.Count;
                }

                lock (this.currentJobIndexLock)
                {
                    this.currentJobIndex++;
                    this.currentJobProgress = 0;
                    this.RaisePropertyChanged(() => this.Progress);

                    if (this.ScanFinished)
                    {
                        DispatchService.BeginInvoke(() =>
                        {
                            this.CancelCommand.Execute(null);
                        });
                    }
                    else
                    {
                        this.ScanNextJob();
                    }
                }
            };

            onDemandInstance.StartScan(jobVM.Job.SourcePath, Config.PreviewCount, 0);
        }
Пример #14
0
        /// <summary>
        /// Gets the scanInstance.
        /// </summary>
        /// <param name="verbosity">
        /// The verbosity.
        /// </param>
        /// <returns>
        /// The <see cref="IHandBrakeInstance"/>.
        /// </returns>
        public static IHandBrakeInstance GetScanInstance(int verbosity)
        {
            if (scanInstance != null)
            {
                scanInstance.Dispose();
                scanInstance = null;
            }

            HandBrakeInstance newInstance = new HandBrakeInstance();

            newInstance.Initialize(verbosity);
            scanInstance = newInstance;

            return(scanInstance);
        }
Пример #15
0
        public string Initialise(int verbosity)
        {
            if (this.handbrakeInstance == null)
            {
                this.handbrakeInstance = new HandBrakeInstance();
            }

            if (this.logHandler == null)
            {
                this.logHandler = new LogHandler();
            }

            this.handbrakeInstance.Initialize(verbosity, true);

            return(null);
        }
Пример #16
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 (previewInstance != null)
            {
                previewInstance.Dispose();
                previewInstance = null;
            }

            HandBrakeInstance newInstance = new HandBrakeInstance();

            newInstance.Initialize(verbosity);
            previewInstance = newInstance;

            HandBrakeUtils.SetDvdNav(!configuration.IsDvdNavDisabled);

            return(previewInstance);
        }
Пример #17
0
        public void StartScan(string path, IAppLogger logger)
        {
            var onDemandInstance = new HandBrakeInstance();

            onDemandInstance.Initialize(Config.LogVerbosity);
            onDemandInstance.ScanProgress += (o, e) =>
            {
                this.ScanProgress?.Invoke(this, new EventArgs <float>((float)e.Progress));
            };
            onDemandInstance.ScanCompleted += (o, e) =>
            {
                this.ScanCompleted?.Invoke(this, new EventArgs <string>(onDemandInstance.TitlesJson));
                onDemandInstance.Dispose();
            };

            onDemandInstance.StartScan(path, Config.PreviewCount, TimeSpan.FromSeconds(Config.MinimumTitleLengthSeconds), 0);
        }
Пример #18
0
        /// <summary>
        /// Start the service
        /// </summary>
        /// <param name="port">
        /// The port.
        /// </param>
        public void Start(string port)
        {
            using (host = new ServiceHost(typeof(ServerService), new Uri(string.Format("net.tcp://127.0.0.1:{0}", port))))
            {
                // Setup a listener
                host.AddServiceEndpoint(typeof(IServerService), new NetTcpBinding(), "IHbService");
                host.Open();
                Console.WriteLine("::: HandBrake Isolation Server - Debug Console:::");
                Console.WriteLine("Service Started. Waiting for Clients...");

                // Setup the services we are going to use.
                IHandBrakeInstance instance = new HandBrakeInstance();
                encodeService = new LibEncode(new UserSettingService(), instance); // TODO this needs wired up with castle

                shutdownFlag = new ManualResetEvent(false);
                shutdownFlag.WaitOne();
            }
        }
        /// <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);
        }
Пример #20
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);
        }
        /// <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);
        }
Пример #22
0
        private void RefreshPreviews()
        {
            this.originalScanInstance = this.ScanInstance;
            this.job = this.mainViewModel.EncodeJob;

            OutputSizeInfo newOutputSizeInfo = this.outputSizeService.Size;

            int width     = newOutputSizeInfo.OutputWidth;
            int height    = newOutputSizeInfo.OutputHeight;
            int parWidth  = newOutputSizeInfo.Par.Num;
            int parHeight = newOutputSizeInfo.Par.Den;

            if (parWidth <= 0 || parHeight <= 0)
            {
                this.HasPreview = false;
                this.Title      = PreviewRes.NoVideoSourceTitle;

                Ioc.Get <IAppLogger>().LogError("HandBrake returned a negative pixel aspect ratio. Cannot show preview.");
                return;
            }

            if (width < 100 || height < 100)
            {
                this.HasPreview = false;
                this.UpdateTitle(newOutputSizeInfo);

                return;
            }

            this.PreviewDisplayHeight = height;
            this.PreviewDisplayWidth  = width * ((double)parWidth / parHeight);

            this.OutputSizeInfo = newOutputSizeInfo;

            var profile = this.PresetsService.SelectedPreset.Preset.EncodingProfile;

            this.PadColor = ColorUtilities.ToWindowsColor(profile.PadColor);

            // Update the number of previews.
            this.previewCount = this.ScanInstance.PreviewCount;
            if (this.selectedPreview >= this.previewCount)
            {
                this.selectedPreview = this.previewCount - 1;
                this.RaisePropertyChanged(nameof(this.SelectedPreview));
            }

            this.RaisePropertyChanged(nameof(this.PreviewCount));

            this.HasPreview = true;

            lock (this.imageSync)
            {
                this.previewImageCache = new BitmapSource[this.previewCount];
                updateVersion++;

                // Clear main work queue.
                this.previewImageWorkQueue.Clear();

                this.imageFileCacheFolder = Path.Combine(
                    Utilities.ImageCacheFolder,
                    Process.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture),
                    updateVersion.ToString(CultureInfo.InvariantCulture));
                if (!Directory.Exists(this.imageFileCacheFolder))
                {
                    Directory.CreateDirectory(this.imageFileCacheFolder);
                }

                // Clear old images out of the file cache.
                this.ClearImageFileCache();

                this.imageFileSync = new List <object>(this.previewCount);
                for (int i = 0; i < this.previewCount; i++)
                {
                    this.imageFileSync.Add(new object());
                }

                this.BeginBackgroundImageLoad();

                this.View?.RefreshImageSize();
            }

            this.UpdateTitle(newOutputSizeInfo);
        }
Пример #23
0
        public Task Encode(string originalFile, string outputFile, int start, int end,
                           IProgress <EncodeProgress> encodeProgresss,
                           CancellationToken cancelToken)
        {
            var taskCompletionSource = new TaskCompletionSource <bool>();

            var instance = new HandBrakeInstance();

            instance.Initialize(1);

            instance.ScanCompleted += (o, args) =>
            {
                try
                {
                    if (start >= end)
                    {
                        throw new Exception("Invalid start and end times.");
                    }
                    var sourceTitle = instance.Titles.TitleList.FirstOrDefault();
                    if (sourceTitle == null)
                    {
                        throw new Exception("Could not read input video.");
                    }

                    var settings = GetDefaultSettings();
                    settings.Destination.File = outputFile;
                    dynamic resolution = settings.Filters.FilterList.First(filter => filter.ID == 11).Settings;

                    resolution.width            = sourceTitle.Geometry.Width;
                    resolution.height           = sourceTitle.Geometry.Height;
                    settings.Source.Range.Start = start * 90000;
                    settings.Source.Range.End   = end * 90000;

                    settings.Source.Path = originalFile;

                    cancelToken.Register(() => instance.StopEncode());

                    instance.StartEncode(settings);
                }
                catch (Exception e)
                {
                    taskCompletionSource.TrySetException(e);
                }
            };

            instance.EncodeProgress += (o, args) => NewMeth(args, encodeProgresss);

            instance.EncodeCompleted += (o, args) =>
            {
                try
                {
                    if (args.Error)
                    {
                        if (cancelToken.IsCancellationRequested)
                        {
                            throw new Exception("Encoding was canceled");
                        }
                        throw new Exception("Encoding failed. I don't know why 'cause this API kinda sucks");
                    }
                    taskCompletionSource.TrySetResult(true);
                }
                catch (Exception e)
                {
                    taskCompletionSource.TrySetException(e);
                }
            };

            instance.StartScan(originalFile, 1, TimeSpan.Zero, 1);

            return(taskCompletionSource.Task);
        }
Пример #24
0
        private void StartEncodeInternal(string scanPath, int titleNumber, Func <JsonScanObject, string> jsonFunc)
        {
            this.logger.Log("Starting encode in-process");

            this.encoding = true;

            this.encodeStartEvent = new ManualResetEventSlim(false);
            this.encodeEndEvent   = new ManualResetEventSlim(false);

            this.instance = new HandBrakeInstance();
            this.instance.Initialize(Config.LogVerbosity, noHardware: false);

            this.instance.ScanCompleted += (o, e) =>
            {
                try
                {
                    string encodeJson = jsonFunc(this.instance.Titles);
                    if (encodeJson != null)
                    {
                        lock (this.encoderLock)
                        {
                            this.instance.StartEncode(encodeJson);
                            this.EncodeStarted?.Invoke(this, EventArgs.Empty);

                            this.encodeStartEvent.Set();
                        }
                    }
                    else
                    {
                        this.EncodeCompleted?.Invoke(this, new EncodeCompletedEventArgs(error: true));

                        this.encodeStartEvent.Set();
                        this.encodeEndEvent.Set();
                    }
                }
                catch (Exception exception)
                {
                    this.logger.LogError("Encoding failed. Please report this error so it can be fixed in the future:" + Environment.NewLine + exception);
                }
            };

            this.instance.EncodeProgress += (o, e) =>
            {
                // Dispatch to avoid deadlocks on callbacks
                DispatchUtilities.BeginInvoke(() =>
                {
                    lock (this.encoderLock)
                    {
                        if (this.encoding)
                        {
                            this.EncodeProgress?.Invoke(this, e);
                        }
                    }
                });
            };

            this.instance.EncodeCompleted += (o, e) =>
            {
                if (this.encoding)
                {
                    this.EncodeCompleted?.Invoke(this, e);

                    this.encoding = false;
                }

                this.encodeEndEvent.Set();
                this.instance.Dispose();
            };

            this.instance.StartScan(scanPath, Config.PreviewCount, TimeSpan.FromSeconds(Config.MinimumTitleLengthSeconds), titleNumber);

            this.encoding = true;
        }
Пример #25
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;
            }
        }
Пример #26
0
        private void RefreshPreviews()
        {
            this.originalScanInstance = this.ScanInstance;

            this.job = this.mainViewModel.EncodeJob;
            VCProfile profile = this.job.EncodingProfile;

            int width, height, parWidth, parHeight;

            this.ScanInstance.GetSize(this.job.HbJob, out width, out height, out parWidth, out parHeight);

            // If we're rotating by 90 degrees, swap width and height for sizing purposes.
            if (profile.Rotation == VCPictureRotation.Clockwise90 || profile.Rotation == VCPictureRotation.Clockwise270)
            {
                int temp = width;
                width  = height;
                height = temp;

                temp      = parWidth;
                parWidth  = parHeight;
                parHeight = temp;
            }

            if (parWidth <= 0 || parHeight <= 0)
            {
                this.HasPreview = false;
                this.Title      = PreviewRes.NoVideoSourceTitle;

                Ioc.Container.GetInstance <ILogger>().LogError("HandBrake returned a negative pixel aspect ratio. Cannot show preview.");
                return;
            }

            this.PreviewDisplayHeight = height;
            this.PreviewDisplayWidth  = width * ((double)parWidth / parHeight);

            // Update the number of previews.
            this.previewCount = this.ScanInstance.PreviewCount;
            if (this.selectedPreview >= this.previewCount)
            {
                this.selectedPreview = this.previewCount - 1;
                this.RaisePropertyChanged(() => this.SelectedPreview);
            }

            this.RaisePropertyChanged(() => this.PreviewCount);

            this.HasPreview = true;

            lock (this.imageSync)
            {
                this.previewImageCache = new BitmapSource[this.previewCount];
                updateVersion++;

                // Clear main work queue.
                this.previewImageWorkQueue.Clear();

                this.imageFileCacheFolder = Path.Combine(Utilities.ImageCacheFolder,
                                                         Process.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture),
                                                         updateVersion.ToString(CultureInfo.InvariantCulture));
                if (!Directory.Exists(this.imageFileCacheFolder))
                {
                    Directory.CreateDirectory(this.imageFileCacheFolder);
                }

                // Clear old images out of the file cache.
                this.ClearImageFileCache();

                this.imageFileSync = new List <object>(this.previewCount);
                for (int i = 0; i < this.previewCount; i++)
                {
                    this.imageFileSync.Add(new object());
                }

                this.BeginBackgroundImageLoad();
            }

            if (parWidth == parHeight)
            {
                this.Title = string.Format(PreviewRes.PreviewWindowTitleSimple, width, height);
            }
            else
            {
                this.Title = string.Format(
                    PreviewRes.PreviewWindowTitleComplex,
                    Math.Round(this.PreviewDisplayWidth),
                    Math.Round(this.PreviewDisplayHeight),
                    width,
                    height);
            }
        }
Пример #27
0
        /// <summary>
        /// Starts an encode.
        /// </summary>
        /// <param name="scanPath">The path to scan.</param>
        /// <param name="titleNumber">The title number to scan.</param>
        /// <param name="jsonFunc">A function to pick the encode JSON given the scan.</param>
        private void StartEncodeInternal(string scanPath, int titleNumber, Func <JsonScanObject, string> jsonFunc)
        {
            try
            {
                this.instance = new HandBrakeInstance();
                this.instance.Initialize(this.passedVerbosity);

                this.instance.ScanCompleted += (o, e) =>
                {
                    try
                    {
                        string encodeJson = jsonFunc(this.instance.Titles);
                        if (encodeJson != null)
                        {
                            lock (this.encodeLock)
                            {
                                this.instance.StartEncode(encodeJson);
                                this.callback.OnEncodeStarted();
                                this.state = EncodeState.Encoding;
                            }
                        }
                        else
                        {
                            this.callback.OnEncodeComplete(error: true);
                            this.CleanUpAndSignalCompletion();
                        }
                    }
                    catch (Exception exception)
                    {
                        this.callback.OnException(exception.ToString());
                        this.CleanUpAndSignalCompletion();
                    }
                };

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

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

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


                this.instance.StartScan(scanPath, this.passedPreviewCount, TimeSpan.FromSeconds(this.passedMinTitleDurationSeconds), titleNumber);
                this.state = EncodeState.Scanning;
            }
            catch (Exception exception)
            {
                this.callback.OnException(exception.ToString());
                throw;
            }
        }
Пример #28
0
        public void StartEncode(VCJob job, ILogger logger, bool preview, int previewNumber, int previewSeconds, double overallSelectedLengthSeconds)
        {
            this.logger = logger;
            this.logger.Log("Starting encode in-process");

            this.encoding = true;

            this.encodeStartEvent = new ManualResetEventSlim(false);
            this.encodeEndEvent   = new ManualResetEventSlim(false);

            this.instance = new HandBrakeInstance();
            this.instance.Initialize(Config.LogVerbosity);

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

                    if (encodeTitle != null)
                    {
                        lock (this.encoderLock)
                        {
                            this.instance.StartEncode(job.HbJob, preview, previewNumber, previewSeconds, overallSelectedLengthSeconds, Config.PreviewCount);
                            this.IsEncodeStarted = true;
                            if (this.EncodeStarted != null)
                            {
                                this.EncodeStarted(this, new EventArgs());
                            }

                            this.encodeStartEvent.Set();
                        }
                    }
                    else
                    {
                        if (this.EncodeCompleted != null)
                        {
                            this.EncodeCompleted(this, new EncodeCompletedEventArgs {
                                Error = true
                            });
                        }

                        this.encodeStartEvent.Set();
                        this.encodeEndEvent.Set();
                    }
                }
                catch (Exception exception)
                {
                    this.logger.LogError("Encoding failed. Please report this error so it can be fixed in the future:" + Environment.NewLine + exception);
                }
            };

            this.instance.EncodeProgress += (o, e) =>
            {
                // Dispatch to avoid deadlocks on callbacks
                DispatchService.BeginInvoke(() =>
                {
                    lock (this.encoderLock)
                    {
                        if (this.encoding && this.EncodeProgress != null)
                        {
                            this.EncodeProgress(this, e);
                        }
                    }
                });
            };

            this.instance.EncodeCompleted += (o, e) =>
            {
                if (this.encoding)
                {
                    if (this.EncodeCompleted != null)
                    {
                        this.EncodeCompleted(this, e);
                    }

                    this.encoding = false;
                }

                this.encodeEndEvent.Set();
                this.instance.Dispose();
            };

            this.instance.StartScan(job.SourcePath, Config.PreviewCount, job.Title);

            this.encoding = true;
        }