Compare commits

...

35 commits

Author SHA1 Message Date
Bogdan
ac441eefd6 Add raw response from ffprobe in MediaAnalysis 2025-11-11 22:38:54 +02:00
Malte Rosenbjerg
cc75e03ec9
Merge pull request #602 from rosenbjerg/add-more-missing-tests
Add more missing tests
2025-10-29 14:28:08 +01:00
Malte Rosenbjerg
5356536f37 Fix linting 2025-10-28 12:21:09 +01:00
Malte Rosenbjerg
f0f60c8bd8 Add more missing tests 2025-10-28 12:19:21 +01:00
Malte Rosenbjerg
55d526ce92
Merge pull request #599 from rosenbjerg/Delegate-WithChapter-overload-with-double-argument-to-long-overload-to-reduce-code
Delegate to WithChapter with long argument overload
2025-10-27 21:23:58 +01:00
Malte Rosenbjerg
ebe60ef5da
Merge branch 'main' into Delegate-WithChapter-overload-with-double-argument-to-long-overload-to-reduce-code 2025-10-27 21:13:04 +01:00
Malte Rosenbjerg
e12bc2a148
Merge pull request #600 from rosenbjerg/ensure-cancellationtoken-passed-to-cancellablethrough-is-not-already-cancelled
Throw if CancellationToken passed to CancellableThrough is not already cancelled
2025-10-27 21:12:52 +01:00
Malte Rosenbjerg
736420e916
Merge branch 'main' into ensure-cancellationtoken-passed-to-cancellablethrough-is-not-already-cancelled 2025-10-27 21:08:42 +01:00
Malte Rosenbjerg
f9a3f2b0dc
Merge pull request #601 from rosenbjerg/fix-changing-of-output-extension-in-BaseSubVideo
Fix changing of output extension in BaseSubVideo
2025-10-27 21:08:31 +01:00
Malte Rosenbjerg
1442c08e37 Lower amount of bitmaps used in tests 2025-10-27 21:03:24 +01:00
Malte Rosenbjerg
cdf2dd5b65 Refine unit tests for cancellation 2025-10-27 21:01:36 +01:00
Malte Rosenbjerg
3c6cb1fb43 Throw if CancellationToken passed to CancellableThrough is not already cancelled 2025-10-27 20:49:35 +01:00
Malte Rosenbjerg
df03c58081 Delegate to WithChapter with long argument overload 2025-10-27 20:45:17 +01:00
Malte Rosenbjerg
2a16824e69 Fix changing of output extension in BaseSubVideo 2025-10-27 20:43:56 +01:00
Malte Rosenbjerg
3b1a1438bb Update nuget details 2025-10-27 20:13:05 +01:00
Malte Rosenbjerg
9b1e373c55
Merge pull request #593 from snechaev/PR-592_Snapshot_Cancellation_Support
Add cancellation token support for the [Gif]SnapshotAsync
2025-10-27 20:12:53 +01:00
Malte Rosenbjerg
935e1cf17c
Merge branch 'main' into PR-592_Snapshot_Cancellation_Support 2025-10-27 19:56:10 +01:00
Malte Rosenbjerg
d916fd3be4 Update nuget details 2025-10-27 19:53:39 +01:00
Malte Rosenbjerg
dbf672fd6a
Merge pull request #597 from rosenbjerg/improve-tests-usage-of-cancellation-token
Improve tests usage of cancellation token
2025-10-27 19:47:19 +01:00
Malte Rosenbjerg
3c8d2c23c1 Use using for CancellationTokenSource 2025-10-27 19:39:13 +01:00
Malte Rosenbjerg
919c6ef526 Use CreateLinkedTokenSource to bind to TestContext cancellationtoken 2025-10-27 19:38:58 +01:00
Malte Rosenbjerg
1346049991
Merge pull request #595 from snechaev/PR-594_Fix_Unexpected_FFMpegException_On_Cancellation
Do not throw unexpected FFMpegException on FFProbe cancallation. Fixes  #594
2025-10-27 19:15:11 +01:00
Sergey Nechaev
67af2aa01d Move cancellation check outside of the ThrowIfExitCodeNotZero() and call it separately in all the async code paths. 2025-10-27 13:36:42 +01:00
Sergey Nechaev
560c791802 Update the ThrowIfExitCodeNotZero() to check the exit code before handling cancellation.
This preserves the original semantics and contract (throw only if the ffprobe exits with a non-zero code).
2025-10-27 13:30:59 +01:00
Sergey Nechaev
e44611bd25 Additional test to verify that FFProbeHelper still throws FFMpegException when FFProbe exits with non-zero code and no cancellation was requested.
Ref.: #594
2025-10-27 13:30:59 +01:00
Sergey Nechaev
b863f5d19e FFProbe: Do not throw FFMpegException if cancellation was requested.
Throw OperationCancelledException in this case to provide more uniform and expected behavior.

