示例#1
0
        private async void btn_analyze_Click(object sender, EventArgs e)
        {
            Settings.Default.LastFolder = tb_dir.Text;
            Settings.Default.Save();

            btn_extract.Enabled = false;

            await FFmpegDownloader.GetLatestVersion(FFmpegVersion.Full);

            var extenssions = new List <string> {
                ".mov", "mp4"
            };

            var files = Directory.EnumerateFiles(tb_dir.Text)
                        .Where(v => extenssions.Any(x => v.ToLower().EndsWith(x)));

            foreach (var file in files)
            {
                var audioStream = (await FFmpeg.GetMediaInfo(file))
                                  .AudioStreams.FirstOrDefault();

                var codec = "Unknown";
                if (audioStream != null)
                {
                    codec = audioStream.Codec;
                }

                var lvi = new ListViewItem(new string[] { file, codec });
                lv.Items.Add(lvi);
            }

            btn_extract.Enabled = true;
        }
示例#2
0
        private async Task Convert()
        {
            DialogResult result     = dialogSaveOutput.ShowDialog();
            string       outputPath = "";

            if (result == DialogResult.OK)
            {
                outputPath = dialogSaveOutput.FileName;
            }
            else
            {
                return;
            }

            txtOutput.Text       = "";
            prgProgressBar.Value = 0;

            string audio = dialogOpenAudioFile.FileName;
            string image = dialogOpenCoverArt.FileName;

            await FFmpegDownloader.GetLatestVersion(FFmpegVersion.Official);

            // FFMpeg arguments based on this answer
            // https://superuser.com/a/1041818
            IConversion conversion = FFmpeg.Conversions.New();

            conversion
            .SetOutput(outputPath)
            .SetOverwriteOutput(true)
            .AddParameter("-loop 1")
            .AddParameter("-y")
            .AddParameter($"-i {image}")
            .AddParameter($"-i {audio}")
            .AddParameter("-shortest")
            .AddParameter("-framerate 2")
            .AddParameter("-acodec copy")
            .AddParameter("-vcodec mjpeg")
            .AddParameter("-preset ultrafast");

            string ffmpegParams = conversion.Build();

            txtOutput.AppendText($"ffmpeg {ffmpegParams}{Environment.NewLine}");

            conversion.OnDataReceived += Conversion_OnDataReceived;
            conversion.OnProgress     += Conversion_OnProgress;

            try
            {
                _state         = State.Converting;
                btnCreate.Text = Language.Stop;
                IConversionResult conversionResult = await conversion.Start(_cts.Token);
            }
            catch (OperationCanceledException) { }
            catch (Exception ex)
            {
                _state         = State.Ready;
                btnCreate.Text = Language.Convert;
                txtOutput.AppendText(Environment.NewLine + Environment.NewLine + ex.Message);
            }
        }
 private async void Window_Loaded(object sender, RoutedEventArgs e)
 {
     Main.Content = pageVodDownload;
     if (!File.Exists("ffmpeg.exe"))
     {
         await FFmpegDownloader.GetLatestVersion(FFmpegVersion.Full);
     }
 }
示例#4
0
        // Points the FFmpeg library to the right executables
        public static void SetFFMpegPath()
        {
            FFmpeg.SetExecutablesPath(FFMPEG_PATH);
#if DEBUG
            // Automatically downloads FFmpeg useful for development
            FFmpegDownloader.GetLatestVersion(FFmpegVersion.Official, FFmpeg.ExecutablesPath);
#endif
        }
示例#5
0
        static void Main(string[] args)
        {
            if (args.Any(x => x.Equals("--download-ffmpeg")))
            {
                Console.WriteLine("[INFO] - Downloading ffmpeg and exiting");
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    FFmpegDownloader.GetLatestVersion(FFmpegVersion.Official).Wait();
                    try
                    {
                        var filePermissions = new Mono.Unix.UnixFileInfo("ffmpeg");
                        filePermissions.FileAccessPermissions = FileAccessPermissions.UserRead | FileAccessPermissions.UserWrite | FileAccessPermissions.GroupRead | FileAccessPermissions.OtherRead | FileAccessPermissions.UserExecute | FileAccessPermissions.GroupExecute | FileAccessPermissions.OtherExecute;
                        filePermissions.Refresh();
                    }
                    catch { }
                }
                else
                {
                    FFmpegDownloader.GetLatestVersion(FFmpegVersion.Full).Wait();
                }
                Environment.Exit(1);
            }

            Options inputOptions  = new Options();
            var     optionsResult = Parser.Default.ParseArguments <Options>(args).WithParsed(r => { inputOptions = r; });

            if (optionsResult.Tag == ParserResultType.NotParsed)
            {
                Environment.Exit(1);
            }


            if (!File.Exists(ffmpegPath) && (inputOptions.FfmpegPath == null || !File.Exists(inputOptions.FfmpegPath)) && !ExistsOnPath(ffmpegPath))
            {
                Console.WriteLine("[ERROR] - Unable to find ffmpeg, exiting. You can download ffmpeg automatically with the argument --download-ffmpeg");
                Environment.Exit(1);
            }

            switch (inputOptions.RunMode)
            {
            case RunMode.VideoDownload:
                DownloadVideo(inputOptions);
                break;

            case RunMode.ClipDownload:
                DownloadClip(inputOptions);
                break;

            case RunMode.ChatDownload:
                DownloadChat(inputOptions);
                break;

            case RunMode.ChatRender:
                RenderChat(inputOptions);
                break;
            }
        }
