Compare commits

...

11 commits

Author SHA1 Message Date
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
6 changed files with 173 additions and 2 deletions

View file

@ -1,4 +1,5 @@
using FFMpegCore.Test.Resources;
using FFMpegCore.Exceptions;
using FFMpegCore.Test.Resources;
namespace FFMpegCore.Test;
@ -285,4 +286,70 @@ 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
Helpers.FFProbeHelper.VerifyFFProbeExists(GlobalFFOptions.Current);
var mp4 = TestResources.Mp4Video;
if (!File.Exists(mp4))
{
Assert.Inconclusive($"Test video not found: {mp4}");
return;
}
var cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken);
var token = cts.Token;
using var semaphore = new SemaphoreSlim(Environment.ProcessorCount, Environment.ProcessorCount);
var tasks = Enumerable.Range(0, 50).Select(x => Task.Run(async () =>
{
await semaphore.WaitAsync(token);
try
{
var analysis = await FFProbe.AnalyseAsync(mp4, cancellationToken: token);
return analysis;
}
finally
{
semaphore.Release();
}
}, token)).ToList();
// Wait for 2 tasks to finish, then cancel all
await Task.WhenAny(tasks);
await Task.WhenAny(tasks);
await cts.CancelAsync();
cts.Dispose();
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"));
}
}

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()

View file

@ -0,0 +1,62 @@
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)
{
Chapters.Add(new FFMetadataChapter(title, Convert.ToInt64(durationSeconds * 1000)));
return this;
}
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

@ -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

@ -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();

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);
}
}