예제 #1
0
        private void RunEncodeInitProcess(JsonEncodeObject jobToStart)
        {
            InitCommand initCommand = new InitCommand
            {
                EnableDiskLogging          = false,
                AllowDisconnectedWorker    = false,
                DisableLibDvdNav           = !this.userSettingService.GetUserSetting <bool>(UserSettingConstants.DisableLibDvdNav),
                EnableHardwareAcceleration = true,
                LogDirectory = DirectoryUtilities.GetLogDirectory(),
                LogVerbosity = this.userSettingService.GetUserSetting <int>(UserSettingConstants.Verbosity)
            };

            initCommand.LogFile = Path.Combine(initCommand.LogDirectory, string.Format("activity_log.worker.{0}.txt", GeneralUtilities.ProcessId));

            JsonSerializerSettings settings = new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            };

            string job = JsonConvert.SerializeObject(new EncodeCommand {
                InitialiseCommand = initCommand, EncodeJob = jobToStart
            }, Formatting.None, settings);

            var task = Task.Run(async() => await this.MakeHttpJsonPostRequest("StartEncode", job));

            task.Wait();
            this.MonitorEncodeProgress();
        }
예제 #2
0
        public RawPreviewData GetPreview(JsonEncodeObject settings, int previewNumber)
        {
            // Fetch the image data from LibHb
            string     taskJson             = JsonSerializer.Serialize(settings, JsonSettings.Options);
            IntPtr     resultingImageStruct = HBFunctions.hb_get_preview3_json(this.Handle, previewNumber, taskJson);
            hb_image_s image = InteropUtilities.ToStructureFromPtr <hb_image_s>(resultingImageStruct);

            // Copy the filled image buffer to a managed array.
            int stride_width    = image.plane[0].stride;
            int stride_height   = image.plane[0].height_stride;
            int imageBufferSize = stride_width * stride_height;

            byte[] managedBuffer = new byte[imageBufferSize];
            Marshal.Copy(image.plane[0].data, managedBuffer, 0, imageBufferSize);

            RawPreviewData preview = new RawPreviewData(managedBuffer, stride_width, stride_height, image.width, image.height);

            // Close the image so we don't leak memory.
            IntPtr nativeJobPtrPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr)));

            Marshal.WriteIntPtr(nativeJobPtrPtr, resultingImageStruct);
            HBFunctions.hb_image_close(nativeJobPtrPtr);
            Marshal.FreeHGlobal(nativeJobPtrPtr);

            return(preview);
        }
예제 #3
0
        private static void ParseSource(EncodeTask task, JsonEncodeObject job)
        {
            if (job?.Source == null)
            {
                return;
            }

            task.PointToPointMode = EnumHelper <PointToPointMode> .GetValue(job.Source.Range.Type);

            switch (task.PointToPointMode)
            {
            case PointToPointMode.Chapters:
            case PointToPointMode.Frames:
                task.StartPoint = job.Source.Range.Start.Value;
                task.EndPoint   = job.Source.Range.End.Value;
                break;

            case PointToPointMode.Seconds:
                task.StartPoint = job.Source.Range.Start.Value / 90000;
                task.EndPoint   = job.Source.Range.End.Value / 90000;
                break;
            }

            task.Source = job.Source.Path;
            task.Title  = job.Source.Title;
            task.Angle  = job.Source.Angle;
        }
예제 #4
0
        public async void StartEncode(JsonEncodeObject jobToStart)
        {
            InitCommand initCommand = new InitCommand
            {
                EnableDiskLogging          = true,
                AllowDisconnectedWorker    = false,
                DisableLibDvdNav           = this.configuration.IsDvdNavDisabled,
                EnableHardwareAcceleration = true,
                LogDirectory = DirectoryUtilities.GetLogDirectory(),
                LogVerbosity = configuration.Verbosity
            };

            initCommand.LogFile = Path.Combine(initCommand.LogDirectory, string.Format("activity_log.worker.{0}.txt", GeneralUtilities.ProcessId));

            JsonSerializerSettings settings = new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            };
            string job = JsonConvert.SerializeObject(new EncodeCommand {
                InitialiseCommand = initCommand, EncodeJob = jobToStart
            }, Formatting.None, settings);

            await this.MakeHttpJsonPostRequest("StartEncode", job);

            this.MonitorEncodeProgress();
        }