示例#6
0
        static void Main()
        {
            FFmpegDownloader.GetLatestVersion(FFmpegVersion.Official).Wait(); //TODO: wrap this into a splash or so

            Application.SetHighDpiMode(HighDpiMode.SystemAware);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FrmStart());
        }
 private async void Window_Loaded(object sender, RoutedEventArgs e)
 {
     Main.Content = pageChatRender;
     Settings.Default.Upgrade();
     Settings.Default.Save();
     if (!File.Exists("ffmpeg.exe"))
     {
         await FFmpegDownloader.GetLatestVersion(FFmpegVersion.Full);
     }
 }
示例#8
0
 public static void GetPrerequisite()
 {
     // Downloads FFMPEG if it's not already there.
     if (!File.Exists(ffmpegLocation))
     {
         FFmpegDownloader.GetLatestVersion(FFmpegVersion.Official, $@"{Directory.GetCurrentDirectory()}\ressources\");
     }
     // Creates temp folder just in case.
     Directory.CreateDirectory(Path.GetDirectoryName(concatFileLocation));
 }
示例#9
0
        public MusicManager()
        {
            _ytClient = new YoutubeClient();

            FFmpegDownloader.GetLatestVersion(FFmpegVersion.Official).Wait();

            if (Directory.Exists(_tmpDir))
            {
                Directory.Delete(_tmpDir, true);
            }
        }
示例#10
0
        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Main.Content = pageVodDownload;
            Settings.Default.Upgrade();
            Settings.Default.Save();
            if (!File.Exists("ffmpeg.exe"))
            {
                await FFmpegDownloader.GetLatestVersion(FFmpegVersion.Full);
            }

            AutoUpdater.Start("https://downloader-update.twitcharchives.workers.dev");
        }
示例#11
0
        private async void CheckFFmpeg()
        {
            if (!File.Exists("ffmpeg.exe") || !File.Exists("ffprobe.exe"))
            {
                buttonOpenFile.Enabled = false;
                LogToConsole("FFmpeg doesn't exist.");
                LogToConsole("Downloading FFmpeg...");
                await FFmpegDownloader.GetLatestVersion(FFmpegVersion.Official);

                LogToConsole("FFmpeg downloaded.");
                buttonOpenFile.Enabled = true;
            }
        }
