• Stars
    star
    1,631
  • Rank 28,685 (Top 0.6 %)
  • Language
    C#
  • License
    MIT License
  • Created almost 6 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A .NET FFMpeg/FFProbe wrapper for easily integrating media analysis and conversion into your C# applications

FFMpegCore

NuGet Badge GitHub issues GitHub stars GitHub CI GitHub code contributors

A .NET Standard FFMpeg/FFProbe wrapper for easily integrating media analysis and conversion into your .NET applications. Supports both synchronous and asynchronous calls

API

FFProbe

Use FFProbe to analyze media files:

var mediaInfo = await FFProbe.AnalyseAsync(inputPath);

or

var mediaInfo = FFProbe.Analyse(inputPath);

FFMpeg

Use FFMpeg to convert your media files. Easily build your FFMpeg arguments using the fluent argument builder:

Convert input file to h264/aac scaled to 720p w/ faststart, for web playback

FFMpegArguments
    .FromFileInput(inputPath)
    .OutputToFile(outputPath, false, options => options
        .WithVideoCodec(VideoCodec.LibX264)
        .WithConstantRateFactor(21)
        .WithAudioCodec(AudioCodec.Aac)
        .WithVariableBitrate(4)
        .WithVideoFilters(filterOptions => filterOptions
            .Scale(VideoSize.Hd))
        .WithFastStart())
    .ProcessSynchronously();

Convert to and/or from streams

await FFMpegArguments
    .FromPipeInput(new StreamPipeSource(inputStream))
    .OutputToPipe(new StreamPipeSink(outputStream), options => options
        .WithVideoCodec("vp9")
        .ForceFormat("webm"))
    .ProcessAsynchronously();

Helper methods

The provided helper methods makes it simple to perform common operations.

Easily capture snapshots from a video file:

// process the snapshot in-memory and use the Bitmap directly
var bitmap = FFMpeg.Snapshot(inputPath, new Size(200, 400), TimeSpan.FromMinutes(1));

// or persists the image on the drive
FFMpeg.Snapshot(inputPath, outputPath, new Size(200, 400), TimeSpan.FromMinutes(1));

You can also capture GIF snapshots from a video file:

FFMpeg.GifSnapshot(inputPath, outputPath, new Size(200, 400), TimeSpan.FromSeconds(10));

// or async
await FFMpeg.GifSnapshotAsync(inputPath, outputPath, new Size(200, 400), TimeSpan.FromSeconds(10));

// you can also supply -1 to either one of Width/Height Size properties if you'd like FFMPEG to resize while maintaining the aspect ratio
await FFMpeg.GifSnapshotAsync(inputPath, outputPath, new Size(480, -1), TimeSpan.FromSeconds(10));

Join video parts into one single file:

FFMpeg.Join(@"..\joined_video.mp4",
    @"..\part1.mp4",
    @"..\part2.mp4",
    @"..\part3.mp4"
);

Create a sub video

FFMpeg.SubVideo(inputPath, 
    outputPath,
    TimeSpan.FromSeconds(0),
    TimeSpan.FromSeconds(30)
);

Join images into a video:

FFMpeg.JoinImageSequence(@"..\joined_video.mp4", frameRate: 1,
    ImageInfo.FromPath(@"..\1.png"),
    ImageInfo.FromPath(@"..\2.png"),
    ImageInfo.FromPath(@"..\3.png")
);

Mute the audio of a video file:

FFMpeg.Mute(inputPath, outputPath);

Extract the audio track from a video file:

FFMpeg.ExtractAudio(inputPath, outputPath);

Add or replace the audio track of a video file:

FFMpeg.ReplaceAudio(inputPath, inputAudioPath, outputPath);

Combine an image with audio file, for youtube or similar platforms

FFMpeg.PosterWithAudio(inputPath, inputAudioPath, outputPath);
// or
var image = Image.FromFile(inputImagePath);
image.AddAudio(inputAudioPath, outputPath);