Fixes #594
2025-10-27 13:30:59 +01:00
Sergey Nechaev
930d493b8c Add test to verify unexpected exception on FFProbe operations cancellation.
Ref.: #594
2025-10-27 13:30:59 +01:00
Malte Rosenbjerg
2f06ec99f3
Merge pull request #596 from rosenbjerg/add-metadata-builder-class
Add metadata builder class
2025-10-25 11:55:52 +02:00
Malte Rosenbjerg
53445322e4 Fix linting 2025-10-25 11:36:40 +02:00
Malte Rosenbjerg
15acd9f0da Add BOM 2025-10-25 11:28:47 +02:00
Malte Rosenbjerg
ef313ea411 Add test verifying functionality 2025-10-25 11:25:52 +02:00
Malte Rosenbjerg
62e829d9b4 Add AddMetaData overload accepting FFMetadataBuilder instance 2025-10-25 11:25:43 +02:00
Malte Rosenbjerg
97053929a9 Add FFMetadataBuilder for easily constructing metadata text 2025-10-25 11:25:16 +02:00
Sergey Nechaev
f5ecbaee68 Fixed a race condition that occurred when handling the cancellation of an asynchronous operation after the FFmpeg process had already exited. Fixes #348.
Related: #592
2025-10-22 16:13:38 +02:00
Sergey Nechaev
b3c201b42e Add cancellation token support to SnapshotAsync, GifSnapshotAsync and SubVideoAsync methods. Fixes #592. 2025-10-21 17:25:51 +02:00
15 changed files with 371 additions and 43 deletions

View file

@ -39,18 +39,21 @@ public static class FFMpegImage
/// <param name="size">Thumbnail size. If width or height equal 0, the other will be computed automatically.</param>
/// <param name="streamIndex">Selected video stream index.</param>
/// <param name="inputFileIndex">Input file index</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Bitmap with the requested snapshot.</returns>
public static async Task<SKBitmap> SnapshotAsync(string input, Size? size = null, TimeSpan? captureTime = null, int? streamIndex = null,
int inputFileIndex = 0)
int inputFileIndex = 0, CancellationToken cancellationToken = default)
{
var source = await FFProbe.AnalyseAsync(input).ConfigureAwait(false);
var source = await FFProbe.AnalyseAsync(input, cancellationToken: cancellationToken).ConfigureAwait(false);
var (arguments, outputOptions) = SnapshotArgumentBuilder.BuildSnapshotArguments(input, source, size, captureTime, streamIndex, inputFileIndex);
using var ms = new MemoryStream();
await arguments
.OutputToPipe(new StreamPipeSink(ms), options => outputOptions(options
.ForceFormat("rawvideo")))
.ProcessAsynchronously();
.CancellableThrough(cancellationToken)
.ProcessAsynchronously()
.ConfigureAwait(false);
ms.Position = 0;
return SKBitmap.Decode(ms);

View file

@ -38,18 +38,21 @@ public static class FFMpegImage
/// <param name="size">Thumbnail size. If width or height equal 0, the other will be computed automatically.</param>
/// <param name="streamIndex">Selected video stream index.</param>
/// <param name="inputFileIndex">Input file index</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Bitmap with the requested snapshot.</returns>
public static async Task<Bitmap> SnapshotAsync(string input, Size? size = null, TimeSpan? captureTime = null, int? streamIndex = null,
int inputFileIndex = 0)
int inputFileIndex = 0, CancellationToken cancellationToken = default)
{
var source = await FFProbe.AnalyseAsync(input).ConfigureAwait(false);
var source = await FFProbe.AnalyseAsync(input, cancellationToken: cancellationToken).ConfigureAwait(false);
var (arguments, outputOptions) = SnapshotArgumentBuilder.BuildSnapshotArguments(input, source, size, captureTime, streamIndex, inputFileIndex);
using var ms = new MemoryStream();
await arguments
.OutputToPipe(new StreamPipeSink(ms), options => outputOptions(options
.ForceFormat("rawvideo")))
.ProcessAsynchronously();
.CancellableThrough(cancellationToken)
.ProcessAsynchronously()
.ConfigureAwait(false);
ms.Position = 0;
return new Bitmap(ms);

View file

@ -93,6 +93,14 @@ public class ArgumentBuilderTest
Assert.AreEqual("-i \"concat:1.mp4|2.mp4|3.mp4|4.mp4\" \"output.mp4\"", str);
}
[TestMethod]
public void Builder_BuildString_DemuxConcat()
{
var str = FFMpegArguments.FromDemuxConcatInput(_concatFiles).OutputToFile("output.mp4", false).Arguments;
Assert.Contains("-f concat -safe 0 -i", str);
Assert.Contains("\"output.mp4\"", str);
}
[TestMethod]
public void Builder_BuildString_Copy_Audio()
{

View file

@ -1,4 +1,6 @@
using FFMpegCore.Test.Resources;
using FFMpegCore.Exceptions;
using FFMpegCore.Helpers;
using FFMpegCore.Test.Resources;
namespace FFMpegCore.Test;
@ -285,4 +287,77 @@ public class FFProbeTests
var info = FFProbe.Analyse(TestResources.Mp4Video, customArguments: "-headers \"Hello: World\"");
Assert.AreEqual(3, info.Duration.Seconds);
}
[TestMethod]
[Timeout(10000, CooperativeCancellation = true)]
public async Task Parallel_FFProbe_Cancellation_Should_Throw_Only_OperationCanceledException()
{
// Warm up FFMpegCore environment
FFProbeHelper.VerifyFFProbeExists(GlobalFFOptions.Current);
var mp4 = TestResources.Mp4Video;
if (!File.Exists(mp4))
{
Assert.Inconclusive($"Test video not found: {mp4}");
return;
}
using var cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken);
using var semaphore = new SemaphoreSlim(Environment.ProcessorCount, Environment.ProcessorCount);
var tasks = Enumerable.Range(0, 50).Select(x => Task.Run(async () =>
{
await semaphore.WaitAsync(cts.Token);
try
{
var analysis = await FFProbe.AnalyseAsync(mp4, cancellationToken: cts.Token);
return analysis;
}
finally
{
semaphore.Release();
}
}, cts.Token)).ToList();
// Wait for 2 tasks to finish, then cancel all
await Task.WhenAny(tasks);
await Task.WhenAny(tasks);
await cts.CancelAsync();
var exceptions = new List<Exception>();
foreach (var task in tasks)
{
try
{
await task;
}
catch (Exception e)
{
exceptions.Add(e);
}
}
Assert.IsNotEmpty(exceptions, "No exceptions were thrown on cancellation. Test was useless. " +
".Try adjust cancellation timings to make cancellation at the moment, when ffprobe is still running.");
// Check that all exceptions are OperationCanceledException
CollectionAssert.AllItemsAreInstancesOfType(exceptions, typeof(OperationCanceledException));
}
[TestMethod]
[Timeout(10000, CooperativeCancellation = true)]
public async Task FFProbe_Should_Throw_FFMpegException_When_Exits_With_Non_Zero_Code()
{
var input = TestResources.SrtSubtitle; //non media file
await Assert.ThrowsAsync<FFMpegException>(async () => await FFProbe.AnalyseAsync(input,
cancellationToken: TestContext.CancellationToken, customArguments: "--some-invalid-argument"));
}
[TestMethod]
public void Probe_Success_Output_Data()
{
var info = FFProbe.Analyse(TestResources.Mp4Video);
Assert.AreNotEqual(0, info.OutputData.Count);
CollectionAssert.Contains(info.OutputData.ToList(), " \"codec_long_name\": \"H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10\",");
}
}

