private void FFmpeg_Completed(object sender, FFmpeg.CompletedEventArgs e)
 {
     if (manager.AppExited)
     {
         return;
     }
     Dispatcher.Invoke(() => {
         FFmpegProcess Proc = sender as FFmpegProcess;
         if (e.Status == CompletionStatus.Error && !Proc.WorkProcess.StartInfo.FileName.EndsWith("avs2yuv.exe"))
         {
             FFmpegErrorWindow.Instance(Owner, Proc);
         }
         // hosts.Remove(Proc);
         if (Proc == task)
         {
             task = null;
             TaskStatusText.Text = "";
         }
         if (autoClose && !HasRunningHosts)
         {
             ClosingState = 2;
             this.Close();
         }
     });
 }
        public void SetSource(string arquivo)
        {
            _sourceOK = false;
            _source   = string.Empty;
            if (!File.Exists(arquivo))
            {
                throw new FileNotFoundException($"Arquivo não encontrado: {arquivo}", arquivo);
            }
            _source    = arquivo;
            _mediaInfo = MediaInfo.GetFileInfo(_source);

            _sourceInfo = new SourceInfo
            {
                Duration   = _mediaInfo.FileDuration,
                Width      = _mediaInfo.VideoStream.Width,
                Height     = _mediaInfo.VideoStream.Height,
                FrameCount = _mediaInfo.FrameCount
            };

            vaiFazer320  = _sourceInfo.Width >= 320;
            vaiFazer480  = _sourceInfo.Width >= 480;
            vaiFazer640  = _sourceInfo.Width >= 640;
            vaiFazer1280 = _sourceInfo.Width >= 1280;

            _source   = arquivo;
            _sourceOK = true;
        }
        protected override void OnMuxing(object sender, DownloadCompletedEventArgs e)
        {
            // Separate file extension.
            DownloadItemData IData = e.DownloadInfo.Data as DownloadItemData;

            FileProgress     VideoFile = e.DownloadInfo.Files.FirstOrDefault(f => f.Type == StreamType.Video);
            FileProgress     AudioFile = e.DownloadInfo.Files.FirstOrDefault(f => f.Type == StreamType.Audio);
            string           SrcFile   = IData.Media.FileName != null ? Settings.NaturalGroundingFolder + IData.Media.FileName : null;
            CompletionStatus Result    = CompletionStatus.Success;

            if (IData.Media.FileName != null && File.Exists(SrcFile) && (VideoFile == null || AudioFile == null))
            {
                // Upgrade audio or video
                FFmpegProcess MInfo       = MediaInfo.GetFileInfo(SrcFile);
                string        VideoFormat = VideoFile != null?Path.GetExtension(VideoFile.Destination).TrimStart('.') : MInfo.VideoStream?.Format;

                string AudioFormat = AudioFile != null?Path.GetExtension(AudioFile.Destination).TrimStart('.') : MInfo.AudioStream?.Format;

                string VideoDestExt = GetFinalExtension(VideoFormat, AudioFormat);
                e.DownloadInfo.Destination = e.DownloadInfo.DestinationNoExt + VideoDestExt;
                Result = MediaMuxer.Muxe(VideoFile?.Destination ?? SrcFile, AudioFile?.Destination ?? SrcFile, e.DownloadInfo.Destination);
            }
            if (Result == CompletionStatus.Success && File.Exists(SrcFile))
            {
                FileOperationAPIWrapper.MoveToRecycleBin(SrcFile);
            }

            e.DownloadInfo.Status = Result == CompletionStatus.Success ? DownloadStatus.Done : DownloadStatus.Failed;
        }