Other available arguments could be found in FFMpegCore.Arguments namespace.

Input piping

With input piping it is possible to write video frames directly from program memory without saving them to jpeg or png and then passing path to input of ffmpeg. This feature also allows for converting video on-the-fly while frames are being generated or received.

An object implementing the IPipeSource interface is used as the source of data. Currently, the IPipeSource interface has two implementations; StreamPipeSource for streams, and RawVideoPipeSource for raw video frames.

Working with raw video frames

Method for generating bitmap frames:

IEnumerable<IVideoFrame> CreateFrames(int count)
{
    for(int i = 0; i < count; i++)
    {
        yield return GetNextFrame(); //method that generates of receives the next frame
    }
}

Then create a RawVideoPipeSource that utilises your video frame source

var videoFramesSource = new RawVideoPipeSource(CreateFrames(64))
{
    FrameRate = 30 //set source frame rate
};
await FFMpegArguments
    .FromPipeInput(videoFramesSource)
    .OutputToFile(outputPath, false, options => options
        .WithVideoCodec(VideoCodec.LibVpx))
    .ProcessAsynchronously();

If you want to use System.Drawing.Bitmaps as IVideoFrames, a BitmapVideoFrameWrapper wrapper class is provided.

Binaries

Installation

If you prefer to manually download them, visit ffbinaries or zeranoe Windows builds.

Windows (using choco)

command: choco install ffmpeg -y

location: C:\ProgramData\chocolatey\lib\ffmpeg\tools\ffmpeg\bin

Mac OSX

command: brew install ffmpeg mono-libgdiplus

location: /usr/local/bin

Ubuntu

command: sudo apt-get install -y ffmpeg libgdiplus

location: /usr/bin

Path Configuration

Option 1

The default value of an empty string (expecting ffmpeg to be found through PATH) can be overwritten via the FFOptions class:

// setting global options
GlobalFFOptions.Configure(new FFOptions { BinaryFolder = "./bin", TemporaryFilesFolder = "/tmp" });

// or
GlobalFFOptions.Configure(options => options.BinaryFolder = "./bin");

// on some systems the absolute path may be required, in which case 
GlobalFFOptions.Configure(new FFOptions { BinaryFolder = Server.MapPath("./bin"), TemporaryFilesFolder = Server.MapPath("/tmp") });

// or individual, per-run options
await FFMpegArguments
    .FromFileInput(inputPath)
    .OutputToFile(outputPath)
    .ProcessAsynchronously(true, new FFOptions { BinaryFolder = "./bin", TemporaryFilesFolder = "/tmp" });

// or combined, setting global defaults and adapting per-run options
GlobalFFOptions.Configure(new FFOptions { BinaryFolder = "./bin", TemporaryFilesFolder = "./globalTmp", WorkingDirectory = "./" });

await FFMpegArguments
    .FromFileInput(inputPath)
    .OutputToFile(outputPath)
    .Configure(options => options.WorkingDirectory = "./CurrentRunWorkingDir")
    .Configure(options => options.TemporaryFilesFolder = "./CurrentRunTmpFolder")
    .ProcessAsynchronously();

Option 2

The root and temp directory for the ffmpeg binaries can be configured via the ffmpeg.config.json file, which will be read on first use only.

{
  "BinaryFolder": "./bin",
  "TemporaryFilesFolder": "/tmp"
}

Supporting both 32 and 64 bit processes

If you wish to support multiple client processor architectures, you can do so by creating two folders, x64 and x86, in the BinaryFolder directory. Both folders should contain the binaries (ffmpeg.exe and ffprobe.exe) built for the respective architectures.

By doing so, the library will attempt to use either /{BinaryFolder}/{ARCH}/(ffmpeg|ffprobe).exe.

If these folders are not defined, it will try to find the binaries in /{BinaryFolder}/(ffmpeg|ffprobe.exe).

