Compare commits

..

1 commit

Author SHA1 Message Date
tqk2811
2eecb92481
Merge 89d4235f7a into 2f06ec99f3 2025-10-26 09:40:37 +01:00
10 changed files with 44 additions and 166 deletions

View file

@ -39,21 +39,18 @@ 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, CancellationToken cancellationToken = default)
int inputFileIndex = 0)
{
var source = await FFProbe.AnalyseAsync(input, cancellationToken: cancellationToken).ConfigureAwait(false);
var source = await FFProbe.AnalyseAsync(input).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")))
.CancellableThrough(cancellationToken)
.ProcessAsynchronously()
.ConfigureAwait(false);
.ProcessAsynchronously();
ms.Position = 0;
return SKBitmap.Decode(ms);

View file

@ -38,21 +38,18 @@ 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, CancellationToken cancellationToken = default)
int inputFileIndex = 0)
{
var source = await FFProbe.AnalyseAsync(input, cancellationToken: cancellationToken).ConfigureAwait(false);
var source = await FFProbe.AnalyseAsync(input).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")))
.CancellableThrough(cancellationToken)
.ProcessAsynchronously()
.ConfigureAwait(false);
.ProcessAsynchronously();
ms.Position = 0;
return new Bitmap(ms);

View file

@ -1,6 +1,4 @@
using FFMpegCore.Exceptions;
using FFMpegCore.Helpers;
using FFMpegCore.Test.Resources;
using FFMpegCore.Test.Resources;
namespace FFMpegCore.Test;
@ -287,68 +285,4 @@ 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"));
}
}

View file