示例#12
0
        private static async Task <int> Main(string[] args)
        {
            Flags = CommandLineFlags.ParseFlags <SubSplitFlags>(args);

            if (Flags == null)
            {
                return(1);
            }

            if (!File.Exists(Flags.InputFile))
            {
                Logger.Error("Program", "Input file does not exist");
                return(4);
            }

            Logger.Info("Program", "Downloading ffmpeg");

            await FFmpegDownloader.GetLatestVersion(FFmpegVersion.Official);

            var probe = await FFmpeg.GetMediaInfo(Flags.InputFile);

            if (probe == null)
            {
                Logger.Error("FFmpeg", "Can't probe media file");
                return(2);
            }

            if (!File.Exists(Flags.PrimarySubtitleFile))
            {
                Logger.Error("Program", "Subtitle file missing");
                return(5);
            }

            var subtitles = SubtitleFile.GetSubtitles(await File.ReadAllLinesAsync(Flags.PrimarySubtitleFile), out var subtitleLeadIn);

            if (!File.Exists(Flags.OverrideSubtitleFile))
            {
                if (!string.IsNullOrEmpty(Flags.OverrideSubtitleFile))
                {
                    Logger.Warn("Program", "Override Subtitle File does not exist");
                }
            }
            else
            {
                subtitles = SubtitleFile.GetSubtitles(await File.ReadAllLinesAsync(Flags.OverrideSubtitleFile), out subtitleLeadIn).Select((t, index) => subtitles.ElementAt(index) with
                {
                    Text         = t.Text,
                    OriginalText = t.OriginalText
                }).ToList();
示例#13
0
        internal static async Task Run()
        {
            Console.Out.WriteLine("[Start] Basic Conversion");
            FileInfo fileToConvert = GetFilesToConvert(".").First();

            //Set directory where app should look for FFmpeg executables.
            FFmpeg.SetExecutablesPath(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "FFmpeg"));
            //Get latest version of FFmpeg. It's great idea if you don't know if you had installed FFmpe1g.
            await FFmpegDownloader.GetLatestVersion(FFmpegVersion.Official);

            //Run conversion
            await RunConversion(fileToConvert);

            Console.Out.WriteLine("[End] Basic Conversion");
        }
示例#14
0
        public async Task Intitialize()
        {
            var location = GetDirectory();

            Log.Information("Initialize FFmpeg with location: {Location}", location);
            if (_options.AutoDownload)
            {
                Log.Information("FFmpeg GetLatestVersion");
                await FFmpegDownloader.GetLatestVersion(
                    FFmpegVersion.Official,
                    location);
            }

            FFmpeg.SetExecutablesPath(location);
        }
示例#15
0
        public override async Task Initialize()
        {
            //download ffmpeg here
            string tempFFmpegFolder = Path.Combine(Path.GetTempPath(), "ffmpeg");

            if (!Directory.Exists(tempFFmpegFolder))
            {
                Directory.CreateDirectory(tempFFmpegFolder);
                Console.WriteLine($"Created directory {tempFFmpegFolder}");
            }

            FFmpeg.SetExecutablesPath(tempFFmpegFolder);

            await FFmpegDownloader.GetLatestVersion(FFmpegVersion.Official, FFmpeg.ExecutablesPath, this);
        }
示例#16
0
        internal static async Task Run()
        {
            Console.Out.WriteLine("[Start] Basic Conversion");
            FileInfo fileToConvert = GetFilesToConvert(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)).First();

            //Set directory where app should look for FFmpeg executables.
            FFmpeg.SetExecutablesPath(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));
            //Get latest version of FFmpeg. It's great idea if you don't know if you had installed FFmpeg.
            await FFmpegDownloader.GetLatestVersion(FFmpegVersion.Official);

            //Run conversion
            await RunConversion(fileToConvert);

            Console.Out.WriteLine("[End] Basic Conversion");
        }
        public VideoHelper()
        {
            InitializeComponent();
            info = new Info(pictureBox1.Width, pictureBox1.Height);


            this.labelBgmVolume.DataBindings.Add("Text", trackBarBgm, "Value");
            this.labelPersonVolume.DataBindings.Add("Text", trackBarPerson, "Value");
            this.labelEndTime.DataBindings.Add("Text", trackBarEndTime, "Value");
            this.labelBeginTime.DataBindings.Add("Text", trackBarBeginTime, "Value");
            this.trackBarEndTime.DataBindings.Add("Minimum", trackBarBeginTime, "Value");
            this.trackBarEndTime.DataBindings.Add("Maximum", trackBarBeginTime, "Maximum");
            this.textBoxThickness.DataBindings.Add("Text", info, "thickness");
            this.textBoxScale.DataBindings.Add("Text", info, "scale");
            this.trackBarBeginTime.DataBindings.Add("Value", info, "BeginTime");
            this.trackBarEndTime.DataBindings.Add("Value", info, "EndTime");
            this.textBoxSubtitlePositionX.DataBindings.Add("Text", info, "X");
            this.textBoxSubtitlePositionY.DataBindings.Add("Text", info, "Y");
            this.pictureBox1.BackColor = Color.Black;
            this.labelSub.MouseDown   += new MouseEventHandler(labelSub_MouseDown);
            this.labelSub.MouseMove   += new MouseEventHandler(labelSub_MouseMove);
            this.labelSub.MouseUp     += new MouseEventHandler(labelSub_MouseUp);
            //this.labelSub.Parent = pictureBox1;
            pictureBox1.Image = info.bmp;
            pictureBox1.Controls.Add(labelSub);
            this.labelSub.BackColor                  = Color.White;
            modeVideoToolStripMenuItem.Checked       = true;
            importAudioFileToolStripMenuItem.Enabled = false;
            this.labelSub.Location = new Point(0, 0);
            if (File.Exists(info.mixed))
            {
                System.IO.File.Delete(info.mixed);
            }
            if (File.Exists(info.bgmTemp))
            {
                System.IO.File.Delete(info.bgmTemp);
            }
            if (File.Exists(info.speechTemp))
            {
                System.IO.File.Delete(info.speechTemp);
            }
            if (!File.Exists("ffmpeg.exe"))
            {
                FFmpegDownloader.GetLatestVersion(FFmpegVersion.Full);
            }
        }