(.exe is only appended on Windows)

Compatibility

Older versions of ffmpeg might not support all ffmpeg arguments available through this library. The library has been tested with version 3.3 to 4.2

Code contributors

Other contributors

License

Copyright Β© 2023

Released under MIT license

More Repositories

1

wsl2-podman

Script for installing WSL2 + podman and podman-compose (or docker and docker-compose)
PowerShell
36
star
2

Instances

A process wrapper for asyncronous use, using Tasks or Events
C#
23
star
3

nxplx

Home media streaming server designed for use on low-power devices, such as Raspberry Pi 4/3 and similar
C#
17
star
4

HandbrakeCliWrapper-NetStandard

A .NET Standard wrapper for HandbrakeCLI
C#
8
star
5

agentdeploy

An agent for managing execution of taco bell style deployment and server management scripts
C#
6
star
6

recreate-sln-structure

A dotnet tool for moving project files into the directories specified by the solution (.sln) file.
C#
4
star
7

SimpleMappings

Simple mappings from object to object - because I just needed a simple-as-can-be mapping library
C#
3
star
8

slnf-gen

A dotnet tool for generating solution filter (.slnf) files based on globs
C#
3
star
9

VLCTube

A tray-application to launch YouTube videos, from a URL, in the VLC media player
JavaScript
3
star
10

pca

a tiny DSL for creating point and click adventures
JavaScript
3
star
11

SessionManager

A minimalist session manager for .NET web server
C#
3
star
12

Memester

for memesters only
C#
2
star
13

FormValidator

Validator for forms (IFormCollection).
C#
2
star
14

RHttpServer.CSharp

New version with NET Core support at https://github.com/rosenbjerg/RedHttpServer.CSharp
C#
2
star
15

BansheeBlog

A simple personal blogging platform - self-hosted, of course
C#
2
star
16

rollup-plugin-html-bundle

Plugin for rollup that generates a html file from a template that either has the bundle included using a script-tag with src or inlined in a script-tag
JavaScript
2
star
17

HelloDocker

Dockerfile
1
star
18

TOI-MobileClient

TOI Xamarin mobile client
C#
1
star
19

bat-launchers

A collection of bat files for launching applications through a container
Batchfile
1
star
20

rosenbjerg.com

1
star
21

JsTemplates

A lightweight pure JavaScript templating engine
JavaScript
1
star
22

EasySettings

A minimalist settings manager using json
C#
1
star
23

TinyIoC

C#
1
star
24

ghaction-common-installer

Install programs needed for CI/CD using apt, chocolatey and homebrew
TypeScript
1
star
25

EventTarget-on

Extension for EventTarget to provide on(..) and off(..) event subscription interface similar to jQuery
JavaScript
1
star
26

AspNetCore.Mvc.RangedStreamResult

C#
1
star
27

dotnet-simple-sln

C#
1
star
28

fs-to-ts

F# to TypeScript type definition converter
HTML
1
star
29

rosenbjerg

GitHub user profile
1
star
30

electron-overleaf

an electron wrapper for overleaf
JavaScript
1
star
31

build-secrets-server

Minimalist build secrets server for use when building containers, based on busybox
Dockerfile
1
star
32

Konsolidat

Simple CLI tool for consolidating nuget package version conflicts in csproj files
C#
1
star
33

img-to-3mf

Simple script for creating 3mf files from images - wrapped in a Dockerfile
Shell
1
star
34

pi-humidifier-web-controller

Python
1
star
35

JsDataBindings

Minimalist databindings in pure JavaScript
JavaScript
1
star
36

Speedlimits

Throttling / rate-limiting library
C#
1
star
37

rosenbjerg.github.io

HTML
1
star
38

velkommen

a webapp for easily creating translations for localisation
HTML
1
star
39

WebSocketChat

Anonymous chat system using websockets
C#
1
star