Merge pull request #423 from rosenbjerg/main

V.5.1.0
This commit is contained in:
Malte Rosenbjerg 2023-03-15 13:51:18 +01:00 committed by GitHub
commit f7d54d32df
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 188 additions and 3 deletions

View file

@ -1,4 +1,5 @@
using FFMpegCore.Arguments; using System.Drawing;
using FFMpegCore.Arguments;
using FFMpegCore.Enums; using FFMpegCore.Enums;
using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudio.TestTools.UnitTesting;
@ -537,5 +538,38 @@ public void Builder_BuildString_PadFilter_Alt()
"-i \"input.mp4\" -vf \"pad=aspect=4/3:x=(ow-iw)/2:y=(oh-ih)/2:color=violet:eval=frame\" \"output.mp4\"", "-i \"input.mp4\" -vf \"pad=aspect=4/3:x=(ow-iw)/2:y=(oh-ih)/2:color=violet:eval=frame\" \"output.mp4\"",
str); str);
} }
[TestMethod]
public void Builder_BuildString_GifPalette()
{
var streamIndex = 0;
var size = new Size(640, 480);
var str = FFMpegArguments
.FromFileInput("input.mp4")
.OutputToFile("output.gif", false, opt => opt
.WithGifPaletteArgument(streamIndex, size))
.Arguments;
Assert.AreEqual($"""
-i "input.mp4" -filter_complex "[0:v] fps=12,scale=w={size.Width}:h={size.Height},split [a][b];[a] palettegen=max_colors=32 [p];[b][p] paletteuse=dither=bayer" "output.gif"
""", str);
}
[TestMethod]
public void Builder_BuildString_GifPalette_NullSize_FpsSupplied()
{
var streamIndex = 1;
var str = FFMpegArguments
.FromFileInput("input.mp4")
.OutputToFile("output.gif", false, opt => opt
.WithGifPaletteArgument(streamIndex, null, 10))
.Arguments;
Assert.AreEqual($"""
-i "input.mp4" -filter_complex "[{streamIndex}:v] fps=10,split [a][b];[a] palettegen=max_colors=32 [p];[b][p] paletteuse=dither=bayer" "output.gif"
""", str);
}
} }
} }

View file