示例#18
0
        public async Task GenerateVideosAsync(CancellationToken cancellationToken)
        {
            await FFmpegDownloader.GetLatestVersion(FFmpegVersion.Official);

            List <Store.Media> videos = await _storeContext.Medias.AsQueryable()
                                        .Where(x => x.MediaType == Store.MediaType.Video)
                                        .ToListAsync(cancellationToken);

            var todo = videos.Count;

            var videoPreview = @"H:\Drive\Moments\System\VideoPreview";

            foreach (Store.Media video in videos)
            {
                todo--;

                var filename = _mediaBlobStore.GetFilename(new MediaBlobData
                {
                    Directory = video.Folder,
                    Filename  = video.Filename,
                    Type      = MediaBlobType.Media
                });

                try
                {
                    var outfile = Path.Combine(videoPreview, $"720P_{video.Id}.mp4");

                    if (!File.Exists(outfile))
                    {
                        var inputLength = new FileInfo(filename).Length / 1024 / 1024;

                        await _videoProcessing.ConvertTo720Async(filename, outfile, cancellationToken);

                        Console.WriteLine($"{todo} - Video created: {Path.GetFileName(outfile)}");

                        var outLength = new FileInfo(outfile).Length / 1024 / 1024;

                        Console.WriteLine($"{inputLength} --> {outLength} (-{100.0 / inputLength * outLength}%)");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error in Media: {video.Id}. --> {ex.Message}");
                }
            }
        }
示例#19
0
        public static async Task Run()
        {
            Console.Out.WriteLine("[Start] Modify streams");

            Queue <FileInfo> filesToConvert = new Queue <FileInfo>(GetFilesToConvert(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)));
            await Console.Out.WriteLineAsync($"Find {filesToConvert.Count()} files to convert.");

            //Set directory where app should look for FFmpeg executables.
            FFmpeg.SetExecutablesPath(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "FFmpeg"));
            //Get latest version of FFmpeg. It's great idea if you don't know if you had installed FFmpe1g.
            await FFmpegDownloader.GetLatestVersion(FFmpegVersion.Official);

            //Run conversion
            await RunConversion(filesToConvert);

            Console.Out.WriteLine("[End] Modify streams");
        }
示例#20
0
        static void Main()
        {
            Display.title          = "Ascier";
            Display.dynamicRefresh = true;
            Display.start();

            string[] directories = { "input", "output", "ffmpeg" };

            for (int i = 0; i < directories.Length; i++)
            {
                if (!Directory.Exists($"{Directory.GetCurrentDirectory()}/{directories[i]}"))
                {
                    Program.Logger.info($"The following directory has not been found.");
                    Program.Logger.info($"{Directory.GetCurrentDirectory()}/{directories[i]}");

                    Directory.CreateDirectory(directories[i]);

                    Program.Logger.info($"{directories[i]} directory has been created.");
                }
                else
                {
                    Program.Logger.info($"{directories[i]} directory has been found.");
                }
            }

            Display.forceRedraw();

            var status = FFmpegDownloader.GetLatestVersion(FFmpegVersion.Official, $"{Directory.GetCurrentDirectory()}/ffmpeg");

            if (!status.IsCompleted)
            {
                Program.Logger.info("Downloading FFMPEG library for video conversion.");
                while (!status.IsCompleted)
                {
                    ;
                }
                Program.Logger.info("Done.");
            }
            else
            {
                Program.Logger.info("ffmpeg has been found.");
            }
        }
示例#21
0
        internal async Task FullProcessPassed()
        {
            var operatingSystemProvider = Substitute.For <IOperatingSystemProvider>();

            operatingSystemProvider.GetOperatingSystem().Returns(x => OperatingSystem.Linux64);
            FFmpegDownloader._linkProvider = new LinkProvider(operatingSystemProvider);
            var ffmpegExecutablesPath = FFmpeg.ExecutablesPath;

            try
            {
                FFmpeg.ExecutablesPath = Path.Combine(Path.GetTempPath(), System.Guid.NewGuid().ToString("N"));

                await FFmpegDownloader.GetLatestVersion();

                Assert.True(File.Exists(Path.Combine(FFmpeg.ExecutablesPath, "ffmpeg")));
                Assert.True(File.Exists(Path.Combine(FFmpeg.ExecutablesPath, "ffprobe")));
            }
            finally
            {
                FFmpeg.ExecutablesPath = ffmpegExecutablesPath;
            }
        }
