FFmpegDotNet 9.9.4
dotnet add package FFmpegDotNet --version 9.9.4
NuGet\Install-Package FFmpegDotNet -Version 9.9.4
<PackageReference Include="FFmpegDotNet" Version="9.9.4" />
<PackageVersion Include="FFmpegDotNet" Version="9.9.4" />
<PackageReference Include="FFmpegDotNet" />
paket add FFmpegDotNet --version 9.9.4
#r "nuget: FFmpegDotNet, 9.9.4"
#:package FFmpegDotNet@9.9.4
#addin nuget:?package=FFmpegDotNet&version=9.9.4
#tool nuget:?package=FFmpegDotNet&version=9.9.4
FFmpeg (.NET Wrapper)
A .NET wrapper library for FFmpeg, built on top of FFmpeg.AutoGen. It provides a managed, object-oriented interface to FFmpeg's C API, making it easier and safer to use FFmpeg from .NET applications, without giving up direct access to the underlying API when you need it.
📚 API Documentation 🧪 Sample Projects
Table of Contents
Overview
FFmpeg is a powerful open-source multimedia framework for handling video, audio, and streams. FFmpeg.AutoGen exposes FFmpeg's native C API to .NET, but using it directly means working with raw pointers and unsafe memory operations.
FFmpeg (.NET Wrapper) builds a high-level, managed abstraction on top of FFmpeg.AutoGen, so you can access FFmpeg's encoding, decoding, transcoding, and streaming capabilities safely from C#, with automatic resource cleanup and idiomatic .NET types.
Getting Started
Prerequisites
- A .NET Standard 2.1–compatible runtime (.NET Core 3.1+, .NET 5+, .NET 6+, Mono, etc.)
- FFmpeg binaries available on your system path (or bundled via NuGet — see Installation)
Supported FFmpeg Versions
FFmpeg 9.0+ ("Lei")
| Library | Version |
|---|---|
| avcodec | 63 |
| avdevice | 63 |
| avfilter | 12 |
| avformat | 63 |
| avutil | 61 |
| swresample | 7 |
| swscale | 10 |
Installation
Install the wrapper from NuGet:
dotnet add package FFmpegDotNet
If you don't already have FFmpeg installed on your system, the FFmpegDotNet.bin.winx64 package bundles the LGPL FFmpeg binaries for Windows x64:
dotnet add package FFmpegDotNet.bin.winx64
Loading FFmpeg Libraries
The FFmpeg namespace includes a static helper class, FFmpegLoader, responsible for locating and initializing the native FFmpeg libraries before use. If Initialize() is not called manually, the library automatically attempts to locate the FFmpeg binaries using the default search order below.
Default search order:
- Current directory (
./) ./ffmpeg/- Platform-specific subdirectories (e.g.
./ffmpeg/win-x64,./ffmpeg/linux-arm64) - The system
PATHenvironment variable
If no suitable library is found, initialization fails and FFmpeg functions become unavailable. You can also point Initialize() at a specific directory if your binaries live somewhere non-standard:
FFmpegLoader.Initialize(@"C:\tools\ffmpeg\bin");
Quick Start
A minimal example using the high-level API to remux a file (copy streams into a new container without re-encoding):
using FFmpeg;
using FFmpeg.Formats;
using FFmpeg.Utils;
FFmpegLoader.Initialize();
using MediaSource src = MediaSource.Open("input.mp4");
using MediaSink dst = MediaSink.Create("output.mkv")!;
// Copy all streams as-is (no decoding/encoding involved).
foreach (var stream in src.Streams)
dst.AddStream(stream);
using AVPacket packet = AVPacket.Allocate();
AVResult32 result;
while (!(result = src.ReadPacket(packet)).IsError)
{
dst.WritePacket(packet).ThrowIfError();
}
if (result != AVResult32.EndOfFile)
result.ThrowIfError();
dst.WriteTrailer().ThrowIfError();
Transcoding
Transcoder drives the whole decode → filter → encode → mux loop, like the ffmpeg command line tool with -vf/-af filters:
using FFmpeg;
using FFmpeg.Codecs;
using FFmpeg.Utils;
FFmpegLoader.Initialize();
using Transcoder transcoder = Transcoder.Create("input.mkv", "output.mp4");
transcoder.CopyStream(transcoder.FindBestInputStream(MediaType.Audio)); // -c:a copy
transcoder.TranscodeStream(transcoder.FindBestInputStream(MediaType.Video), // -c:v mpeg4 -vf scale=1280:-2 -b:v 4M
CodecID.MPEG4,
filter: "scale=1280:-2",
configure: encoder => encoder.BitRate = 4_000_000);
transcoder.Start = TimeSpan.FromSeconds(10); // -ss 10 (before -i)
transcoder.Duration = TimeSpan.FromMinutes(1); // -t 60
transcoder.ProgressChanged += (_, progress) => Console.WriteLine(progress);
await transcoder.RunAsync();
A filter can be a description string, a factory that is called with a FilterGraphContext (input stream and current frame format) whenever the graph is built — e.g. ctx => $"scale={ctx.Width / 2}:-2", or one returning a FilterGraph object — or a FilterGraph object itself. Prefer strings or factories: a configured graph cannot be reset, so when the input format changes mid-stream the graph is built again, and a graph object can then only be recreated with FilterGraph.Copy(), which keeps just the filters' options. Encoder properties you don't set (size, pixel/sample format, sample rate, channel layout, time base) are taken from the filtered frames; the ones you set are enforced by the filter graph. Re-encoded streams are trimmed frame-exactly, copied streams start at the keyframe before Start, as with ffmpeg. For a frame-level pipeline of your own, see the Filters example, which uses CodecContext, FilterGraph and MediaSink directly.
For finer control over decoding, filtering, or encoding, see the high-level abstractions below or browse the example projects.
Important Classes
The FFmpeg namespace provides managed wrapper classes around FFmpeg's core C structs and APIs. These classes simplify interacting with FFmpeg by handling resource management, initialization, and data conversion automatically.
Core Low-Level Wrappers
These classes map directly to FFmpeg's internal structures and are typically used when building advanced or custom media pipelines.
| Class | Description |
|---|---|
FFmpeg.Formats.FormatContext |
Wraps AVFormatContext. Handles input/output container formats, stream information, and demuxing/muxing. |
FFmpeg.Codecs.CodecContext |
Wraps AVCodecContext. Manages codecs for encoding and decoding audio/video streams. |
FFmpeg.Utils.AVPacket |
Wraps AVPacket. Represents encoded data (compressed frames or packets). |
FFmpeg.Utils.AVFrame |
Wraps AVFrame. Represents decoded, uncompressed media frames in memory. |
FFmpeg.Filters.FilterGraph |
Wraps AVFilterGraph. Provides access to FFmpeg's filter system (resizing, color correction, etc.). |
FFmpeg.Images.SwsContext |
Wraps SwsContext. Handles image scaling and pixel format conversion via libswscale. |
FFmpeg.Audio.SwrContext |
Wraps SwrContext. Handles audio resampling, format conversion, and channel layout adjustments via libswresample. |
Note: These classes closely follow FFmpeg's internal lifecycle patterns and implement
IDisposable. Always dispose them (or wrap them in ausingstatement) when no longer needed to avoid leaking native resources.
High-Level Abstractions
If your goal is simply to read, decode, encode, or transcode media, use these instead of managing FormatContext and CodecContext directly.
| Class | Description |
|---|---|
MediaSource |
Simplifies reading and decoding frames from a file or stream. Handles demuxing and decoding internally. |
MediaSink |
Simplifies encoding and writing frames to a file or stream. Handles muxing and encoding internally. |
Transcoder |
Reads from a MediaSource and writes to a MediaSink, copying, re-encoding or filtering each stream (simple filter graphs as with ffmpeg -vf/-af), with exact Start/Duration trimming, progress events and preview frames. See Transcoding. |
These abstractions are ideal for typical scenarios such as:
- Extracting frames from a video
- Re-encoding media to a different format
- Streaming or piping decoded frames to other components
Examples
Complete sample applications are available in the FFmpeg.Examples repository, ranging from low-level API usage to the higher-level abstractions provided by FFmpegDotNet. Each project is intentionally small and focused, demonstrating a single feature or workflow:
- Opening media files with
DemuxerContext - Decoding audio and video streams
- Reading and writing media containers
- Audio resampling with
SwrContext - Image scaling and pixel format conversion with
SwsContext - Using
MediaSourcefor simplified decoding - Encoding
- Filters
- A simple video player
Contributing
Contributions, bug reports, and feature requests are welcome. Please open an issue or pull request on GitHub.
License
This project is licensed under the LGPL-2.1 License. FFmpeg itself is licensed separately under the LGPL/GPL — see the FFmpeg legal page for details on which license applies to your build.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. net11.0 is compatible. |
| .NET Core | netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.1 is compatible. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.1
- FFmpegDotNet._AutoGen (>= 9.0.1.1 && < 10.0.0)
- System.Runtime.CompilerServices.Unsafe (>= 6.1.2)
-
net10.0
- FFmpegDotNet._AutoGen (>= 9.0.1.1 && < 10.0.0)
-
net11.0
- FFmpegDotNet._AutoGen (>= 9.0.1.1 && < 10.0.0)
-
net8.0
- FFmpegDotNet._AutoGen (>= 9.0.1.1 && < 10.0.0)
-
net9.0
- FFmpegDotNet._AutoGen (>= 9.0.1.1 && < 10.0.0)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on FFmpegDotNet:
| Package | Downloads |
|---|---|
|
FFmpegDotNet.Skia
Provides SkiaSharp integration for the FFmpeg .NET wrapper (FFmpegDotNet). Converts FFmpeg AVFrames to SKImage or SKBitmap and back, with crop, color space (YUV matrix, range, HDR) and alpha handling, and includes high-level classes (FFCodec2Skia, SKVideo, SKAnimatedImage) for decoding and rendering videos and animated images with Skia. The package version starts with the FFmpeg major version: 8.x for FFmpegDotNet 8 (FFmpeg 8.1), 9.x for FFmpegDotNet 9 (FFmpeg 9.0). |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 9.9.4 | 153 | 11/19/2026 |
| 9.9.3.1 | 92 | 11/19/2026 |
| 9.9.3 | 89 | 11/19/2026 |
| 9.9.2 | 87 | 11/19/2026 |
| 9.9.1 | 89 | 11/19/2026 |
| 9.9.0.2 | 92 | 11/18/2026 |
| 9.9.0.1 | 234 | 9/3/2026 |
| 9.9.0 | 145 | 9/2/2026 |
| 8.1.2.15 | 135 | 11/19/2026 |
| 8.1.2.14 | 86 | 11/18/2026 |
| 8.1.2.13 | 153 | 9/2/2026 |
| 8.1.2.12 | 138 | 9/1/2026 |
| 8.1.2.11 | 199 | 8/16/2026 |
| 8.1.2.10 | 134 | 8/16/2026 |
| 8.1.2.9 | 143 | 8/15/2026 |
| 8.1.2.8 | 176 | 8/14/2026 |
| 8.1.2.6 | 163 | 7/30/2026 |
| 8.1.2.5 | 144 | 7/28/2026 |
| 8.1.2.4 | 148 | 7/26/2026 |
| 8.1.2.3 | 154 | 7/25/2026 |
FFmpeg 9.0.1 - "Lei"
Version numbering scheme changed: FFMpegMajor.Major.Minor.Patch
--- 9.9.4.0 ---
Codecs, FFmpeg.Codecs.(Audio|Video|Image) contains multiple standard codecs which help you to create and configure encoders.
--- 9.9.3.1 ---
BugFix: SetOption(string,IDictionary) was changed by Claude to behave like SetOption(IDictionary) and not setting the underlying Dictionary like intended. SetOption(IDictionary) is no obsolet use SetOptions instead.
--- 9.9.3.0 ---
SwsContext uses FFmpeg's current scaling API (sws_scale_frame on a dynamic context): new SwsContext() or new SwsContext(SwsAlgorithm) is not tied to an image size or format, adapts to every frame, image or buffer (ImageInfo) and only sets the conversion up again when they or the settings change.
Frames are converted with their color properties: YUV matrix, range, chroma location, and primaries/transfer function, including HDR to SDR tone mapping when the destination asks for other primaries or transfer. Color properties the destination frame leaves unspecified are taken from the source and written to it, like FFmpeg's scale filter.
Added settings: Scaler, ChromaScaler, ScalerParam1/2, Flags, Algorithm, Threads, Dither, AlphaBlend, GammaCorrect, Intent and Backends, with the enums SwsScaler, SwsDither, SwsAlphaBlend, SwsIntent and SwsBackend, and SwsFlags.Unstable.
Added: Setup (prepare or check a conversion), IsNoOp, IsSupportedInput/IsSupportedOutput and IsSupported for color spaces, primaries, transfer functions and frames; Convert overloads for frames and raw buffers or spans described by an ImageInfo.
BugFix: converting frames without a pixel format aborted the process inside FFmpeg; Convert returns InvalidArgument instead.
SVTAV1 converts with a dynamic context, so its input frames no longer all need the size of the first frame.
Behaviour changes:
Frames tagged with a YUV matrix (e.g. BT.709) are converted with that matrix; the old API always used BT.601. Untagged frames and raw buffers give the same results as before.
The static SwsContext.Convert helpers and Image.ConvertTo use dynamic contexts.
If only one of the frames is marked interlaced, both are scaled as progressive frames, as FFmpeg's scale filter does by default.
A no-op conversion into a frame without a buffer references the source buffers instead of copying them.
Obsolete: the fixed-size constructor (sws_getContext), its Source*/Destination* properties and size helpers, the Convert overloads that rely on the fixed size, CheckContext, and SwsFlags.ErrorDiffusion (use Dither) and DirectBGR (no effect). They keep working on fixed contexts.
--- 9.9.2.0 ---
Typed filters (namespaces Filters.VideoFilters and Filters.AudioFilters) with Allocate/Create and a property for every FFmpeg option; setters throw if FFmpeg rejects the value:
video: Scale, Crop, Pad, Fps, Transpose, HFlip, VFlip, SetSar, SetDar, SetPts, Trim, Yadif, Fade, Overlay; audio: Volume, AResample, ATempo, AMix, ASetPts, ATrim, AFade, LoudNorm.
Quality metrics: Ssim and Psnr, with SsimScore/PsnrScore to read the per-frame scores from the frame metadata and SsimStatistics/PsnrStatistics to compute the averages the way FFmpeg logs them. LibVmaf (needs an FFmpeg built with --enable-libvmaf, see LibVmaf.IsAvailable) with VmafLog to read its XML log.
Added: BufferSrcParameters.AlphaMode/HWFramesContext, VideoBufferSource.SampleAspectRatio (the misspelled PixelAspectRation is obsolete), accepted output formats for VideoBufferSink/AudioBufferSink (Create overloads and Accepted* properties).
BugFix: FilterLink.SourcePadIndex/DestinationPadIndex were wrong (AVFilterPad is opaque in FFmpeg 9), so FilterGraph.Copy broke graphs with filters that have several pads (split, overlay, ...).
BugFix: FilterGraph.Copy dropped the options of buffer sinks and leaked the new graph when it failed; parsing a graph did not initialize the in/out lists; FilterContext.Delete left a dangling pointer.
BugFix: the Transcoder failed and the PlaybackEngine faulted when a filter graph stopped taking input (e.g. trim); the output now ends there and later frames are dropped.
BugFix: SubtitleRect.ToString returned null for bitmap subtitles.
Behaviour changes:
The Create methods of filters throw when the initialization fails and remove the filter from the graph again.
FilterContext.As<T> and the typed filter constructors throw InvalidCastException for a filter of another type.
The PlaybackEngine throws when its filter graph cannot be configured again after a flush.
SubtitleRect.Text and ASS are nullable (they are NULL for bitmap subtitles).
The package no longer depends on System.IO.Pipelines and System.Security.Permissions (both were unused).
--- 9.9.1.0 ---
Transcoder rewritten (breaking change), modelled on MediaSource/MediaSink and the ffmpeg command line tool:
CopyStream, TranscodeStream (encoder, optional simple filter graph as with -vf/-af, configure callback, encoder options) and FilterStream (re-encode with the input codec) map the streams; Run, RunAsync, ProcessNext and Finish drive it.
Filters can be given as a description string, as a factory (Func<FilterGraphContext, string> or FilterGraphFactory) that is called for every build with the input stream and the current frame format, or as an unconfigured FilterGraph object, which is copied (FilterGraph.Copy) for every build and therefore not recommended when the graph may have to be rebuilt.
Each re-encoded audio/video stream runs through its own filter graph; encoder properties that are not set are taken from the filtered frames, the ones that are set (size, frame rate, pixel/sample format, sample rate, channel layout) are enforced. Graphs are rebuilt when the decoded format changes mid-stream.
Start/Duration work like ffmpeg -ss (input) and -t: re-encoded streams are trimmed frame-exactly, copied streams start at the keyframe before Start. Audio decoders get enough preroll after seeking that initial padding no longer cuts into the range.
Subtitles can be copied or re-encoded (with the decoder's subtitle header); chapters inside the range, metadata and dispositions are copied.
ProgressChanged/Position/ExpectedDuration report progress; TryGetPreviewFrame/PreviewFrameUpdated give thread-safe preview frames (the PreviewFrame property was removed). Cancelling Run/RunAsync still finishes a valid output file.
Fixed: scalers/resamplers were recreated for every frame and leaked, packets were mapped 1:1 to frames, encoders were opened before their extradata could reach the muxer header.
Added: CodecContext.SubtitleHeader, AudioBufferSink.SetFrameSize, OptionQueryableBase.IsSetToDefault/TryIsSetToDefault.
PlaybackEngine: SetVideoFilterFactory/SetAudioFilterFactory take the same factories as the Transcoder; they are called again whenever the graph is set up again (after seeking), instead of copying the graph.
BugFix: FilterGraph.Copy (and therefore FilterGraph.Flush and the PlaybackEngine filters) failed for filters with unset options whose text form cannot be parsed back, e.g. aresample ("0 channels").
BugFix: PlaybackEngine threw a NullReferenceException after a filter was removed (SetVideoFilter/SetAudioFilter with null).
BugFix: CodecContext.ChannelLayout was read-only, so the channel layout of an encoder could not be set.
BugFix: MediaSource.CodecContexts threw for inputs with streams without a decoder (data, attachments).
--- 9.9.0.2 ---
Many BugFixes found in a code review (also released for FFmpeg 8 as 8.1.2.14):
IO: custom IOContext callbacks are rooted and no longer let exceptions escape into native code; IOContext/CodecContext can be finalized; use-after-free when opening custom IO failed; IOStreamContext no longer throws on construction; seeking works for seekable IOContexts.
Formats/Codecs: MuxerContext double dispose, NoFile check and time base rescaling; FormatContext.Seekable returns None without an I/O context again; extradata is padded as FFmpeg requires; SendFrame no longer changes an open encoder's time base; encoded subtitle packets use a correct time base; MediaSource keeps its decoders, drains all of them at end of file and SeekExactly ends only for the requested stream; seeks past ~35 minutes and timestamp setters past ~6.6 hours no longer overflow.
Utils: Rational +, - and int * Rational overflow; TimeSpan / Rational saturated; AVPacket leak and Size overrun; AVFrame.GetData/Copy/Size/Clone for bottom-up and audio frames; AVBuffer.ReplaceWith use-after-free; Move/Clone/Reference onto itself emptied the packet; AVResult64.ToString named wrong errors.
Audio: AudioFifo layout conversion and peeks beyond one chunk, pinning of channel spans; SwrContext wrote past the buffer when converting at an offset; AudioBuffer Copy/MakeWriteable shared data through stale plane pointers, planar-to-packed copies were wrong; AudioClock counted time twice after Pause; ChannelLayout.Init kept a freed map after a failure.
Collections: CircularArray.IndexOf/Clear, AVChapter removal keeps its order, SubtitleRect text setters crashed, hardware device/frames context references crashed when empty.
Options: binary options were read from the wrong address; bool in SetOption(name, object); dictionary overloads use av_opt_set_dict2 and remove the entries that were set.
MediaPlayer: VideoBuffer/AudioBuffer lost writes and CanSeek was reversed, AudioBuffer binary search could loop forever, SetBufferSize estimate, Stop state.
Misc: SVTAV1.CreateAvif encoded the wrong frame; Transcoder decoded a packet twice; Logger kept no prefix state across av_log calls; FormatContext.Url is read as UTF-8; SwsContext throws if it cannot be created.
Behaviour changes:
TryGetOption(Option, out object): Color options are returned as string ("0xRRGGBBAA"), Duration as long (microseconds), array options as the string FFmpeg produces.
SetOption(name, IDictionary) applies every entry as its own option (av_opt_set_dict2); `name` is not used.
AudioBuffer.CopyTo/CopyToPacked throw ArgumentOutOfRangeException for a start index outside the buffer. SetBufferSize throws for a non-positive size or when no data rate can be determined.
ChannelLayout custom channel names must be shorter than 16 bytes (UTF-8).
PlaybackEngine: a decoding error now moves the player to Faulted and raises Faulted, it was only logged before.
--- 9.9.0.1 ---
BugFix: - Fixed a bug concerning the incorrect size of CLong/CULong on Windows or 32bit and netstandard.
See AutoGen (v9.0.1.1) release notes for more details.