Example #4
0
        private void FixContainer(VideoListItem item)
        {
            SetStatus(item, VideoListItemStatusEnum.Converting);
            string SrcFile = Settings.NaturalGroundingFolder + item.FileName;

            if (item.FileName != null && File.Exists(SrcFile))
            {
                FFmpegProcess FileInfo = MediaInfo.GetFileInfo(SrcFile);
                string        Ext1     = Path.GetExtension(item.FileName).ToLower();
                string        Ext2     = DownloadBusiness.GetFinalExtension(FileInfo.VideoStream?.Format, FileInfo.AudioStream?.Format);
                if ((Ext2 == ".mp4" || Ext2 == ".webm") && Ext1 != Ext2)
                {
                    string DstFile = item.FileName.Substring(0, item.FileName.Length - Ext1.Length) + Ext2;
                    if (MediaMuxer.Muxe(SrcFile, SrcFile, Settings.NaturalGroundingFolder + DstFile) == CompletionStatus.Success)
                    {
                        FileOperationAPIWrapper.MoveToRecycleBin(SrcFile);
                        // Change database binding.
                        EditVideoBusiness Business     = new EditVideoBusiness();
                        Media             ExistingData = Business.GetVideoById(item.MediaId.Value);
                        if (ExistingData != null)
                        {
                            // Edit video info.
                            ExistingData.FileName = DstFile;
                            Business.Save();
                            SetStatus(item, VideoListItemStatusEnum.Done);
                            return;
                        }
                    }
                }
            }
            SetStatus(item, VideoListItemStatusEnum.Failed);
        }
        private void FFmpeg_ProgressUpdated(object sender, FFmpeg.StatusUpdatedEventArgs e)
        {
            if (manager.AppExited)
            {
                return;
            }
            Dispatcher.Invoke(() => {
                FFmpegProcess Proc = sender as FFmpegProcess;
                long Frames        = 0;
                for (int i = 0; i < hosts.Count; i++)
                {
                    if (hosts[i].LastStatusReceived != null)
                    {
                        Frames += hosts[i].LastStatusReceived.Frame;
                    }
                }
                WorkProgressBar.Value = FrameDone + Frames;
                PercentText.Text      = (WorkProgressBar.Value / WorkProgressBar.Maximum).ToString("p1");
                SetPageTitle(PercentText.Text);
                // FpsText.Text = e.Status.Fps.ToString();

                // Time left will be updated only once per 2 updates to prevent changing too quickly
                EstimatedTimeLeftToggle = (EstimatedTimeLeftToggle + 1) % 2;
                if (EstimatedTimeLeftToggle == 0 && timeCalc != null)
                {
                    timeCalc.Calculate(Frames);
                    if (timeCalc.ResultTimeLeft > TimeSpan.Zero)
                    {
                        TimeLeftText.Text = timeCalc.ResultTimeLeft.ToString(timeCalc.ResultTimeLeft.TotalHours < 1 ? "m\\:ss" : "h\\:mm\\:ss");
                        FpsText.Text      = timeCalc.ResultFps.ToString("0.0");
                    }
                }
            });
        }
Example #6
0
        /// <summary>
        /// Returns the audio gain that can be applied to an audio file.
        /// </summary>
        /// <param name="settings">The source file to analyze.</param>
        /// <param name="options">The options that control the behaviors of the process.</param>
        /// <returns>A float value representing the audio gain that can be applied, or null if it failed.</returns>
        public static float?GetAudioGain(string filePath, ProcessStartOptions options)
        {
            FFmpegProcess Worker = new FFmpegProcess(options);
            string        Args   = string.Format(@"-i ""{0}"" -af ""volumedetect"" -f null NUL", filePath);

            Worker.RunFFmpeg(Args);
            float? Result     = null;
            string FileString = Worker.Output;
            // Find max_volume.
            string SearchVal = "max_volume: ";
            int    Pos1      = FileString.IndexOf(SearchVal);

            if (Pos1 >= 0)
            {
                Pos1 += SearchVal.Length;
                // Find end of line.
                int Pos2 = FileString.IndexOf('\r', Pos1);
                if (Pos2 >= 0)
                {
                    string MaxVolString = FileString.Substring(Pos1, Pos2 - Pos1);
                    if (MaxVolString.Length > 3)
                    {
                        // Remove ' dB'
                        MaxVolString = MaxVolString.Substring(0, MaxVolString.Length - 3);
                        float MaxVol = 0;
                        if (float.TryParse(MaxVolString, out MaxVol))
                        {
                            Result = Math.Abs(MaxVol);
                        }
                    }
                }
            }
            return(Result);
        }
Example #7
0
        public object Get()
        {
            // RODAR antes: apt-get install ffmpeg

            FFmpegConfig.SetDirectories("ffmpeg", "ffprobe", "/tmp/");

            var location = "input";

            var bytes = System.IO.File.ReadAllBytes(location);

            System.IO.File.WriteAllBytes("/tmp/input.mp4", bytes);

            var input = FFmpegProcess.GetInfo(location);

            return(new { FFmpegResult = input, Locations = Directory.GetFiles("/tmp/") });

            //if (input.Streams.Any(p => p.codec_type.Equals("video")))
            //{
            //    var destinationthumb = Path.ChangeExtension(file, "jpg");
            //    FFmpegProcess.GetThumbNail(file, destinationthumb);
            //}
            //else if (input.Streams.Any(p => p.codec_type.Equals("audio")))
            //{
            //    Console.WriteLine($"Duration: {input.Format.durationTs}");
            //}
        }
        protected override void WorkerDoWork(DoWorkEventArgs e)
        {
            try
            {
                using (var logger = OperationLogger.Create(OperationLogger.FFmpegDLogFile))
                {
                    var ffmpeg = new FFmpegProcess(logger);

                    if (_end == TimeSpan.MinValue)
                    {
                        ffmpeg.Crop(this.Input, this.Output, _start, this.ReportProgress, _cts.Token);
                    }
                    else
                    {
                        ffmpeg.Crop(this.Input, this.Output, _start, _end, this.ReportProgress, _cts.Token);
                    }
                }

                _start = _end = TimeSpan.MinValue;

                e.Result = this.CancellationPending ? OperationStatus.Canceled : OperationStatus.Success;
            }
            catch (Exception ex)
            {
                Common.SaveException(ex);
                Helper.DeleteFiles(this.Output);
                e.Result = OperationStatus.Failed;
            }
        }
 public void DisplayTask(FFmpegProcess taskArg)
 {
     Dispatcher.Invoke(() => {
         if (taskArg.Options.IsMainTask)
         {
             host                = taskArg;
             host.InfoUpdated   += FFmpeg_InfoUpdated;
             host.StatusUpdated += FFmpeg_StatusUpdated;
             host.Completed     += FFmpeg_Completed;
             PercentText.Text    = 0.ToString("p1");
             SetPageTitle(PercentText.Text);
         }
         else
         {
             task = taskArg;
             TaskStatusText.Text = task.Options.Title;
             task.Completed     += (sender, e) => {
                 FFmpegProcess Proc = (FFmpegProcess)sender;
                 Dispatcher.Invoke(() => {
                     if (e.Status == CompletionStatus.Error && !Proc.WorkProcess.StartInfo.FileName.EndsWith("avs2yuv.exe"))
                     {
                         FFmpegErrorWindow.Instance(Owner, Proc);
                     }
                     TaskStatusText.Text = "";
                     task = null;
                     if (autoClose)
                     {
                         this.Close();
                     }
                 });
             };
         }
     });
 }