示例#22
0
        private static async Task ExtractAudio(string path, MediaType.MediaCodec codec)
        {
            var currentFolder = Directory.GetCurrentDirectory();
            var ffmpegPath    = $"{currentFolder}/FFmpeg";

            FFmpeg.SetExecutablesPath(ffmpegPath, "FFmpeg");
            await FFmpegDownloader.GetLatestVersion(FFmpegVersion.Official, ffmpegPath);

            FileInfo fi         = new FileInfo(path);
            string   inputPath  = fi.FullName;
            string   outputPath = Path.ChangeExtension(inputPath, codec.ToString());

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

            var conversion = await FFmpeg.Conversions.FromSnippet.ExtractAudio(inputPath, outputPath);

            await conversion.Start();

            await Task.Delay(500);
        }
示例#23
0
        private static async Task GenerateThumbnailDuration(long vodId)
        {
            Logger _logger = new NLog.LogFactory().GetCurrentClassLogger();

            try {
                await FFmpegDownloader.GetLatestVersion(FFmpegVersion.Official);
            } catch (NotImplementedException) {
                _logger.Warn("OS not supported. Skipping thumbnail generation.");
                return;
            }

            Stream stream;

            using (var context = new MainDataContext()) {
                stream = context.Streams.FirstOrDefault(item => item.streamId == vodId);

                if (stream != null)
                {
                    stream.duration = FFmpeg.GetMediaInfo(GlobalConfig.GetGlobalConfig("contentRootPath") + stream.location + stream.fileName).Result
                                      .Duration
                                      .Seconds;
                }

                context.SaveChanges();
            }

            if (stream != null)
            {
                Task <IMediaInfo> streamFile =
                    FFmpeg.GetMediaInfo(Path.Combine(GlobalConfig.GetGlobalConfig("contentRootPath"), stream.location, stream.fileName));
                var conversion = await FFmpeg.Conversions.New()
                                 .AddStream(streamFile.Result.Streams.FirstOrDefault())
                                 .AddParameter("-vframes 1 -s 320x180")
                                 .SetOutput(Path.Combine(GlobalConfig.GetGlobalConfig("contentRootPath"), stream.location, "thumbnail.jpg"))
                                 .Start();
            }
        }
示例#24
0
        public async Task <string> ConvertMp4ToMp3AndGetMp3Path(string mp4Path)
        {
            if (!File.Exists(mp4Path))
            {
                throw new FileNotFoundException($"MP4 was not found at the specified path {mp4Path}. Audio conversion failed.");
            }

            var executablePath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
            await FFmpegDownloader.GetLatestVersion(FFmpegVersion.Official, executablePath);

            FFmpeg.SetExecutablesPath(executablePath);

            var mp3Path = mp4Path.Replace(".mp4", ".mp3");

            await(await FFmpeg.Conversions.FromSnippet.Convert(mp4Path, mp3Path))
            .SetOutputFormat(Format.mp3)
            .SetOverwriteOutput(true)
            .AddParameter("-qscale:a 0")
            .Start();

            File.Delete(mp4Path);

            return(mp3Path);
        }
示例#25
0
 private async static Task DownloadFFmpegExecutables(string destinationPath)
 {
     await FFmpegDownloader.GetLatestVersion(FFmpegVersion.Full, destinationPath);
 }