예제 #5
0
        /// <summary>
        /// Starts an encode, given a VidCoder job and some extra data.
        /// </summary>
        /// <param name="job">The VidCoder job to run.</param>
        /// <param name="previewNumber">The preview number to run.</param>
        /// <param name="previewSeconds">The number of seconds the preview should be.</param>
        /// <param name="defaultChapterNameFormat">The default format for chapter names.</param>
        public void StartEncode(
            VCJob job,
            int previewNumber,
            int previewSeconds,
            string defaultChapterNameFormat)
        {
            this.StartEncodeInternal(
                job.SourcePath,
                job.Title,
                scanObject =>
            {
                SourceTitle encodeTitle = scanObject.TitleList.FirstOrDefault(title => title.Index == job.Title);
                if (encodeTitle != null)
                {
                    JsonEncodeFactory factory = new JsonEncodeFactory(ServiceLocator.Current.GetInstance <ILogger>());

                    JsonEncodeObject encodeObject = factory.CreateJsonObject(
                        job,
                        encodeTitle,
                        defaultChapterNameFormat,
                        previewNumber,
                        previewSeconds,
                        this.passedPreviewCount);

                    return(JsonConvert.SerializeObject(encodeObject, JsonSettings.HandBrakeJsonSerializerSettings));
                }
                else
                {
                    return(null);
                }
            });
        }
예제 #6
0
        /// <summary>
        /// Starts an encode with the given encode JSON.
        /// </summary>
        /// <param name="encodeJson">The encode JSON.</param>
        /// <remarks>Used for debug testing of raw encode JSON.</remarks>
        public void StartEncode(string encodeJson)
        {
            // Extract the scan title and path from the encode JSON.
            JsonEncodeObject encodeObject = JsonConvert.DeserializeObject <JsonEncodeObject>(encodeJson);

            this.StartEncodeInternal(encodeObject.Source.Path, encodeObject.Source.Title, scanObject => encodeJson);
        }
예제 #7
0
        public void StartEncode(JsonEncodeObject encodeObject)
        {
            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
            };

            string encode = JsonConvert.SerializeObject(encodeObject, Formatting.Indented, settings);

            HBFunctions.hb_add_json(this.hbHandle, InteropUtilities.ToUtf8PtrFromString(encode));
            HBFunctions.hb_start(this.hbHandle);

            this.encodePollTimer          = new Timer();
            this.encodePollTimer.Interval = EncodePollIntervalMs;

            this.encodePollTimer.Elapsed += (o, e) =>
            {
                try
                {
                    this.PollEncodeProgress();
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(exc);
                }
            };
            this.encodePollTimer.Start();
        }
예제 #8
0
        public Task StartEncodeAsync(string encodeJson, IAppLogger logger)
        {
            this.logger = logger;

            // Extract the scan title and path from the encode JSON.
            JsonEncodeObject encodeObject = JsonConvert.DeserializeObject <JsonEncodeObject>(encodeJson);

            this.StartEncodeInternal(encodeObject.Source.Path, encodeObject.Source.Title, scanObject => encodeJson);
            return(Task.CompletedTask);
        }
예제 #9
0
        private static void ParsePar(EncodeTask task, JsonEncodeObject job)
        {
            if (job.PAR == null)
            {
                return;
            }

            task.PixelAspectX = job.PAR.Num;
            task.PixelAspectY = job.PAR.Den;
        }
예제 #10
0
        public async void StartEncode(JsonEncodeObject jobToStart)
        {
            JsonSerializerSettings settings = new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            };
            string job = JsonConvert.SerializeObject(jobToStart, Formatting.None, settings);

            await this.MakeHttpJsonPostRequest("StartEncode", job);

            this.MonitorEncodeProgress();
        }
예제 #11
0
        public void StartEncode(JsonEncodeObject encodeObject)
        {
            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
            };

            string encode = JsonConvert.SerializeObject(encodeObject, Formatting.Indented, settings);

            this.StartEncode(encode);
        }
예제 #12
0
 public void StartEncode(JsonEncodeObject jobToStart)
 {
     if (this.IsServerRunning())
     {
         Thread thread1 = new Thread(() => RunEncodeInitProcess(jobToStart));
         thread1.Start();
     }
     else
     {
         this.EncodeCompleted?.Invoke(sender: this, e: new EncodeCompletedEventArgs(-10));
     }
 }
예제 #13
0
        internal static HBConfiguration CreateConfig(JsonEncodeObject job)
        {
            //                    range.SeekPoints = configuration.PreviewScanCount;
            // 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;
             * }*/

            return(new HBConfiguration());
        }