Example #10
0
 public void KillFFmpegProcess()
 {
     if (Process.GetProcessesByName(FFmpegName).Length > 0)
     {
         FFmpegProcess?.Kill();
     }
 }
Example #11
0
        /// <summary>
        /// Gets an AviSynth clip information by running a script that outputs the frame count to a file.
        /// </summary>
        /// <param name="source">The AviSynth script to get information about.</param>
        /// <param name="options">The options that control the behaviors of the process.</param>
        /// <returns>The frame count.</returns>
        public static long GetFrameCount(string source, ProcessStartOptions options)
        {
            if (!File.Exists(source))
            {
                return(0);
            }
            string TempScriptBase = Path.ChangeExtension(source, null);
            string TempScript     = PathManager.GetTempFile("avs");
            string TempResult     = Path.ChangeExtension(TempScript, "txt");

            AviSynthScriptBuilder Script;

            if (source.ToLower().EndsWith(".avs"))
            {
                // Read source script and remove MT. Also remove Deshaker if present.
                string FileContent = File.ReadAllText(source);
                FileContent.Replace(Environment.NewLine + "Deshaker", Environment.NewLine + "#Deshaker");
                Script = new AviSynthScriptBuilder(FileContent);
                Script.RemoveMT();
            }
            else
            {
                // Generate script to read media file.
                Script = new AviSynthScriptBuilder();
                Script.AddPluginPath();
                Script.OpenDirect(source, false);
            }
            // Get frame count.
            Script.AppendLine();
            Script.AppendLine(@"WriteFileStart(""{0}"", ""FrameRate""{1}""Framecount"")", TempResult, @", """""" "","" """""", ");
            Script.AppendLine("Trim(0,-1)");
            Script.WriteToFile(TempScript);

            // Run script.
            FFmpegProcess Worker = new FFmpegProcess(options);

            Worker.RunAvisynth(TempScript);

            // Read frame count
            long Result = 0;

            if (File.Exists(TempResult))
            {
                string   FileString = File.ReadAllText(TempResult);
                string[] FileValues = FileString.Split(',');
                try {
                    //Result.FrameRate = float.Parse(FileValues[0], CultureInfo.InvariantCulture);
                    Result = int.Parse(FileValues[1]);
                }
                catch {
                }
            }

            // Delete temp files.
            File.Delete(TempScript);
            File.Delete(TempResult);

            return(Result);
        }
 protected override void WorkerCompleted(RunWorkerCompletedEventArgs e)
 {
     if (this.IsSuccessful)
     {
         this.Duration = (long)FFmpegProcess.GetDuration(this.Input).Value.TotalSeconds;
         this.FileSize = Helper.GetFileSize(this.Output);
     }
 }
        public void StartConversion(string destinationFolder)
        {
            if (State == ConversionStateEnum.InProgress)
            {
                return;
            }

            _startTicks = DateTime.Now.Ticks;
            State       = ConversionStateEnum.InProgress;

            _destinationFolder = destinationFolder;
            _timeLeftCalc      = new TimeLeftCalculator(SourceInfo.FrameCount, 400);

            var dest320x180 = Path.Combine(destinationFolder, "320x180");

            if (vaiFazer320 && !Directory.Exists(dest320x180))
            {
                Directory.CreateDirectory(dest320x180); // deixa deisparar aqui se não for possível criar
            }
            var dest480x270 = Path.Combine(destinationFolder, "480x270");

            if (vaiFazer480 && !Directory.Exists(dest480x270))
            {
                Directory.CreateDirectory(dest480x270);
            }

            var dest640x360 = Path.Combine(destinationFolder, "640x360");

            if (vaiFazer640 && !Directory.Exists(dest640x360))
            {
                Directory.CreateDirectory(dest640x360);
            }

            var dest1280x720 = Path.Combine(destinationFolder, "1280x720");

            if (vaiFazer1280 && !Directory.Exists(dest1280x720))
            {
                Directory.CreateDirectory(dest1280x720);
            }


            fi = new FFmpegProcess(
                new ProcessStartOptions {
                Priority = ProcessPriorityClass.BelowNormal, DisplayMode = FFmpegDisplayMode.None
            }
                );

            fi.Completed     += Fi_Completed;
            fi.StatusUpdated += Fi_StatusUpdated;

            var cmd = $"-i \"{_source}\" " + // arquivo de entrada
                      (!vaiFazer320 ? string.Empty : $" -c:a aac -strict experimental -ac 2 -b:a 64k -ar 44100 -c:v libx264 -pix_fmt yuv420p -profile:v baseline -level 1.3 -maxrate 192K -bufsize 1M -crf 18 -r 10 -g 30 -f hls -hls_time 9 -hls_list_size 0 -s 320x180 -hls_segment_filename \"{dest320x180}\\%03d.ts\" \"{dest320x180}\\{SEGMENT_MANIFEST_FILE_NAME}\"") +
                      (!vaiFazer480 ? string.Empty : $" -c:a aac -strict experimental -ac 2 -b:a 64k -ar 44100 -c:v libx264 -pix_fmt yuv420p -profile:v baseline -level 2.1 -maxrate 500K -bufsize 2M -crf 18 -r 10 -g 30  -f hls -hls_time 9 -hls_list_size 0 -s 480x270 -hls_segment_filename \"{dest480x270}\\%03d.ts\" \"{dest480x270}\\{SEGMENT_MANIFEST_FILE_NAME}\"") +
                      (!vaiFazer640 ? string.Empty : $" -c:a aac -strict experimental -ac 2 -b:a 96k -ar 44100 -c:v libx264 -pix_fmt yuv420p -profile:v baseline -level 3.1 -maxrate 1M -bufsize 3M -crf 18 -r 24 -g 72 -f hls -hls_time 9 -hls_list_size 0 -s 640x360 -hls_segment_filename \"{dest640x360}\\%03d.ts\" \"{dest640x360}\\{SEGMENT_MANIFEST_FILE_NAME}\"") +
                      (!vaiFazer1280 ? string.Empty : $" -c:a aac -strict experimental -ac 2 -b:a 96k -ar 44100 -c:v libx264 -pix_fmt yuv420p -profile:v main -level 3.2 -maxrate 2M -bufsize 6M -crf 18 -r 24 -g 72 -f hls -hls_time 9 -hls_list_size 0 -s 1280x720  -hls_segment_filename \"{dest1280x720}\\%03d.ts\" \"{dest1280x720}\\{SEGMENT_MANIFEST_FILE_NAME}\"");

            fi.RunFFmpeg(cmd);
        }
        public static void Instance(Window parent, FFmpegProcess host)
        {
            FFmpegErrorWindow F = new FFmpegErrorWindow();

            F.Owner           = parent;
            F.Title           = (host.LastCompletionStatus == CompletionStatus.Timeout ? "Timeout: " : "Failed: ") + host.Options.Title;
            F.OutputText.Text = host.CommandWithArgs + Environment.NewLine + Environment.NewLine + host.Output;
            F.Show();
        }
        private void PlayMedia()
        {
            FFmpegProcess infoReader = MediaInfo.GetFileInfo(playManager.NowPlaying);

            AutoPitchBusiness.CreateScript(playManager.NowPlaying, infoReader, AppPaths.Player432hzScriptFile);
            Player.Host.Source = null;
            Player.Host.Source = AppPaths.Player432hzScriptFile;
            Player.Host.Title  = Path.GetFileName(playManager.NowPlaying);
        }
Example #16
0
        public async Task <IFile> ExtractAsync(IFile videoFile)
        {
            if (videoFile == null)
            {
                throw new ArgumentNullException(nameof(videoFile));
            }

            if (videoFile.StorageType != StorageType.FileSystem)
            {
                throw new Exception("FFMpeg can work only with file on FileSystem");
            }

            //get full path for audio
            var audioFullpath = Path.Combine(
                _fileResolver.GetAudioFolderPath(StorageType.FileSystem),
                videoFile.Filename + "." + _audioOptions.Value.DefaultFormat);

            //get video
            var videofilePath = _fileResolver.VideoFilePath(videoFile.Filename, videoFile.Extension, StorageType.FileSystem);

            if (File.Exists(audioFullpath))
            {
                File.Delete(audioFullpath);
            }

            //extract audio from video
            var ffMpeg = new FFmpegProcess();

            ffMpeg.RunFFmpeg(string.Format(FFMpegExtractAudioFormat,
                                           videofilePath,
                                           _audioOptions.Value.DefaultFormat,
                                           _audioOptions.Value.BitRate,
                                           audioFullpath));

            //delete video
            File.Delete(videofilePath);

            var match = FindDurationRegex.Match(ffMpeg.Output);

            if (match.Success)
            {
                _duration = int.Parse(match.Groups[1].Value) * 3600 +
                            int.Parse(match.Groups[2].Value) * 60 +
                            int.Parse(match.Groups[3].Value) +
                            int.Parse(match.Groups[4].Value) / 100.0;
            }

            //return info about audio file
            return(new PCFile
            {
                Filename = videoFile.Filename,
                Extension = "." + _audioOptions.Value.DefaultFormat,
                Duration = _duration,
                StorageType = StorageType.FileSystem
            });
        }
Example #17
0
        /// <summary>
        /// Prepares the files of an existing job that we resume.
        /// </summary>
        /// <returns>Whether job still needs to execute.</returns>
        //private bool PrepareResumeJob(MediaEncoderSettings settings) {
        //    AvisynthTools.EditStartPosition(settings.ScriptFile, 0);
        //    // At least one segment has been processed. Check if the entire file has been processed.
        //    ProcessStartOptions Options = new ProcessStartOptions(settings.JobIndex, "Resuming...", false).TrackProcess(settings);
        //    Task<long> TaskCount = Task.Run(() => AvisynthTools.GetFrameCount(settings.ScriptFile, Options));

        //    int Segment = 0;
        //    List<Task<long>> TaskList = new List<Task<long>>();
        //    while (File.Exists(PathManager.GetOutputFile(settings.JobIndex, ++Segment, settings.VideoCodec)) && settings.CompletionStatus != CompletionStatus.Cancelled) {
        //        string SegmentFile = PathManager.GetOutputFile(settings.JobIndex, Segment, settings.VideoCodec);
        //        // Discard segments of less than 10kb.
        //        if (new FileInfo(SegmentFile).Length > 10000) {
        //            int SegmentLocal = Segment;
        //            TaskList.Add(Task.Run(() => AvisynthTools.GetFrameCount(PathManager.GetOutputFile(settings.JobIndex, SegmentLocal, settings.VideoCodec), null)));
        //        } else {
        //            // There shouldn't be any resumed job following a segment that is being deleted.
        //            File.Delete(SegmentFile);
        //            break;
        //        }
        //    }

        //    long OutputFrames = 0;
        //    Task.WaitAll(TaskList.ToArray());
        //    foreach (Task<long> item in TaskList) {
        //        OutputFrames += item.Result;
        //    }

        //    TaskCount.Wait();
        //    if (settings.CompletionStatus == CompletionStatus.Cancelled)
        //        return false;

        //    long ScriptFrames = TaskCount.Result;
        //    if (OutputFrames >= ScriptFrames) {
        //        // Job completed.
        //        //EncodingCompletedEventArgs EncodeResult = FinalizeEncoding(settings, null);
        //        //if (EncodeResult != null)
        //        //    EncodingCompleted(this, EncodeResult);
        //        //else {
        //        //    PathManager.DeleteJobFiles(settings.JobIndex);
        //        //}
        //        return false;
        //    } else {
        //        // Resume with new segment.
        //        AvisynthTools.EditStartPosition(settings.ScriptFile, OutputFrames);
        //        settings.ResumeSegment = Segment;
        //        settings.ResumePos = OutputFrames;
        //        File.Delete(settings.OutputFile);
        //        return true;
        //    }
        //}

        private async Task GetMediaInfo(string previewFile, MediaEncoderSettings settings)
        {
            FFmpegProcess FInfo = await Task.Run(() => MediaInfo.GetFileInfo(previewFile));

            FFmpegVideoStreamInfo VInfo = FInfo.VideoStream;
            FFmpegAudioStreamInfo AInfo = settings.ConvertToAvi ? await Task.Run(() => MediaInfo.GetFileInfo(settings.FilePath).AudioStream) : FInfo.AudioStream;

            settings.SourceWidth  = FInfo.VideoStream.Width;
            settings.SourceHeight = FInfo.VideoStream.Height;
            if (settings.SourceHeight > 768)
            {
                settings.OutputHeight = settings.SourceHeight.Value;
            }
            settings.SourceAspectRatio = (float)(VInfo?.PixelAspectRatio ?? 1);
            // Fix last track of VCDs that is widescreen.
            if (settings.SourceHeight == 288 && settings.SourceWidth == 352 && settings.SourceAspectRatio == 1.485f)
            {
                settings.SourceAspectRatio = 1.092f;
            }
            settings.SourceFrameRate = VInfo?.FrameRate;

            settings.SourceAudioFormat = AInfo?.Format;
            settings.SourceVideoFormat = VInfo?.Format;
            bool IsTvRange = VInfo?.ColorRange != "pc";

            if (!string.IsNullOrEmpty(VInfo?.ColorMatrix))
            {
                settings.SourceColorMatrix = VInfo.ColorMatrix.EndsWith("601") ? (IsTvRange ? ColorMatrix.Rec601 : ColorMatrix.Pc601) : (IsTvRange ? ColorMatrix.Rec709 : ColorMatrix.Pc709);
            }
            else
            {
                settings.SourceColorMatrix = VInfo?.Height < 600 ? (IsTvRange ? ColorMatrix.Rec601 : ColorMatrix.Pc601) : (IsTvRange ? ColorMatrix.Rec709 : ColorMatrix.Pc709);
            }
            settings.SourceChromaPlacement = string.Compare(VInfo?.Format, "mpeg1video", true) == 0 ? ChromaPlacement.MPEG1 : ChromaPlacement.MPEG2;
            settings.DegrainPrefilter      = VInfo?.Height < 600 ? DegrainPrefilters.SD : DegrainPrefilters.HD;

            settings.SourceVideoBitrate = (int)(new FileInfo(previewFile).Length / FInfo.FileDuration.TotalSeconds / 1024 * 8);
            settings.SourceAudioBitrate = AInfo?.Bitrate;
            if (!settings.HasAudioOptions)
            {
                settings.AudioQuality = AInfo?.Bitrate > 0 ? AInfo.Bitrate : 256;
            }
            if (settings.AudioQuality > 384)
            {
                settings.AudioQuality = 384;
            }
            settings.SourceBitDepth = 8; // VInfo.BitDepth;
            //settings.DenoiseD = 2;
            //settings.DenoiseA = settings.SourceHeight < 720 ? 2 : 1;
            settings.Position      = FInfo.FileDuration.TotalSeconds / 2;
            settings.VideoAction   = settings.SourceHeight >= 1080 ? VideoAction.x264 : VideoAction.x265;
            settings.EncodeQuality = settings.SourceHeight >= 1080 ? 23 : 22;
            settings.EncodePreset  = settings.SourceHeight >= 1080 ? EncodePresets.veryslow : EncodePresets.medium;
            // Use Cache to open file when file is over 500MB
            settings.CalculateSize();
        }
 public static void CreateScript(string inputFile, FFmpegProcess infoReader, string scriptPath = null)
 {
     //if (LastScriptPath != null)
     //    PathManager.SafeDelete(LastScriptPath);
     if (scriptPath == null)
     {
         scriptPath = GetAutoPitchFilePath(inputFile, infoReader?.VideoStream?.Format);
     }
     ChangePitchBusiness.CreateScript(inputFile, infoReader, scriptPath);
     LastScriptPath = scriptPath;
 }
Example #19
0
        public BasicEncoder(Dispatcher dispatcher, string name)
        {
            _dispatcher = dispatcher;
            _process    = new FFmpegProcess(name);
            _process.OutputDataReceived += _process_OutputDataReceived;
            _process.ProcessExited      += _process_ProcessExited;

            this.FPS     = "-";
            this.Time    = "-";
            this.Bitrate = "-";
        }
        /// <summary>
        /// Saves the audio output of specified script into a WAV file.
        /// </summary>
        /// <param name="settings">An object containing the encoding settings.</param>
        /// <param name="destination">The WAV file to write.</param>
        /// <param name="options">The options that control the behaviors of the process.</param>
        public static void SaveAudioToWav(MediaEncoderSettings settings, string destination, ProcessStartOptions options)
        {
            string TempFile = settings.TempFile + ".avs";
            AviSynthScriptBuilder Script = new AviSynthScriptBuilder();

            if (settings.VideoAction != VideoAction.Copy)
            {
                // Read source script.
                Script.Script = File.ReadAllText(settings.ScriptFile);
                // Remote MT code.
                Script.RemoveMT();
                Script.AppendLine("Trim(0,0)");
            }
            else
            {
                // Read full video file.
                Script.AddPluginPath();
                if (settings.ConvertToAvi || settings.InputFile.ToLower().EndsWith(".avi"))
                {
                    Script.OpenAvi(settings.InputFile, !string.IsNullOrEmpty(settings.SourceAudioFormat));
                }
                else
                {
                    Script.OpenDirect(settings.InputFile, !string.IsNullOrEmpty(settings.SourceAudioFormat));
                }
                Script.AppendLine("KillVideo()");
            }
            Script.AppendLine();
            // Add audio gain.
            if (settings.AudioGain.HasValue && settings.AudioGain != 0)
            {
                Script.AppendLine("AmplifydB({0})", settings.AudioGain.Value);
            }
            if (settings.ChangeAudioPitch)
            {
                // Change pitch to 432hz.
                Script.LoadPluginDll("TimeStretch.dll");
                Script.AppendLine("ResampleAudio(48000)");
                Script.AppendLine("TimeStretchPlugin(pitch = 100.0 * 0.98181819915771484)");
            }
            // Add TWriteWAV.
            Script.AppendLine();
            Script.LoadPluginDll("TWriteAVI.dll");
            Script.AppendLine(@"TWriteWAV(""{0}"", true)", Script.GetAsciiPath(destination));
            Script.AppendLine("ForceProcessWAV()");

            // Write temp script.
            Script.WriteToFile(TempFile);
            // Execute. It aways returns an error but the file is generated.
            FFmpegProcess Worker = new FFmpegProcess(options);

            Worker.RunAvisynth(TempFile);
            File.Delete(TempFile);
        }
        private async Task LoadMediaInfoAsync()
        {
            FFmpegProcess FileInfo = await Task.Run(() => MediaInfo.GetFileInfo(Settings.NaturalGroundingFolder + video.FileName));

            DimensionText.GetBindingExpression(TextBox.TextProperty).UpdateTarget();
            DisablePitchCheckBox.IsEnabled = FileInfo?.VideoStream?.PixelAspectRatio == 1;
            if (!DisablePitchCheckBox.IsEnabled)
            {
                video.DisablePitch = false;
            }
        }
Example #22
0
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            ProcessStartOptions options = new ProcessStartOptions(FFmpegDisplayMode.Interface);
            //FFmpegProcess process = new FFmpegProcess(start);

            string arguments = e.Argument.ToString();

            worker_process = new FFmpegProcess(options);

            worker_process.StatusUpdated += Worker_StatusUpdated;
            e.Result = worker_process.RunFFmpeg(arguments);
        }
        public ConvertOperation(string input,
                                string output,
                                TimeSpan start,
                                TimeSpan end)
            : this(input, output)
        {
            _mode  = ConvertingMode.File;
            _start = start;
            _end   = end;

            this.Duration = (long)FFmpegProcess.GetDuration(this.Input).Value.TotalSeconds;
        }
Example #24
0
        /// <summary>
        /// Loads the Length, Width and Height of specified media file.
        /// </summary>
        /// <param name="item">The media file to read.</param>
        /// <returns>True if data was loaded, false if no data was needed.</returns>
        public async Task LoadFileEntryInfoAsync(Media item)
        {
            FFmpegProcess FileInfo = await Task.Run(() => MediaInfo.GetFileInfo(Settings.NaturalGroundingFolder + item.FileName));

            if (FileInfo.FileDuration > TimeSpan.Zero)
            {
                item.Length = (short)FileInfo.FileDuration.TotalSeconds;
            }
            if (FileInfo.VideoStream != null && FileInfo.VideoStream.Height > 0)
            {
                item.Height = (short)FileInfo.VideoStream.Height;
            }
        }
Example #25
0
        public static int GetAudioBitrateMuxe(string file)
        {
            int    Result  = 0;
            string TmpFile = PathManager.TempFilesPath + "GetBitrate - " + Path.GetFileNameWithoutExtension(file) + ".aac";

            if (MediaMuxer.Muxe(null, file, TmpFile) == CompletionStatus.Success)
            {
                FFmpegProcess InfoReader = MediaInfo.GetFileInfo(TmpFile);
                Result = InfoReader.AudioStream?.Bitrate ?? 0;
            }
            File.Delete(TmpFile);
            return(Result);
        }
 private void FFmpeg_Completed(object sender, FFmpeg.CompletedEventArgs e)
 {
     Dispatcher.Invoke(() => {
         FFmpegProcess Proc = sender as FFmpegProcess;
         if (e.Status == CompletionStatus.Error && !Proc.WorkProcess.StartInfo.FileName.EndsWith("avs2yuv.exe"))
         {
             FFmpegErrorWindow.Instance(Owner, Proc);
         }
         if (autoClose)
         {
             this.Close();
         }
     });
 }
        /// <summary>
        /// Encodes specified audio file according to settings. The script file must already be written.
        /// </summary>
        /// <param name="settings">An object containing the encoding settings.</param>
        /// <returns>The endoding completion status..</returns>
        public static CompletionStatus EncodeAudio(MediaEncoderSettings settings)
        {
            CompletionStatus    Result  = CompletionStatus.Success;
            string              WavFile = PathManager.GetAudioFile(settings.JobIndex, AudioActions.Wav);
            ProcessStartOptions Options = new ProcessStartOptions(settings.JobIndex, "Exporting Audio", false).TrackProcess(settings);

            if (!File.Exists(WavFile))
            {
                EncoderBusiness.SaveAudioToWav(settings, WavFile, Options);
                if (settings.CompletionStatus == CompletionStatus.Cancelled)
                {
                    File.Delete(WavFile);
                    return(CompletionStatus.Cancelled);
                }
                if (!File.Exists(WavFile))
                {
                    settings.Cancel();
                    return(CompletionStatus.Error);
                }
            }

            string DestFile = PathManager.GetAudioFile(settings.JobIndex, settings.AudioAction);

            if (!File.Exists(DestFile))
            {
                Options.Title = "Encoding Audio";
                if (settings.AudioAction == AudioActions.Opus)
                {
                    string        Args   = string.Format(@"--bitrate {0} ""{1}"" ""{2}""", settings.AudioQuality, WavFile, DestFile);
                    FFmpegProcess Worker = new FFmpegProcess(Options);
                    Result = Worker.Run("Encoder\\opusenc.exe", Args);
                }
                else if (settings.AudioAction == AudioActions.Aac || settings.AudioAction == AudioActions.Flac)
                {
                    Result = MediaEncoder.Encode(WavFile, null,
                                                 settings.AudioAction == AudioActions.Flac ? "flac" : "aac",
                                                 string.Format("-b:a {0}k", settings.AudioQuality),
                                                 DestFile,
                                                 Options);
                }
            }

            if (Result != CompletionStatus.Success || !File.Exists(DestFile))
            {
                File.Delete(DestFile);
                settings.Cancel();
            }
            return(Result);
        }