示例#26
0
        async void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            totalbytes     = 0;
            collectedbytes = 0;
            string audiomp4  = "Audio.mp4";
            string Audiomp3  = "Audio.mp3";
            string VideoFile = "Video.mp4";

            Status.Text = "Checking tools";

            async Task SourceDownloader(string name, YouTubeVideo vid)
            {
                var  client    = new HttpClient();
                long?totalByte = 0;

                using (Stream output = File.OpenWrite(name))
                {
                    using (var request = new HttpRequestMessage(HttpMethod.Head, vid.Uri))
                    {
                        totalByte = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).Result.Content.Headers.ContentLength;
                    }
                    totalbytes += (long)totalByte;
                    using (var input = await client.GetStreamAsync(vid.Uri))
                    {
                        byte[] buffer = new byte[16 * 1024];
                        int    read;
                        int    totalRead = 0;

                        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            output.Write(buffer, 0, read);
                            totalRead      += read;
                            collectedbytes += read;
                            long x = collectedbytes * 100 / totalbytes;
                            Dataprogress.Text = bytetobigger(collectedbytes) + "/" + bytetobigger(totalbytes);
                            progressBar1.Invoke((MethodInvoker)(() => progressBar1.Value = (int)x));
                        }
                    }
                }
                client.Dispose();
            }

            await FFmpegDownloader.GetLatestVersion(FFmpegVersion.Full);

            async Task DownloadWork(string link, int playlist = -1)
            {
                if (playlist < 0)
                {
                    Status.Text = "Downloading ..";
                }
                else
                {
                    Status.Text = (playlist + 1).ToString() + "/" + listVidsIds.Count.ToString();
                }
                var video       = youTube.GetAllVideos(link);
                var Targetaudio = video.Where(j => j.AdaptiveKind == AdaptiveKind.Audio && j.AudioBitrate.ToString() == selectedAudioQuality).Select(j => j);
                var TargetVideo = video.Where(j => j.AdaptiveKind == AdaptiveKind.Video && j.Format == VideoFormat.Mp4 && j.Resolution.ToString() == selectedVideoQality).Select(j => j);

                VidTitle.Invoke((MethodInvoker)(() => VidTitle.Text = video.ToList()[0].Title));
                Task au = SourceDownloader(audiomp4, Targetaudio.ToList()[0]);

                if (SoundOnly.Checked != true)
                {
                    Task  vide = SourceDownloader(VideoFile, TargetVideo.ToList()[0]);
                    await au;
                    FFMpeg.ExtractAudio(audiomp4, Audiomp3);
                    fileDelete(audiomp4);
                    await vide;
                    FFMpeg.ReplaceAudio(VideoFile, Audiomp3, FilePath.Text + TargetVideo.ToList()[0].FullName);
                    fileDelete(VideoFile);
                    fileDelete(Audiomp3);
                }
                else
                {
                    await au;
                    FFMpeg.ExtractAudio(audiomp4, FilePath.Text + TargetVideo.ToList()[0].Title + ".mp3");
                    fileDelete(audiomp4);
                }

                if (playlist < 0)
                {
                    Status.Text = "Done. ";
                }
                else
                {
                    Status.Text = "Done (" + (playlist + 1).ToString() + "/" + listVidsIds.Count.ToString() + ")";
                }
                Dataprogress.Text = "";
            }

            if (listVidsIds.Count > 0)
            {
                for (int i = 0; i < listVidsIds.Count; i++)
                {
                    await DownloadWork(watchLink + listVidsIds.ElementAt(i), i);
                }
            }
            else
            {
                await DownloadWork(videoLink.Text);
            }
        }
示例#27
0
        static async void RunConversion(string inPath, string outPath)
        {
            //Set directory where app should look for FFmpeg
            //FFmpeg.SetExecutablesPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "FFmpeg");
            FFmpeg.SetExecutablesPath(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "FFmpeg"));
            //Get latest version of FFmpeg. It's great idea if you don't know if you had installed FFmpeg.
            FFmpegDownloader.GetLatestVersion(FFmpegVersion.Official);

            Queue         filesToConvert = new Queue();
            DirectoryInfo di             = new DirectoryInfo(inPath);

            foreach (FileInfo file in di.GetFiles())
            {
                if (file.Extension == ".mp3")
                {
                    filesToConvert.Enqueue(file);
                }
            }
            await Console.Out.WriteLineAsync($"Find {filesToConvert.Count} files to convert.");

            //string filePath = Path.Combine("C:", "samples", "SampleVideo.mp4");
            //string inputMp3Path = Path.Combine("E:", "bai1.mp3");
            //IMediaInfo mediaInfo = await FFmpeg.GetMediaInfo(inputMp3Path);

            //while (filesToConvert.(out FileInfo fileToConvert))
            foreach (FileInfo fileToConvert in filesToConvert)
            {
                Console.WriteLine("1");
                //Save file to the same location with changed extension
                //string outputFileName = Path.ChangeExtension(fileToConvert.FullName, ".mp4");
                IMediaInfo mediaInfo = await FFmpeg.GetMediaInfo(fileToConvert.DirectoryName);

                //var mediaInfo = await MediaInfo.Get(fileToConvert);
                //var videoStream = mediaInfo.VideoStreams.First();
                var audioStream = mediaInfo.AudioStreams.First();

                audioStream.SetBitrate(8000)
                .SetChannels(1)
                .SetSampleRate(24000)
                .SetCodec(AudioCodec.mp3);
                ////Change some parameters of video stream
                ////videoStream
                ////    Rotate video counter clockwise
                ////    .Rotate(RotateDegrees.CounterClockwise)
                ////    Set size to 480p
                ////    .SetSize(VideoSize.Hd480)
                ////    Set codec which will be used to encode file.If not set it's set automatically according to output file extension
                ////   .SetCodec(VideoCodec.H264);

                //Create new conversion object
                var conversion = FFmpeg.Conversions.New()
                                 //Add audio stream to output file
                                 .AddStream(audioStream)
                                 //Set output file path
                                 .SetOutput(outPath)
                                 //SetOverwriteOutput to overwrite files. It's useful when we already run application before
                                 .SetOverwriteOutput(true)
                                 //Disable multithreading
                                 .UseMultiThread(false)
                                 //Set conversion preset. You have to chose between file size and quality of video and duration of conversion
                                 .SetPreset(ConversionPreset.UltraFast);

                //Add log to OnProgress
                //conversion.OnProgress += async (sender, args) =>
                //{
                //    //Show all output from FFmpeg to console
                //    await Console.Out.WriteLineAsync($"[{args.Duration}/{args.TotalLength}][{args.Percent}%] {fileToConvert.Name}");
                //};
                //Start conversion
                conversion.Start();

                Console.WriteLine($"Finished converion file [{fileToConvert.Name}]");
            }
        }
 public PresentationService(IVideoService videoService)
 {
     _videoService = videoService;
     FFmpegDownloader.GetLatestVersion(FFmpegVersion.Full).GetAwaiter().GetResult();
 }
