public Startup(IConfiguration configuration) { Configuration = configuration; FFMpegOptions.Configure(new FFMpegOptions { RootDirectory = "./ffmpeg/bin", TempDirectory = "./tmp" }); }
static void Main(string[] args) { Console.WriteLine("Welcome to EASY ANIMATION COMPOSER"); if (args.Length > 0) { ConsoleMode = true; } if (ConsoleMode) { RunConsole(args); } else { Console.WriteLine("You can also run program with arguments: eacomposer [name] [path-to-dir-with-images] [FPS]"); args = new string[3]; Console.WriteLine("Write project name: "); args[0] = Console.ReadLine(); Console.WriteLine("Write directory name: "); args[1] = Console.ReadLine(); Console.WriteLine("Write FPS (15 by default): "); string tmp = Console.ReadLine(); if (string.IsNullOrEmpty(tmp)) { args[2] = "15"; } else { args[2] = tmp; } RunConsole(args); } fps += fps / 10; FFMpegOptions.Configure(new FFMpegOptions { RootDirectory = AppContext.BaseDirectory + @"\bin" }); Console.WriteLine($"Working on project {name}"); Console.WriteLine($"Step 1: Add images ({img_paths.Capacity})"); ImageInfo[] frames = new ImageInfo[img_paths.Capacity]; for (int i = 0; i < img_paths.Capacity; i++) { Console.Write('.'); frames[i] = new ImageInfo(img_paths[i]); } path += "/" + name + ".mp4"; if (File.Exists(path)) { new FileInfo(path).Delete(); } Console.WriteLine(); Console.WriteLine($"Step 2: Creating video on path {path}"); FFMpeg encoder = new FFMpeg(); encoder.JoinImageSequence(new FileInfo(path), fps, frames); Console.WriteLine($"Finished!"); encoder.Dispose(); }
public async Task Produce(IBoundedQueue <MutableByteImage> sourceQueue) { try { if (!string.IsNullOrWhiteSpace(_arguments.PathToFfmpeg)) { FFMpegOptions.Configure(new FFMpegOptions { RootDirectory = _arguments.PathToFfmpeg }); } var result = await FFProbe.AnalyseAsync(_arguments.InputFile).ConfigureAwait(false); var width = result.PrimaryVideoStream.Width; var height = result.PrimaryVideoStream.Height; var bpp = Image.GetPixelFormatSize(System.Drawing.Imaging.PixelFormat.Format24bppRgb) / 8; var pixelsPerFrame = width * height; var frameSizeInBytes = pixelsPerFrame * bpp; _logger.WriteLine("Input from ffmpeg currently only supports rgb24-convertable input", Verbosity.Warning); var chunksQueue = BoundedQueueFactory.Get <byte[]>(4, "In-ChuQ"); using var memoryStream = new ChunkedSimpleMemoryStream(frameSizeInBytes, chunksQueue); // new MemoryStream(frameSizeInBytes); StreamPipeSink sink = new StreamPipeSink(memoryStream); var args = FFMpegArguments .FromFileInput(_arguments.InputFile).OutputToPipe(sink, options => options.DisableChannel(FFMpegCore.Enums.Channel.Audio) .UsingMultithreading(true) .ForceFormat("rawvideo") .WithCustomArgument(_arguments.CustomArgs ?? string.Empty) .ForcePixelFormat("bgr24")) .NotifyOnProgress( percent => _logger.NotifyFillstate(Convert.ToInt32(percent), "InputVideoParsing"), TimeSpan.FromSeconds(1)); var produceTask = args.ProcessAsynchronously(true).ContinueWith((_) => { chunksQueue.CompleteAdding(); sourceQueue.CompleteAdding(); }); var consumeTask = ParseInputStream(sourceQueue, chunksQueue, width, height, memoryStream) .ContinueWith((_) => _logger.WriteLine("finished reading", Verbosity.Info)); await Task.WhenAll(produceTask, consumeTask); _logger.WriteLine("finished reading", Verbosity.Info); } catch (System.ComponentModel.Win32Exception) { _logger.WriteLine("Couldn't find ffmpeg", Verbosity.Error); } catch (Exception e) { _logger.LogException(e); } }
public void FFMpegStartup() { var CurrentDirectory = Environment.CurrentDirectory; var rootDirectory = Path.Combine(CurrentDirectory, "lib"); FFMpegOptions.Configure(new FFMpegOptions { RootDirectory = rootDirectory }); }
public MainWindow() { string y = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location))); string ff = y + @"\FFMPEG\bin\"; string[] files = Directory.GetFiles(y, "*.exe", SearchOption.AllDirectories); List <string> ls = new List <string>(); foreach (var item in files) { if (Path.GetFileName(item).Equals("ffmpeg.exe")) { ff = Path.GetDirectoryName(item); } } try { //FFMpegOptions.Configure(new FFMpegOptions { RootDirectory = y +@"\FFMPEG\bin\" }); FFMpegOptions.Configure(new FFMpegOptions { RootDirectory = ff }); encoder = new FFMpeg(); } catch (FFMpegCore.FFMPEG.Exceptions.FFMpegException) { FFMpegOptions.Configure(new FFMpegOptions { RootDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\FFMPEG\bin\" }); encoder = new FFMpeg(); } Console.WriteLine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\FFMPEG\bin\"); InitializeComponent(); files = Directory.GetFiles(y, "*.dll", SearchOption.AllDirectories); ls = new List <string>(); foreach (string s in files) { string ss = Path.GetFileName(s); if (ss.Equals("ffms2.dll") || ss.Equals("ImageSeq.dll") || ss.Equals("VSFilterMod.dll")) { ls.Add(s); } } //Builder.SetPlugins(new string[]{ //y+@"\FFMPEG\Plugins\ffms2.dll", //y+@"\FFMPEG\Plugins\ImageSeq.dll", //y+@"\FFMPEG\Plugins\VSFilterMod.dll" //}); Builder.SetPlugins(ls.ToArray()); }
public void Video_OutputsData() { var outputFile = new TemporaryFile("out.mp4"); var dataReceived = false; FFMpegOptions.Configure(opt => opt.Encoding = Encoding.UTF8); var success = FFMpegArguments .FromFileInput(TestResources.Mp4Video) .WithGlobalOptions(options => options .WithVerbosityLevel(VerbosityLevel.Info)) .OutputToFile(outputFile, false, opt => opt .WithDuration(TimeSpan.FromSeconds(2))) .NotifyOnOutput((_, _) => dataReceived = true) .ProcessSynchronously(); Assert.IsTrue(dataReceived); Assert.IsTrue(success); Assert.IsTrue(File.Exists(outputFile)); }
public void Options_Overrided() { var original = FFMpegOptions.Options; try { FFMpegOptions.Configure(new FFMpegOptions { RootDirectory = "Whatever" }); Assert.AreEqual( FFMpegOptions.Options.RootDirectory, "Whatever" ); } finally { FFMpegOptions.Configure(original); } }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { AddOptions <EmailOptions>(services); AddOptions <SessionOptions>(services); AddOptions <FileStorageOptions>(services); FFMpegOptions.Configure(new FFMpegOptions { RootDirectory = "" }); services.AddSwaggerGen(c => c.SwaggerDoc("v1", new OpenApiInfo { Title = "Memester API", Version = "v1" })); HangfireContext.EnsureCreated(_configuration.GetConnectionString("HangfirePgsql")); ConfigureHangfire(GlobalConfiguration.Configuration); services.AddHangfire(ConfigureHangfire); services.AddHangfireServer(options => { options.WorkerCount = Math.Min(Environment.ProcessorCount * 2 - 1, 16); options.Queues = JobQueues.All; }); services.AddMvc().AddJsonOptions(options => ConfigureJsonSerializer(options.JsonSerializerOptions)); services.AddDbContext <DatabaseContext>(options => options.UseNpgsql(_configuration.GetConnectionString("Pgsql"), b => b.MigrationsAssembly(typeof(DatabaseContext).Assembly.FullName))); services.AddScoped(typeof(OperationContext), _ => new OperationContext()); services.AddScoped(typeof(IHttpSessionService), typeof(CookieSessionService)); services.AddScoped(typeof(ScrapingService)); services.AddScoped(typeof(IndexingService)); services.AddScoped(typeof(FileStorageService)); services.AddScoped(typeof(AuthenticationService)); services.AddSingleton(typeof(IEmailService), typeof(MailkitEmailService)); services.AddSingleton(typeof(SessionService)); services.AddSingleton(typeof(Random)); services.AddTransient <IAsyncInitialized, FileStorageService>(); // services.AddTransient<IAsyncInitialized, DatabaseContext>(); }
private void ConverterV2(FileDesc file) { FFMpegOptions.Configure(new FFMpegOptions { RootDirectory = @"D:\Git\RocketMov\RocketMov\ffmpeg" }); var fileInfo = FFProbe.Analyse(file.PathIn); FFMpegArguments .FromFileInput(file.PathIn) .OutputToFile(file.PathOut, true, options => options .WithVideoCodec(VideoCodec.LibX264) .WithConstantRateFactor(21) .WithAudioCodec(AudioCodec.Aac) .WithVideoBitrate(_convertOptions.Bitrate) .WithFastStart() .Scale(_convertOptions.Width, _convertOptions.Height) .UsingThreads(4)) .NotifyOnProgress(onConvertProgress, fileInfo.Duration) .CancellableThrough(out _cancelConvertion) .ProcessSynchronously(); }
static void Main(string[] args) { FFMpegOptions.Configure(new FFMpegOptions { RootDirectory = ".\\ffmpeg\\bin" }); var url = args[0]; Console.WriteLine($"Загрузка вебинара по ссылке: {url}"); var streamUrl = GetStreamUrl(url); Console.WriteLine($"Получили ссылку на стрим: {streamUrl}"); var videoFileListUrl = GetVideoFileListUrl(streamUrl); Console.WriteLine($"Получили ссылку на плейлист: {streamUrl}"); var fileName = args[1]; var encoder = new FFMpeg(); Console.WriteLine($"Начало записи вебинара в файл: {fileName}"); var fileInfo = new FileInfo(fileName); var videoInfo = encoder.SaveM3U8Stream(new Uri(videoFileListUrl), fileInfo); Console.WriteLine($"Вебинар сохранен, размер файла: {fileInfo.Length}, формат: {videoInfo.VideoFormat}"); }
private void YesButton_Click(object sender, RoutedEventArgs e) { //user wants an audio copy, create the copy and close the window once done. var inputFile = fileName; var outputFile = fileName + ".mp3"; audioProgress.Maximum = 100; //set FFMpegCore Binary FFMpegOptions.Configure(new FFMpegOptions { RootDirectory = "C:\\Program Files (x86)\\FFMPEG\\bin" }); FFMpeg ffmpeg = new FFMpeg(); ffmpeg.OnProgress += (percentage) => audioProgress.Value = percentage; Thread converter = new Thread(new ThreadStart(() => ffmpeg.ExtractAudio(VideoInfo.FromPath(inputFile), new FileInfo(outputFile)))); converter.Start(); //done, go back. NavigationService.GoBack(); }
private async void button3_Click(object sender, EventArgs e) { if (encoder != null && encoder.IsWorking) { MessageBox.Show("Ya estás procesando uno o más videos, espera que se termine el proceso actual o abórtalo para iniciar un nuevo trabajo", "Información", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } int alto = 720, ancho = 1280; if (resolucion720.Checked) { alto = 720; ancho = 1280; } if (resolucion1080.Checked) { alto = 1080; ancho = 1920; } if (resolucion4K.Checked) { alto = 2160; ancho = 3840; } if (ffmpegPath != null && ffmpegPath != "") { FFMpegOptions.Configure(new FFMpegOptions { RootDirectory = Path.GetDirectoryName(ffmpegPath) }); encoder = new FFMpeg(); var AudioQuality = FFMpegCore.FFMPEG.Enums.AudioQuality.Hd; //Attacheo el listener encoder.OnProgress += OnProgress2; textProgressBar4.Value = 0; foreach (String ruta in listBox1.Items) { try { textProgressBar3.Value = 0; await Task.Run(() => { //ffmpeg -i VID_20200202_163129.mp4 -c:v libx264 -b:v 8M -minrate 8M -preset medium -vf scale=1280:720 -c:a aac -b:a 192K VID_20200202_163129_converted.mp4 var container = new ArgumentContainer { new InputArgument(new VideoInfo(ruta)), new VideoCodecArgument(FFMpegCore.FFMPEG.Enums.VideoCodec.LibX264, 8000), new SpeedArgument(FFMpegCore.FFMPEG.Enums.Speed.Medium), new ScaleArgument(ancho, alto), new AudioCodecArgument(FFMpegCore.FFMPEG.Enums.AudioCodec.Aac, FFMpegCore.FFMPEG.Enums.AudioQuality.Normal), new ThreadsArgument(0), new OutputArgument(new FileInfo(textBox1.Text + "\\" + Path.GetFileNameWithoutExtension(ruta) + "_convertido.mp4")) }; encoder.Convert(container); }); textProgressBar4.Value++; } catch (Exception ex) { } } } else { MessageBox.Show("Debes indicar la ruta al ejecutable de ffmpeg", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public async Task Produce(ConcurrentQueue <MutableByteImage> queue) { try { FFMpegOptions.Configure(new FFMpegOptions { RootDirectory = _arguments.PathToFfmpeg }); var result = await FFProbe.AnalyseAsync(_arguments.InputFiles.First()).ConfigureAwait(false); var width = result.PrimaryVideoStream.Width; var height = result.PrimaryVideoStream.Height; var bpp = Image.GetPixelFormatSize(System.Drawing.Imaging.PixelFormat.Format24bppRgb) / 8; var pixelsPerFrame = width * height; var frameSizeInBytes = pixelsPerFrame * bpp; _logger.WriteLine("Input from ffmpeg currently only supports rgb24-convertable input", Verbosity.Warning); var chunksQueue = new ConcurrentQueue <byte[]>(); using var memoryStream = new ChunkedMemoryStream(frameSizeInBytes, chunksQueue); // new MemoryStream(frameSizeInBytes); StreamPipeSink sink = new StreamPipeSink(memoryStream); var args = FFMpegArguments .FromInputFiles(_arguments.InputFiles) .UsingMultithreading(true) .ForceFormat("rawvideo") .ForcePixelFormat("bgr24") .OutputToPipe(sink) .NotifyOnProgress( percent => _logger.NotifyFillstate(Convert.ToInt32(percent), "InputVideoParsing"), TimeSpan.FromSeconds(1)); var produceTask = args.ProcessAsynchronously(true).ContinueWith((_) => parsingFinished.Cancel()); var consumeTask = ParseInputStream(queue, chunksQueue, width, height, frameSizeInBytes, memoryStream); await Task.WhenAll(produceTask, consumeTask); // await Task.WhenAny(produceTask, consumeTask).ConfigureAwait(false); } catch (Exception e) { } async Task ParseInputStream(ConcurrentQueue <MutableByteImage> queue, ConcurrentQueue <byte[]> chunksQueue, int width, int height, int frameSizeInBytes, ChunkedMemoryStream memoryStream) { int count = 0; while (true) //while ((memoryStream.HasUnwrittenData || chunksQueue.Count > 0) && !parsingFinished.IsCancellationRequested) { try { var foo = await chunksQueue.TryDequeueOrWait(parsingFinished); if (foo.cancelled) { break; } _logger.NotifyFillstate(++count, "ParsedImages"); _logger.NotifyFillstate(chunksQueue.Count, "ChunkedQueue"); queue.Enqueue(_factory.FromBytes(width, height, foo.item)); } catch (Exception e) { _logger.LogException(e); } await queue.WaitForBufferSpace(24); } Console.WriteLine(memoryStream.HasUnwrittenData); } }