Merge branch 'bugfix/ensure-ffmpeg-not-found-throws-ffmpegexception' of https://github.com/rosenbjerg/FFMpegCore into bugfix/ensure-ffmpeg-not-found-throws-ffmpegexception

This commit is contained in:
Malte Rosenbjerg 2025-10-17 15:38:47 +02:00
commit 5fa92707e6
17 changed files with 334 additions and 73 deletions

View file

@ -1,28 +1,24 @@
name: CI name: CI
on: on:
push:
branches:
- master
paths:
- .github/workflows/ci.yml
- FFMpegCore/**
- FFMpegCore.Test/**
pull_request: pull_request:
branches: branches:
- main - main
- release - release
paths: paths:
- .github/workflows/ci.yml - .github/workflows/ci.yml
- FFMpegCore/** - Directory.Build.props
- FFMpegCore.Test/** - FFMpegCore/**
- FFMpegCore.Test/**
- FFMpegCore.Extensions.SkiaSharp/**
- FFMpegCore.Extensions.System.Drawing.Common/**
jobs: jobs:
ci: ci:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
matrix: matrix:
os: [windows-latest, ubuntu-latest, macos-13] os: [windows-latest, ubuntu-latest, macos-latest]
timeout-minutes: 7 timeout-minutes: 7
steps: steps:
@ -34,21 +30,24 @@ jobs:
with: with:
dotnet-version: '8.0.x' dotnet-version: '8.0.x'
- name: Lint with dotnet - if: matrix.os == 'ubuntu-latest'
name: Lint with dotnet
run: dotnet format FFMpegCore.sln --severity warn --verify-no-changes run: dotnet format FFMpegCore.sln --severity warn --verify-no-changes
- name: Prepare FFMpeg - name: Setup FFmpeg
uses: FedericoCarboni/setup-ffmpeg@v3 uses: AnimMouse/setup-ffmpeg@ae28d57dabbb148eff63170b6bf7f2b60062cbae # 1.1.0
with: with:
token: ${{ secrets.GITHUB_TOKEN }} version: ${{ matrix.os != 'macos-latest' && '7.1' || '711' }}
token: ${{ github.token }}
- name: Test with dotnet - name: Test with dotnet
run: dotnet test FFMpegCore.sln --collect "XPlat Code Coverage" --logger GitHubActions run: dotnet test FFMpegCore.sln --collect "XPlat Code Coverage" --logger GitHubActions
- if: matrix.os == 'windows-latest' - if: matrix.os == 'windows-latest'
name: Upload coverage reports to Codecov name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v5 uses: codecov/codecov-action@v4
with: with:
fail_ci_if_error: true fail_ci_if_error: true
directory: FFMpegCore.Test/TestResults directory: FFMpegCore.Test/TestResults
token: ${{ secrets.CODECOV_TOKEN }} token: ${{ secrets.CODECOV_TOKEN }}
os: windows

View file

@ -13,5 +13,14 @@
<PackageProjectUrl>https://github.com/rosenbjerg/FFMpegCore</PackageProjectUrl> <PackageProjectUrl>https://github.com/rosenbjerg/FFMpegCore</PackageProjectUrl>
<PackageLicenseExpression>MIT</PackageLicenseExpression> <PackageLicenseExpression>MIT</PackageLicenseExpression>
<NeutralLanguage>en</NeutralLanguage> <NeutralLanguage>en</NeutralLanguage>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(GITHUB_ACTIONS)' == 'true'">
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
</PropertyGroup>
</Project> </Project>

View file

@ -3,18 +3,17 @@
<PropertyGroup> <PropertyGroup>
<IsPackable>true</IsPackable> <IsPackable>true</IsPackable>
<Description>Image extension for FFMpegCore using SkiaSharp</Description> <Description>Image extension for FFMpegCore using SkiaSharp</Description>
<PackageVersion>5.0.0</PackageVersion> <PackageVersion>5.0.2</PackageVersion>
<PackageOutputPath>../nupkg</PackageOutputPath> <PackageOutputPath>../nupkg</PackageOutputPath>
<PackageReleaseNotes> <PackageReleaseNotes>Bump dependencies</PackageReleaseNotes>
</PackageReleaseNotes>
<PackageTags>ffmpeg ffprobe convert video audio mediafile resize analyze muxing skiasharp</PackageTags> <PackageTags>ffmpeg ffprobe convert video audio mediafile resize analyze muxing skiasharp</PackageTags>
<Authors>Malte Rosenbjerg, Vlad Jerca, Max Bagryantsev, Dimitri Vranken</Authors> <Authors>Malte Rosenbjerg, Vlad Jerca, Max Bagryantsev, Dimitri Vranken</Authors>
<ProduceReferenceAssembly>true</ProduceReferenceAssembly> <ProduceReferenceAssembly>true</ProduceReferenceAssembly>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="SkiaSharp" Version="2.88.6" /> <PackageReference Include="SkiaSharp" Version="3.116.1" />
<PackageReference Include="SkiaSharp.NativeAssets.Linux.NoDependencies" Version="2.88.6" /> <PackageReference Include="SkiaSharp.NativeAssets.Linux.NoDependencies" Version="3.116.1" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View file

@ -3,17 +3,16 @@
<PropertyGroup> <PropertyGroup>
<IsPackable>true</IsPackable> <IsPackable>true</IsPackable>
<Description>Image extension for FFMpegCore using System.Common.Drawing</Description> <Description>Image extension for FFMpegCore using System.Common.Drawing</Description>
<PackageVersion>5.0.0</PackageVersion> <PackageVersion>5.0.2</PackageVersion>
<PackageOutputPath>../nupkg</PackageOutputPath> <PackageOutputPath>../nupkg</PackageOutputPath>
<PackageReleaseNotes> <PackageReleaseNotes>Bump dependencies</PackageReleaseNotes>
</PackageReleaseNotes>
<PackageTags>ffmpeg ffprobe convert video audio mediafile resize analyze muxing</PackageTags> <PackageTags>ffmpeg ffprobe convert video audio mediafile resize analyze muxing</PackageTags>
<Authors>Malte Rosenbjerg, Vlad Jerca, Max Bagryantsev</Authors> <Authors>Malte Rosenbjerg, Vlad Jerca, Max Bagryantsev</Authors>
<ProduceReferenceAssembly>true</ProduceReferenceAssembly> <ProduceReferenceAssembly>true</ProduceReferenceAssembly>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="System.Drawing.Common" Version="7.0.0"/> <PackageReference Include="System.Drawing.Common" Version="9.0.2" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View file

@ -9,6 +9,7 @@ namespace FFMpegCore.Test
public class ArgumentBuilderTest public class ArgumentBuilderTest
{ {
private readonly string[] _concatFiles = { "1.mp4", "2.mp4", "3.mp4", "4.mp4" }; private readonly string[] _concatFiles = { "1.mp4", "2.mp4", "3.mp4", "4.mp4" };
private readonly string[] _multiFiles = { "1.mp3", "2.mp3", "3.mp3", "4.mp3" };
[TestMethod] [TestMethod]
public void Builder_BuildString_IO_1() public void Builder_BuildString_IO_1()
@ -611,5 +612,86 @@ namespace FFMpegCore.Test
-i "input.mp4" -f tee "[movflags=faststart]output.mp4|[f=mpegts:select=\'0:v:0\']http://server/path" -i "input.mp4" -f tee "[movflags=faststart]output.mp4|[f=mpegts:select=\'0:v:0\']http://server/path"
""", str); """, str);
} }
[TestMethod]
public void Builder_BuildString_MultiInput()
{
var audioStreams = string.Join("", _multiFiles.Select((item, index) => $"[{index}:0]"));
var mixFilter = $"{audioStreams}amix=inputs={_multiFiles.Length}:duration=longest:dropout_transition=1:normalize=0[final]";
var ffmpegArgs = $"-filter_complex \"{mixFilter}\" -map \"[final]\"";
var str = FFMpegArguments
.FromFileInput(_multiFiles)
.OutputToFile("output.mp3", overwrite: true, options => options
.WithCustomArgument(ffmpegArgs)
.WithAudioCodec(AudioCodec.LibMp3Lame) // Set the audio codec to MP3
.WithAudioBitrate(128) // Set the bitrate to 128kbps
.WithAudioSamplingRate(48000) // Set the sample rate to 48kHz
.WithoutMetadata() // Remove metadata
.WithCustomArgument("-ac 2 -write_xing 0 -id3v2_version 0")) // Force 2 Channels
.Arguments;
Assert.AreEqual($"-i \"1.mp3\" -i \"2.mp3\" -i \"3.mp3\" -i \"4.mp3\" -filter_complex \"[0:0][1:0][2:0][3:0]amix=inputs=4:duration=longest:dropout_transition=1:normalize=0[final]\" -map \"[final]\" -c:a libmp3lame -b:a 128k -ar 48000 -map_metadata -1 -ac 2 -write_xing 0 -id3v2_version 0 \"output.mp3\" -y", str);
}
[TestMethod]
public void Pre_VerifyExists_AllFilesExist()
{
// Arrange
var filePaths = new List<string>
{
Path.GetTempFileName(),
Path.GetTempFileName(),
Path.GetTempFileName()
};
var argument = new MultiInputArgument(true, filePaths);
try
{
// Act & Assert
argument.Pre(); // No exception should be thrown
}
finally
{
// Cleanup
foreach (var filePath in filePaths)
{
File.Delete(filePath);
}
}
}
[TestMethod]
public void Pre_VerifyExists_SomeFilesNotExist()
{
// Arrange
var filePaths = new List<string>
{
Path.GetTempFileName(),
"file2.mp4",
"file3.mp4"
};
var argument = new MultiInputArgument(true, filePaths);
try
{
// Act & Assert
Assert.ThrowsException<FileNotFoundException>(() => argument.Pre());
}
finally
{
// Cleanup
File.Delete(filePaths[0]);
}
}
[TestMethod]
public void Pre_VerifyExists_NoFilesExist()
{
// Arrange
var filePaths = new List<string>
{
"file1.mp4",
"file2.mp4",
"file3.mp4"
};
var argument = new MultiInputArgument(true, filePaths);
// Act & Assert
Assert.ThrowsException<FileNotFoundException>(() => argument.Pre());
}
} }
} }

View file

@ -8,19 +8,19 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.2"> <PackageReference Include="coverlet.collector" Version="6.0.4">
<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="7.0.0" /> <PackageReference Include="FluentAssertions" Version="8.0.1" />
<PackageReference Include="GitHubActionsTestLogger" Version="2.4.1"> <PackageReference Include="GitHubActionsTestLogger" Version="2.4.1">
<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.12.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.13.0" />
<PackageReference Include="MSTest.TestAdapter" Version="3.6.4" /> <PackageReference Include="MSTest.TestAdapter" Version="3.8.0" />
<PackageReference Include="MSTest.TestFramework" Version="3.6.4" /> <PackageReference Include="MSTest.TestFramework" Version="3.8.0" />
<PackageReference Include="SkiaSharp" Version="2.88.6" /> <PackageReference Include="SkiaSharp" Version="3.116.1" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View file

@ -467,7 +467,7 @@ namespace FFMpegCore.Test
} }
[TestMethod, Timeout(BaseTimeoutMilliseconds)] [TestMethod, Timeout(BaseTimeoutMilliseconds)]
public void Video_Snapshot_PersistSnapshot() public void Video_Snapshot_Png_PersistSnapshot()
{ {
using var outputPath = new TemporaryFile("out.png"); using var outputPath = new TemporaryFile("out.png");
var input = FFProbe.Analyse(TestResources.Mp4Video); var input = FFProbe.Analyse(TestResources.Mp4Video);
@ -480,6 +480,63 @@ namespace FFMpegCore.Test
Assert.AreEqual("png", analysis.PrimaryVideoStream!.CodecName); Assert.AreEqual("png", analysis.PrimaryVideoStream!.CodecName);
} }
[TestMethod, Timeout(BaseTimeoutMilliseconds)]
public void Video_Snapshot_Jpg_PersistSnapshot()
{
using var outputPath = new TemporaryFile("out.jpg");
var input = FFProbe.Analyse(TestResources.Mp4Video);
FFMpeg.Snapshot(TestResources.Mp4Video, outputPath);
var analysis = FFProbe.Analyse(outputPath);
Assert.AreEqual(input.PrimaryVideoStream!.Width, analysis.PrimaryVideoStream!.Width);
Assert.AreEqual(input.PrimaryVideoStream.Height, analysis.PrimaryVideoStream!.Height);
Assert.AreEqual("mjpeg", analysis.PrimaryVideoStream!.CodecName);
}
[TestMethod, Timeout(BaseTimeoutMilliseconds)]
public void Video_Snapshot_Bmp_PersistSnapshot()
{
using var outputPath = new TemporaryFile("out.bmp");
var input = FFProbe.Analyse(TestResources.Mp4Video);
FFMpeg.Snapshot(TestResources.Mp4Video, outputPath);
var analysis = FFProbe.Analyse(outputPath);
Assert.AreEqual(input.PrimaryVideoStream!.Width, analysis.PrimaryVideoStream!.Width);
Assert.AreEqual(input.PrimaryVideoStream.Height, analysis.PrimaryVideoStream!.Height);
Assert.AreEqual("bmp", analysis.PrimaryVideoStream!.CodecName);
}
[TestMethod, Timeout(BaseTimeoutMilliseconds)]
public void Video_Snapshot_Webp_PersistSnapshot()
{
using var outputPath = new TemporaryFile("out.webp");
var input = FFProbe.Analyse(TestResources.Mp4Video);
FFMpeg.Snapshot(TestResources.Mp4Video, outputPath);
var analysis = FFProbe.Analyse(outputPath);
Assert.AreEqual(input.PrimaryVideoStream!.Width, analysis.PrimaryVideoStream!.Width);
Assert.AreEqual(input.PrimaryVideoStream.Height, analysis.PrimaryVideoStream!.Height);
Assert.AreEqual("webp", analysis.PrimaryVideoStream!.CodecName);
}
[TestMethod, Timeout(BaseTimeoutMilliseconds)]
public void Video_Snapshot_Exception_PersistSnapshot()
{
using var outputPath = new TemporaryFile("out.asd");
try
{
FFMpeg.Snapshot(TestResources.Mp4Video, outputPath);
}
catch (Exception ex)
{
Assert.IsTrue(ex is ArgumentException);
}
}
[TestMethod, Timeout(BaseTimeoutMilliseconds)] [TestMethod, Timeout(BaseTimeoutMilliseconds)]
public void Video_Snapshot_Rotated_PersistSnapshot() public void Video_Snapshot_Rotated_PersistSnapshot()
{ {

View file

@ -8,6 +8,6 @@
/// <param name="context"></param> /// <param name="context"></param>
/// <returns></returns> /// <returns></returns>
//public string GetText(StringBuilder context); //public string GetText(StringBuilder context);
public string GetText(IEnumerable<IArgument> context); string GetText(IEnumerable<IArgument> context);
} }
} }

View file

@ -0,0 +1,47 @@
namespace FFMpegCore.Arguments
{
/// <summary>
/// Represents input parameters for multiple files
/// </summary>
public class MultiInputArgument : IInputArgument
{
public readonly bool VerifyExists;
public readonly IEnumerable<string> FilePaths;
public MultiInputArgument(bool verifyExists, IEnumerable<string> filePaths)
{
VerifyExists = verifyExists;
FilePaths = filePaths;
}
public MultiInputArgument(IEnumerable<string> filePaths, bool verifyExists) : this(verifyExists, filePaths) { }
public void Pre()
{
if (VerifyExists)
{
var missingFiles = new List<string>();
foreach (var filePath in FilePaths)
{
if (!File.Exists(filePath))
{
missingFiles.Add(filePath);
}
}
if (missingFiles.Any())
{
throw new FileNotFoundException($"The following input files were not found: {string.Join(", ", missingFiles)}");
}
}
}
public Task During(CancellationToken cancellationToken = default) => Task.CompletedTask;
public void Post() { }
/// <summary>
/// Generates a combined input argument text for all file paths
/// </summary>
public string Text => string.Join(" ", FilePaths.Select(filePath => $"-i \"{filePath}\""));
}
}

View file

@ -36,8 +36,8 @@ namespace FFMpegCore.Arguments
public interface IVideoFilterArgument public interface IVideoFilterArgument
{ {
public string Key { get; } string Key { get; }
public string Value { get; } string Value { get; }
} }
public class VideoFilterOptions public class VideoFilterOptions

View file

@ -15,9 +15,33 @@
public static Codec LibX265 => FFMpeg.GetCodec("libx265"); public static Codec LibX265 => FFMpeg.GetCodec("libx265");
public static Codec LibVpx => FFMpeg.GetCodec("libvpx"); public static Codec LibVpx => FFMpeg.GetCodec("libvpx");
public static Codec LibTheora => FFMpeg.GetCodec("libtheora"); public static Codec LibTheora => FFMpeg.GetCodec("libtheora");
public static Codec Png => FFMpeg.GetCodec("png");
public static Codec MpegTs => FFMpeg.GetCodec("mpegts"); public static Codec MpegTs => FFMpeg.GetCodec("mpegts");
public static Codec LibaomAv1 => FFMpeg.GetCodec("libaom-av1"); public static Codec LibaomAv1 => FFMpeg.GetCodec("libaom-av1");
public static class Image
{
public static Codec Png => FFMpeg.GetCodec("png");
public static Codec Jpg => FFMpeg.GetCodec("mjpeg");
public static Codec Bmp => FFMpeg.GetCodec("bmp");
public static Codec Webp => FFMpeg.GetCodec("webp");
public static Codec GetByExtension(string path)
{
var ext = Path.GetExtension(path);
switch (ext)
{
case FileExtension.Image.Png:
return Png;
case FileExtension.Image.Jpg:
return Jpg;
case FileExtension.Image.Bmp:
return Bmp;
case FileExtension.Image.Webp:
return Webp;
default: throw new NotSupportedException($"Unsupported image extension: {ext}");
}
}
}
} }
public static class AudioCodec public static class AudioCodec

View file

@ -10,7 +10,10 @@
"libxvpx" => WebM, "libxvpx" => WebM,
"libxtheora" => Ogv, "libxtheora" => Ogv,
"mpegts" => Ts, "mpegts" => Ts,
"png" => Png, "png" => Image.Png,
"jpg" => Image.Jpg,
"bmp" => Image.Bmp,
"webp" => Image.Webp,
_ => throw new Exception("The extension for this video type is not defined.") _ => throw new Exception("The extension for this video type is not defined.")
}; };
} }
@ -18,8 +21,16 @@
public static readonly string Ts = VideoType.MpegTs.Extension; public static readonly string Ts = VideoType.MpegTs.Extension;
public static readonly string Ogv = VideoType.Ogv.Extension; public static readonly string Ogv = VideoType.Ogv.Extension;
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 Mp3 = ".mp3"; public static readonly string Mp3 = ".mp3";
public static readonly string Gif = ".gif"; public static readonly string Gif = ".gif";
public static class Image
{
public const string Png = ".png";
public const string Jpg = ".jpg";
public const string Bmp = ".bmp";
public const string Webp = ".webp";
public static readonly List<string> All = [Png, Jpg, Bmp, Webp];
}
} }
} }

View file

@ -20,16 +20,11 @@ namespace FFMpegCore
/// <returns>Bitmap with the requested snapshot.</returns> /// <returns>Bitmap with the requested snapshot.</returns>
public static bool Snapshot(string input, string output, Size? size = null, TimeSpan? captureTime = null, int? streamIndex = null, int inputFileIndex = 0) public static bool Snapshot(string input, string output, Size? size = null, TimeSpan? captureTime = null, int? streamIndex = null, int inputFileIndex = 0)
{ {
if (Path.GetExtension(output) != FileExtension.Png) CheckSnapshotOutputExtension(output, FileExtension.Image.All);
{
output = Path.Combine(Path.GetDirectoryName(output), Path.GetFileNameWithoutExtension(output) + FileExtension.Png);
}
var source = FFProbe.Analyse(input); var source = FFProbe.Analyse(input);
var (arguments, outputOptions) = SnapshotArgumentBuilder.BuildSnapshotArguments(input, source, size, captureTime, streamIndex, inputFileIndex);
return arguments return SnapshotProcess(input, output, source, size, captureTime, streamIndex, inputFileIndex)
.OutputToFile(output, true, outputOptions)
.ProcessSynchronously(); .ProcessSynchronously();
} }
/// <summary> /// <summary>
@ -44,47 +39,55 @@ namespace FFMpegCore
/// <returns>Bitmap with the requested snapshot.</returns> /// <returns>Bitmap with the requested snapshot.</returns>
public static async Task<bool> SnapshotAsync(string input, string output, Size? size = null, TimeSpan? captureTime = null, int? streamIndex = null, int inputFileIndex = 0) public static async Task<bool> SnapshotAsync(string input, string output, Size? size = null, TimeSpan? captureTime = null, int? streamIndex = null, int inputFileIndex = 0)
{ {
if (Path.GetExtension(output) != FileExtension.Png) CheckSnapshotOutputExtension(output, FileExtension.Image.All);
{
output = Path.Combine(Path.GetDirectoryName(output), Path.GetFileNameWithoutExtension(output) + FileExtension.Png);
}
var source = await FFProbe.AnalyseAsync(input).ConfigureAwait(false); var source = await FFProbe.AnalyseAsync(input).ConfigureAwait(false);
var (arguments, outputOptions) = SnapshotArgumentBuilder.BuildSnapshotArguments(input, source, size, captureTime, streamIndex, inputFileIndex);
return await arguments return await SnapshotProcess(input, output, source, size, captureTime, streamIndex, inputFileIndex)
.OutputToFile(output, true, outputOptions)
.ProcessAsynchronously(); .ProcessAsynchronously();
} }
public static bool GifSnapshot(string input, string output, Size? size = null, TimeSpan? captureTime = null, TimeSpan? duration = null, int? streamIndex = null) 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) CheckSnapshotOutputExtension(output, [FileExtension.Gif]);
{
output = Path.Combine(Path.GetDirectoryName(output), Path.GetFileNameWithoutExtension(output) + FileExtension.Gif);
}
var source = FFProbe.Analyse(input); var source = FFProbe.Analyse(input);
var (arguments, outputOptions) = SnapshotArgumentBuilder.BuildGifSnapshotArguments(input, source, size, captureTime, duration, streamIndex);
return arguments return GifSnapshotProcess(input, output, source, size, captureTime, duration, streamIndex)
.OutputToFile(output, true, outputOptions)
.ProcessSynchronously(); .ProcessSynchronously();
} }
public static async Task<bool> GifSnapshotAsync(string input, string output, Size? size = null, TimeSpan? captureTime = null, TimeSpan? duration = null, int? streamIndex = null) 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) CheckSnapshotOutputExtension(output, [FileExtension.Gif]);
{
output = Path.Combine(Path.GetDirectoryName(output), Path.GetFileNameWithoutExtension(output) + FileExtension.Gif);
}
var source = await FFProbe.AnalyseAsync(input).ConfigureAwait(false); var source = await FFProbe.AnalyseAsync(input).ConfigureAwait(false);
return await GifSnapshotProcess(input, output, source, size, captureTime, duration, streamIndex)
.ProcessAsynchronously();
}
private static FFMpegArgumentProcessor SnapshotProcess(string input, string output, IMediaAnalysis source, Size? size = null, TimeSpan? captureTime = null, int? streamIndex = null, int inputFileIndex = 0)
{
var (arguments, outputOptions) = SnapshotArgumentBuilder.BuildSnapshotArguments(input, output, source, size, captureTime, streamIndex, inputFileIndex);
return arguments.OutputToFile(output, true, outputOptions);
}
private static FFMpegArgumentProcessor GifSnapshotProcess(string input, string output, IMediaAnalysis source, Size? size = null, TimeSpan? captureTime = null, TimeSpan? duration = null, int? streamIndex = null)
{
var (arguments, outputOptions) = SnapshotArgumentBuilder.BuildGifSnapshotArguments(input, source, size, captureTime, duration, streamIndex); var (arguments, outputOptions) = SnapshotArgumentBuilder.BuildGifSnapshotArguments(input, source, size, captureTime, duration, streamIndex);
return await arguments return arguments.OutputToFile(output, true, outputOptions);
.OutputToFile(output, true, outputOptions) }
.ProcessAsynchronously();
private static void CheckSnapshotOutputExtension(string output, List<string> extensions)
{
if (!extensions.Contains(Path.GetExtension(output).ToLower()))
{
throw new ArgumentException(
$"Invalid snapshot output extension: {output}, needed: {string.Join(",", FileExtension.Image.All)}");
}
} }
/// <summary> /// <summary>

View file

@ -21,6 +21,7 @@ namespace FFMpegCore
public static FFMpegArguments FromConcatInput(IEnumerable<string> filePaths, Action<FFMpegArgumentOptions>? addArguments = null) => new FFMpegArguments().WithInput(new ConcatArgument(filePaths), addArguments); public static FFMpegArguments FromConcatInput(IEnumerable<string> filePaths, Action<FFMpegArgumentOptions>? addArguments = null) => new FFMpegArguments().WithInput(new ConcatArgument(filePaths), addArguments);
public static FFMpegArguments FromDemuxConcatInput(IEnumerable<string> filePaths, Action<FFMpegArgumentOptions>? addArguments = null) => new FFMpegArguments().WithInput(new DemuxConcatArgument(filePaths), addArguments); public static FFMpegArguments FromDemuxConcatInput(IEnumerable<string> filePaths, Action<FFMpegArgumentOptions>? addArguments = null) => new FFMpegArguments().WithInput(new DemuxConcatArgument(filePaths), addArguments);
public static FFMpegArguments FromFileInput(string filePath, bool verifyExists = true, Action<FFMpegArgumentOptions>? addArguments = null) => new FFMpegArguments().WithInput(new InputArgument(verifyExists, filePath), addArguments); public static FFMpegArguments FromFileInput(string filePath, bool verifyExists = true, Action<FFMpegArgumentOptions>? addArguments = null) => new FFMpegArguments().WithInput(new InputArgument(verifyExists, filePath), addArguments);
public static FFMpegArguments FromFileInput(IEnumerable<string> filePath, bool verifyExists = true, Action<FFMpegArgumentOptions>? addArguments = null) => new FFMpegArguments().WithInput(new MultiInputArgument(verifyExists, filePath), addArguments);
public static FFMpegArguments FromFileInput(FileInfo fileInfo, Action<FFMpegArgumentOptions>? addArguments = null) => new FFMpegArguments().WithInput(new InputArgument(fileInfo.FullName, false), addArguments); public static FFMpegArguments FromFileInput(FileInfo fileInfo, Action<FFMpegArgumentOptions>? addArguments = null) => new FFMpegArguments().WithInput(new InputArgument(fileInfo.FullName, false), addArguments);
public static FFMpegArguments FromUrlInput(Uri uri, Action<FFMpegArgumentOptions>? addArguments = null) => new FFMpegArguments().WithInput(new InputArgument(uri.AbsoluteUri, false), addArguments); public static FFMpegArguments FromUrlInput(Uri uri, Action<FFMpegArgumentOptions>? addArguments = null) => new FFMpegArguments().WithInput(new InputArgument(uri.AbsoluteUri, false), addArguments);
public static FFMpegArguments FromDeviceInput(string device, Action<FFMpegArgumentOptions>? addArguments = null) => new FFMpegArguments().WithInput(new InputDeviceArgument(device), addArguments); public static FFMpegArguments FromDeviceInput(string device, Action<FFMpegArgumentOptions>? addArguments = null) => new FFMpegArguments().WithInput(new InputDeviceArgument(device), addArguments);
@ -35,6 +36,7 @@ namespace FFMpegCore
public FFMpegArguments AddConcatInput(IEnumerable<string> filePaths, Action<FFMpegArgumentOptions>? addArguments = null) => WithInput(new ConcatArgument(filePaths), addArguments); public FFMpegArguments AddConcatInput(IEnumerable<string> filePaths, Action<FFMpegArgumentOptions>? addArguments = null) => WithInput(new ConcatArgument(filePaths), addArguments);
public FFMpegArguments AddDemuxConcatInput(IEnumerable<string> filePaths, Action<FFMpegArgumentOptions>? addArguments = null) => WithInput(new DemuxConcatArgument(filePaths), addArguments); public FFMpegArguments AddDemuxConcatInput(IEnumerable<string> filePaths, Action<FFMpegArgumentOptions>? addArguments = null) => WithInput(new DemuxConcatArgument(filePaths), addArguments);
public FFMpegArguments AddFileInput(string filePath, bool verifyExists = true, Action<FFMpegArgumentOptions>? addArguments = null) => WithInput(new InputArgument(verifyExists, filePath), addArguments); public FFMpegArguments AddFileInput(string filePath, bool verifyExists = true, Action<FFMpegArgumentOptions>? addArguments = null) => WithInput(new InputArgument(verifyExists, filePath), addArguments);
public FFMpegArguments AddFileInput(IEnumerable<string> filePath, bool verifyExists = true, Action<FFMpegArgumentOptions>? addArguments = null) => WithInput(new MultiInputArgument(verifyExists, filePath), addArguments);
public FFMpegArguments AddFileInput(FileInfo fileInfo, Action<FFMpegArgumentOptions>? addArguments = null) => WithInput(new InputArgument(fileInfo.FullName, false), addArguments); public FFMpegArguments AddFileInput(FileInfo fileInfo, Action<FFMpegArgumentOptions>? addArguments = null) => WithInput(new InputArgument(fileInfo.FullName, false), addArguments);
public FFMpegArguments AddUrlInput(Uri uri, Action<FFMpegArgumentOptions>? addArguments = null) => WithInput(new InputArgument(uri.AbsoluteUri, false), addArguments); public FFMpegArguments AddUrlInput(Uri uri, Action<FFMpegArgumentOptions>? addArguments = null) => WithInput(new InputArgument(uri.AbsoluteUri, false), addArguments);
public FFMpegArguments AddDeviceInput(string device, Action<FFMpegArgumentOptions>? addArguments = null) => WithInput(new InputDeviceArgument(device), addArguments); public FFMpegArguments AddDeviceInput(string device, Action<FFMpegArgumentOptions>? addArguments = null) => WithInput(new InputDeviceArgument(device), addArguments);

View file

@ -9,6 +9,30 @@ public static class SnapshotArgumentBuilder
{ {
public static (FFMpegArguments, Action<FFMpegArgumentOptions> outputOptions) BuildSnapshotArguments( public static (FFMpegArguments, Action<FFMpegArgumentOptions> outputOptions) BuildSnapshotArguments(
string input, string input,
string output,
IMediaAnalysis source,
Size? size = null,
TimeSpan? captureTime = null,
int? streamIndex = null,
int inputFileIndex = 0)
{
return BuildSnapshotArguments(input, VideoCodec.Image.GetByExtension(output), source, size, captureTime, streamIndex, inputFileIndex);
}
public static (FFMpegArguments, Action<FFMpegArgumentOptions> outputOptions) BuildSnapshotArguments(
string input,
IMediaAnalysis source,
Size? size = null,
TimeSpan? captureTime = null,
int? streamIndex = null,
int inputFileIndex = 0)
{
return BuildSnapshotArguments(input, VideoCodec.Image.Png, source, size, captureTime, streamIndex, inputFileIndex);
}
private static (FFMpegArguments, Action<FFMpegArgumentOptions> outputOptions) BuildSnapshotArguments(
string input,
Codec codec,
IMediaAnalysis source, IMediaAnalysis source,
Size? size = null, Size? size = null,
TimeSpan? captureTime = null, TimeSpan? captureTime = null,
@ -26,7 +50,7 @@ public static class SnapshotArgumentBuilder
.Seek(captureTime)), .Seek(captureTime)),
options => options options => options
.SelectStream((int)streamIndex, inputFileIndex) .SelectStream((int)streamIndex, inputFileIndex)
.WithVideoCodec(VideoCodec.Png) .WithVideoCodec(codec)
.WithFrameOutputCount(1) .WithFrameOutputCount(1)
.Resize(size)); .Resize(size));
} }

View file

@ -3,10 +3,15 @@
<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.1.0</PackageVersion> <PackageVersion>5.2.0</PackageVersion>
<PackageOutputPath>../nupkg</PackageOutputPath> <PackageOutputPath>../nupkg</PackageOutputPath>
<PackageReleaseNotes> <PackageReleaseNotes>- **Instances and Packages Updates**: Updates to various instances and packages by rosenbjerg.
</PackageReleaseNotes> - **Audio and Video Enhancements**: Additions include a Copy option to Audio Codec and a Crop option to Arguments by brett-baker; video-stream level added to FFProbe analysis by Kaaybi; AV1 support for smaller snapshots and videos by BenediktBertsch; multiple input files support by AddyMills; HDR color properties support added to FFProbe analysis by Tomiscout.
- **System.Text.Json Bump**: Update by Kaaybi.
- **FFMpeg Processors and Utilities**: Modification for handling durations over 24 hours in `FFMpegArgumentProcessor` by alahane-techtel; fix for snapshots with correct width/height from rotated videos by Hagfjall.
- **Feature Additions and Fixes**: Support for multiple outputs and tee muxer by duggaraju; custom ffprob arguments by vfrz; fix for null reference exception with tags container by rosenbjerg; Chapter Modell change by vortex852456; codec copy added to the SaveM3U8Stream method by rpaschoal.
- **Closed and Non-merged Contributions**: Notable closed contributions include JSON source generators usage by onionware-github; Snapshot overload by 3UR; FromRawInput method by pedoc; runtime ffmpeg suite installation by yuqian5; and support for scale_npp by vicwilliam.
- **Miscellaneous Fixes**: Minor readme corrections by NaBian; fix for ffmpeg path issue by devedse.</PackageReleaseNotes>
<PackageTags>ffmpeg ffprobe convert video audio mediafile resize analyze muxing</PackageTags> <PackageTags>ffmpeg ffprobe convert video audio mediafile resize analyze muxing</PackageTags>
<Authors>Malte Rosenbjerg, Vlad Jerca, Max Bagryantsev</Authors> <Authors>Malte Rosenbjerg, Vlad Jerca, Max Bagryantsev</Authors>
<PackageReadmeFile>README.md</PackageReadmeFile> <PackageReadmeFile>README.md</PackageReadmeFile>
@ -17,8 +22,8 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Instances" Version="3.0.0" /> <PackageReference Include="Instances" Version="3.0.1" />
<PackageReference Include="System.Text.Json" Version="9.0.0" /> <PackageReference Include="System.Text.Json" Version="9.0.2" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View file

@ -1,5 +1,5 @@
# [FFMpegCore](https://www.nuget.org/packages/FFMpegCore/) # [FFMpegCore](https://www.nuget.org/packages/FFMpegCore/)
[![NuGet Badge](https://buildstats.info/nuget/FFMpegCore)](https://www.nuget.org/packages/FFMpegCore/) [![NuGet Version](https://img.shields.io/nuget/v/FFMpegCore)](https://www.nuget.org/packages/FFMpegCore/)
[![GitHub issues](https://img.shields.io/github/issues/rosenbjerg/FFMpegCore)](https://github.com/rosenbjerg/FFMpegCore/issues) [![GitHub issues](https://img.shields.io/github/issues/rosenbjerg/FFMpegCore)](https://github.com/rosenbjerg/FFMpegCore/issues)
[![GitHub stars](https://img.shields.io/github/stars/rosenbjerg/FFMpegCore)](https://github.com/rosenbjerg/FFMpegCore/stargazers) [![GitHub stars](https://img.shields.io/github/stars/rosenbjerg/FFMpegCore)](https://github.com/rosenbjerg/FFMpegCore/stargazers)
[![GitHub](https://img.shields.io/github/license/rosenbjerg/FFMpegCore)](https://github.com/rosenbjerg/FFMpegCore/blob/master/LICENSE) [![GitHub](https://img.shields.io/github/license/rosenbjerg/FFMpegCore)](https://github.com/rosenbjerg/FFMpegCore/blob/master/LICENSE)