示例#29
0
        internal async Task FullProcessPassed()
        {
            const OperatingSystem os = OperatingSystem.Linux64;

            var operatingSystemProvider = Substitute.For <IOperatingSystemProvider>();

            operatingSystemProvider.GetOperatingSystem().Returns(x => os);
            FFmpegDownloader._linkProvider = new LinkProvider(operatingSystemProvider);
            var ffmpegExecutablesPath = FFmpeg.ExecutablesPath;

            try
            {
                FFmpeg.ExecutablesPath = Path.Combine(Path.GetTempPath(), System.Guid.NewGuid().ToString("N"));

                string ffmpegPath  = FFmpegDownloader.ComputeFileDestinationPath("ffmpeg", os);
                string ffprobePath = FFmpegDownloader.ComputeFileDestinationPath("ffprobe", os);

                // 1- First download

                await FFmpegDownloader.GetLatestVersion().ConfigureAwait(false);

                Assert.True(File.Exists(ffmpegPath));
                Assert.True(File.Exists(ffprobePath));

                // 2- Check updates (same version)

                await FFmpegDownloader.GetLatestVersion().ConfigureAwait(false);

                Assert.True(File.Exists(ffmpegPath));
                Assert.True(File.Exists(ffprobePath));

                // 3- Check updates (outdated version)

                var fFbinariesVersionInfo = new FFbinariesVersionInfo
                {
                    Version = new Version().ToString() // "0.0"
                };
                FFmpegDownloader.SaveVersion(fFbinariesVersionInfo);

                await FFmpegDownloader.GetLatestVersion().ConfigureAwait(false);

                Assert.True(File.Exists(ffmpegPath));
                Assert.True(File.Exists(ffprobePath));

                // 4- Missing ffmpeg

                File.Delete(ffmpegPath);

                await FFmpegDownloader.GetLatestVersion().ConfigureAwait(false);

                Assert.True(File.Exists(ffmpegPath));
                Assert.True(File.Exists(ffprobePath));

                // 5- Missing ffprobe

                File.Delete(ffprobePath);

                await FFmpegDownloader.GetLatestVersion().ConfigureAwait(false);

                Assert.True(File.Exists(ffmpegPath));
                Assert.True(File.Exists(ffprobePath));
            }
            finally
            {
                FFmpeg.ExecutablesPath = ffmpegExecutablesPath;
            }
        }
        private async void bGo_Click(object sender, RoutedEventArgs e)
        {
            textStatus.Text = "Preparing";
            gridMain.Dispatcher.Invoke(new Action(() => { }), DispatcherPriority.Render);
            var    downloader = new YoutubeDL();
            string fileName   = "";

            downloader.VideoUrl = tbLink.Text;
            downloader.Options.FilesystemOptions.NoMtime = true;
            //downloader.Options.VideoFormatOptions.Format = NYoutubeDL.Helpers.Enums.VideoFormat.best;
            downloader.Options.VerbositySimulationOptions.CallHome = false;
            downloader.Options.GeneralOptions.Update = true;
            //downloader.Options.VideoFormatOptions.FormatAdvanced =
            string videoTitleNoFilter = downloader.GetDownloadInfo().Title;
            string videoTitle         = Regex.Replace(videoTitleNoFilter, @"[^a-z,0-9, ,-]", "", RegexOptions.IgnoreCase);
            Random random             = new Random();
            int    randomInt          = random.Next(1, 1000);

            downloader.Options.FilesystemOptions.Output = filePath + $"\\video{randomInt}";
            if (cboxCut.IsChecked == false && cboxConvert.IsChecked == false)
            {
                downloader.Options.FilesystemOptions.Output = filePath + $"\\{videoTitle}";
            }
            downloader.YoutubeDlPath = runningPath + "\\youtube-dl.exe";
            if (rbBest.IsChecked == true)
            {
                downloader.Options.VideoFormatOptions.FormatAdvanced = "best";
            }
            else
            {
                downloader.Options.VideoFormatOptions.FormatAdvanced = "worst";
            }
            if (cboxResolution.Text != "Auto")
            {
                downloader.Options.VideoFormatOptions.FormatAdvanced += $"[height <=? {Int32.Parse(cboxResolution.Text.TrimEnd('p'))}]";
            }

            textStatus.Text = "Downloading";
            downloader.DownloadAsync();
            while (downloader.IsDownloading)
            {
                pbProgress.Value = downloader.Info.VideoProgress;
                textETA.Text     = "ETA: " + downloader.Info.Eta;
                textSpeed.Text   = "Speed: " + downloader.Info.DownloadRate;
                gridMain.Dispatcher.Invoke(new Action(() => { }), DispatcherPriority.Render);
            }
            pbProgress.Value = 0;
            textETA.Text     = "ETA: ?";
            textSpeed.Text   = "Speed: ?";
            gridMain.Dispatcher.Invoke(new Action(() => { }), DispatcherPriority.Render);
            foreach (string file in Directory.GetFiles(filePath))
            {
                if (Path.GetFileName(file).StartsWith($"video{randomInt}"))
                {
                    fileName = file;
                }
            }

            if (cboxCut.IsChecked == true || cboxConvert.IsChecked == true)
            {
                pbProgress.IsIndeterminate = true;
                textStatus.Text            = "Getting FFmpeg";
                gridMain.Dispatcher.Invoke(new Action(() => { }), DispatcherPriority.Render);
                if (!File.Exists(runningPath + "\\ffmpeg.exe"))
                {
                    await FFmpegDownloader.GetLatestVersion(FFmpegVersion.Full, runningPath);
                }
                textStatus.Text = "Processing";
                gridMain.Dispatcher.Invoke(new Action(() => { }), DispatcherPriority.Render);
                var conversions = FFmpeg.Conversions.New();
                if (cboxCut.IsChecked == true)
                {
                    conversions.AddParameter($"-ss {TimeSpan.FromSeconds(Int32.Parse(tbFrom.Text))}");
                }
                conversions.AddParameter($"-i \"{fileName}\"");
                if (cboxConvert.IsChecked == true)
                {
                    conversions.SetOutput($"{filePath}\\{videoTitle}{cbConvertType.Text}");
                }
                else
                {
                    conversions.SetOutput($"{filePath}\\{videoTitle}{Path.GetExtension(fileName)}");
                }
                if (cboxCut.IsChecked == true)
                {
                    conversions.AddParameter($"-to {TimeSpan.FromSeconds(Int32.Parse(tbTo.Text) - Int32.Parse(tbFrom.Text))}");
                }

                /*
                 * if (cboxConvert.IsChecked == true && cboxCut.IsChecked == false)
                 *  await conversions.AddParameter($"-i \"{fileName}\" \"{filePath}\\{videoTitle}{cbConvertType.Text}\"").Start();
                 * if (cboxConvert.IsChecked == true && cboxCut.IsChecked == true)
                 *  await conversions.AddParameter($"-ss {TimeSpan.FromSeconds(Int32.Parse(tbFrom.Text))} -i \"{fileName}\" -to {TimeSpan.FromSeconds(Int32.Parse(tbTo.Text) - Int32.Parse(tbFrom.Text))} -c copy \"{filePath + $"\\{videoTitle}{cbConvertType.Text}"}\"").Start();
                 * if (cboxConvert.IsChecked == false && cboxCut.IsChecked == true)
                 *  await conversions.AddParameter($"-ss {TimeSpan.FromSeconds(Int32.Parse(tbFrom.Text))} -i \"{fileName}\" -to {TimeSpan.FromSeconds(Int32.Parse(tbTo.Text) - Int32.Parse(tbFrom.Text))} -c copy \"{filePath + $"\\{videoTitle}{Path.GetExtension(fileName)}"}\"").Start();*/
                await conversions.Start();

                File.Delete(fileName);
                pbProgress.IsIndeterminate = false;
            }
            textStatus.Text = "Idle";
        }