Example #28
0
        private async Task QueryLocalAsync()
        {
            if (video == null || video.FileName == null)
            {
                return;
            }

            string SrcFile = Settings.NaturalGroundingFolder + video.FileName;

            if (File.Exists(SrcFile))
            {
                DownloadPlaylistBusiness Business = new DownloadPlaylistBusiness();
                var IsHigher = await Business.IsHigherQualityAvailable(bestFormat, Settings.NaturalGroundingFolder + video.FileName);

                if (Business.LastInfoReader != null)
                {
                    localInfo = Business.LastInfoReader;
                    long LocalFileSize = new FileInfo(SrcFile).Length;
                    if (localInfo?.VideoStream != null)
                    {
                        LocalVideoText.Text = string.Format("{0} {1}p ({2}mb)", FirstCharToUpper(localInfo.VideoStream.Format), localInfo.VideoStream.Height, LocalFileSize / 1024 / 1024);
                    }
                    if (localInfo.AudioStream != null)
                    {
                        LocalAudioText.Text = string.Format("{0} {1}", localInfo.AudioStream.Format, localInfo.AudioStream.Bitrate > 0 ? localInfo.AudioStream.Bitrate.ToString() + "kbps" : "");
                    }
                    LocalVideoText.Visibility = localInfo.VideoStream != null ? Visibility.Visible : Visibility.Hidden;
                    LocalAudioText.Visibility = localInfo.AudioStream != null ? Visibility.Visible : Visibility.Hidden;

                    if (IsHigher == VideoListItemStatusEnum.BetterAudioAvailable)
                    {
                        LocalVideoOption.IsChecked = true;
                    }
                    else if (IsHigher == VideoListItemStatusEnum.BetterVideoAvailable)
                    {
                        LocalAudioOption.IsChecked = true;
                    }
                    else if (IsHigher == VideoListItemStatusEnum.OK)
                    {
                        LocalVideoOption.IsChecked = true;
                        LocalAudioOption.IsChecked = true;
                    }

                    GridLocalFile.Visibility = Visibility.Visible;
                }
            }
            DownloadButton.IsEnabled = true;
        }
