mirror of
https://github.com/rosenbjerg/FFMpegCore.git
synced 2025-12-15 10:35:44 +00:00
Compare commits
28 commits
855f220eb6
...
7a2b09bf17
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7a2b09bf17 | ||
|
|
3b1a1438bb | ||
|
|
9b1e373c55 | ||
|
|
935e1cf17c | ||
|
|
d916fd3be4 | ||
|
|
dbf672fd6a | ||
|
|
3c8d2c23c1 | ||
|
|
919c6ef526 | ||
|
|
1346049991 | ||
|
|
67af2aa01d | ||
|
|
560c791802 | ||
|
|
e44611bd25 | ||
|
|
b863f5d19e | ||
|
|
930d493b8c | ||
|
|
f5ecbaee68 | ||
|
|
b3c201b42e | ||
|
|
adfc781e4c | ||
|
|
b10cf5fd76 | ||
|
|
0956870875 | ||
|
|
c60e217a2f | ||
|
|
ca305cd8cd | ||
|
|
dac8f97e8b | ||
|
|
52ed136459 | ||
|
|
b063d37464 | ||
|
|
935980568c | ||
|
|
91e8e1e18d | ||
|
|
f71e172f66 | ||
|
|
a6e90e2078 |
17 changed files with 470 additions and 32 deletions
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
using FFMpegCore.Test.Resources;
|
||||
using FFMpegCore.Exceptions;
|
||||
using FFMpegCore.Helpers;
|
||||
using FFMpegCore.Test.Resources;
|
||||
|
||||
namespace FFMpegCore.Test;
|
||||
|
||||
|
|
@ -285,4 +287,68 @@ 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"));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,8 +19,25 @@ public class VideoTest
|
|||
{
|
||||
private const int BaseTimeoutMilliseconds = 60_000;
|
||||
|
||||
private string _segmentPathSource = "";
|
||||
|
||||
public TestContext TestContext { get; set; }
|
||||
|
||||
[TestInitialize]
|
||||
public void Setup()
|
||||
{
|
||||
_segmentPathSource = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}-");
|
||||
}
|
||||
|
||||
[TestCleanup]
|
||||
public void Cleanup()
|
||||
{
|
||||
foreach (var file in Directory.EnumerateFiles(Path.GetDirectoryName(_segmentPathSource), Path.GetFileName(_segmentPathSource) + "*"))
|
||||
{
|
||||
File.Delete(file);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(BaseTimeoutMilliseconds, CooperativeCancellation = true)]
|
||||
public void Video_ToOGV()
|
||||
|
|
@ -732,7 +749,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);
|
||||
|
|
@ -748,7 +766,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);
|
||||
|
|
@ -1050,7 +1069,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
|
||||
|
|
@ -1061,7 +1080,6 @@ public class VideoTest
|
|||
.WithVideoCodec(VideoCodec.LibX264)
|
||||
.WithSpeedPreset(Speed.VeryFast))
|
||||
.CancellableThrough(cts.Token)
|
||||
.CancellableThrough(TestContext.CancellationToken)
|
||||
.ProcessAsynchronously(false);
|
||||
|
||||
cts.CancelAfter(300);
|
||||
|
|
@ -1077,7 +1095,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,7 +1106,6 @@ public class VideoTest
|
|||
.WithVideoCodec(VideoCodec.LibX264)
|
||||
.WithSpeedPreset(Speed.VeryFast))
|
||||
.CancellableThrough(cts.Token)
|
||||
.CancellableThrough(TestContext.CancellationToken)
|
||||
.ProcessAsynchronously();
|
||||
|
||||
cts.CancelAfter(300);
|
||||
|
|
@ -1102,7 +1119,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
|
||||
|
|
@ -1126,7 +1143,7 @@ public class VideoTest
|
|||
{
|
||||
using var outputFile = new TemporaryFile("out.mp4");
|
||||
|
||||
var cts = new CancellationTokenSource();
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken);
|
||||
|
||||
cts.Cancel();
|
||||
var task = FFMpegArguments
|
||||
|
|
@ -1149,7 +1166,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
|
||||
|
|
@ -1174,4 +1191,99 @@ public class VideoTest
|
|||
Assert.AreEqual("h264", outputInfo.PrimaryVideoStream.CodecName);
|
||||
Assert.AreEqual("aac", outputInfo.PrimaryAudioStream!.CodecName);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(BaseTimeoutMilliseconds, CooperativeCancellation = true)]
|
||||
public void Video_Segmented_File_Output()
|
||||
{
|
||||
using var input = File.OpenRead(TestResources.WebmVideo);
|
||||
var success = FFMpegArguments
|
||||
.FromPipeInput(new StreamPipeSource(input))
|
||||
.OutPutToSegmentedFiles(
|
||||
new SegmentArgument($"{_segmentPathSource}%Y-%m-%d_%H-%M-%S.mkv", true, segmentOptions => segmentOptions
|
||||
.Strftime(true)
|
||||
.Wrap()
|
||||
.Time()
|
||||
.ResetTimeStamps()),
|
||||
options => options
|
||||
.CopyChannel()
|
||||
.WithVideoCodec("h264")
|
||||
.ForceFormat("matroska")
|
||||
.WithConstantRateFactor(21)
|
||||
.WithVideoBitrate(3000)
|
||||
.WithFastStart()
|
||||
.WithVideoFilters(filterOptions => filterOptions
|
||||
.Scale(VideoSize.Hd)
|
||||
.DrawText(DrawTextOptions.Create(@"'%{localtime}.%{eif\:1M*t-1K*trunc(t*1K)\:d\:3}'",
|
||||
@"C:/Users/yan.gauthier/AppData/Local/Microsoft/Windows/Fonts/Roboto-Regular.ttf")
|
||||
.WithParameter("fontcolor", "yellow")
|
||||
.WithParameter("fontsize", "40")
|
||||
.WithParameter("x", "(w-text_w)")
|
||||
.WithParameter("y", "(h - text_h)")
|
||||
.WithParameter("rate", "19")
|
||||
)
|
||||
)
|
||||
)
|
||||
.CancellableThrough(TestContext.CancellationToken)
|
||||
.ProcessSynchronously(false);
|
||||
Assert.IsTrue(success);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(BaseTimeoutMilliseconds, CooperativeCancellation = true)]
|
||||
public void Video_MultiOutput_With_Segmented_File_Output()
|
||||
{
|
||||
using var input = File.OpenRead(TestResources.WebmVideo);
|
||||
var success = FFMpegArguments
|
||||
.FromPipeInput(new StreamPipeSource(input))
|
||||
.MultiOutput(args => args
|
||||
.OutputToFile($"{_segmentPathSource}2", true, options => options
|
||||
.CopyChannel()
|
||||
.WithVideoCodec("mjpeg")
|
||||
.ForceFormat("matroska")
|
||||
.WithConstantRateFactor(21)
|
||||
.WithVideoBitrate(4000)
|
||||
.WithFastStart()
|
||||
.WithVideoFilters(filterOptions => filterOptions
|
||||
.Scale(VideoSize.Hd)
|
||||
.DrawText(DrawTextOptions.Create(@"'%{localtime}.%{eif\:1M*t-1K*trunc(t*1K)\:d\:3}'",
|
||||
@"C:/Users/yan.gauthier/AppData/Local/Microsoft/Windows/Fonts/Roboto-Regular.ttf")
|
||||
.WithParameter("fontcolor", "yellow")
|
||||
.WithParameter("fontsize", "40")
|
||||
.WithParameter("x", "(w-text_w)")
|
||||
.WithParameter("y", "(h - text_h)")
|
||||
.WithParameter("rate", "19")
|
||||
)
|
||||
)
|
||||
)
|
||||
.OutPutToSegmentedFiles(
|
||||
new SegmentArgument($"{_segmentPathSource}%Y-%m-%d_%H-%M-%S.mkv", true, segmentOptions => segmentOptions
|
||||
.Strftime(true)
|
||||
.Wrap()
|
||||
.Time()
|
||||
.ResetTimeStamps()),
|
||||
options => options
|
||||
.CopyChannel()
|
||||
.WithVideoCodec("h264")
|
||||
.ForceFormat("matroska")
|
||||
.WithConstantRateFactor(21)
|
||||
.WithVideoBitrate(3000)
|
||||
.WithFastStart()
|
||||
.WithVideoFilters(filterOptions => filterOptions
|
||||
.Scale(VideoSize.Hd)
|
||||
.DrawText(DrawTextOptions.Create(@"'%{localtime}.%{eif\:1M*t-1K*trunc(t*1K)\:d\:3}'",
|
||||
@"C:/Users/yan.gauthier/AppData/Local/Microsoft/Windows/Fonts/Roboto-Regular.ttf")
|
||||
.WithParameter("fontcolor", "yellow")
|
||||
.WithParameter("fontsize", "40")
|
||||
.WithParameter("x", "(w-text_w)")
|
||||
.WithParameter("y", "(h - text_h)")
|
||||
.WithParameter("rate", "19")
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
.CancellableThrough(TestContext.CancellationToken)
|
||||
.ProcessSynchronously(false);
|
||||
Assert.IsTrue(success);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
114
FFMpegCore/FFMpeg/Arguments/OutputSegmentArgument.cs
Normal file
114
FFMpegCore/FFMpeg/Arguments/OutputSegmentArgument.cs
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
using FFMpegCore.Exceptions;
|
||||
|
||||
namespace FFMpegCore.Arguments;
|
||||
|
||||
/// <summary>
|
||||
/// Represents output parameter
|
||||
/// </summary>
|
||||
public class OutputSegmentArgument : IOutputArgument
|
||||
{
|
||||
public readonly SegmentArgumentOptions Options;
|
||||
public readonly bool Overwrite;
|
||||
public readonly string SegmentPattern;
|
||||
|
||||
public OutputSegmentArgument(SegmentArgument segmentArgument)
|
||||
{
|
||||
SegmentPattern = segmentArgument.SegmentPattern;
|
||||
Overwrite = segmentArgument.Overwrite;
|
||||
var segmentArgumentobj = new SegmentArgumentOptions();
|
||||
segmentArgument.Options?.Invoke(segmentArgumentobj);
|
||||
Options = segmentArgumentobj;
|
||||
}
|
||||
|
||||
public void Pre()
|
||||
{
|
||||
if (int.TryParse(Options.Arguments.FirstOrDefault(x => x.Key == "segment_time").Value, out var result) && result < 1)
|
||||
{
|
||||
throw new FFMpegException(FFMpegExceptionType.Process, "Parameter SegmentTime cannot be negative or equal to zero");
|
||||
}
|
||||
|
||||
if (Options.Arguments.FirstOrDefault(x => x.Key == "segment_time").Value == "0")
|
||||
{
|
||||
throw new FFMpegException(FFMpegExceptionType.Process, "Parameter SegmentWrap cannot equal to zero");
|
||||
}
|
||||
}
|
||||
|
||||
public Task During(CancellationToken cancellationToken = default)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public void Post()
|
||||
{
|
||||
}
|
||||
|
||||
public string Text => GetText();
|
||||
|
||||
private string GetText()
|
||||
{
|
||||
var arguments = Options.Arguments
|
||||
.Where(arg => !string.IsNullOrWhiteSpace(arg.Value) && !string.IsNullOrWhiteSpace(arg.Key))
|
||||
.Select(arg =>
|
||||
{
|
||||
return arg.Value;
|
||||
});
|
||||
|
||||
return $"-f segment {string.Join(" ", arguments)} \"{SegmentPattern}\"{(Overwrite ? " -y" : string.Empty)}";
|
||||
}
|
||||
}
|
||||
|
||||
public interface ISegmentArgument
|
||||
{
|
||||
string Key { get; }
|
||||
string Value { get; }
|
||||
}
|
||||
|
||||
public class SegmentArgumentOptions
|
||||
{
|
||||
public List<ISegmentArgument> Arguments { get; } = new();
|
||||
|
||||
public SegmentArgumentOptions ResetTimeStamps(bool resetTimestamps = true)
|
||||
{
|
||||
return WithArgument(new SegmentResetTimeStampsArgument(resetTimestamps));
|
||||
}
|
||||
|
||||
public SegmentArgumentOptions Strftime(bool enable = false)
|
||||
{
|
||||
return WithArgument(new SegmentStrftimeArgument(enable));
|
||||
}
|
||||
|
||||
public SegmentArgumentOptions Time(int time = 60)
|
||||
{
|
||||
return WithArgument(new SegmentTimeArgument(time));
|
||||
}
|
||||
|
||||
public SegmentArgumentOptions Wrap(int limit = -1)
|
||||
{
|
||||
return WithArgument(new SegmentWrapArgument(limit));
|
||||
}
|
||||
|
||||
public SegmentArgumentOptions WithCustomArgument(string argument)
|
||||
{
|
||||
return WithArgument(new SegmentCustomArgument(argument));
|
||||
}
|
||||
|
||||
private SegmentArgumentOptions WithArgument(ISegmentArgument argument)
|
||||
{
|
||||
Arguments.Add(argument);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
public class SegmentArgument
|
||||
{
|
||||
public readonly Action<SegmentArgumentOptions> Options;
|
||||
public readonly bool Overwrite;
|
||||
public readonly string SegmentPattern;
|
||||
|
||||
public SegmentArgument(string segmentPattern, bool overwrite, Action<SegmentArgumentOptions> options)
|
||||
{
|
||||
SegmentPattern = segmentPattern;
|
||||
Overwrite = overwrite;
|
||||
Options = options;
|
||||
}
|
||||
}
|
||||
14
FFMpegCore/FFMpeg/Arguments/SegmentCustomArgument.cs
Normal file
14
FFMpegCore/FFMpeg/Arguments/SegmentCustomArgument.cs
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
namespace FFMpegCore.Arguments;
|
||||
|
||||
public class SegmentCustomArgument : ISegmentArgument
|
||||
{
|
||||
public readonly string Argument;
|
||||
|
||||
public SegmentCustomArgument(string argument)
|
||||
{
|
||||
Argument = argument;
|
||||
}
|
||||
|
||||
public string Key => "custom";
|
||||
public string Value => Argument ?? string.Empty;
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
namespace FFMpegCore.Arguments;
|
||||
|
||||
/// <summary>
|
||||
/// Represents reset_timestamps parameter
|
||||
/// </summary>
|
||||
public class SegmentResetTimeStampsArgument : ISegmentArgument
|
||||
{
|
||||
public readonly bool ResetTimestamps;
|
||||
|
||||
/// <summary>
|
||||
/// Represents reset_timestamps parameter
|
||||
/// </summary>
|
||||
/// <param name="resetTimestamps">true if files timestamps are to be reset</param>
|
||||
public SegmentResetTimeStampsArgument(bool resetTimestamps)
|
||||
{
|
||||
ResetTimestamps = resetTimestamps;
|
||||
}
|
||||
|
||||
public string Key { get; } = "reset_timestamps";
|
||||
public string Value => ResetTimestamps ? "-reset_timestamps 1" : string.Empty;
|
||||
}
|
||||
23
FFMpegCore/FFMpeg/Arguments/SegmentStrftimeArgument.cs
Normal file
23
FFMpegCore/FFMpeg/Arguments/SegmentStrftimeArgument.cs
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
namespace FFMpegCore.Arguments;
|
||||
|
||||
/// <summary>
|
||||
/// Use the strftime function to define the name of the new segments to write. If this is selected, the output segment name must contain a
|
||||
/// strftime function template. Default value is 0.
|
||||
/// </summary>
|
||||
public class SegmentStrftimeArgument : ISegmentArgument
|
||||
{
|
||||
public readonly bool Enable;
|
||||
|
||||
/// <summary>
|
||||
/// Use the strftime function to define the name of the new segments to write. If this is selected, the output segment name must contain a
|
||||
/// strftime function template. Default value is 0.
|
||||
/// </summary>
|
||||
/// <param name="enable">true to enable strftime</param>
|
||||
public SegmentStrftimeArgument(bool enable)
|
||||
{
|
||||
Enable = enable;
|
||||
}
|
||||
|
||||
public string Key { get; } = "strftime";
|
||||
public string Value => Enable ? "-strftime 1" : string.Empty;
|
||||
}
|
||||
21
FFMpegCore/FFMpeg/Arguments/SegmentTimeArgument.cs
Normal file
21
FFMpegCore/FFMpeg/Arguments/SegmentTimeArgument.cs
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
namespace FFMpegCore.Arguments;
|
||||
|
||||
/// <summary>
|
||||
/// Represents segment_time parameter
|
||||
/// </summary>
|
||||
public class SegmentTimeArgument : ISegmentArgument
|
||||
{
|
||||
public readonly int Time;
|
||||
|
||||
/// <summary>
|
||||
/// Represents segment_time parameter
|
||||
/// </summary>
|
||||
/// <param name="time">time in seconds of the segment</param>
|
||||
public SegmentTimeArgument(int time)
|
||||
{
|
||||
Time = time;
|
||||
}
|
||||
|
||||
public string Key { get; } = "segment_time";
|
||||
public string Value => Time <= 0 ? string.Empty : $"-segment_time {Time}";
|
||||
}
|
||||
21
FFMpegCore/FFMpeg/Arguments/SegmentWrapArgument.cs
Normal file
21
FFMpegCore/FFMpeg/Arguments/SegmentWrapArgument.cs
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
namespace FFMpegCore.Arguments;
|
||||
|
||||
/// <summary>
|
||||
/// Represents segment_wrap parameter
|
||||
/// </summary>
|
||||
public class SegmentWrapArgument : ISegmentArgument
|
||||
{
|
||||
public readonly int Limit;
|
||||
|
||||
/// <summary>
|
||||
/// Represents segment_wrap parameter
|
||||
/// </summary>
|
||||
/// <param name="limit">limit value after which segment index will wrap around</param>
|
||||
public SegmentWrapArgument(int limit)
|
||||
{
|
||||
Limit = limit;
|
||||
}
|
||||
|
||||
public string Key { get; } = "segment_wrap";
|
||||
public string Value => Limit <= 0 ? string.Empty : $"-segment_wrap {Limit}";
|
||||
}
|
||||
|
|
@ -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,
|
||||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -166,12 +166,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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -157,6 +157,11 @@ public sealed class FFMpegArguments : FFMpegArgumentsBase
|
|||
return ToProcessor(new OutputPipeArgument(reader), addArguments);
|
||||
}
|
||||
|
||||
public FFMpegArgumentProcessor OutPutToSegmentedFiles(SegmentArgument segmentArgument, Action<FFMpegArgumentOptions>? addArguments = null)
|
||||
{
|
||||
return ToProcessor(new OutputSegmentArgument(segmentArgument), addArguments);
|
||||
}
|
||||
|
||||
private FFMpegArgumentProcessor ToProcessor(IOutputArgument argument, Action<FFMpegArgumentOptions>? addArguments)
|
||||
{
|
||||
var args = new FFMpegArgumentOptions();
|
||||
|
|
|
|||
|
|
@ -29,6 +29,11 @@ public class FFMpegMultiOutputOptions
|
|||
return AddOutput(new OutputPipeArgument(reader), addArguments);
|
||||
}
|
||||
|
||||
public FFMpegMultiOutputOptions OutPutToSegmentedFiles(SegmentArgument segmentArgument, Action<FFMpegArgumentOptions>? addArguments = null)
|
||||
{
|
||||
return AddOutput(new OutputSegmentArgument(segmentArgument), addArguments);
|
||||
}
|
||||
|
||||
public FFMpegMultiOutputOptions AddOutput(IOutputArgument argument, Action<FFMpegArgumentOptions>? addArguments)
|
||||
{
|
||||
var args = new FFMpegArgumentOptions();
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue