Compare commits

...

19 commits

Author SHA1 Message Date
SinisterMaya
855f220eb6
Merge adfc781e4c into 2f06ec99f3 2025-10-27 11:12:24 +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
Malte Rosenbjerg
adfc781e4c
Merge branch 'main' into Add_Segment_muxer_output 2025-10-17 20:38:10 +02:00
Malte Rosenbjerg
b10cf5fd76 Remove accessibility modifiers on interface 2025-10-16 15:17:19 +02:00
Malte Rosenbjerg
0956870875 Run code cleanup 2025-10-16 15:14:14 +02:00
Malte Rosenbjerg
c60e217a2f Update code after update from main 2025-10-16 15:00:43 +02:00
Malte Rosenbjerg
ca305cd8cd Merge branch 'main' into pr/538 2025-10-16 14:56:40 +02:00
Malte Rosenbjerg
dac8f97e8b
Merge branch 'main' into Add_Segment_muxer_output 2025-10-16 10:01:16 +02:00
Malte Rosenbjerg
52ed136459
Merge branch 'main' into Add_Segment_muxer_output 2024-12-05 10:11:57 +01:00
Malte Rosenbjerg
b063d37464
Merge branch 'main' into Add_Segment_muxer_output 2024-12-04 21:00:15 +01:00
Yan Gauthier
935980568c Removed excessive whitespace 2024-08-15 16:32:12 -04:00
Yan Gauthier
91e8e1e18d Added JsonIgnore to Encoding on FFOptions since a breacking change in System.Text.Json introduced in .NET8.0 prevent us from deserializing this type https://github.com/dotnet/docs/issues/37041 2024-08-15 15:28:01 -04:00
Yan Gauthier
f71e172f66 Added option to use the segment muxer allowing output to file to be segmented. There's a SegmentCustomArgument for the arguments I did not implement. 2024-08-15 15:26:03 -04:00
Yan Gauthier
a6e90e2078 Updated System.Text.Json because of vulnerabilities 2024-08-15 10:08:18 -04:00
10 changed files with 437 additions and 0 deletions

View file

@ -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()
@ -82,6 +99,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()
@ -1140,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);
}
}

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

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

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

View file

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

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

View 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}";
}

View 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}";
}

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

View file

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