Merge branch 'main' into chore/deterministic-dotnet-builds

This commit is contained in:
Vlad Jerca 2024-06-28 13:52:40 +02:00 committed by GitHub
commit 5e62d9ba36
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
24 changed files with 463 additions and 59 deletions

View file

@ -12,8 +12,8 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="SkiaSharp" Version="2.88.3" /> <PackageReference Include="SkiaSharp" Version="2.88.6" />
<PackageReference Include="SkiaSharp.NativeAssets.Linux.NoDependencies" Version="2.88.3" /> <PackageReference Include="SkiaSharp.NativeAssets.Linux.NoDependencies" Version="2.88.6" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

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,78 @@ 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);
}
[TestMethod]
public void Builder_BuildString_MultiOutput()
{
var str = FFMpegArguments.FromFileInput("input.mp4")
.MultiOutput(args => args
.OutputToFile("output.mp4", overwrite: true, args => args.CopyChannel())
.OutputToFile("output.ts", overwrite: false, args => args.CopyChannel().ForceFormat("mpegts"))
.OutputToUrl("http://server/path", options => options.ForceFormat("webm")))
.Arguments;
Assert.AreEqual($"""
-i "input.mp4" -c:a copy -c:v copy "output.mp4" -y -c:a copy -c:v copy -f mpegts "output.ts" -f webm http://server/path
""", str);
}
[TestMethod]
public void Builder_BuildString_MBROutput()
{
var str = FFMpegArguments.FromFileInput("input.mp4")
.MultiOutput(args => args
.OutputToFile("sd.mp4", overwrite: true, args => args.Resize(1200, 720))
.OutputToFile("hd.mp4", overwrite: false, args => args.Resize(1920, 1080)))
.Arguments;
Assert.AreEqual($"""
-i "input.mp4" -s 1200x720 "sd.mp4" -y -s 1920x1080 "hd.mp4"
""", str);
}
[TestMethod]
public void Builder_BuildString_TeeOutput()
{
var str = FFMpegArguments.FromFileInput("input.mp4")
.OutputToTee(args => args
.OutputToFile("output.mp4", overwrite: false, args => args.WithFastStart())
.OutputToUrl("http://server/path", options => options.ForceFormat("mpegts").SelectStream(0, channel: Channel.Video)))
.Arguments;
Assert.AreEqual($"""
-i "input.mp4" -f tee "[movflags=faststart]output.mp4|[f=mpegts:select=\'0:v:0\']http://server/path"
""", str);
}
} }
} }

View file

@ -8,19 +8,19 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="coverlet.collector" Version="3.2.0"> <PackageReference Include="coverlet.collector" Version="6.0.0">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="FluentAssertions" Version="6.10.0" /> <PackageReference Include="FluentAssertions" Version="6.12.0" />
<PackageReference Include="GitHubActionsTestLogger" Version="2.0.1"> <PackageReference Include="GitHubActionsTestLogger" Version="2.3.3">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.5.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.7.2" />
<PackageReference Include="MSTest.TestAdapter" Version="3.0.2" /> <PackageReference Include="MSTest.TestAdapter" Version="3.1.1" />
<PackageReference Include="MSTest.TestFramework" Version="3.0.2" /> <PackageReference Include="MSTest.TestFramework" Version="3.1.1" />
<PackageReference Include="SkiaSharp" Version="2.88.3" /> <PackageReference Include="SkiaSharp" Version="2.88.6" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View file