@ -1,4 +1,5 @@
using System.Drawing.Imaging; using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.Versioning; using System.Runtime.Versioning;
using System.Text; using System.Text;
using FFMpegCore.Arguments; using FFMpegCore.Arguments;
@ -479,6 +480,64 @@ public void Video_Snapshot_PersistSnapshot()
Assert.AreEqual("png", analysis.PrimaryVideoStream!.CodecName); Assert.AreEqual("png", analysis.PrimaryVideoStream!.CodecName);
} }
[TestMethod, Timeout(BaseTimeoutMilliseconds)]
public void Video_GifSnapshot_PersistSnapshot()
{
using var outputPath = new TemporaryFile("out.gif");
var input = FFProbe.Analyse(TestResources.Mp4Video);
FFMpeg.GifSnapshot(TestResources.Mp4Video, outputPath, captureTime: TimeSpan.FromSeconds(0));
var analysis = FFProbe.Analyse(outputPath);
Assert.AreNotEqual(input.PrimaryVideoStream!.Width, analysis.PrimaryVideoStream!.Width);
Assert.AreNotEqual(input.PrimaryVideoStream.Height, analysis.PrimaryVideoStream!.Height);
Assert.AreEqual("gif", analysis.PrimaryVideoStream!.CodecName);
}
[TestMethod, Timeout(BaseTimeoutMilliseconds)]
public void Video_GifSnapshot_PersistSnapshot_SizeSupplied()
{
using var outputPath = new TemporaryFile("out.gif");
var input = FFProbe.Analyse(TestResources.Mp4Video);
var desiredGifSize = new Size(320, 240);
FFMpeg.GifSnapshot(TestResources.Mp4Video, outputPath, desiredGifSize, captureTime: TimeSpan.FromSeconds(0));
var analysis = FFProbe.Analyse(outputPath);
Assert.AreNotEqual(input.PrimaryVideoStream!.Width, desiredGifSize.Width);
Assert.AreNotEqual(input.PrimaryVideoStream.Height, desiredGifSize.Height);
Assert.AreEqual("gif", analysis.PrimaryVideoStream!.CodecName);
}
[TestMethod, Timeout(BaseTimeoutMilliseconds)]
public async Task Video_GifSnapshot_PersistSnapshotAsync()
{
using var outputPath = new TemporaryFile("out.gif");
var input = FFProbe.Analyse(TestResources.Mp4Video);
await FFMpeg.GifSnapshotAsync(TestResources.Mp4Video, outputPath, captureTime: TimeSpan.FromSeconds(0));
var analysis = FFProbe.Analyse(outputPath);
Assert.AreNotEqual(input.PrimaryVideoStream!.Width, analysis.PrimaryVideoStream!.Width);
Assert.AreNotEqual(input.PrimaryVideoStream.Height, analysis.PrimaryVideoStream!.Height);
Assert.AreEqual("gif", analysis.PrimaryVideoStream!.CodecName);
}
[TestMethod, Timeout(BaseTimeoutMilliseconds)]
public async Task Video_GifSnapshot_PersistSnapshotAsync_SizeSupplied()
{
using var outputPath = new TemporaryFile("out.gif");
var input = FFProbe.Analyse(TestResources.Mp4Video);
var desiredGifSize = new Size(320, 240);
await FFMpeg.GifSnapshotAsync(TestResources.Mp4Video, outputPath, desiredGifSize, captureTime: TimeSpan.FromSeconds(0));
var analysis = FFProbe.Analyse(outputPath);
Assert.AreNotEqual(input.PrimaryVideoStream!.Width, desiredGifSize.Width);
Assert.AreNotEqual(input.PrimaryVideoStream.Height, desiredGifSize.Height);
Assert.AreEqual("gif", analysis.PrimaryVideoStream!.CodecName);
}
[TestMethod, Timeout(BaseTimeoutMilliseconds)] [TestMethod, Timeout(BaseTimeoutMilliseconds)]
public void Video_Join() public void Video_Join()
{ {

View file

@ -0,0 +1,24 @@
using System.Drawing;
namespace FFMpegCore.Arguments
{
public class GifPaletteArgument : IArgument
{
private readonly int _streamIndex;
private readonly int _fps;
private readonly Size? _size;
public GifPaletteArgument(int streamIndex, int fps, Size? size)
{
_streamIndex = streamIndex;
_fps = fps;
_size = size;
}
private string ScaleText => _size.HasValue ? $"scale=w={_size.Value.Width}:h={_size.Value.Height}," : string.Empty;
public string Text => $"-filter_complex \"[{_streamIndex}:v] fps={_fps},{ScaleText}split [a][b];[a] palettegen=max_colors=32 [p];[b][p] paletteuse=dither=bayer\"";
}
}

View file

@ -20,5 +20,6 @@ public static string Extension(this Codec type)
public static readonly string WebM = VideoType.WebM.Extension; public static readonly string WebM = VideoType.WebM.Extension;
public static readonly string Png = ".png"; public static readonly string Png = ".png";
public static readonly string Mp3 = ".mp3"; public static readonly string Mp3 = ".mp3";
public static readonly string Gif = ".gif";
} }
} }

View file

@ -57,6 +57,36 @@ public static async Task<bool> SnapshotAsync(string input, string output, Size?
.ProcessAsynchronously(); .ProcessAsynchronously();
} }
public static bool GifSnapshot(string input, string output, Size? size = null, TimeSpan? captureTime = null, TimeSpan? duration = null, int? streamIndex = null)
{
if (Path.GetExtension(output)?.ToLower() != FileExtension.Gif)
{
output = Path.Combine(Path.GetDirectoryName(output), Path.GetFileNameWithoutExtension(output) + FileExtension.Gif);
}
var source = FFProbe.Analyse(input);
var (arguments, outputOptions) = SnapshotArgumentBuilder.BuildGifSnapshotArguments(input, source, size, captureTime, duration, streamIndex);
return arguments
.OutputToFile(output, true, outputOptions)
.ProcessSynchronously();
}
public static async Task<bool> GifSnapshotAsync(string input, string output, Size? size = null, TimeSpan? captureTime = null, TimeSpan? duration = null, int? streamIndex = null)
{
if (Path.GetExtension(output)?.ToLower() != FileExtension.Gif)
{
output = Path.Combine(Path.GetDirectoryName(output), Path.GetFileNameWithoutExtension(output) + FileExtension.Gif);
}
var source = await FFProbe.AnalyseAsync(input).ConfigureAwait(false);
var (arguments, outputOptions) = SnapshotArgumentBuilder.BuildGifSnapshotArguments(input, source, size, captureTime, duration, streamIndex);
return await arguments
.OutputToFile(output, true, outputOptions)
.ProcessAsynchronously();
}
/// <summary> /// <summary>
/// Converts an image sequence to a video. /// Converts an image sequence to a video.
/// </summary> /// </summary>