예제 #14
0
        public async void StartEncode(JsonEncodeObject jobToStart)
        {
            JsonSerializerSettings settings = new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            };
            string job = JsonConvert.SerializeObject(jobToStart, Formatting.Indented, settings);

            var values = new Dictionary <string, string> {
                { "jpb", job }
            };

            await this.MakeHttpPostRequest("StartEncode", values);

            this.MonitorEncodeProgress();
        }
예제 #15
0
        private static void ParseAudio(EncodeTask task, JsonEncodeObject job)
        {
            if (job.Audio == null)
            {
                return;
            }

            task.AllowedPassthruOptions.AudioAllowAACPass    = job.Audio.CopyMask.Contains(EnumHelper <AudioEncoder> .GetShortName(AudioEncoder.AacPassthru));
            task.AllowedPassthruOptions.AudioAllowAC3Pass    = job.Audio.CopyMask.Contains(EnumHelper <AudioEncoder> .GetShortName(AudioEncoder.Ac3Passthrough));
            task.AllowedPassthruOptions.AudioAllowDTSHDPass  = job.Audio.CopyMask.Contains(EnumHelper <AudioEncoder> .GetShortName(AudioEncoder.DtsHDPassthrough));
            task.AllowedPassthruOptions.AudioAllowDTSPass    = job.Audio.CopyMask.Contains(EnumHelper <AudioEncoder> .GetShortName(AudioEncoder.DtsPassthrough));
            task.AllowedPassthruOptions.AudioAllowEAC3Pass   = job.Audio.CopyMask.Contains(EnumHelper <AudioEncoder> .GetShortName(AudioEncoder.EAc3Passthrough));
            task.AllowedPassthruOptions.AudioAllowFlacPass   = job.Audio.CopyMask.Contains(EnumHelper <AudioEncoder> .GetShortName(AudioEncoder.FlacPassthru));
            task.AllowedPassthruOptions.AudioAllowMP3Pass    = job.Audio.CopyMask.Contains(EnumHelper <AudioEncoder> .GetShortName(AudioEncoder.Mp3Passthru));
            task.AllowedPassthruOptions.AudioAllowTrueHDPass = job.Audio.CopyMask.Contains(EnumHelper <AudioEncoder> .GetShortName(AudioEncoder.TrueHDPassthrough));
            task.AllowedPassthruOptions.AudioEncoderFallback = EnumHelper <AudioEncoder> .GetValue(job.Audio.FallbackEncoder);

            foreach (HandBrake.Interop.Interop.Json.Encode.AudioTrack item in job.Audio.AudioList)
            {
                HBMixdown mixdown    = HandBrakeEncoderHelpers.Mixdowns.FirstOrDefault(m => m.Id == item.Mixdown);
                HBRate    sampleRate = HandBrakeEncoderHelpers.AudioSampleRates.FirstOrDefault(s => s.Rate == item.Samplerate);

                AudioTrack track = new AudioTrack();
                track.ScannedTrack = new Scan.Model.Audio(item.Track); // When adding to the queue, we don't need the full context. Editing queue will recovery this.
                track.Encoder      = EnumHelper <AudioEncoder> .GetValue(item.Encoder);

                track.Gain       = (int)item.Gain;
                track.MixDown    = mixdown?.ShortName;
                track.TrackName  = item.Name;
                track.SampleRate = sampleRate?.Rate ?? 48;  // TODO this may not work. Check
                track.DRC        = item.DRC;

                if (!track.IsPassthru && item.Bitrate.HasValue)
                {
                    track.Bitrate         = item.Bitrate.Value;
                    track.EncoderRateType = AudioEncoderRateType.Bitrate;
                }

                if (!track.IsPassthru && item.Quality.HasValue)
                {
                    track.Quality         = item.Quality.Value;
                    track.EncoderRateType = AudioEncoderRateType.Quality;
                }

                task.AudioTracks.Add(track);
            }
        }
예제 #16
0
        /*
         * TODO:
         * 1. OpenCL and HWD Support
         * 2. Rotate Support
         */

        /// <summary>
        /// The create.
        /// </summary>
        /// <param name="job">
        /// The encode job.
        /// </param>
        /// <param name="title">
        /// The title.
        /// </param>
        /// <returns>
        /// The <see cref="JsonEncodeObject"/>.
        /// </returns>
        internal static JsonEncodeObject Create(EncodeJob job, Title title)
        {
            JsonEncodeObject encode = new JsonEncodeObject
            {
                SequenceID  = 0,
                Audio       = CreateAudio(job),
                Destination = CreateDestination(job),
                Filter      = CreateFilter(job, title),
                PAR         = CreatePAR(job, title),
                MetaData    = CreateMetaData(job),
                Source      = CreateSource(job),
                Subtitle    = CreateSubtitle(job),
                Video       = CreateVideo(job)
            };

            return(encode);
        }