Example #29
0
        private CompletionStatus ExecuteComplex(string src, string dst)
        {
            string DstEncode  = GetPathWithoutExtension(dst) + "_.mp4";
            string DstExtract = GetPathWithoutExtension(dst) + "_.mkv";
            string DstAac     = GetPathWithoutExtension(dst) + "_.aac";

            jobId++;
            CompletionStatus Result;

            FFmpegConfig.UserInterfaceManager.Start(jobId, "Encoding to H264/AAC (Complex)");

            ProcessStartOptions OptionsMain = new ProcessStartOptions(jobId, "", true);
            FFmpegProcess       ProcessMain = null;

            OptionsMain.Started += (sender, e) => {
                ProcessMain = e.Process;
            };
            Task <CompletionStatus> TaskMain = Task.Run(() => MediaEncoder.Encode(src, "h264", null, "", DstEncode, OptionsMain));

            ProcessStartOptions Options = new ProcessStartOptions(jobId, "Extracting Audio", false);

            Result = MediaMuxer.ExtractAudio(src, DstExtract, Options);
            if (Result == CompletionStatus.Success)
            {
                Options.Title = "Encoding Audio";
                Result        = MediaEncoder.Encode(DstExtract, null, "aac", null, DstAac, Options);
            }

            if (Result != CompletionStatus.Success)
            {
                ProcessMain?.Cancel();
            }

            TaskMain.Wait();
            CompletionStatus Result2 = TaskMain.Result;

            if (Result == CompletionStatus.Success && Result2 == CompletionStatus.Success)
            {
                Options.Title = "Muxing Audio and Video";
                Result        = MediaMuxer.Muxe(DstEncode, DstAac, dst, Options);
            }

            File.Delete(DstEncode);
            File.Delete(DstExtract);
            File.Delete(DstAac);
            FFmpegConfig.UserInterfaceManager.Stop(jobId);
            return(Result);
        }
        /// <summary>
        /// Encodes an Avisynth script through X264 10bit.
        /// </summary>
        /// <param name="source">The script to encode.</param>
        /// <param name="encodeArgs">Options for x264.</param>
        /// <param name="destination">The destination file.</param>
        /// <param name="options">The options for starting the process.</param>
        /// <returns></returns>
        public static CompletionStatus EncodeX264_10bit(string source, string encodeArgs, string destination, ProcessStartOptions options)
        {
            File.Delete(destination);
            StringBuilder Query = new StringBuilder("--demuxer y4m ");

            Query.Append(encodeArgs);
            Query.Append(" -o \"");
            Query.Append(destination);
            Query.Append("\" -");

            // Run x264 with query.
            FFmpegProcess    Worker = new FFmpegProcess(options);
            CompletionStatus Result = Worker.RunAvisynthToEncoder(source, Query.ToString(), EncoderApp.x264, AppPaths.X264Path);

            return(Result);
        }