@ -46,7 +46,7 @@ public async Task PacketAnalysis_Async()
var packets = packetAnalysis.Packets; var packets = packetAnalysis.Packets;
Assert.AreEqual(96, packets.Count); Assert.AreEqual(96, packets.Count);
Assert.IsTrue(packets.All(f => f.CodecType == "video")); Assert.IsTrue(packets.All(f => f.CodecType == "video"));
Assert.AreEqual("K_", packets[0].Flags); Assert.IsTrue(packets[0].Flags.StartsWith("K_"));
Assert.AreEqual(1362, packets.Last().Size); Assert.AreEqual(1362, packets.Last().Size);
} }
@ -57,7 +57,7 @@ public void PacketAnalysis_Sync()
Assert.AreEqual(96, packets.Count); Assert.AreEqual(96, packets.Count);
Assert.IsTrue(packets.All(f => f.CodecType == "video")); Assert.IsTrue(packets.All(f => f.CodecType == "video"));
Assert.AreEqual("K_", packets[0].Flags); Assert.IsTrue(packets[0].Flags.StartsWith("K_"));
Assert.AreEqual(1362, packets.Last().Size); Assert.AreEqual(1362, packets.Last().Size);
} }
@ -70,7 +70,7 @@ public void PacketAnalysisAudioVideo_Sync()
var actual = packets.Select(f => f.CodecType).Distinct().ToList(); var actual = packets.Select(f => f.CodecType).Distinct().ToList();
var expected = new List<string> { "audio", "video" }; var expected = new List<string> { "audio", "video" };
CollectionAssert.AreEquivalent(expected, actual); CollectionAssert.AreEquivalent(expected, actual);
Assert.IsTrue(packets.Where(t => t.CodecType == "audio").All(f => f.Flags == "K_")); Assert.IsTrue(packets.Where(t => t.CodecType == "audio").All(f => f.Flags.StartsWith("K_")));
Assert.AreEqual(75, packets.Count(t => t.CodecType == "video")); Assert.AreEqual(75, packets.Count(t => t.CodecType == "video"));
Assert.AreEqual(141, packets.Count(t => t.CodecType == "audio")); Assert.AreEqual(141, packets.Count(t => t.CodecType == "audio"));
} }
@ -105,6 +105,7 @@ public void Probe_Success()
{ {
var info = FFProbe.Analyse(TestResources.Mp4Video); var info = FFProbe.Analyse(TestResources.Mp4Video);
Assert.AreEqual(3, info.Duration.Seconds); Assert.AreEqual(3, info.Duration.Seconds);
Assert.AreEqual(0, info.Chapters.Count);
Assert.AreEqual("5.1", info.PrimaryAudioStream!.ChannelLayout); Assert.AreEqual("5.1", info.PrimaryAudioStream!.ChannelLayout);
Assert.AreEqual(6, info.PrimaryAudioStream.Channels); Assert.AreEqual(6, info.PrimaryAudioStream.Channels);
@ -235,5 +236,12 @@ public async Task Probe_Success_32BitWavBitDepth_Async()
Assert.IsNotNull(info.PrimaryAudioStream); Assert.IsNotNull(info.PrimaryAudioStream);
Assert.AreEqual(32, info.PrimaryAudioStream.BitDepth); Assert.AreEqual(32, info.PrimaryAudioStream.BitDepth);
} }
[TestMethod]
public void Probe_Success_Custom_Arguments()
{
var info = FFProbe.Analyse(TestResources.Mp4Video, customArguments: "-headers \"Hello: World\"");
Assert.AreEqual(3, info.Duration.Seconds);
}
} }
} }

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,10 @@
namespace FFMpegCore.Arguments
{
/// <summary>
/// Represents a copy codec parameter
/// </summary>
public class CopyCodecArgument : IArgument
{
public string Text => $"-codec copy";
}
}

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

@ -0,0 +1,57 @@

namespace FFMpegCore.Arguments
{
internal class OutputTeeArgument : IOutputArgument
{
private readonly FFMpegMultiOutputOptions _options;
public OutputTeeArgument(FFMpegMultiOutputOptions options)
{
if (options.Outputs.Count == 0)
{
throw new ArgumentException("Atleast one output must be specified.", nameof(options));
}
_options = options;
}
public string Text => $"-f tee \"{string.Join("|", _options.Outputs.Select(MapOptions))}\"";
public Task During(CancellationToken cancellationToken = default) => Task.CompletedTask;
public void Post()
{
}
public void Pre()
{
}
private static string MapOptions(FFMpegArgumentOptions option)
{
var optionPrefix = string.Empty;
if (option.Arguments.Count > 1)
{
var options = option.Arguments.Take(option.Arguments.Count - 1);
optionPrefix = $"[{string.Join(":", options.Select(MapArgument))}]";
}
var output = option.Arguments.OfType<IOutputArgument>().Single();
return $"{optionPrefix}{output.Text.Trim('"')}";
}
private static string MapArgument(IArgument argument)
{
if (argument is MapStreamArgument map)
{
return map.Text.Replace("-map ", "select=\\'") + "\\'";
}
else if (argument is BitStreamFilterArgument bitstreamFilter)
{
return bitstreamFilter.Text.Replace("-bsf:", "bsfs/").Replace(' ', '=');
}
return argument.Text.TrimStart('-').Replace(' ', '=');
}
}
}