예제 #17
0
        /// <summary>
        /// The create.
        /// </summary>
        /// <param name="job">
        /// The encode job.
        /// </param>
        /// <param name="configuration">
        /// The configuration.
        /// </param>
        /// <returns>
        /// The <see cref="JsonEncodeObject"/>.
        /// </returns>
        internal static JsonEncodeObject Create(EncodeTask job, HBConfiguration configuration)
        {
            JsonEncodeObject encode = new JsonEncodeObject
            {
                SequenceID  = 0,
                Audio       = CreateAudio(job),
                Destination = CreateDestination(job),
                Filters     = CreateFilters(job),
                PAR         = CreatePAR(job),
                Metadata    = CreateMetadata(job),
                Source      = CreateSource(job, configuration),
                Subtitle    = CreateSubtitle(job),
                Video       = CreateVideo(job, configuration)
            };

            return(encode);
        }
예제 #18
0
        private static void ParseSubtitle(EncodeTask task, JsonEncodeObject job)
        {
            if (job.Subtitle == null)
            {
                return;
            }

            if (job.Subtitle.Search.Enable)
            {
                Model.Models.SubtitleTrack subtitleTrack = new Model.Models.SubtitleTrack();
                subtitleTrack.Burned       = job.Subtitle.Search.Burn;
                subtitleTrack.Default      = job.Subtitle.Search.Default;
                subtitleTrack.Forced       = job.Subtitle.Search.Forced;
                subtitleTrack.SubtitleType = SubtitleType.ForeignAudioSearch;
                subtitleTrack.SourceTrack  = new Scan.Model.Subtitle(0);
                task.SubtitleTracks.Add(subtitleTrack);
            }

            foreach (SubtitleTrack subtitle in job.Subtitle.SubtitleList)
            {
                if (subtitle.ID == 0)
                {
                    continue; // Foreign Audio Scan
                }

                Model.Models.SubtitleTrack subtitleTrack = new Model.Models.SubtitleTrack();

                subtitle.ID           = subtitle.ID;
                subtitleTrack.Burned  = subtitle.Burn;
                subtitleTrack.Default = subtitle.Default;
                subtitleTrack.Forced  = subtitle.Forced;

                if (!string.IsNullOrEmpty(subtitle.Import.Filename))
                {
                    subtitleTrack.SubtitleType = subtitle.Import.Filename.EndsWith("srt") ?  SubtitleType.SRT : SubtitleType.SSA;
                    subtitleTrack.SrtCharCode  = subtitle.Import.Codeset;
                    subtitleTrack.SrtFileName  = subtitle.Import.Filename;
                    subtitleTrack.SrtLangCode  = subtitle.Import.Language;
                    subtitleTrack.SrtLang      = HandBrakeLanguagesHelper.Get(subtitleTrack.SrtLangCode).EnglishName;
                    subtitleTrack.SrtOffset    = subtitleTrack.SrtOffset;
                }

                task.SubtitleTracks.Add(null);
            }
        }
예제 #19
0
        private static void ParseMetaData(EncodeTask task, JsonEncodeObject job)
        {
            if (job.Metadata == null)
            {
                return;
            }

            task.MetaData.Artist          = job.Metadata.Artist;
            task.MetaData.Album           = job.Metadata.Album;
            task.MetaData.AlbumArtist     = job.Metadata.AlbumArtist;
            task.MetaData.Comment         = job.Metadata.Comment;
            task.MetaData.Composer        = job.Metadata.Composer;
            task.MetaData.Description     = job.Metadata.Description;
            task.MetaData.Genre           = job.Metadata.Genre;
            task.MetaData.LongDescription = job.Metadata.LongDescription;
            task.MetaData.Name            = job.Metadata.Name;
            task.MetaData.ReleaseDate     = job.Metadata.ReleaseDate;
        }
