MediaToolkitNet.FFmpeg
1.0.0
dotnet add package MediaToolkitNet.FFmpeg --version 1.0.0
NuGet\Install-Package MediaToolkitNet.FFmpeg -Version 1.0.0
<PackageReference Include="MediaToolkitNet.FFmpeg" Version="1.0.0" />
<PackageVersion Include="MediaToolkitNet.FFmpeg" Version="1.0.0" />
<PackageReference Include="MediaToolkitNet.FFmpeg" />
paket add MediaToolkitNet.FFmpeg --version 1.0.0
#r "nuget: MediaToolkitNet.FFmpeg, 1.0.0"
#:package MediaToolkitNet.FFmpeg@1.0.0
#addin nuget:?package=MediaToolkitNet.FFmpeg&version=1.0.0
#tool nuget:?package=MediaToolkitNet.FFmpeg&version=1.0.0
MediaToolkit.NET
Low-level wrappers over the native media stacks for .NET 10, plus one cross-platform API on top of them: device enumeration, camera and microphone capture, audio playback, decoding, recording, probing and transcoding.
Interop goes through [LibraryImport] and unmanaged function pointers. COM on
Windows is called directly through vtable slots, without [ComImport] or the
built-in COM marshaller, so the assemblies stay AOT- and trim-safe.
Install
dotnet add package MediaToolkitNet.All
MediaToolkitNet.All pulls in every backend and selects one at runtime. Take a
single backend instead when you do not want the rest:
| Package | Contents |
|---|---|
MediaToolkitNet.All |
Facade: backend registry and per-platform selection |
MediaToolkitNet.Abstractions |
Abstractions only; no native code, no dependencies |
MediaToolkitNet.Interop |
Native loading, UTF-8 marshalling, COM vtable access |
MediaToolkitNet.FFmpeg |
FFmpeg 7.x, 8.x or 9.x: demux, decode, encode, mux, filter graphs, probing, transcoding, frame reader |
MediaToolkitNet.Mpv |
libmpv client API: playback, filter chains, probing, and its encoding mode as a transcoder |
MediaToolkitNet.Windows |
Media Foundation, WASAPI, DirectShow (devices, graph, Sample Grabber) |
MediaToolkitNet.Linux |
V4L2, ALSA, PulseAudio |
MediaToolkitNet.GStreamer |
GStreamer 1.x on Linux: pipelines, appsink, GstDiscoverer probing, transcoding |
MediaToolkitNet.MacOS |
AVFoundation, CoreAudio |
Quick start
using MediaToolkitNet;
using MediaToolkitNet.Abstractions.Capture;
using MediaToolkitNet.Abstractions.Frames;
// Whichever backend this machine actually has.
using var capture = MediaToolkitNetBackends.CreateVideoCapture(VideoCaptureSettings.Default);
capture.FrameCaptured += (in VideoFrame frame) =>
{
// The frame is borrowed: it is valid only inside this handler.
// Copy the data out if you need to keep it.
ReadOnlySpan<byte> luma = frame.GetPlane(0);
};
capture.Start();
List what a machine can do:
foreach (var backend in MediaToolkitNetBackends.Registered)
{
Console.WriteLine($"{backend.Name}: {backend.IsAvailable}, {backend.Capabilities}");
}
foreach (var device in MediaToolkitNetBackends.EnumerateDevices())
{
Console.WriteLine($"{device.Kind} {device.Name}");
}
Convert, probe and read files
A conversion is described once, as a TranscodeRequest: which streams of which
inputs, copied or re-encoded, subtitles converted or burned in, a trim, tags and
chapters. The first backend that can do all of it runs the job — FFmpeg, then
GStreamer, then mpv — and one that cannot says why before anything is written.
using MediaToolkitNet.Abstractions.Recording;
using MediaToolkitNet.Abstractions.Transcoding;
// Every stream copied into another container.
await MediaToolkitNetBackends.TranscodeAsync(TranscodeRequest.Remux("in.mkv", "out.mp4"));
// A minute of it, re-encoded, with subtitles from another file burned in.
await MediaToolkitNetBackends.TranscodeAsync(new TranscodeRequest("clip.mp4")
{
Inputs = ["in.mkv", "in.en.srt"],
Start = TimeSpan.FromMinutes(1),
End = TimeSpan.FromMinutes(2),
Streams =
[
OutputStream.Video(StreamSource.First(MediaStreamKind.Video),
new VideoOutputSettings(MediaCodec.H264) { Width = 1280, Quality = 23 }),
OutputStream.Audio(StreamSource.First(MediaStreamKind.Audio, language: "eng"),
new AudioOutputSettings(MediaCodec.Aac) { BitrateBitsPerSecond = 160_000 }),
OutputStream.BurnIn(StreamSource.First(MediaStreamKind.Subtitle, input: 1),
StreamSource.First(MediaStreamKind.Video)),
],
});
A specific backend can be asked directly, and asked first whether it can:
var transcoder = new FFmpegTranscoder();
foreach (var issue in transcoder.Validate(request))
{
Console.WriteLine(issue); // "error: ..." or "warning: ..."
}
await transcoder.RunAsync(request, new Progress<TranscodeProgress>(p => Console.Write($"\r{p.Fraction:P0}")));
The backends differ a good deal:
| FFmpeg | GStreamer | mpv | |
|---|---|---|---|
| Stream copy, container change | yes | video and audio | — |
| Re-encode video / audio | yes | yes | one track each |
| Several audio or video streams | yes | yes | — |
| Subtitle copy / conversion | yes | — | — |
| Subtitle burn-in | text (libass) | text | yes |
| Several inputs | yes | yes | external audio and subtitles |
| Trim, tags | yes | yes | yes |
| Chapters | yes | Matroska only, untrimmed | — |
Probing reads the container, streams (codec, language, title, default and forced
flags), tags and chapters, and numbers streams the same way on every backend.
FFmpegMediaReader reads decoded frames, in order or at a time, converted to the
format asked for:
MediaInfo info = MediaToolkitNetBackends.Probe("in.mkv");
using var reader = FFmpegMediaReader.Open("in.mkv",
new MediaReaderOptions { VideoPixelFormat = PixelFormat.Bgra32, VideoWidth = 640, VideoHeight = 360 });
reader.Video!.TryReadAt(TimeSpan.FromSeconds(12), (in VideoFrame frame) => Save(frame));
foreach (var cue in reader.SubtitleStreams[0].ReadAll())
{
Console.WriteLine($"{cue.Start} {cue.Text}");
}
Files, URLs and untrusted input
The FFmpeg backend opens local files and pipes only, so a path taken from
somebody else cannot make your process connect to a host of their choosing or read
other files through a playlist. Network URLs (http://, https://, rtsp://,
tcp://, udp://...) and playlists (HLS, DASH, concat) are refused by
FFmpegProber, FFmpegMediaReader and FFmpegTranscoder, with
avformat_open_input(...): Invalid argument and without connecting.
FFmpegPlayer and capture devices are not restricted.
If your application opens URLs on purpose, allow them once at start-up:
FFmpegDemuxer.AllowNetworkByDefault = true;
var info = new FFmpegProber().Probe("https://example.com/clip.mp4");
or for a single reader, with just the protocols it needs:
using var reader = FFmpegMediaReader.Open("https://example.com/clip.mp4",
new MediaReaderOptions
{
DemuxerOptions = new Dictionary<string, string>
{
["protocol_whitelist"] = "file,http,https,tcp,tls,crypto",
},
});
The GStreamer and mpv backends accept URLs as before.
Processing graphs
Each stack is wrapped in its own terms, because the shapes are genuinely different:
// libavfilter: the same chain the ffmpeg command line takes after -vf.
var input = new VideoFormat(1920, 1080, PixelFormat.Bgr24, 30);
using var chain = FFmpegFilterGraph.ForVideo(input, "scale=640:-1,hflip");
chain.Push(sourceFrame);
while (chain.TryReceive((in VideoFrame frame) => Save(frame)))
{
}
// DirectShow: filters and pins, with frames handed back by the Sample Grabber.
using var graph = DirectShowGraph.Create();
var grabber = DirectShowSampleGrabber.AddTo(graph);
grabber.AcceptVideo(PixelFormat.Bgr24);
grabber.VideoGrabbed += (in VideoFrame frame) => Save(frame);
// GStreamer: a whole pipeline from one gst-launch string.
using var pipeline = GStreamerPipeline.Parse(
"filesrc location=clip.mp4 ! decodebin ! videoconvert ! appsink name=sink");
var sink = pipeline.GetSink("sink");
What each backend provides
| Capability | Windows | Linux | macOS | FFmpeg | mpv |
|---|---|---|---|---|---|
| Device enumeration | MF + WASAPI + DShow | ALSA + V4L2 | CoreAudio + AVF | avdevice | — |
| Video capture | IMFSourceReader |
V4L2 mmap | AVCaptureSession |
— | — |
| Audio capture | WASAPI (+ loopback) | ALSA / PulseAudio | AudioQueue | — | — |
| Audio render | WASAPI | ALSA / PulseAudio | AudioQueue | — | — |
| Playback | — | — | AVPlayer |
decode to frames | full |
| Recording to file | IMFSinkWriter |
— | — | encode + mux | — |
| Filter graph | DirectShow + Sample Grabber | GStreamer pipeline | — | libavfilter | vf / af chains |
| Probing a file | — | GstDiscoverer | — | libavformat | track list |
| Transcoding | — | GStreamer pipeline | — | full | encoding mode |
| Reading frames from a file | — | — | — | FFmpegMediaReader |
— |
A dash means the backend does not take that role: FFmpeg owns no audio output, mpv never hands frames back, and on Linux and macOS writing files is the FFmpeg backend's job.
Requirements
- .NET 10, and a 64-bit process: every mapped struct layout assumes a 64-bit pointer.
- No native binary ships in any package. The platform backends only call
libraries that are already part of the operating system, but:
MediaToolkitNet.FFmpegneeds FFmpeg 7.x, 8.x or 9.x as shared libraries. The loader reads the versions it actually got and refuses a mixture belonging to no single series.libavfilteris optional: without it filter graphs and re-encoding transcodes are unavailable;MediaToolkitNet.Mpvneeds libmpv (libmpv-2.dll,libmpv.so.2), built with encoding support for transcoding;MediaToolkitNet.GStreamerneeds GStreamer 1.x and its plugins, and binds the Linux library names, so it reports itself unavailable elsewhere. Probing needs gst-plugins-base (libgstpbutils).
- Native libraries are looked for in any directory given to
NativeSearchPaths.Prepend, then beside the application, in itsnativeandruntimes/<rid>/nativefolders, and finally where the operating system looks (on Windows, thePATH).
A backend whose libraries are missing reports IsAvailable == false instead of
throwing, so probing is always safe.
Status
From 1.0.0 the public API follows semantic versioning. The release notes of each version say what changed and what can break.
Exercised against real hardware:
- on Windows 11: device enumeration, camera capture, WASAPI audio capture, recording to H.264, HEVC and AAC through Media Foundation, the DirectShow graph with the Sample Grabber, and FFmpeg and libmpv transcoding;
- the FFmpeg backend against FFmpeg 7.1.5 on Debian 13 and Windows 11, and against FFmpeg 9.0.1 on Windows 11, with every struct offset checked against the library actually installed;
- libavfilter, FFmpeg transcoding and the frame reader, and probing and transcoding through GStreamer 1.26.2 and libmpv 2.5, on Debian 13.
Not run yet: mpv playback, FFmpeg 8 and 9 transcoding, the macOS backend, and the V4L2, ALSA and PulseAudio paths on Linux. They compile and are guarded at runtime — a layout that cannot be confirmed disables the feature rather than proceeding — but that is not the same as having been run. See the release notes for the full picture before depending on it.
Links
MIT licensed.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | 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. |
-
net10.0
- MediaToolkitNet.Abstractions (>= 1.0.0)
- MediaToolkitNet.Interop (>= 1.0.0)
NuGet packages (2)
Showing the top 2 NuGet packages that depend on MediaToolkitNet.FFmpeg:
| Package | Downloads |
|---|---|
|
MediaToolkitNet.Mpv
libmpv backend for MediaToolkit.NET: a self-rendering media player driven through the mpv client API, including property access, the event loop, filter chains and encoding mode. libmpv is not included and must be present at runtime. |
|
|
MediaToolkitNet.All
MediaToolkit.NET: one API over the native media stacks. This package pulls in every backend and selects the right one for the current operating system. Install a single backend package instead if you only need one. |
GitHub repositories
This package is not used by any popular GitHub repositories.
MediaToolkit.NET 1.0.0 - the first stable release.
Follows an audit of 0.3.1 for bugs, resource leaks and vulnerabilities. Every
fix was written test first, and the findings were reproduced on Windows 11 and
Debian 13 before they were fixed. The public API follows semantic versioning
from here. Four behaviours changed, and each can break a caller that worked
before.
CHANGES THAT CAN BREAK EXISTING CODE
- FFmpeg inputs are local files and pipes by default. FFmpegProber,
FFmpegMediaReader and FFmpegTranscoder refuse network URLs (http://, https://,
rtsp://, tcp://, udp://...) and playlists (HLS, DASH, concat), so a path that
came from somebody else cannot make the process connect anywhere or read other
files. To open URLs on purpose, set FFmpegDemuxer.AllowNetworkByDefault = true
once at start-up, or give one reader
MediaReaderOptions.DemuxerOptions["protocol_whitelist"]. FFmpegPlayer and
capture devices are not restricted; GStreamer and mpv accept URLs as before.
The README has examples.
- All three transcoders write a partial file beside the output and rename it when
the job has finished. An output that is a link to an input no longer overwrites
the input, and a failed or refused job no longer deletes a file that was
already at the output path. The output directory must allow creating a file.
- Native library search is narrower: the walk up to src/FFMpeg/<platform> needs a
folder holding MediaToolkit.NET.slnx, relative and empty PATH entries are not
used, and on Windows the default search order (current directory included) is
no longer the fallback.
- MpvPlayer sets ytdl=no and load-scripts=no by default (put them back through
Options); MpvFilterChain.Lavfi returns lavfi=graph=%N%... instead of
lavfi=[...]; planar audio with more than 8 channels pushed to a filter graph
throws ArgumentException; Ole32.Initialize returns true for S_FALSE.
FIXED
- GStreamer video read past a buffer shorter than its caps and aborted the
process. FrameBounds.FitsIn now checks every frame in the GStreamer,
DirectShow, Media Foundation, V4L2 and AVFoundation producers.
- MpvPlayer: access violation when Stop, Pause or Volume ran while another
thread disposed it.
- FFmpegPlayer: Seek while paused used the decoder from two threads; Dispose from
inside a frame handler freed the media under the worker; a read blocked on the
network held Dispose for the whole timeout (the input is now interruptible:
FFmpegDemuxer.Interrupt and ClearInterrupt).
- A subscriber that throws from Failed no longer ends the process, on any
backend (SafeEvents.RaiseFailed).
- FFmpeg audio frames described themselves with the format known at open; they
now carry their own, and FFmpegMediaReader follows a stream that changes rate,
channels or size part way through.
- TryReadAt on MPEG-TS returned the key frame after the requested time.
- Transcoding audio from MP2 failed; a timestamp that jumps back is repaired; a
video that changes size is rebuilt; encoder options nobody recognised are
reported as warnings (FFmpeg and mpv).
- WasapiRenderer.Write no longer waits for ever on a stopped endpoint.
- Leaks: FFmpegDemuxer.Open, FFmpegRecorder and the DirectShowGraph constructor
on failure; wrappers the DirectShow graph kept until disposal; V4L2 mappings
(and the descriptor is now close-on-exec); a variant in the DirectShow
property reader; unbalanced COM initialisation on the capture threads; mpv's
argument vector.
NEW PUBLIC API
PartialOutput, FrameBounds.FitsIn and SafeEvents.RaiseFailed (Abstractions);
FFmpegDemuxer.AllowNetworkByDefault, Open(..., allowPlaylists, allowNetwork),
Interrupt() and ClearInterrupt().
NOT COVERED
- WASAPI, Media Foundation, V4L2, ALSA and PulseAudio still join their worker
with a two-second timeout and then free native objects, and a capture whose
loop failed still reports IsRunning until Stop. FFmpegPlayer and MpvPlayer no
longer have this.
- The macOS backend changed (frame checks, Failed handling) and has never been
run. A callback in flight during Dispose and a restart after Stop are open.
- A connect already in progress inside FFmpegDemuxer.Open cannot be interrupted;
pass rw_timeout through DemuxerOptions. Only FFmpegPlayer interrupts reads.
- The Media Foundation recorder does not check a frame against its stream's
format.
VERIFIED BY RUNNING
- Debian 13, FFmpeg 7.1.5, GStreamer 1.26.2, libmpv 2.5: 213 unit and 124
integration tests pass.
- Windows 11: 213 unit and 107 integration tests pass, 15 skip (GStreamer is
Linux-only); DirectShow, WASAPI, Media Foundation and camera capture were also
run by hand.
- Not run: FFmpeg 8 and 9 transcoding, mpv playback, the macOS backend, the V4L2,
ALSA and PulseAudio paths.
Full notes: https://github.com/yartat/MediaToolkit.NET/releases/tag/v1.0.0
Issues: https://github.com/yartat/MediaToolkit.NET/issues