@ -154,7 +154,7 @@ public class VideoTest
{
using var outputFile = new TemporaryFile($"out{VideoType.Mp4.Extension}");
var videoFramesSource = new RawVideoPipeSource(BitmapSource.CreateBitmaps(64, pixelFormat, 256, 256));
var videoFramesSource = new RawVideoPipeSource(BitmapSource.CreateBitmaps(128, pixelFormat, 256, 256));
var success = FFMpegArguments
.FromPipeInput(videoFramesSource)
.OutputToFile(outputFile, false, opt => opt
@ -474,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(64, pixelFormat, 256, 256));
var input = new RawVideoPipeSource(BitmapSource.CreateBitmaps(128, pixelFormat, 256, 256));
var success = await FFMpegArguments
.FromPipeInput(input)
@ -511,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(64, pixelFormat, 256, 256));
var videoFramesSource = new RawVideoPipeSource(BitmapSource.CreateBitmaps(128, pixelFormat, 256, 256));
FFMpegArguments
.FromPipeInput(videoFramesSource)
@ -565,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(64, pixelFormat, 256, 256));
var videoFramesSource = new RawVideoPipeSource(BitmapSource.CreateBitmaps(128, pixelFormat, 256, 256));
var success = FFMpegArguments
.FromPipeInput(videoFramesSource)
@ -732,8 +732,7 @@ 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),
cancellationToken: TestContext.CancellationToken);
await FFMpeg.GifSnapshotAsync(TestResources.Mp4Video, outputPath, captureTime: TimeSpan.FromSeconds(0));
var analysis = FFProbe.Analyse(outputPath);
Assert.AreNotEqual(input.PrimaryVideoStream!.Width, analysis.PrimaryVideoStream!.Width);
@ -749,8 +748,7 @@ 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),
cancellationToken: TestContext.CancellationToken);
await FFMpeg.GifSnapshotAsync(TestResources.Mp4Video, outputPath, desiredGifSize, TimeSpan.FromSeconds(0));
var analysis = FFProbe.Analyse(outputPath);
Assert.AreNotEqual(input.PrimaryVideoStream!.Width, desiredGifSize.Width);
@ -927,7 +925,7 @@ public class VideoTest
{
using var resStream = new MemoryStream();
var reader = new StreamPipeSink(resStream);
var writer = new RawVideoPipeSource(BitmapSource.CreateBitmaps(64, pixelFormat, 128, 128));
var writer = new RawVideoPipeSource(BitmapSource.CreateBitmaps(128, pixelFormat, 128, 128));
FFMpegArguments
.FromPipeInput(writer)
@ -1052,7 +1050,7 @@ public class VideoTest
{
using var outputFile = new TemporaryFile("out.mp4");
using var cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken);
var cts = new CancellationTokenSource();
var task = FFMpegArguments
.FromFileInput("testsrc2=size=320x240[out0]; sine[out1]", false, args => args
@ -1063,6 +1061,7 @@ public class VideoTest
.WithVideoCodec(VideoCodec.LibX264)
.WithSpeedPreset(Speed.VeryFast))
.CancellableThrough(cts.Token)
.CancellableThrough(TestContext.CancellationToken)
.ProcessAsynchronously(false);
cts.CancelAfter(300);
@ -1078,7 +1077,7 @@ public class VideoTest
{
using var outputFile = new TemporaryFile("out.mp4");
using var cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken);
var cts = new CancellationTokenSource();
var task = FFMpegArguments
.FromFileInput("testsrc2=size=320x240[out0]; sine[out1]", false, args => args
@ -1089,6 +1088,7 @@ public class VideoTest
.WithVideoCodec(VideoCodec.LibX264)
.WithSpeedPreset(Speed.VeryFast))
.CancellableThrough(cts.Token)
.CancellableThrough(TestContext.CancellationToken)
.ProcessAsynchronously();
cts.CancelAfter(300);
@ -1102,7 +1102,7 @@ public class VideoTest
{
using var outputFile = new TemporaryFile("out.mp4");
using var cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken);
var cts = new CancellationTokenSource();
var task = FFMpegArguments
.FromFileInput("testsrc2=size=320x240[out0]; sine[out1]", false, args => args
@ -1122,12 +1122,13 @@ public class VideoTest
[TestMethod]
[Timeout(BaseTimeoutMilliseconds, CooperativeCancellation = true)]
public void Video_Cancel_CancellationToken_BeforeProcessing_Throws()
public void Video_Cancel_CancellationToken_Before_Throws()
{
using var outputFile = new TemporaryFile("out.mp4");
using var cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken);
var cts = new CancellationTokenSource();
cts.Cancel();
var task = FFMpegArguments
.FromFileInput("testsrc2=size=320x240[out0]; sine[out1]", false, args => args
.WithCustomArgument("-re")
@ -1138,29 +1139,8 @@ public class VideoTest
.WithSpeedPreset(Speed.VeryFast))
.CancellableThrough(cts.Token);
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));
Assert.ThrowsExactly<OperationCanceledException>(() => task.CancellableThrough(TestContext.CancellationToken)
.ProcessSynchronously());
}
[TestMethod]
@ -1169,7 +1149,7 @@ public class VideoTest
{
using var outputFile = new TemporaryFile("out.mp4");
using var cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken);
var cts = new CancellationTokenSource();
var task = FFMpegArguments
.FromFileInput("testsrc2=size=320x240[out0]; sine[out1]", false, args => args

View file

@ -26,7 +26,8 @@ public class FFMetadataBuilder
public FFMetadataBuilder WithChapter(string title, double durationSeconds)
{
return WithChapter(title, Convert.ToInt64(durationSeconds * 1000));
Chapters.Add(new FFMetadataChapter(title, Convert.ToInt64(durationSeconds * 1000)));
return this;
}
public string GetMetadataFileContent()

View file

@ -37,19 +37,16 @@ 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, CancellationToken cancellationToken = default)
int inputFileIndex = 0)
{
CheckSnapshotOutputExtension(output, FileExtension.Image.All);
var source = await FFProbe.AnalyseAsync(input, cancellationToken: cancellationToken).ConfigureAwait(false);
var source = await FFProbe.AnalyseAsync(input).ConfigureAwait(false);
return await SnapshotProcess(input, output, source, size, captureTime, streamIndex, inputFileIndex)
.CancellableThrough(cancellationToken)
.ProcessAsynchronously()
.ConfigureAwait(false);
.ProcessAsynchronously();
}
public static bool GifSnapshot(string input, string output, Size? size = null, TimeSpan? captureTime = null, TimeSpan? duration = null,
@ -64,16 +61,14 @@ 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, CancellationToken cancellationToken = default)
int? streamIndex = null)
{
CheckSnapshotOutputExtension(output, [FileExtension.Gif]);
var source = await FFProbe.AnalyseAsync(input, cancellationToken: cancellationToken).ConfigureAwait(false);
var source = await FFProbe.AnalyseAsync(input).ConfigureAwait(false);
return await GifSnapshotProcess(input, output, source, size, captureTime, duration, streamIndex)
.CancellableThrough(cancellationToken)
.ProcessAsynchronously()
.ConfigureAwait(false);
.ProcessAsynchronously();
}
private static FFMpegArgumentProcessor SnapshotProcess(string input, string output, IMediaAnalysis source, Size? size = null, TimeSpan? captureTime = null,
@ -297,7 +292,7 @@ public static class FFMpeg
{
if (Path.GetExtension(input) != Path.GetExtension(output))
{
output = Path.ChangeExtension(output, Path.GetExtension(input));
output = Path.Combine(Path.GetDirectoryName(output), Path.GetFileNameWithoutExtension(output), Path.GetExtension(input));
}
return FFMpegArguments
@ -326,15 +321,11 @@ 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,
CancellationToken cancellationToken = default)
public static async Task<bool> SubVideoAsync(string input, string output, TimeSpan startTime, TimeSpan endTime)
{
return await BaseSubVideo(input, output, startTime, endTime)
.CancellableThrough(cancellationToken)
.ProcessAsynchronously()
.ConfigureAwait(false);
.ProcessAsynchronously();
}
/// <summary>

View file

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

View file

@ -3,15 +3,13 @@
<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.4.0</PackageVersion>
<PackageVersion>5.3.0</PackageVersion>
<PackageOutputPath>../nupkg</PackageOutputPath>
<PackageReleaseNotes>
- 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
- **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
</PackageReleaseNotes>
<PackageTags>ffmpeg ffprobe convert video audio mediafile resize analyze muxing</PackageTags>
<Authors>Malte Rosenbjerg, Vlad Jerca, Max Bagryantsev</Authors>

View file

@ -105,7 +105,6 @@ 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 DeserializeOutput(result);
@ -150,7 +149,6 @@ 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 DeserializeOutput(result);
@ -183,7 +181,6 @@ 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).ConfigureAwait(false);
return await instance.WaitForExitAsync(cancellationToken);
}
}