예제 #20
0
        private static void ParseVideo(EncodeTask task, JsonEncodeObject job)
        {
            task.VideoEncoder = EnumHelper <VideoEncoder> .GetValue(job.Video.Encoder);

            task.ExtraAdvancedArguments = job.Video.Options;

            HBVideoEncoder videoEncoder = HandBrakeEncoderHelpers.VideoEncoders.FirstOrDefault(e => e.ShortName == job.Video.Encoder);

            if (videoEncoder == null)
            {
                Debug.WriteLine("Video encoder is not supported on this system.");
            }

            task.VideoLevel   = new VideoLevel(job.Video.Level, job.Video.Level);
            task.VideoPreset  = new VideoPreset(job.Video.Preset, job.Video.Preset);
            task.VideoProfile = new VideoProfile(job.Video.Profile, job.Video.Profile);

            if (!string.IsNullOrEmpty(job.Video.Tune))
            {
                string[] splitTunes = job.Video.Tune.Split(',');
                foreach (string tune in splitTunes)
                {
                    task.VideoTunes.Add(new VideoTune(tune, tune));
                }
            }

            if (job.Video.Quality.HasValue)
            {
                task.VideoEncodeRateType = VideoEncodeRateType.ConstantQuality;
                task.Quality             = job.Video.Quality;
            }

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

            // job.Video.ColorMatrixCode;  Not currently supported in the GUI.
        }
예제 #21
0
        /*
         * TODO
         * 1. Reconstruct the Config
         * 2. Reconstruct Queue State
         * 3. Update JSON API. See #1481
         */

        internal static EncodeTask Create(JsonEncodeObject job)
        {
            if (job == null)
            {
                return(null);
            }

            EncodeTask task = new EncodeTask();

            ParseSource(task, job);
            ParseDestination(task, job);
            ParsePar(task, job);
            ParseVideo(task, job);
            ParseAudio(task, job);
            ParseSubtitle(task, job);
            ParseFilters(task, job);
            ParseMetaData(task, job);

            return(task);
        }
예제 #22
0
        private static void ParseDestination(EncodeTask task, JsonEncodeObject job)
        {
            if (job.Destination == null)
            {
                return;
            }

            task.Destination   = job.Destination.File;
            task.OptimizeMP4   = job.Destination.Mp4Options.Mp4Optimize;
            task.IPod5GSupport = job.Destination.Mp4Options.IpodAtom;
            task.AlignAVStart  = job.Destination.AlignAVStart;
            task.OutputFormat  = EnumHelper <OutputFormat> .GetValue(job.Destination.Mux);

            task.IncludeChapterMarkers = job.Destination.ChapterMarkers;
            int chapter = 0;

            foreach (Chapter item in job.Destination.ChapterList)
            {
                chapter = chapter + 1;
                task.ChapterNames.Add(new ChapterMarker(0, item.Name, TimeSpan.MinValue));
            }
        }
예제 #23
0
        public Task StartEncodeAsync(
            VCJob job,
            IAppLogger logger,
            bool preview,
            int previewNumber,
            int previewSeconds,
            double overallSelectedLengthSeconds)
        {
            this.logger = logger;

            this.StartEncodeInternal(
                job.SourcePath,
                job.Title,
                scanObject =>
            {
                SourceTitle encodeTitle = scanObject.TitleList.FirstOrDefault(title => title.Index == job.Title);
                if (encodeTitle != null)
                {
                    JsonEncodeFactory factory = new JsonEncodeFactory(logger);

                    JsonEncodeObject jsonEncodeObject = factory.CreateJsonObject(
                        job,
                        encodeTitle,
                        EncodingRes.DefaultChapterName,
                        preview ? previewNumber : -1,
                        previewSeconds,
                        Config.PreviewCount);

                    return(JsonConvert.SerializeObject(jsonEncodeObject, JsonSettings.HandBrakeJsonSerializerSettings));
                }
                else
                {
                    return(null);
                }
            });

            return(Task.CompletedTask);
        }
예제 #24
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>
        /// <returns>
        /// The <see cref="BitmapImage"/>.
        /// </returns>
        public BitmapImage GetPreview(EncodeTask job, int preview)
        {
            if (this.instance == null)
            {
                return(null);
            }

            BitmapImage bitmapImage = null;

            try
            {
                EncodeTaskFactory factory    = new EncodeTaskFactory(this.userSettingService);
                JsonEncodeObject  jobDict    = factory.Create(job, HBConfigurationFactory.Create());
                RawPreviewData    bitmapData = this.instance.GetPreview(jobDict, preview);
                bitmapImage = BitmapUtilities.ConvertToBitmapImage(BitmapUtilities.ConvertByteArrayToBitmap(bitmapData));
            }
            catch (AccessViolationException e)
            {
                Debug.WriteLine(e);
            }

            return(bitmapImage);
        }