View file

@ -6,6 +6,8 @@ public class ChapterData
public TimeSpan Start { get; private set; } public TimeSpan Start { get; private set; }
public TimeSpan End { get; private set; } public TimeSpan End { get; private set; }
public TimeSpan Duration => End - Start;
public ChapterData(string title, TimeSpan start, TimeSpan end) public ChapterData(string title, TimeSpan start, TimeSpan end)
{ {
Title = title; Title = title;

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>
@ -303,7 +333,10 @@ public static bool SaveM3U8Stream(Uri uri, string output)
} }
return FFMpegArguments return FFMpegArguments
.FromUrlInput(uri) .FromUrlInput(uri, options =>
{
options.WithCopyCodec();
})
.OutputToFile(output) .OutputToFile(output)
.ProcessSynchronously(); .ProcessSynchronously();
} }

View file

@ -76,6 +76,8 @@ 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 WithCopyCodec() => WithArgument(new CopyCodecArgument());
public FFMpegArgumentOptions WithArgument(IArgument argument) public FFMpegArgumentOptions WithArgument(IArgument argument)
{ {

View file

@ -71,6 +71,21 @@ private FFMpegArgumentProcessor ToProcessor(IOutputArgument argument, Action<FFM
return new FFMpegArgumentProcessor(this); return new FFMpegArgumentProcessor(this);
} }
public FFMpegArgumentProcessor OutputToTee(Action<FFMpegMultiOutputOptions> addOutputs, Action<FFMpegArgumentOptions>? addArguments = null)
{
var outputs = new FFMpegMultiOutputOptions();
addOutputs(outputs);
return ToProcessor(new OutputTeeArgument(outputs), addArguments);
}
public FFMpegArgumentProcessor MultiOutput(Action<FFMpegMultiOutputOptions> addOutputs)
{
var args = new FFMpegMultiOutputOptions();
addOutputs(args);
Arguments.AddRange(args.Arguments);
return new FFMpegArgumentProcessor(this);
}
internal void Pre() internal void Pre()
{ {
foreach (var argument in Arguments.OfType<IInputOutputArgument>()) foreach (var argument in Arguments.OfType<IInputOutputArgument>())

View file

@ -0,0 +1,29 @@
using FFMpegCore.Arguments;
using FFMpegCore.Pipes;
namespace FFMpegCore
{
public class FFMpegMultiOutputOptions
{
internal readonly List<FFMpegArgumentOptions> Outputs = new();
public IEnumerable<IArgument> Arguments => Outputs.SelectMany(o => o.Arguments);
public FFMpegMultiOutputOptions OutputToFile(string file, bool overwrite = true, Action<FFMpegArgumentOptions>? addArguments = null) => AddOutput(new OutputArgument(file, overwrite), addArguments);
public FFMpegMultiOutputOptions OutputToUrl(string uri, Action<FFMpegArgumentOptions>? addArguments = null) => AddOutput(new OutputUrlArgument(uri), addArguments);
public FFMpegMultiOutputOptions OutputToUrl(Uri uri, Action<FFMpegArgumentOptions>? addArguments = null) => AddOutput(new OutputUrlArgument(uri.ToString()), addArguments);
public FFMpegMultiOutputOptions OutputToPipe(IPipeSink reader, Action<FFMpegArgumentOptions>? addArguments = null) => AddOutput(new OutputPipeArgument(reader), addArguments);
public FFMpegMultiOutputOptions AddOutput(IOutputArgument argument, Action<FFMpegArgumentOptions>? addArguments)
{
var args = new FFMpegArgumentOptions();
addArguments?.Invoke(args);
args.Arguments.Add(argument);
Outputs.Add(args);
return this;
}
}
}

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>
@ -18,7 +18,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Instances" Version="3.0.0" /> <PackageReference Include="Instances" Version="3.0.0" />
<PackageReference Include="System.Text.Json" Version="7.0.2" /> <PackageReference Include="System.Text.Json" Version="7.0.3" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View file

@ -10,52 +10,52 @@ namespace FFMpegCore
{ {
public static class FFProbe public static class FFProbe
{ {
public static IMediaAnalysis Analyse(string filePath, FFOptions? ffOptions = null) public static IMediaAnalysis Analyse(string filePath, FFOptions? ffOptions = null, string? customArguments = null)
{ {
ThrowIfInputFileDoesNotExist(filePath); ThrowIfInputFileDoesNotExist(filePath);
var processArguments = PrepareStreamAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current); var processArguments = PrepareStreamAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current, customArguments);
var result = processArguments.StartAndWaitForExit(); var result = processArguments.StartAndWaitForExit();
ThrowIfExitCodeNotZero(result); ThrowIfExitCodeNotZero(result);
return ParseOutput(result); return ParseOutput(result);
} }
public static FFProbeFrames GetFrames(string filePath, FFOptions? ffOptions = null) public static FFProbeFrames GetFrames(string filePath, FFOptions? ffOptions = null, string? customArguments = null)
{ {
ThrowIfInputFileDoesNotExist(filePath); ThrowIfInputFileDoesNotExist(filePath);
var instance = PrepareFrameAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current); var instance = PrepareFrameAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current, customArguments);
var result = instance.StartAndWaitForExit(); var result = instance.StartAndWaitForExit();
ThrowIfExitCodeNotZero(result); ThrowIfExitCodeNotZero(result);
return ParseFramesOutput(result); return ParseFramesOutput(result);
} }
public static FFProbePackets GetPackets(string filePath, FFOptions? ffOptions = null) public static FFProbePackets GetPackets(string filePath, FFOptions? ffOptions = null, string? customArguments = null)
{ {
ThrowIfInputFileDoesNotExist(filePath); ThrowIfInputFileDoesNotExist(filePath);
var instance = PreparePacketAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current); var instance = PreparePacketAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current, customArguments);
var result = instance.StartAndWaitForExit(); var result = instance.StartAndWaitForExit();
ThrowIfExitCodeNotZero(result); ThrowIfExitCodeNotZero(result);
return ParsePacketsOutput(result); return ParsePacketsOutput(result);
} }
public static IMediaAnalysis Analyse(Uri uri, FFOptions? ffOptions = null) public static IMediaAnalysis Analyse(Uri uri, FFOptions? ffOptions = null, string? customArguments = null)
{ {
var instance = PrepareStreamAnalysisInstance(uri.AbsoluteUri, ffOptions ?? GlobalFFOptions.Current); var instance = PrepareStreamAnalysisInstance(uri.AbsoluteUri, ffOptions ?? GlobalFFOptions.Current, customArguments);
var result = instance.StartAndWaitForExit(); var result = instance.StartAndWaitForExit();
ThrowIfExitCodeNotZero(result); ThrowIfExitCodeNotZero(result);
return ParseOutput(result); return ParseOutput(result);
} }
public static IMediaAnalysis Analyse(Stream stream, FFOptions? ffOptions = null) public static IMediaAnalysis Analyse(Stream stream, FFOptions? ffOptions = null, string? customArguments = null)
{ {
var streamPipeSource = new StreamPipeSource(stream); var streamPipeSource = new StreamPipeSource(stream);
var pipeArgument = new InputPipeArgument(streamPipeSource); var pipeArgument = new InputPipeArgument(streamPipeSource);
var instance = PrepareStreamAnalysisInstance(pipeArgument.PipePath, ffOptions ?? GlobalFFOptions.Current); var instance = PrepareStreamAnalysisInstance(pipeArgument.PipePath, ffOptions ?? GlobalFFOptions.Current, customArguments);
pipeArgument.Pre(); pipeArgument.Pre();
var task = instance.StartAndWaitForExitAsync(); var task = instance.StartAndWaitForExitAsync();
@ -75,57 +75,57 @@ public static IMediaAnalysis Analyse(Stream stream, FFOptions? ffOptions = null)
return ParseOutput(result); return ParseOutput(result);
} }
public static async Task<IMediaAnalysis> AnalyseAsync(string filePath, FFOptions? ffOptions = null, CancellationToken cancellationToken = default) public static async Task<IMediaAnalysis> AnalyseAsync(string filePath, FFOptions? ffOptions = null, CancellationToken cancellationToken = default, string? customArguments = null)
{ {
ThrowIfInputFileDoesNotExist(filePath); ThrowIfInputFileDoesNotExist(filePath);
var instance = PrepareStreamAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current); var instance = PrepareStreamAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current, customArguments);
var result = await instance.StartAndWaitForExitAsync(cancellationToken).ConfigureAwait(false); var result = await instance.StartAndWaitForExitAsync(cancellationToken).ConfigureAwait(false);
ThrowIfExitCodeNotZero(result); ThrowIfExitCodeNotZero(result);
return ParseOutput(result); return ParseOutput(result);
} }
public static FFProbeFrames GetFrames(Uri uri, FFOptions? ffOptions = null) public static FFProbeFrames GetFrames(Uri uri, FFOptions? ffOptions = null, string? customArguments = null)
{ {
var instance = PrepareFrameAnalysisInstance(uri.AbsoluteUri, ffOptions ?? GlobalFFOptions.Current); var instance = PrepareFrameAnalysisInstance(uri.AbsoluteUri, ffOptions ?? GlobalFFOptions.Current, customArguments);
var result = instance.StartAndWaitForExit(); var result = instance.StartAndWaitForExit();
ThrowIfExitCodeNotZero(result); ThrowIfExitCodeNotZero(result);
return ParseFramesOutput(result); return ParseFramesOutput(result);
} }
public static async Task<FFProbeFrames> GetFramesAsync(string filePath, FFOptions? ffOptions = null, CancellationToken cancellationToken = default) public static async Task<FFProbeFrames> GetFramesAsync(string filePath, FFOptions? ffOptions = null, CancellationToken cancellationToken = default, string? customArguments = null)
{ {
ThrowIfInputFileDoesNotExist(filePath); ThrowIfInputFileDoesNotExist(filePath);
var instance = PrepareFrameAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current); var instance = PrepareFrameAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current, customArguments);
var result = await instance.StartAndWaitForExitAsync(cancellationToken).ConfigureAwait(false); var result = await instance.StartAndWaitForExitAsync(cancellationToken).ConfigureAwait(false);
return ParseFramesOutput(result); return ParseFramesOutput(result);
} }
public static async Task<FFProbePackets> GetPacketsAsync(string filePath, FFOptions? ffOptions = null, CancellationToken cancellationToken = default) public static async Task<FFProbePackets> GetPacketsAsync(string filePath, FFOptions? ffOptions = null, CancellationToken cancellationToken = default, string? customArguments = null)
{ {
ThrowIfInputFileDoesNotExist(filePath); ThrowIfInputFileDoesNotExist(filePath);
var instance = PreparePacketAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current); var instance = PreparePacketAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current, customArguments);
var result = await instance.StartAndWaitForExitAsync(cancellationToken).ConfigureAwait(false); var result = await instance.StartAndWaitForExitAsync(cancellationToken).ConfigureAwait(false);
return ParsePacketsOutput(result); return ParsePacketsOutput(result);
} }
public static async Task<IMediaAnalysis> AnalyseAsync(Uri uri, FFOptions? ffOptions = null, CancellationToken cancellationToken = default) public static async Task<IMediaAnalysis> AnalyseAsync(Uri uri, FFOptions? ffOptions = null, CancellationToken cancellationToken = default, string? customArguments = null)
{ {
var instance = PrepareStreamAnalysisInstance(uri.AbsoluteUri, ffOptions ?? GlobalFFOptions.Current); var instance = PrepareStreamAnalysisInstance(uri.AbsoluteUri, ffOptions ?? GlobalFFOptions.Current, customArguments);
var result = await instance.StartAndWaitForExitAsync(cancellationToken).ConfigureAwait(false); var result = await instance.StartAndWaitForExitAsync(cancellationToken).ConfigureAwait(false);
ThrowIfExitCodeNotZero(result); ThrowIfExitCodeNotZero(result);
return ParseOutput(result); return ParseOutput(result);
} }
public static async Task<IMediaAnalysis> AnalyseAsync(Stream stream, FFOptions? ffOptions = null, CancellationToken cancellationToken = default) public static async Task<IMediaAnalysis> AnalyseAsync(Stream stream, FFOptions? ffOptions = null, CancellationToken cancellationToken = default, string? customArguments = null)
{ {
var streamPipeSource = new StreamPipeSource(stream); var streamPipeSource = new StreamPipeSource(stream);
var pipeArgument = new InputPipeArgument(streamPipeSource); var pipeArgument = new InputPipeArgument(streamPipeSource);
var instance = PrepareStreamAnalysisInstance(pipeArgument.PipePath, ffOptions ?? GlobalFFOptions.Current); var instance = PrepareStreamAnalysisInstance(pipeArgument.PipePath, ffOptions ?? GlobalFFOptions.Current, customArguments);
pipeArgument.Pre(); pipeArgument.Pre();
var task = instance.StartAndWaitForExitAsync(cancellationToken); var task = instance.StartAndWaitForExitAsync(cancellationToken);
@ -148,9 +148,9 @@ public static async Task<IMediaAnalysis> AnalyseAsync(Stream stream, FFOptions?
return ParseOutput(result); return ParseOutput(result);
} }
public static async Task<FFProbeFrames> GetFramesAsync(Uri uri, FFOptions? ffOptions = null, CancellationToken cancellationToken = default) public static async Task<FFProbeFrames> GetFramesAsync(Uri uri, FFOptions? ffOptions = null, CancellationToken cancellationToken = default, string? customArguments = null)
{ {
var instance = PrepareFrameAnalysisInstance(uri.AbsoluteUri, ffOptions ?? GlobalFFOptions.Current); var instance = PrepareFrameAnalysisInstance(uri.AbsoluteUri, ffOptions ?? GlobalFFOptions.Current, customArguments);
var result = await instance.StartAndWaitForExitAsync(cancellationToken).ConfigureAwait(false); var result = await instance.StartAndWaitForExitAsync(cancellationToken).ConfigureAwait(false);
return ParseFramesOutput(result); return ParseFramesOutput(result);
} }
@ -212,18 +212,18 @@ private static void ThrowIfExitCodeNotZero(IProcessResult result)
} }
} }
private static ProcessArguments PrepareStreamAnalysisInstance(string filePath, FFOptions ffOptions) private static ProcessArguments PrepareStreamAnalysisInstance(string filePath, FFOptions ffOptions, string? customArguments)
=> PrepareInstance($"-loglevel error -print_format json -show_format -sexagesimal -show_streams \"{filePath}\"", ffOptions); => PrepareInstance($"-loglevel error -print_format json -show_format -sexagesimal -show_streams -show_chapters \"{filePath}\"", ffOptions, customArguments);
private static ProcessArguments PrepareFrameAnalysisInstance(string filePath, FFOptions ffOptions) private static ProcessArguments PrepareFrameAnalysisInstance(string filePath, FFOptions ffOptions, string? customArguments)
=> PrepareInstance($"-loglevel error -print_format json -show_frames -v quiet -sexagesimal \"{filePath}\"", ffOptions); => PrepareInstance($"-loglevel error -print_format json -show_frames -v quiet -sexagesimal \"{filePath}\"", ffOptions, customArguments);
private static ProcessArguments PreparePacketAnalysisInstance(string filePath, FFOptions ffOptions) private static ProcessArguments PreparePacketAnalysisInstance(string filePath, FFOptions ffOptions, string? customArguments)
=> PrepareInstance($"-loglevel error -print_format json -show_packets -v quiet -sexagesimal \"{filePath}\"", ffOptions); => PrepareInstance($"-loglevel error -print_format json -show_packets -v quiet -sexagesimal \"{filePath}\"", ffOptions, customArguments);
private static ProcessArguments PrepareInstance(string arguments, FFOptions ffOptions) private static ProcessArguments PrepareInstance(string arguments, FFOptions ffOptions, string? customArguments)
{ {
FFProbeHelper.RootExceptionCheck(); FFProbeHelper.RootExceptionCheck();
FFProbeHelper.VerifyFFProbeExists(ffOptions); FFProbeHelper.VerifyFFProbeExists(ffOptions);
var startInfo = new ProcessStartInfo(GlobalFFOptions.GetFFProbeBinaryPath(ffOptions), arguments) var startInfo = new ProcessStartInfo(GlobalFFOptions.GetFFProbeBinaryPath(ffOptions), $"{arguments} {customArguments}")
{ {
StandardOutputEncoding = ffOptions.Encoding, StandardOutputEncoding = ffOptions.Encoding,
StandardErrorEncoding = ffOptions.Encoding, StandardErrorEncoding = ffOptions.Encoding,

View file

@ -11,6 +11,9 @@ public class FFProbeAnalysis
[JsonPropertyName("format")] [JsonPropertyName("format")]
public Format Format { get; set; } = null!; public Format Format { get; set; } = null!;
[JsonPropertyName("chapters")]
public List<Chapter> Chapters { get; set; } = null!;
[JsonIgnore] [JsonIgnore]
public IReadOnlyList<string> ErrorData { get; set; } = new List<string>(); public IReadOnlyList<string> ErrorData { get; set; } = new List<string>();
} }
@ -87,7 +90,7 @@ public class FFProbeStream : ITagsContainer, IDispositionContainer
public Dictionary<string, int> Disposition { get; set; } = null!; public Dictionary<string, int> Disposition { get; set; } = null!;
[JsonPropertyName("tags")] [JsonPropertyName("tags")]
public Dictionary<string, string> Tags { get; set; } = null!; public Dictionary<string, string>? Tags { get; set; }
[JsonPropertyName("side_data_list")] [JsonPropertyName("side_data_list")]
public List<Dictionary<string, JsonValue>> SideData { get; set; } = null!; public List<Dictionary<string, JsonValue>> SideData { get; set; } = null!;
@ -126,7 +129,31 @@ public class Format : ITagsContainer
public int ProbeScore { get; set; } public int ProbeScore { get; set; }
[JsonPropertyName("tags")] [JsonPropertyName("tags")]
public Dictionary<string, string> Tags { get; set; } = null!; public Dictionary<string, string>? Tags { get; set; }
}
public class Chapter : ITagsContainer
{
[JsonPropertyName("id")]
public long Id { get; set; }
[JsonPropertyName("time_base")]
public string TimeBase { get; set; } = null!;
[JsonPropertyName("start")]
public long Start { get; set; }
[JsonPropertyName("start_time")]
public string StartTime { get; set; } = null!;
[JsonPropertyName("end")]
public long End { get; set; }
[JsonPropertyName("end_time")]
public string EndTime { get; set; } = null!;
[JsonPropertyName("tags")]
public Dictionary<string, string>? Tags { get; set; }
} }
public interface IDispositionContainer public interface IDispositionContainer
@ -136,7 +163,7 @@ public interface IDispositionContainer
public interface ITagsContainer public interface ITagsContainer
{ {
Dictionary<string, string> Tags { get; set; } Dictionary<string, string>? Tags { get; set; }
} }
public static class TagExtensions public static class TagExtensions