View file

@ -82,6 +82,40 @@ public class VideoTest
Assert.IsTrue(success);
}
[TestMethod]
[Timeout(BaseTimeoutMilliseconds, CooperativeCancellation = true)]
public async Task Video_MetadataBuilder()
{
using var outputFile = new TemporaryFile($"out{VideoType.Mp4.Extension}");
await FFMpegArguments
.FromFileInput(TestResources.WebmVideo)
.AddMetaData(FFMetadataBuilder.Empty()
.WithTag("title", "noname")
.WithTag("artist", "unknown")
.WithChapter("Chapter 1", 1.1)
.WithChapter("Chapter 2", 1.23))
.OutputToFile(outputFile, false, opt => opt
.WithVideoCodec(VideoCodec.LibX264))
.CancellableThrough(TestContext.CancellationToken)
.ProcessAsynchronously();
var analysis = await FFProbe.AnalyseAsync(outputFile, cancellationToken: TestContext.CancellationToken);
Assert.IsTrue(analysis.Format.Tags!.TryGetValue("title", out var title));
Assert.IsTrue(analysis.Format.Tags!.TryGetValue("artist", out var artist));
Assert.AreEqual("noname", title);
Assert.AreEqual("unknown", artist);
Assert.HasCount(2, analysis.Chapters);
Assert.AreEqual("Chapter 1", analysis.Chapters.First().Title);
Assert.AreEqual(1.1, analysis.Chapters.First().Duration.TotalSeconds);
Assert.AreEqual(1.1, analysis.Chapters.First().End.TotalSeconds);
Assert.AreEqual("Chapter 2", analysis.Chapters.Last().Title);
Assert.AreEqual(1.23, analysis.Chapters.Last().Duration.TotalSeconds);
Assert.AreEqual(1.1 + 1.23, analysis.Chapters.Last().End.TotalSeconds);
}
[TestMethod]
[Timeout(BaseTimeoutMilliseconds, CooperativeCancellation = true)]
public void Video_ToH265_MKV_Args()
@ -120,7 +154,7 @@ public class VideoTest
{
using var outputFile = new TemporaryFile($"out{VideoType.Mp4.Extension}");
var videoFramesSource = new RawVideoPipeSource(BitmapSource.CreateBitmaps(128, pixelFormat, 256, 256));
var videoFramesSource = new RawVideoPipeSource(BitmapSource.CreateBitmaps(64, pixelFormat, 256, 256));
var success = FFMpegArguments
.FromPipeInput(videoFramesSource)
.OutputToFile(outputFile, false, opt => opt
@ -440,7 +474,7 @@ public class VideoTest
private static async Task Video_ToTS_Args_Pipe_Internal(dynamic pixelFormat, CancellationToken cancellationToken)
{
using var output = new TemporaryFile($"out{VideoType.Ts.Extension}");
var input = new RawVideoPipeSource(BitmapSource.CreateBitmaps(128, pixelFormat, 256, 256));
var input = new RawVideoPipeSource(BitmapSource.CreateBitmaps(64, pixelFormat, 256, 256));
var success = await FFMpegArguments
.FromPipeInput(input)
@ -477,7 +511,7 @@ public class VideoTest
public void RawVideoPipeSource_Ogv_Scale(SKColorType pixelFormat)
{
using var outputFile = new TemporaryFile($"out{VideoType.Ogv.Extension}");
var videoFramesSource = new RawVideoPipeSource(BitmapSource.CreateBitmaps(128, pixelFormat, 256, 256));
var videoFramesSource = new RawVideoPipeSource(BitmapSource.CreateBitmaps(64, pixelFormat, 256, 256));
FFMpegArguments
.FromPipeInput(videoFramesSource)
@ -531,7 +565,7 @@ public class VideoTest
private static void Video_ToMP4_Resize_Args_Pipe_Internal(dynamic pixelFormat, CancellationToken cancellationToken)
{
using var outputFile = new TemporaryFile($"out{VideoType.Mp4.Extension}");
var videoFramesSource = new RawVideoPipeSource(BitmapSource.CreateBitmaps(128, pixelFormat, 256, 256));
var videoFramesSource = new RawVideoPipeSource(BitmapSource.CreateBitmaps(64, pixelFormat, 256, 256));
var success = FFMpegArguments
.FromPipeInput(videoFramesSource)
@ -555,6 +589,19 @@ public class VideoTest
Assert.AreEqual(bitmap.RawFormat, ImageFormat.Png);
}
[SupportedOSPlatform("windows")]
[OsSpecificTestMethod(OsPlatforms.Windows)]
[Timeout(BaseTimeoutMilliseconds, CooperativeCancellation = true)]
public async Task Video_SnapshotAsync_InMemory_SystemDrawingCommon()
{
using var bitmap = await FFMpegImage.SnapshotAsync(TestResources.Mp4Video, cancellationToken: TestContext.CancellationToken);
var input = await FFProbe.AnalyseAsync(TestResources.Mp4Video, cancellationToken: TestContext.CancellationToken);
Assert.AreEqual(input.PrimaryVideoStream!.Width, bitmap.Width);
Assert.AreEqual(input.PrimaryVideoStream.Height, bitmap.Height);
Assert.AreEqual(bitmap.RawFormat, ImageFormat.Png);
}
[TestMethod]
[Timeout(BaseTimeoutMilliseconds, CooperativeCancellation = true)]
public void Video_Snapshot_InMemory_SkiaSharp()
@ -568,6 +615,19 @@ public class VideoTest
// e.g. Bgra8888 on Windows and Rgba8888 on macOS.
}
[TestMethod]
[Timeout(BaseTimeoutMilliseconds, CooperativeCancellation = true)]
public async Task Video_SnapshotAsync_InMemory_SkiaSharp()
{
using var bitmap = await Extensions.SkiaSharp.FFMpegImage.SnapshotAsync(TestResources.Mp4Video, cancellationToken: TestContext.CancellationToken);
var input = await FFProbe.AnalyseAsync(TestResources.Mp4Video, cancellationToken: TestContext.CancellationToken);
Assert.AreEqual(input.PrimaryVideoStream!.Width, bitmap.Width);
Assert.AreEqual(input.PrimaryVideoStream.Height, bitmap.Height);
// Note: The resulting ColorType is dependent on the execution environment and therefore not assessed,
// e.g. Bgra8888 on Windows and Rgba8888 on macOS.
}
[TestMethod]
[Timeout(BaseTimeoutMilliseconds, CooperativeCancellation = true)]
public void Video_Snapshot_Png_PersistSnapshot()
@ -583,6 +643,21 @@ public class VideoTest
Assert.AreEqual("png", analysis.PrimaryVideoStream!.CodecName);
}
[TestMethod]
[Timeout(BaseTimeoutMilliseconds, CooperativeCancellation = true)]
public async Task Video_SnapshotAsync_Png_PersistSnapshot()
{
using var outputPath = new TemporaryFile("out.png");
var input = await FFProbe.AnalyseAsync(TestResources.Mp4Video, cancellationToken: TestContext.CancellationToken);
await FFMpeg.SnapshotAsync(TestResources.Mp4Video, outputPath, cancellationToken: TestContext.CancellationToken);
var analysis = FFProbe.Analyse(outputPath);
Assert.AreEqual(input.PrimaryVideoStream!.Width, analysis.PrimaryVideoStream!.Width);
Assert.AreEqual(input.PrimaryVideoStream.Height, analysis.PrimaryVideoStream!.Height);
Assert.AreEqual("png", analysis.PrimaryVideoStream!.CodecName);
}
[TestMethod]
[Timeout(BaseTimeoutMilliseconds, CooperativeCancellation = true)]
public void Video_Snapshot_Jpg_PersistSnapshot()
@ -698,7 +773,8 @@ public class VideoTest
using var outputPath = new TemporaryFile("out.gif");
var input = FFProbe.Analyse(TestResources.Mp4Video);
await FFMpeg.GifSnapshotAsync(TestResources.Mp4Video, outputPath, captureTime: TimeSpan.FromSeconds(0));
await FFMpeg.GifSnapshotAsync(TestResources.Mp4Video, outputPath, captureTime: TimeSpan.FromSeconds(0),
cancellationToken: TestContext.CancellationToken);
var analysis = FFProbe.Analyse(outputPath);
Assert.AreNotEqual(input.PrimaryVideoStream!.Width, analysis.PrimaryVideoStream!.Width);
@ -714,7 +790,8 @@ public class VideoTest
var input = FFProbe.Analyse(TestResources.Mp4Video);
var desiredGifSize = new Size(320, 240);
await FFMpeg.GifSnapshotAsync(TestResources.Mp4Video, outputPath, desiredGifSize, TimeSpan.FromSeconds(0));
await FFMpeg.GifSnapshotAsync(TestResources.Mp4Video, outputPath, desiredGifSize, TimeSpan.FromSeconds(0),
cancellationToken: TestContext.CancellationToken);
var analysis = FFProbe.Analyse(outputPath);
Assert.AreNotEqual(input.PrimaryVideoStream!.Width, desiredGifSize.Width);
@ -745,6 +822,46 @@ public class VideoTest
Assert.AreEqual(input.PrimaryVideoStream.Width, result.PrimaryVideoStream.Width);
}
[TestMethod]
[Timeout(BaseTimeoutMilliseconds, CooperativeCancellation = true)]
public void Video_Convert_Webm()
{
using var outputPath = new TemporaryFile("out.webm");
var success = FFMpeg.Convert(TestResources.Mp4Video, outputPath, VideoType.WebM);
Assert.IsTrue(success);
Assert.IsTrue(File.Exists(outputPath));
var input = FFProbe.Analyse(TestResources.Mp4Video);
var result = FFProbe.Analyse(outputPath);
Assert.AreEqual(input.Duration.Days, result.Duration.Days);
Assert.AreEqual(input.Duration.Hours, result.Duration.Hours);
Assert.AreEqual(input.Duration.Minutes, result.Duration.Minutes);
Assert.AreEqual(input.Duration.Seconds, result.Duration.Seconds);
Assert.AreEqual(input.PrimaryVideoStream!.Height, result.PrimaryVideoStream!.Height);
Assert.AreEqual(input.PrimaryVideoStream.Width, result.PrimaryVideoStream.Width);
}
[TestMethod]
[Timeout(BaseTimeoutMilliseconds, CooperativeCancellation = true)]
public void Video_Convert_Ogv()
{
using var outputPath = new TemporaryFile("out.ogv");
var success = FFMpeg.Convert(TestResources.Mp4Video, outputPath, VideoType.Ogv);
Assert.IsTrue(success);
Assert.IsTrue(File.Exists(outputPath));
var input = FFProbe.Analyse(TestResources.Mp4Video);
var result = FFProbe.Analyse(outputPath);
Assert.AreEqual(input.Duration.Days, result.Duration.Days);
Assert.AreEqual(input.Duration.Hours, result.Duration.Hours);
Assert.AreEqual(input.Duration.Minutes, result.Duration.Minutes);
Assert.AreEqual(input.Duration.Seconds, result.Duration.Seconds);
Assert.AreEqual(input.PrimaryVideoStream!.Height, result.PrimaryVideoStream!.Height);
Assert.AreEqual(input.PrimaryVideoStream.Width, result.PrimaryVideoStream.Width);
}
[TestMethod]
[Timeout(2 * BaseTimeoutMilliseconds, CooperativeCancellation = true)]
public void Video_Join_Image_Sequence()
@ -891,7 +1008,7 @@ public class VideoTest
{
using var resStream = new MemoryStream();
var reader = new StreamPipeSink(resStream);
var writer = new RawVideoPipeSource(BitmapSource.CreateBitmaps(128, pixelFormat, 128, 128));
var writer = new RawVideoPipeSource(BitmapSource.CreateBitmaps(64, pixelFormat, 128, 128));
FFMpegArguments
.FromPipeInput(writer)
@ -1016,7 +1133,7 @@ public class VideoTest
{
using var outputFile = new TemporaryFile("out.mp4");
var cts = new CancellationTokenSource();
using var cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken);
var task = FFMpegArguments
.FromFileInput("testsrc2=size=320x240[out0]; sine[out1]", false, args => args
@ -1027,7 +1144,6 @@ public class VideoTest
.WithVideoCodec(VideoCodec.LibX264)
.WithSpeedPreset(Speed.VeryFast))
.CancellableThrough(cts.Token)
.CancellableThrough(TestContext.CancellationToken)
.ProcessAsynchronously(false);
cts.CancelAfter(300);
@ -1043,7 +1159,7 @@ public class VideoTest
{
using var outputFile = new TemporaryFile("out.mp4");
var cts = new CancellationTokenSource();
using var cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken);
var task = FFMpegArguments
.FromFileInput("testsrc2=size=320x240[out0]; sine[out1]", false, args => args
@ -1054,7 +1170,6 @@ public class VideoTest
.WithVideoCodec(VideoCodec.LibX264)
.WithSpeedPreset(Speed.VeryFast))
.CancellableThrough(cts.Token)
.CancellableThrough(TestContext.CancellationToken)
.ProcessAsynchronously();
cts.CancelAfter(300);
@ -1068,7 +1183,7 @@ public class VideoTest
{
using var outputFile = new TemporaryFile("out.mp4");
var cts = new CancellationTokenSource();
using var cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken);
var task = FFMpegArguments
.FromFileInput("testsrc2=size=320x240[out0]; sine[out1]", false, args => args
@ -1088,13 +1203,12 @@ public class VideoTest
[TestMethod]
[Timeout(BaseTimeoutMilliseconds, CooperativeCancellation = true)]
public void Video_Cancel_CancellationToken_Before_Throws()
public void Video_Cancel_CancellationToken_BeforeProcessing_Throws()
{
using var outputFile = new TemporaryFile("out.mp4");
var cts = new CancellationTokenSource();
using var cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken);
cts.Cancel();
var task = FFMpegArguments
.FromFileInput("testsrc2=size=320x240[out0]; sine[out1]", false, args => args
.WithCustomArgument("-re")
@ -1105,8 +1219,29 @@ public class VideoTest
.WithSpeedPreset(Speed.VeryFast))
.CancellableThrough(cts.Token);
Assert.ThrowsExactly<OperationCanceledException>(() => task.CancellableThrough(TestContext.CancellationToken)
.ProcessSynchronously());
cts.Cancel();
Assert.ThrowsExactly<OperationCanceledException>(() => task.ProcessSynchronously());
}
[TestMethod]
[Timeout(BaseTimeoutMilliseconds, CooperativeCancellation = true)]
public void Video_Cancel_CancellationToken_BeforePassing_Throws()
{
using var outputFile = new TemporaryFile("out.mp4");
using var cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken);
cts.Cancel();
var task = FFMpegArguments
.FromFileInput("testsrc2=size=320x240[out0]; sine[out1]", false, args => args
.WithCustomArgument("-re")
.ForceFormat("lavfi"))
.OutputToFile(outputFile, false, opt => opt
.WithAudioCodec(AudioCodec.Aac)
.WithVideoCodec(VideoCodec.LibX264)
.WithSpeedPreset(Speed.VeryFast));
Assert.ThrowsExactly<OperationCanceledException>(() => task.CancellableThrough(cts.Token));
}
[TestMethod]
@ -1115,7 +1250,7 @@ public class VideoTest
{
using var outputFile = new TemporaryFile("out.mp4");
var cts = new CancellationTokenSource();
using var cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken);
var task = FFMpegArguments
.FromFileInput("testsrc2=size=320x240[out0]; sine[out1]", false, args => args

View file

@ -0,0 +1,61 @@
using System.Text;
namespace FFMpegCore;
public class FFMetadataBuilder
{
private Dictionary<string, string> Tags { get; } = new();
private List<FFMetadataChapter> Chapters { get; } = [];
public static FFMetadataBuilder Empty()
{
return new FFMetadataBuilder();
}
public FFMetadataBuilder WithTag(string key, string value)
{
Tags.Add(key, value);
return this;
}
public FFMetadataBuilder WithChapter(string title, long durationMs)
{
Chapters.Add(new FFMetadataChapter(title, durationMs));
return this;
}
public FFMetadataBuilder WithChapter(string title, double durationSeconds)
{
return WithChapter(title, Convert.ToInt64(durationSeconds * 1000));
}
public string GetMetadataFileContent()
{
var sb = new StringBuilder();
sb.AppendLine(";FFMETADATA1");
foreach (var tag in Tags)
{
sb.AppendLine($"{tag.Key}={tag.Value}");
}
long totalDurationMs = 0;
foreach (var chapter in Chapters)
{
sb.AppendLine("[CHAPTER]");
sb.AppendLine("TIMEBASE=1/1000");
sb.AppendLine($"START={totalDurationMs}");
sb.AppendLine($"END={totalDurationMs + chapter.DurationMs}");
sb.AppendLine($"title={chapter.Title}");
totalDurationMs += chapter.DurationMs;
}
return sb.ToString();
}
private class FFMetadataChapter(string title, long durationMs)
{
public string Title { get; } = title;
public long DurationMs { get; } = durationMs;
}
}

View file

@ -37,16 +37,19 @@ public static class FFMpeg
/// <param name="size">Thumbnail size. If width or height equal 0, the other will be computed automatically.</param>
/// <param name="streamIndex">Selected video stream index.</param>
/// <param name="inputFileIndex">Input file index</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <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)
int inputFileIndex = 0, CancellationToken cancellationToken = default)
{
CheckSnapshotOutputExtension(output, FileExtension.Image.All);
var source = await FFProbe.AnalyseAsync(input).ConfigureAwait(false);
var source = await FFProbe.AnalyseAsync(input, cancellationToken: cancellationToken).ConfigureAwait(false);
return await SnapshotProcess(input, output, source, size, captureTime, streamIndex, inputFileIndex)
.ProcessAsynchronously();
.CancellableThrough(cancellationToken)
.ProcessAsynchronously()
.ConfigureAwait(false);
}
public static bool GifSnapshot(string input, string output, Size? size = null, TimeSpan? captureTime = null, TimeSpan? duration = null,
@ -61,14 +64,16 @@ public static class FFMpeg
}
public static async Task<bool> GifSnapshotAsync(string input, string output, Size? size = null, TimeSpan? captureTime = null, TimeSpan? duration = null,
int? streamIndex = null)
int? streamIndex = null, CancellationToken cancellationToken = default)
{
CheckSnapshotOutputExtension(output, [FileExtension.Gif]);
var source = await FFProbe.AnalyseAsync(input).ConfigureAwait(false);
var source = await FFProbe.AnalyseAsync(input, cancellationToken: cancellationToken).ConfigureAwait(false);
return await GifSnapshotProcess(input, output, source, size, captureTime, duration, streamIndex)
.ProcessAsynchronously();
.CancellableThrough(cancellationToken)
.ProcessAsynchronously()
.ConfigureAwait(false);
}
private static FFMpegArgumentProcessor SnapshotProcess(string input, string output, IMediaAnalysis source, Size? size = null, TimeSpan? captureTime = null,
@ -292,7 +297,7 @@ public static class FFMpeg
{
if (Path.GetExtension(input) != Path.GetExtension(output))
{
output = Path.Combine(Path.GetDirectoryName(output), Path.GetFileNameWithoutExtension(output), Path.GetExtension(input));
output = Path.ChangeExtension(output, Path.GetExtension(input));
}
return FFMpegArguments
@ -321,11 +326,15 @@ public static class FFMpeg
/// <param name="output">Output video file.</param>
/// <param name="startTime">The start time of when the sub video needs to start</param>
/// <param name="endTime">The end time of where the sub video needs to end</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Output video information.</returns>
public static async Task<bool> SubVideoAsync(string input, string output, TimeSpan startTime, TimeSpan endTime)
public static async Task<bool> SubVideoAsync(string input, string output, TimeSpan startTime, TimeSpan endTime,
CancellationToken cancellationToken = default)
{
return await BaseSubVideo(input, output, startTime, endTime)
.ProcessAsynchronously();
.CancellableThrough(cancellationToken)
.ProcessAsynchronously()
.ConfigureAwait(false);
}
/// <summary>

View file

@ -85,6 +85,7 @@ public class FFMpegArgumentProcessor
public FFMpegArgumentProcessor CancellableThrough(CancellationToken token, int timeout = 0)
{
token.ThrowIfCancellationRequested();
_cancellationTokenRegistration?.Dispose();
_cancellationTokenRegistration = token.Register(() => Cancel(timeout));
return this;
@ -166,12 +167,28 @@ public class FFMpegArgumentProcessor
void OnCancelEvent(object sender, int timeout)
{
instance.SendInput("q");
ExecuteIgnoringFinishedProcessExceptions(() => instance.SendInput("q"));
if (!cancellationTokenSource.Token.WaitHandle.WaitOne(timeout, true))
{
cancellationTokenSource.Cancel();
instance.Kill();
ExecuteIgnoringFinishedProcessExceptions(() => instance.Kill());
}
static void ExecuteIgnoringFinishedProcessExceptions(Action action)
{
try
{
action();
}
catch (Instances.Exceptions.InstanceProcessAlreadyExitedException)
{
//ignore
}
catch (ObjectDisposedException)
{
//ignore
}
}
}

View file

@ -109,6 +109,11 @@ public sealed class FFMpegArguments : FFMpegArgumentsBase
return WithInput(new MetaDataArgument(content), addArguments);
}
public FFMpegArguments AddMetaData(FFMetadataBuilder metaDataBuilder, Action<FFMpegArgumentOptions>? addArguments = null)
{
return WithInput(new MetaDataArgument(metaDataBuilder.GetMetadataFileContent()), addArguments);
}
public FFMpegArguments AddMetaData(IReadOnlyMetaData metaData, Action<FFMpegArgumentOptions>? addArguments = null)
{
return WithInput(new MetaDataArgument(MetaDataSerializer.Instance.Serialize(metaData)), addArguments);

View file

@ -3,13 +3,15 @@
<PropertyGroup>
<IsPackable>true</IsPackable>
<Description>A .NET Standard FFMpeg/FFProbe wrapper for easily integrating media analysis and conversion into your .NET applications</Description>
<PackageVersion>5.3.0</PackageVersion>
<PackageVersion>5.4.0</PackageVersion>
<PackageOutputPath>../nupkg</PackageOutputPath>
<PackageReleaseNotes>
- **Fixed race condition on Named pipe dispose/disconnect** by techtel-pstevens
- **More extensions for snapshot function(jpg, bmp, webp)** by GorobVictor
- **Include more GUID characters in pipe path** by reima, rosenbjerg
- **Updated dependencies and minor cleanup**: by rosenbjerg
- Fixed exception thrown on cancelling ffprobe analysis - by snechaev
- Support for cancellationtoken in SnapsnotAsync methods - by snechaev
- Added FFMetadataBuilder - by rosenbjerg
- Fix JoinImageSequence by passing framerate argument to input as well as output - by rosenbjerg
- Change fps input from int to double - by rosenbjerg
- Fix GetCreationTime method on ITagsContainer - by rosenbjerg
</PackageReleaseNotes>
<PackageTags>ffmpeg ffprobe convert video audio mediafile resize analyze muxing</PackageTags>
<Authors>Malte Rosenbjerg, Vlad Jerca, Max Bagryantsev</Authors>

View file

@ -84,6 +84,7 @@ public static class FFProbe
var instance = PrepareStreamAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current, customArguments);
var result = await instance.StartAndWaitForExitAsync(cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
ThrowIfExitCodeNotZero(result);
return ParseOutput(result);
@ -123,6 +124,7 @@ public static class FFProbe
{
var instance = PrepareStreamAnalysisInstance(uri.AbsoluteUri, ffOptions ?? GlobalFFOptions.Current, customArguments);
var result = await instance.StartAndWaitForExitAsync(cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
ThrowIfExitCodeNotZero(result);
return ParseOutput(result);
@ -150,6 +152,7 @@ public static class FFProbe
}
var result = await task.ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
ThrowIfExitCodeNotZero(result);
pipeArgument.Post();
@ -174,7 +177,9 @@ public static class FFProbe
throw new FormatNullException();
}
ffprobeAnalysis.OutputData = instance.OutputData;
ffprobeAnalysis.ErrorData = instance.ErrorData;
return new MediaAnalysis(ffprobeAnalysis);
}

View file

@ -11,6 +11,8 @@ public class FFProbeAnalysis
[JsonPropertyName("chapters")] public List<Chapter> Chapters { get; set; } = null!;
[JsonIgnore] public IReadOnlyList<string> OutputData { get; set; } = new List<string>();
[JsonIgnore] public IReadOnlyList<string> ErrorData { get; set; } = new List<string>();
}

View file

@ -13,5 +13,6 @@ public interface IMediaAnalysis
List<VideoStream> VideoStreams { get; }
List<AudioStream> AudioStreams { get; }
List<SubtitleStream> SubtitleStreams { get; }
IReadOnlyList<string> OutputData { get; }
IReadOnlyList<string> ErrorData { get; }
}