View file

@ -76,6 +76,7 @@ public FFMpegArgumentOptions DeselectStreams(IEnumerable<int> streamIndices, int
public FFMpegArgumentOptions WithAudibleEncryptionKeys(string key, string iv) => WithArgument(new AudibleEncryptionKeyArgument(key, iv)); public FFMpegArgumentOptions WithAudibleEncryptionKeys(string key, string iv) => WithArgument(new AudibleEncryptionKeyArgument(key, iv));
public FFMpegArgumentOptions WithAudibleActivationBytes(string activationBytes) => WithArgument(new AudibleEncryptionKeyArgument(activationBytes)); public FFMpegArgumentOptions WithAudibleActivationBytes(string activationBytes) => WithArgument(new AudibleEncryptionKeyArgument(activationBytes));
public FFMpegArgumentOptions WithTagVersion(int id3v2Version = 3) => WithArgument(new ID3V2VersionArgument(id3v2Version)); public FFMpegArgumentOptions WithTagVersion(int id3v2Version = 3) => WithArgument(new ID3V2VersionArgument(id3v2Version));
public FFMpegArgumentOptions WithGifPaletteArgument(int streamIndex, Size? size, int fps = 12) => WithArgument(new GifPaletteArgument(streamIndex, fps, size));
public FFMpegArgumentOptions WithArgument(IArgument argument) public FFMpegArgumentOptions WithArgument(IArgument argument)
{ {

View file

@ -31,6 +31,31 @@ public static (FFMpegArguments, Action<FFMpegArgumentOptions> outputOptions) Bui
.Resize(size)); .Resize(size));
} }
public static (FFMpegArguments, Action<FFMpegArgumentOptions> outputOptions) BuildGifSnapshotArguments(
string input,
IMediaAnalysis source,
Size? size = null,
TimeSpan? captureTime = null,
TimeSpan? duration = null,
int? streamIndex = null,
int fps = 12)
{
var defaultGifOutputSize = new Size(480, -1);
captureTime ??= TimeSpan.FromSeconds(source.Duration.TotalSeconds / 3);
size = PrepareSnapshotSize(source, size) ?? defaultGifOutputSize;
streamIndex ??= source.PrimaryVideoStream?.Index
?? source.VideoStreams.FirstOrDefault()?.Index
?? 0;
return (FFMpegArguments
.FromFileInput(input, false, options => options
.Seek(captureTime)
.WithDuration(duration)),
options => options
.WithGifPaletteArgument((int)streamIndex, size, fps));
}
private static Size? PrepareSnapshotSize(IMediaAnalysis source, Size? wantedSize) private static Size? PrepareSnapshotSize(IMediaAnalysis source, Size? wantedSize)
{ {
if (wantedSize == null || (wantedSize.Value.Height <= 0 && wantedSize.Value.Width <= 0) || source.PrimaryVideoStream == null) if (wantedSize == null || (wantedSize.Value.Height <= 0 && wantedSize.Value.Width <= 0) || source.PrimaryVideoStream == null)

View file

@ -3,7 +3,7 @@
<PropertyGroup> <PropertyGroup>
<IsPackable>true</IsPackable> <IsPackable>true</IsPackable>
<Description>A .NET Standard FFMpeg/FFProbe wrapper for easily integrating media analysis and conversion into your .NET applications</Description> <Description>A .NET Standard FFMpeg/FFProbe wrapper for easily integrating media analysis and conversion into your .NET applications</Description>
<PackageVersion>5.0.2</PackageVersion> <PackageVersion>5.1.0</PackageVersion>
<PackageOutputPath>../nupkg</PackageOutputPath> <PackageOutputPath>../nupkg</PackageOutputPath>
<PackageReleaseNotes> <PackageReleaseNotes>
</PackageReleaseNotes> </PackageReleaseNotes>

View file

@ -63,6 +63,17 @@ var bitmap = FFMpeg.Snapshot(inputPath, new Size(200, 400), TimeSpan.FromMinutes
FFMpeg.Snapshot(inputPath, outputPath, new Size(200, 400), TimeSpan.FromMinutes(1)); FFMpeg.Snapshot(inputPath, outputPath, new Size(200, 400), TimeSpan.FromMinutes(1));
``` ```
### You can also capture GIF snapshots from a video file:
```csharp
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: ### Join video parts into one single file:
```csharp ```csharp
FFMpeg.Join(@"..\joined_video.mp4", FFMpeg.Join(@"..\joined_video.mp4",