View file

@ -1,9 +1,12 @@
namespace FFMpegCore using FFMpegCore.Builders.MetaData;
namespace FFMpegCore
{ {
public interface IMediaAnalysis public interface IMediaAnalysis
{ {
TimeSpan Duration { get; } TimeSpan Duration { get; }
MediaFormat Format { get; } MediaFormat Format { get; }
List<ChapterData> Chapters { get; }
AudioStream? PrimaryAudioStream { get; } AudioStream? PrimaryAudioStream { get; }
VideoStream? PrimaryVideoStream { get; } VideoStream? PrimaryVideoStream { get; }
SubtitleStream? PrimarySubtitleStream { get; } SubtitleStream? PrimarySubtitleStream { get; }

View file

@ -1,4 +1,5 @@
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using FFMpegCore.Builders.MetaData;
namespace FFMpegCore namespace FFMpegCore
{ {
@ -7,6 +8,7 @@ internal class MediaAnalysis : IMediaAnalysis
internal MediaAnalysis(FFProbeAnalysis analysis) internal MediaAnalysis(FFProbeAnalysis analysis)
{ {
Format = ParseFormat(analysis.Format); Format = ParseFormat(analysis.Format);
Chapters = analysis.Chapters.Select(c => ParseChapter(c)).ToList();
VideoStreams = analysis.Streams.Where(stream => stream.CodecType == "video").Select(ParseVideoStream).ToList(); VideoStreams = analysis.Streams.Where(stream => stream.CodecType == "video").Select(ParseVideoStream).ToList();
AudioStreams = analysis.Streams.Where(stream => stream.CodecType == "audio").Select(ParseAudioStream).ToList(); AudioStreams = analysis.Streams.Where(stream => stream.CodecType == "audio").Select(ParseAudioStream).ToList();
SubtitleStreams = analysis.Streams.Where(stream => stream.CodecType == "subtitle").Select(ParseSubtitleStream).ToList(); SubtitleStreams = analysis.Streams.Where(stream => stream.CodecType == "subtitle").Select(ParseSubtitleStream).ToList();
@ -28,6 +30,15 @@ private MediaFormat ParseFormat(Format analysisFormat)
}; };
} }
private ChapterData ParseChapter(Chapter analysisChapter)
{
var title = analysisChapter.Tags.FirstOrDefault(t => t.Key == "title").Value;
var start = MediaAnalysisUtils.ParseDuration(analysisChapter.StartTime);
var end = MediaAnalysisUtils.ParseDuration(analysisChapter.EndTime);
return new ChapterData(title, start, end);
}
public TimeSpan Duration => new[] public TimeSpan Duration => new[]
{ {
Format.Duration, Format.Duration,
@ -37,6 +48,8 @@ private MediaFormat ParseFormat(Format analysisFormat)
public MediaFormat Format { get; } public MediaFormat Format { get; }
public List<ChapterData> Chapters { get; }
public AudioStream? PrimaryAudioStream => AudioStreams.OrderBy(stream => stream.Index).FirstOrDefault(); public AudioStream? PrimaryAudioStream => AudioStreams.OrderBy(stream => stream.Index).FirstOrDefault();
public VideoStream? PrimaryVideoStream => VideoStreams.OrderBy(stream => stream.Index).FirstOrDefault(); public VideoStream? PrimaryVideoStream => VideoStreams.OrderBy(stream => stream.Index).FirstOrDefault();
public SubtitleStream? PrimarySubtitleStream => SubtitleStreams.OrderBy(stream => stream.Index).FirstOrDefault(); public SubtitleStream? PrimarySubtitleStream => SubtitleStreams.OrderBy(stream => stream.Index).FirstOrDefault();

View file

@ -1,6 +1,6 @@
namespace FFMpegCore namespace FFMpegCore
{ {
public class MediaFormat public class MediaFormat : ITagsContainer
{ {
public TimeSpan Duration { get; set; } public TimeSpan Duration { get; set; }
public TimeSpan StartTime { get; set; } public TimeSpan StartTime { get; set; }

View file

@ -2,7 +2,7 @@
namespace FFMpegCore namespace FFMpegCore
{ {
public abstract class MediaStream public abstract class MediaStream : ITagsContainer
{ {
public int Index { get; set; } public int Index { get; set; }
public string CodecName { get; set; } = null!; public string CodecName { get; set; } = null!;

View file

@ -30,12 +30,23 @@ private static string GetFFBinaryPath(string name, FFOptions ffOptions)
} }
var target = Environment.Is64BitProcess ? "x64" : "x86"; var target = Environment.Is64BitProcess ? "x64" : "x86";
if (Directory.Exists(Path.Combine(ffOptions.BinaryFolder, target))) var possiblePaths = new List<string>()
{ {
ffName = Path.Combine(target, ffName); Path.Combine(ffOptions.BinaryFolder, target),
ffOptions.BinaryFolder
};
foreach (var possiblePath in possiblePaths)
{
var possibleFFMpegPath = Path.Combine(possiblePath, ffName);
if (File.Exists(possibleFFMpegPath))
{
return possibleFFMpegPath;
}
} }
return Path.Combine(ffOptions.BinaryFolder, ffName); //Fall back to the assumption this tool exists in the PATH
return ffName;
} }
private static FFOptions LoadFFOptions() private static FFOptions LoadFFOptions()

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",
@ -76,7 +87,7 @@ FFMpeg.Join(@"..\joined_video.mp4",
``` csharp ``` csharp
FFMpeg.SubVideo(inputPath, FFMpeg.SubVideo(inputPath,
outputPath, outputPath,
TimeSpan.FromSeconds(0) TimeSpan.FromSeconds(0),
TimeSpan.FromSeconds(30) TimeSpan.FromSeconds(30)
); );
``` ```