View file

@ -9,10 +9,11 @@ internal class MediaAnalysis : IMediaAnalysis
internal MediaAnalysis(FFProbeAnalysis analysis)
{
Format = ParseFormat(analysis.Format);
Chapters = analysis.Chapters.Select(c => ParseChapter(c)).ToList();
Chapters = analysis.Chapters.Select(ParseChapter).ToList();
VideoStreams = analysis.Streams.Where(stream => stream.CodecType == "video").Select(ParseVideoStream).ToList();
AudioStreams = analysis.Streams.Where(stream => stream.CodecType == "audio").Select(ParseAudioStream).ToList();
SubtitleStreams = analysis.Streams.Where(stream => stream.CodecType == "subtitle").Select(ParseSubtitleStream).ToList();
OutputData = analysis.OutputData;
ErrorData = analysis.ErrorData;
}
@ -29,6 +30,7 @@ internal class MediaAnalysis : IMediaAnalysis
public List<VideoStream> VideoStreams { get; }
public List<AudioStream> AudioStreams { get; }
public List<SubtitleStream> SubtitleStreams { get; }
public IReadOnlyList<string> OutputData { get; }
public IReadOnlyList<string> ErrorData { get; }
private MediaFormat ParseFormat(Format analysisFormat)

View file

@ -13,6 +13,6 @@ public static class ProcessArgumentsExtensions
public static async Task<IProcessResult> StartAndWaitForExitAsync(this ProcessArguments processArguments, CancellationToken cancellationToken = default)
{
using var instance = processArguments.Start();
return await instance.WaitForExitAsync(cancellationToken);
return await instance.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
}
}