예제 #25
0
        public void StartEncode(EncodeJob job, Title title)
        {
            JsonEncodeObject encodeObject = EncodeFactory.Create(job, title);

            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
            };

            string encode = JsonConvert.SerializeObject(encodeObject, Formatting.Indented, settings);

            HBFunctions.hb_add_json(this.hbHandle, InteropUtilities.ToUtf8PtrFromString(encode));
            HBFunctions.hb_start(this.hbHandle);

            this.encodePollTimer          = new Timer();
            this.encodePollTimer.Interval = EncodePollIntervalMs;

            this.encodePollTimer.Elapsed += (o, e) =>
            {
                this.PollEncodeProgress();
            };
            this.encodePollTimer.Start();
        }
예제 #26
0
        private static void ParseFilters(EncodeTask task, JsonEncodeObject job)
        {
            // Crop scale
            Filter cropscaleFilter = job.Filters.FilterList.FirstOrDefault(f => f.ID == (int)hb_filter_ids.HB_FILTER_CROP_SCALE);

            if (cropscaleFilter != null)
            {
                var filterSettings = cropscaleFilter.Settings;
                int cropTop        = filterSettings.Value <int>("crop-top");
                int cropBottom     = filterSettings.Value <int>("crop-bottom");
                int cropLeft       = filterSettings.Value <int>("crop-left");
                int cropRight      = filterSettings.Value <int>("crop-right");
                int width          = filterSettings.Value <int>("width");
                int height         = filterSettings.Value <int>("height");

                task.Width           = width;
                task.Height          = height;
                task.Cropping.Top    = cropTop;
                task.Cropping.Bottom = cropBottom;
                task.Cropping.Left   = cropLeft;
                task.Cropping.Right  = cropRight;
            }

            // Grayscale
            Filter grayscaleFilter = job.Filters.FilterList.FirstOrDefault(f => f.ID == (int)hb_filter_ids.HB_FILTER_GRAYSCALE);

            if (grayscaleFilter != null)
            {
                task.Grayscale = true;
            }

            // Rotate
            Filter rotationFilter = job.Filters.FilterList.FirstOrDefault(f => f.ID == (int)hb_filter_ids.HB_FILTER_ROTATE);

            if (rotationFilter != null)
            {
                var filterSettings = rotationFilter.Settings;
                task.Rotation  = filterSettings.Value <int>("angle");
                task.FlipVideo = filterSettings.Value <string>("hflip") == "1";
            }

            // Deblock
            Filter deblockFilter = job.Filters.FilterList.FirstOrDefault(f => f.ID == (int)hb_filter_ids.HB_FILTER_DEBLOCK);

            if (deblockFilter != null)
            {
                var filterSettings = deblockFilter.Settings;
                task.Deblock = filterSettings.Value <string>("qp").ToInt();
            }

            // Sharpen
            Filter lapsharpFilter = job.Filters.FilterList.FirstOrDefault(f => f.ID == (int)hb_filter_ids.HB_FILTER_LAPSHARP);

            if (lapsharpFilter != null)
            {
                var filterSettings = lapsharpFilter.Settings;
                task.Sharpen = Sharpen.LapSharp; // TODO Preset / Tune
            }

            Filter unsharpFilter = job.Filters.FilterList.FirstOrDefault(f => f.ID == (int)hb_filter_ids.HB_FILTER_UNSHARP);

            if (unsharpFilter != null)
            {
                var filterSettings = unsharpFilter.Settings;
                task.Sharpen = Sharpen.UnSharp;  // TODO Preset / Tune
            }

            // Denoise
            Filter hqdn3dFilter = job.Filters.FilterList.FirstOrDefault(f => f.ID == (int)hb_filter_ids.HB_FILTER_HQDN3D);

            if (hqdn3dFilter != null)
            {
                var filterSettings = hqdn3dFilter.Settings;
                task.Denoise = Denoise.hqdn3d; // TODO Preset / Tune
            }

            Filter nlmeansFilter = job.Filters.FilterList.FirstOrDefault(f => f.ID == (int)hb_filter_ids.HB_FILTER_NLMEANS);

            if (nlmeansFilter != null)
            {
                var filterSettings = nlmeansFilter.Settings;
                task.Denoise = Denoise.NLMeans;  // TODO Preset / Tune
            }

            // Detelecine
            Filter detelecineFilter = job.Filters.FilterList.FirstOrDefault(f => f.ID == (int)hb_filter_ids.HB_FILTER_DETELECINE);

            if (detelecineFilter != null)
            {
                var filterSettings = detelecineFilter.Settings;
                task.Detelecine = Detelecine.Default; // TODO Handle Custom
            }

            // Deinterlace
            Filter deinterlaceFilter = job.Filters.FilterList.FirstOrDefault(f => f.ID == (int)hb_filter_ids.HB_FILTER_DEINTERLACE);

            if (deinterlaceFilter != null)
            {
                var filterSettings = deinterlaceFilter.Settings;
                task.DeinterlaceFilter = DeinterlaceFilter.Yadif; // TODO Handle Preset / Custom
            }

            Filter decombFilter = job.Filters.FilterList.FirstOrDefault(f => f.ID == (int)hb_filter_ids.HB_FILTER_DECOMB);

            if (decombFilter != null)
            {
                var filterSettings = decombFilter.Settings;
                task.DeinterlaceFilter = DeinterlaceFilter.Decomb; // TODO Handle Preset / Custom
            }

            // Interlace Detection
            Filter combDetect = job.Filters.FilterList.FirstOrDefault(f => f.ID == (int)hb_filter_ids.HB_FILTER_COMB_DETECT);

            if (combDetect != null)
            {
                var filterSettings = combDetect.Settings;
                task.CombDetect = CombDetect.Default; // TODO Handle Preset / Custom
            }

            // Framerate

            Filter framerateFilter = job.Filters.FilterList.FirstOrDefault(f => f.ID == (int)hb_filter_ids.HB_FILTER_VFR);

            if (framerateFilter != null)
            {
                var filterSettings = framerateFilter.Settings;
                task.FramerateMode = (FramerateMode)filterSettings.Value <int>("mode"); // TODO numbers may not be in correct order.
                string rate = filterSettings.Value <string>("rate");                    // TODO Handle Rate.  num/den  hb_video_framerate_get_from_name
            }
        }
