cmxl / ffmpeg.net Goto Github PK
View Code? Open in Web Editor NEW.NET wrapper for common ffmpeg tasks
License: MIT License
.NET wrapper for common ffmpeg tasks
License: MIT License
Using default ConversionOptions instance (since using null throws a null reference exception), using valid source path, using valid target path. GetThumbnailAsync executes without errors but the target file is not created.
Given a crop and resize applied to a 640x480 video:
var conversionOptions = new ConversionOptions
{
CustomHeight = 100,
CustomWidth = 100,
SourceCrop = new CropRectangle {Width = 480, Height = 480}
};
await engine.GetThumbnailAsync(mediaFile, outputFile, conversionOptions)
I would expect both the crop and the resize would be applied.
But only the crop is applied.
I suspect this is because the above results in:
ffmpeg.exe -y -ss 1.0 -i input.mov -vframes 1 -filter:v "crop=480:4809::" -vf "scale=100:100" output.jpg
Rather than:
ffmpeg.exe -y -ss 1.0 -i input.mov -vframes 1 -filter:v "crop=480:4809::, scale=100:100" output.jpg
With the filters appended together, see https://stackoverflow.com/questions/22523006/how-to-use-filter-and-vf-command-on-ffmpeg
Supports custom FFmpeg command line arguments - NO!
There are still missing many tests for this library.
Any contribution is very welcome.
Tests are implemented via XUnit which is included in the dotnet sdk by default.
You can run tests via cmd:
dotnet test tests\FFmpeg.NET.Tests\FFmpeg.NET.Tests.csproj
Or just open the Testexplorer in Visual Studio 2017 / 2019:
Tests -> Windows -> Test Explorer
You should see all implemented tests after rebuilding the project.
Hello:
I have made one small mp4 video with duration of only 1 second, it was made of many images. And I want to make one big mp4 video with duration of 1 minute, I think I can repeat the 1 second video 60 times, to make one minute mp4 video.
And I tried the following ffmpeg command directly in my PC (Windows 10), it works:
C:\Videos>ffmpeg -stream_loop 60 -i Second1.mp4 -c copy Minute1.mp4
I want to know how I can do the same using this repo?
Thanks,
Hello,
Could you update sound volume option with FFmpeg.NET wrapper ?
I would like to down or up the audio volume or convert a file with no audio.
For volume, The FFmpeg command is like this :
" -af "volume=-5dB" " (here it decrease for -5db)
For no audio, The FFmpeg command is like this :
" -an "
Thanks for your help.
Great work
hello i try follow up the code with "Subscribe to events" tutorial everything fine only the "TotalDuration", While convert the video file it always show 00:00:00
Hello i want to use this inside my Youtube Downloader to add an Audio Track to a Video so they could download with highest resolution + audio. How to do this? (without mixing, the audio should be a seperate track if opening the video in Vegas or similar)
I need more information how to use the wrapper in more different situations. For example I want to convert every frame from a video to a single picture. As a workaround i use the ffmpeg direct with the process.start("ffmpeg"," -i inputfile.mp4 -o output.bmp") (macOS) but I know this procedure works on windows, too. Thank you.
Hello:
I want to see if I can use this repo to cut one video (mp4 format).
I created one C# WinForms project (target .NET 5.0), add nuget package:
Install-Package xFFmpeg.NET -Version 6.0.0
The following is my C# code:
using FFmpeg.NET;
using System.IO;
public static async Task FFMPEG_Cut_Video1(string input_file1, string output_file1)
{
try
{
if (!File.Exists(input_file1))
{
Debug.Print("Input video not found, quit!");
return "FileNOTFound";
}
MediaFile video_in = new(input_file1);
MediaFile video_out = new(output_file1);
Engine ffmpeg = new(FFMPEG_Engine);
ConversionOptions options = new();
options.CutMedia(TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(25));
await ffmpeg.ConvertAsync((InputFile)video_in, (OutputFile)video_out, options);
}
catch (InvalidCastException ex)
{
Debug.Print(ex.Message);
}
return "Cut_OK";
}
private async void Form1_Load(object sender, EventArgs e)
{
await FFMPEG_Cut_Video1("C:\Videos\1.mp4", "C:\Videos\cut1.mp4");
}
However, when I run my code, I got the following error:
System.InvalidCastException
HResult=0x80004002
Message=Unable to cast object of type 'FFmpeg.NET.MediaFile' to type 'FFmpeg.NET.InputFile'.
Source=System.Private.CoreLib
StackTrace:
at System.Runtime.CompilerServices.CastHelpers.ChkCast_Helper(Void* toTypeHnd, Object obj)
at System.Runtime.CompilerServices.CastHelpers.ChkCastClassSpecial(Void* toTypeHnd, Object obj)
at B20VideoSeekerSportRadarForm.Form1.<FFMPEG_Cut_Video1>d__7.MoveNext() in C:\Videos\VideoCut\Form1.cs:line 89
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at B20VideoSeekerSportRadarForm.Form1.<Form1_Load>d__8.MoveNext() in C:\Videos\VideoCut\Form1.cs:line 97
This exception was originally thrown at this call stack:
B20VideoSeekerSportRadarForm.Form1.FFMPEG_Cut_Video1(string, string) in Form1.cs
[External Code]
B20VideoSeekerSportRadarForm.Form1.Form1_Load(object, System.EventArgs) in Form1.cs
Please advise how I can fix this?
Using ffmpeg command, I can cut the video file, but I would like to use API in my C# program.
PS: I am using Windows 10 (Version 21H1), and Visual Studio 2019 (Version 16.10.4)
Thanks,
If I pass a CancellationToken to ConvertAsync (for example), and then call Cancel() on the Token, the ffmpegnet library throws an exception with the message "A task was cancelled". That is good. However, the ffmpeg.exe process is not cancelled, and it continues to run in the background to completion, which can of course take a long time and consume large resources depending on the task.
I suggest that the library should catch the cancel exception, and abort the ffmpeg.exe process, and then rethrow the exception or throw one of your own exceptions. I believe you can abort the ffmpeg.exe process by sending "q" to the input stream of the process. This is better than just killing the process because "q" will leave the output file in a valid state.
Currently, FFmpeg.NET is parsing durations from metadata using TryParse
without specifying an IFormatProvider
. On machines with a non-default locale (e.g. having comma as a decimal separator), this will lead to a mismatch with FFmpeg which still uses the universal dot as a separator. Instead, we should use CultureInfo.InvariantCulture
. Will open a pull request for this.
Hi.
After build project I get below warning:
Severity Code Description Project File Line Suppression State
Warning Found conflicts between different versions of "System.ValueTuple" that could not be resolved. These reference conflicts are listed in the build log when log verbosity is set to detailed.
Project runs, but how solve this?
NET Framework 4.6.1Unable to install
Severity Code Description Item File Line Prohibited display status
Error The package "xFFmpeg.NET 7.0.1" could not be installed. You are trying to install this package into a project whose target is ".NETFramework, Version=v4.6.1", but the package does not contain any assembly references or content files that are compatible with the framework. For more information, please contact the package author.
You should update the code samples on the main page, because MediaFile is now an abstract class and can't be used directly.
var inputFile = new InputFile (@"C:\Path\To_Video.flv");
var outputFile = new OutputFile (@"C:\Path\To_Save_Image.jpg");
etc.
Currently the library does support for only local file. Please add new method ConvertAsync
that accepts URL as string.
Unless there is a good reason to have the thread SynchronizationContext
preserved, all of your await ...
calls throughout the library should have .ConfigureAwait(false)
appended.
Not having this causes deadlocks when having to call your library in a synchronous manner such as:
var meta = ffmpeg.GetMetaDataAsync(input).GetAwaiter().GetResult();
Obviously you would ideally not call it this way using .GetAwaiter().GetResult()
and instead use async+await 'all the way down'. But sometimes this is not an option.
Can I save thumbnail in MemoryStream?
Hello:
I have downloaded quite a number of videos, all the videos are in M3U8 format, and I have saved them as MP4 format videos.
But I found that almost all the videos, their starting time is not 0.
For example, I have one video file (C:\Videos\1.mp4), its duration is 2 hours, but when I used VLC player to play this mp4 video file, I can see that the starting time is: 01:00:00, and ending time is: 03:00:00. It has actual duration of 2 hours, but not from 00:00:00 to 02:00:00.
Can I use the repo to convert this mp4 video using the same format (not changing other parameter), but change the starting time to 00:00:00 and ending time to its duration?
If yes, please let me know where I can find code sample (C#) to do this?
Thanks,
I'm getting the following exit code: -1073741515. I downloaded ffmpeg from the link on https://ffmpeg.org/download.html and extracted ffmpeg.exe from the bin directory to a local directory. My thoughts are that windows security gets in the way of write permissions for the app, but that's just a guess. Any insights you might have on this would be greatly appreciated. Generating .mp4 thumbnails by hand sucks! :-(
Best regards,
John Carnegie
[email protected]
mobil: 972 567 1422
Code:
public async Task HowToAsync(string file, string thumb)
{
var inputFile = new MediaFile(file);
var outputFile = new MediaFile(thumb);
var ffmpeg = new Engine(@"C:<path>\64bit\ffmpeg.exe"); //path excluded
ffmpeg.Error += OnError;
// Saves the frame located on the 5th second of the video.
var options = new ConversionOptions { Seek = TimeSpan.FromSeconds(5) };
var result = await ffmpeg.GetThumbnailAsync(inputFile, outputFile, options);
return thumb; // code incomplete
}
private void OnError(object sender, ConversionErrorEventArgs e)
{
Console.WriteLine("[{0} => {1}]: Error: {2}\n{3}", e.Input.FileInfo.Name, e.Output.FileInfo.Name, e.Exception.ExitCode, e.Exception.InnerException);
}
hi ,Tobias Haimerl . how to use in linux ?
Hello how exactly can i use custom arguments?
i was doing await ffmpeg.ExecuteAsync(args) where args are arguments which normally work when writing them in concole after ffmpeg.exe
When i start it just does nothing. Also if i write a total nonsene argument, it does not throw an error or something, it just does nothing :/
Hi,
I am trying to convert a file from .webm format to .gif using streams. I have been testing and the engine works fine if I use files. However, if I use streams, the engine freezes when I call the ConvertAsync function, no event or error is raised in the process. Here is the code that I am using.
I am using the version 7.1.3
Engine ffmpeg = new Engine();
ffmpeg.Progress += OnProgress;
ffmpeg.Data += OnData;
ffmpeg.Error += OnError;
ffmpeg.Complete += OnComplete;
var options = new ConversionOptions
{
ExtraArguments = "-f gif -vf \"fps=30,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse\" -loop 0 -y"
};
InputFile input = new InputFile("https://statics.memondo.com/p/99/gifs/2010/12/GIF_8818_745f4adf060a4d08bf83f77d6ac899d5_taconazo_magico.webm");
Stream stream = await ffmpeg.ConvertAsync(input, options, default);
In my application I converted movie from 3gp to mp4. 3gp movie is recorded on mobile phone and it is tall and narrow like screen of mobile phone.
After convertion the movie is tall but isn't narrow, it's wide. The resolution in both cases is 1920x1680
My code looks like that:
```
var conversionOptions = new ConversionOptions
{
MaxVideoDuration = TimeSpan.FromSeconds(60),
VideoAspectRatio = VideoAspectRatio.R16_9,
VideoSize = VideoSize.Hd1080,
AudioSampleRate = AudioSampleRate.Hz44100,
// CustomWidth = 200
};
await ffmpeg.ConvertAsync(inputFile, outputFileMp4, conversionOptions);
How to keep shape of the movie to be like from mobile phone?
I am processing audio files that are 6 days long. When I call GetMetaDataAsync
, the duration is returned as zero. Also I do not get Progress
events after 24 hours of audio have been processed.
This happens because the code uses TimeSpan.TryParse
to parse the duration string that is output by ffmpeg. TimeSpan.TryParse
does not handle hours that are greater than 23 (it expects days). Ffmpeg however produces a duration in h:mm:ss.fff
format where the hours field can grow as large as necessary.
Is there a way to make use of NVENC with this wrapper without having to switch to executeasync.
I'm fond of being able to attach event handlers to report progress as this is running on a server for me. But without setting custom attributes using execute I can't see a way to switch to NVENC encoding.
Is this possible?
Would it be possible to use this for Desktop Capture on Windows?
the demo command is "ffmpeg -f dshow -i video="screen-capture-recorder" output.mkv"
Edit: "-f dshow -i video="screen-capture-recorder" output.mkv" does not work since I don't have "screen-capture-recorder" installed. There was no error thrown though.
"-f gdigrab -framerate 30 -i desktop output.mkv" Does work but I am not sure how to stop it.
Hello:
I am now using Visual Studio 2022, and I want to test the sample code for WinFrom project using the latest version (7.0.1)
PM> Install-Package xFFmpeg.NET -Version 7.0.1
var inputFile = new MediaFile (@"C:\Path\To_Video.flv");
var outputFile = new MediaFile (@"C:\Path\To_Save_ExtractedVideo.flv");
var ffmpeg = new Engine("C:\ffmpeg\ffmpeg.exe");
var options = new ConversionOptions();
// This example will create a 25 second video, starting from the
// 30th second of the original video.
//// First parameter requests the starting frame to cut the media from.
//// Second parameter requests how long to cut the video.
options.CutMedia(TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(25));
await ffmpeg.ConvertAsync(inputFile, outputFile, options);
But I got compiler error:
Error CS1503 Argument 1: cannot convert from 'FFmpeg.NET.MediaFile' to 'FFmpeg.NET.InputFile'
Error CS1503 Argument 2: cannot convert from 'FFmpeg.NET.MediaFile' to 'FFmpeg.NET.OutputFile'
Error CS1503 Argument 3: cannot convert from 'FFmpeg.NET.ConversionOptions' to 'System.Threading.CancellationToken'
It seems the new version 7.0.1 is rather different from previous version, at least for the code examples.
Please advise on how to fix it!
Thanks,
When specifying conversion options, FFmpeg.NET allows me to do something like the following:
var conversionOptions = new ConversionOptions()
{
AudioBitRate = Encoding.AudioBitrate,
RemoveAudio = Encoding.EnableAudio,
VideoBitRate = Encoding.VideoBitrate,
VideoFormat = FFmpeg.NET.Enums.VideoFormat.webm,
VideoSize = FFmpeg.NET.Enums.VideoSize.Custom
};
My assumption is that the VideoSize
property is what controls how big or small the output file's size will be, as there's no docstring specifying the behavior. There's an enum for VideoSize
that allows us to declare a custom size, but I don't know how I can specify it outside of providing it via ExtraArguments
.
When ffmpeg.exe reports an error (via a non-zero exit code) , this library raises the Error event twice with the same message.
Hello! I want to deploy my app on Ubuntu, but i need to set engine path to Engine type. How i can use this in ubuntu? Can you help me, please
I have observed that occasionally Engine.GetMetaDataAsync()
is returning null
. I can replicate this in a test, running this method a number of times in parallel for different mp4 files.
I was previously sharing the same Engine
instance but am observing the same behaviour when creating an instance per invocation.
Is this method not thread-safe? Or is the actual issue that the underlying FFMpeg executable itself isn't thread-safe? I'm using the latest official Windows build; configuration below:
ffmpeg version 4.1.3 Copyright (c) 2000-2019 the FFmpeg developers
built with gcc 8.3.1 (GCC) 20190414
configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth
I am using FFmpeg.NET version 3.3.1.
Hi, I want to use this repository in my a project via Nuget xFFmpeg.NET, but it don't supported .NET Core 3.1.
Can you include .NET Core 3.1 verion into the nuget package, please.
I want to change the quality of the video but when I try and use the:
var conversionOptions = new ConversionOptions {
VideoCodec = VideoCodec.nvenc_h264,
HWAccel = HWAccel.cuda,
VideoFps = fps,
VideoBitRate = bitrateValue,
VideoSize = VideoSize.Hd720
};
the resulting video is corrupted, ive tried removing the a few of the option and it seems that VideoSize is making the issue. how can I fix that?
Attempting to set the ConversionOptions VideoFormat to VideoCodec.libvpx__vp9 results in FFMpeg being called with the argument libvpx__vp9
instead of libvpx-vp9
, which FFMpeg rejects as an unknown codec.
As a temporary workaround I'm leaving the VideoCodec unspecified and passing ExtraArguments = "-c:v libvpx-vp9"
When I'm using GetMetadataAsync, it turns out the output/error streams are not flushed before we mark the task as completed. In my case this means the library only receives the first FFmpeg result line, which just contains the header. The fix seems relatively easy - I added process.WaitForExit();
in the process.Exited += ...
handler which forces the streams to be flushed. Putting the call there should be safe since we know the process itself is already finished. I'll open a pull request for this issue too.
If not, how do I need to expand?
Heelo,
Last update (v.3.3.3) seems not to update the e.ProcessedDuration.TotalSeconds value
The e.fps works.
Thanks a lot for your help.
Hi,
I would like to be able to cut video (using ConvertAsync) but with lossless codec (-codec copy).
I know I can use prepare the full, custom path and call ExecuteAsync but it would be nice ConvertAsync also supports custom parameters (or at least codec specification). Or maybe it is possible already somehow?
greetings
Bartek
I am converting files from webm to mp3's and i can't quite figure out how to get the overall progress of the process to display in a progress bar.
I have subscribed to the progress event and thats about how far i got.
How would i properly get the overall progress?
I am writing a program to split a large audio file into smaller segments. I use the ExecuteAsync
method and pass the -f segment
and -segment_time
options in the arguments parameter. This works, but I do not get any Progress
events from ffmpeg.net.
The problem is that ffmpeg produces a minimal progress data line when using the segment option. In this configuration, the progress data lines look like this:
size=N/A time=00:11:00.11 bitrate=N/A speed=1.32e+03x
The "N/A" values confuse the parser in ffmpeg.net, and it does not see these as valid progress lines.
I am able to work around the problem by subscribing to the Data
event and performing my own parsing to check for progress lines. But it would be nice if ffmpeg could handle these lines and produce Progress
events itself.
try
{
var inputFile = new MediaFile(path);
var ffmpeg = new FFmpeg.NET.Engine.FFmpeg();
var data = ffmpeg.GetMetaData(inputFile); /// here it is, no exception catched application just not continue indefinetelly
duration = data.Duration;
} catch( Exception ex)
{
Debug.WriteLine(ex);
}
My project is developed by.net 4.0, now nuget cannot be used, install-package xffmpegnet-version 3.4.0 cannot be installed。
ERROR:
The severity code indicates that the project file line forbids display status
The warning failed to resolve the main reference "netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51", Because it is the framework assemblies "System. Diagnostics. Tracing, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = b03f5f7f11d50a3a" indirect dependencies, and in the frame of the current target failed to resolve the assembly. ". NETFramework, Version = v4.0 ". To resolve this issue, remove references to "netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51", Or the application of the goal to contain "System. Diagnostics. Tracing, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = b03f5f7f11d50a3a" framework Version. FFmpegDemo
I want to convert wave file to 128Kbps, i can add new enum in AudioSampleRate as Hz4000, so that it will compress the file size and convert it to 128Kbs, but my question is this library support in Linux server.
I am following a posted example to generate poster frame for an mp4 video of 50 megabytes in size (without using direct reference to ffmpeg executable).
I am using ffmpeg 4.3.1. and this is the only installed version.
var inputFile = new MediaFile (@"C:\Path\To_Video.flv");
var outputFile = new MediaFile (@"C:\Path\To_Save_Image.jpg");
var ffmpeg = new Engine();
// Saves the frame located on the 15th second of the video.
var options = new ConversionOptions { Seek = TimeSpan.FromSeconds(15) };
await ffmpeg.GetThumbnailAsync(inputFile, outputFile, options);
The above code results into infinite loop somewhere in ffmpeg on the last line.
At the same time command below works perfectly, so ffmpeg should not be an issue.
ffmpeg -ss 00:00:05.01 -i random.mp4 -frames:v 1 myimage.jpg
By any chance does anyone have an idea what I might be doing wrong?
Is this a library-related issue or an issue related to ffmpeg executable?
Hi @yagotome. Great library! Is it possible to set the thumbnail size when you call this?
var options = new ConversionOptions { Seek = TimeSpan.FromSeconds(15) };
await ffmpeg.GetThumbnailAsync(inputFile, outputFile, options);
Thanks.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.