예제 #27
0
        public void StartEncode(JsonEncodeObject jobToStart)
        {
            Thread thread1 = new Thread(() => RunEncodeInitProcess(jobToStart));

            thread1.Start();
        }
예제 #28
0
        public void StartEncode(JsonEncodeObject encodeObject)
        {
            string encode = JsonSerializer.Serialize(encodeObject, JsonSettings.Options);

            this.StartEncode(encode);
        }
예제 #29
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));
            }
        }
예제 #30
0
        public Main()
        {
            Ioc.Container.RegisterSingleton <Main>(() => this);
            this.InitializeComponent();

            this.sourceRow.Height = new GridLength(Config.SourcePaneHeightStar, GridUnitType.Star);
            this.queueRow.Height  = new GridLength(Config.QueuePaneHeightStar, GridUnitType.Star);

            this.Activated += (sender, args) =>
            {
                DispatchUtilities.BeginInvoke(async() =>
                {
                    // Need to yield here for some reason, otherwise the activation is blocked.
                    await Task.Yield();
                    this.toastNotificationService.Clear();
                });
            };

            this.notifyIcon = new NotifyIcon
            {
                Visible = false
            };
            this.notifyIcon.Click       += (sender, args) => { this.RestoreWindow(); };
            this.notifyIcon.DoubleClick += (sender, args) => { this.RestoreWindow(); };

            StreamResourceInfo streamResourceInfo = System.Windows.Application.GetResourceStream(new Uri("pack://application:,,,/VidCoder_icon.ico"));

            if (streamResourceInfo != null)
            {
                Stream iconStream = streamResourceInfo.Stream;
                this.notifyIcon.Icon = new Icon(iconStream);
            }

            this.RefreshQueueColumns();
            this.LoadCompletedColumnWidths();

#if DEBUG
            var debugDropDown = new DropDownButton {
                Header = "Debug"
            };

            var loadScanFromJsonItem = new Fluent.MenuItem {
                Header = "Load scan from JSON..."
            };
            loadScanFromJsonItem.Click += (sender, args) =>
            {
                DebugJsonDialog dialog = new DebugJsonDialog("Debug Scan JSON");
                dialog.ShowDialog();
                if (!string.IsNullOrWhiteSpace(dialog.Json))
                {
                    try
                    {
                        var scanObject = JsonConvert.DeserializeObject <JsonScanObject>(dialog.Json);
                        this.viewModel.UpdateFromNewVideoSource(new VideoSource {
                            Titles = scanObject.TitleList, FeatureTitle = scanObject.MainFeature
                        });
                    }
                    catch (Exception exception)
                    {
                        MessageBox.Show(this, "Could not parse scan JSON:" + Environment.NewLine + Environment.NewLine + exception.ToString());
                    }
                }
            };
            debugDropDown.Items.Add(loadScanFromJsonItem);

            var queueFromJsonItem = new Fluent.MenuItem {
                Header = "Queue job from JSON..."
            };
            queueFromJsonItem.Click += (sender, args) =>
            {
                if (!this.viewModel.HasVideoSource)
                {
                    StaticResolver.Resolve <IMessageBoxService>().Show("Must open source before adding queue job from JSON");
                    return;
                }

                EncodeJobViewModel jobViewModel = this.viewModel.CreateEncodeJobVM();
                DebugJsonDialog    dialog       = new DebugJsonDialog("Debug Encode JSON");
                dialog.ShowDialog();

                if (!string.IsNullOrWhiteSpace(dialog.Json))
                {
                    try
                    {
                        JsonEncodeObject encodeObject = JsonConvert.DeserializeObject <JsonEncodeObject>(dialog.Json);

                        jobViewModel.DebugEncodeJsonOverride = dialog.Json;
                        jobViewModel.Job.FinalOutputPath     = encodeObject.Destination.File;
                        jobViewModel.Job.SourcePath          = encodeObject.Source.Path;

                        this.processingService.Queue(jobViewModel);
                    }
                    catch (Exception exception)
                    {
                        MessageBox.Show(this, "Could not parse encode JSON:" + Environment.NewLine + Environment.NewLine + exception.ToString());
                    }
                }
            };
            debugDropDown.Items.Add(queueFromJsonItem);

            var throwExceptionItem = new Fluent.MenuItem {
                Header = "Throw exception"
            };
            throwExceptionItem.Click += (sender, args) =>
            {
                throw new InvalidOperationException("Rats.");
            };
            debugDropDown.Items.Add(throwExceptionItem);

            var addLogItem = new Fluent.MenuItem {
                Header = "Add 1 log item"
            };
            addLogItem.Click += (sender, args) =>
            {
                StaticResolver.Resolve <IAppLogger>().Log("This is a log item");
            };
            debugDropDown.Items.Add(addLogItem);

            var addTenLogItems = new Fluent.MenuItem {
                Header = "Add 10 log items"
            };
            addTenLogItems.Click += (sender, args) =>
            {
                for (int i = 0; i < 10; i++)
                {
                    StaticResolver.Resolve <IAppLogger>().Log("This is a log item");
                }
            };
            debugDropDown.Items.Add(addTenLogItems);

            var addLongLogItem = new Fluent.MenuItem {
                Header = "Add long log item"
            };
            addLongLogItem.Click += (sender, args) =>
            {
                StaticResolver.Resolve <IAppLogger>().Log("This is a log item\r\nthat is split into multiple lines\r\nOh yes indeed");
            };
            debugDropDown.Items.Add(addLongLogItem);

            var doAnActionItem = new Fluent.MenuItem {
                Header = "Perform action"
            };
            doAnActionItem.Click += (sender, args) =>
            {
                var app = (App)System.Windows.Application.Current;
                app.ChangeTheme(new Uri("/Themes/Dark.xaml", UriKind.Relative));
            };
            debugDropDown.Items.Add(doAnActionItem);

            this.toolsRibbonGroupBox.Items.Add(debugDropDown);
#endif

            this.DataContextChanged += this.OnDataContextChanged;
            TheDispatcher            = this.Dispatcher;

            this.statusText.Opacity = 0.0;

            NameScope.SetNameScope(this, new NameScope());
            this.RegisterName("StatusText", this.statusText);

            var storyboard = (Storyboard)this.FindResource("StatusTextStoryboard");
            storyboard.Completed += (sender, args) =>
            {
                this.statusText.Visibility = Visibility.Collapsed;
            };

            this.presetTreeViewContainer.PresetTreeView.OnHierarchyMouseUp += (sender, args) =>
            {
                this.presetButton.IsDropDownOpen = false;
            };

            this.presetButton.DropDownOpened += (sender, args) =>
            {
                var item = UIUtilities.FindDescendant <TreeViewItem>(this.presetTreeViewContainer.PresetTreeView, viewItem =>
                {
                    return(viewItem.Header == this.viewModel.PresetsService.SelectedPreset);
                });

                if (item != null)
                {
                    UIUtilities.BringIntoView(item);
                }
            };

            this.Loaded += (e, o) =>
            {
                this.RestoredWindowState = this.WindowState;
            };

            this.statusService.MessageShown += (o, e) =>
            {
                this.ShowStatusMessage(e.Value);
            };

            this.queueView.SelectionChanged += this.QueueView_SelectionChanged;
        }