Merge branch 'main' into main

This commit is contained in:
Malte Rosenbjerg 2023-10-05 12:17:18 +02:00 committed by GitHub
commit bba4a9f39b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 241 additions and 36 deletions

View file

@ -571,5 +571,45 @@ public void Builder_BuildString_GifPalette_NullSize_FpsSupplied()
-i "input.mp4" -filter_complex "[{streamIndex}:v] fps=10,split [a][b];[a] palettegen=max_colors=32 [p];[b][p] paletteuse=dither=bayer" "output.gif"
""", str);
}
[TestMethod]
public void Builder_BuildString_MultiOutput()
{
var str = FFMpegArguments.FromFileInput("input.mp4")
.MultiOutput(args => args
.OutputToFile("output.mp4", overwrite: true, args => args.CopyChannel())
.OutputToFile("output.ts", overwrite: false, args => args.CopyChannel().ForceFormat("mpegts"))
.OutputToUrl("http://server/path", options => options.ForceFormat("webm")))
.Arguments;
Assert.AreEqual($"""
-i "input.mp4" -c:a copy -c:v copy "output.mp4" -y -c:a copy -c:v copy -f mpegts "output.ts" -f webm http://server/path
""", str);
}
[TestMethod]
public void Builder_BuildString_MBROutput()
{
var str = FFMpegArguments.FromFileInput("input.mp4")
.MultiOutput(args => args
.OutputToFile("sd.mp4", overwrite: true, args => args.Resize(1200, 720))
.OutputToFile("hd.mp4", overwrite: false, args => args.Resize(1920, 1080)))
.Arguments;
Assert.AreEqual($"""
-i "input.mp4" -s 1200x720 "sd.mp4" -y -s 1920x1080 "hd.mp4"
""", str);
}
[TestMethod]
public void Builder_BuildString_TeeOutput()
{
var str = FFMpegArguments.FromFileInput("input.mp4")
.OutputToTee(args => args
.OutputToFile("output.mp4", overwrite: false, args => args.WithFastStart())
.OutputToUrl("http://server/path", options => options.ForceFormat("mpegts").SelectStream(0, channel: Channel.Video)))
.Arguments;
Assert.AreEqual($"""
-i "input.mp4" -f tee "[movflags=faststart]output.mp4|[f=mpegts:select=\'0:v:0\']http://server/path"
""", str);
}
}
}

View file

@ -105,6 +105,7 @@ public void Probe_Success()
{
var info = FFProbe.Analyse(TestResources.Mp4Video);
Assert.AreEqual(3, info.Duration.Seconds);
Assert.AreEqual(0, info.Chapters.Count);
Assert.AreEqual("5.1", info.PrimaryAudioStream!.ChannelLayout);
Assert.AreEqual(6, info.PrimaryAudioStream.Channels);
@ -235,5 +236,12 @@ public async Task Probe_Success_32BitWavBitDepth_Async()
Assert.IsNotNull(info.PrimaryAudioStream);
Assert.AreEqual(32, info.PrimaryAudioStream.BitDepth);
}
[TestMethod]
public void Probe_Success_Custom_Arguments()
{
var info = FFProbe.Analyse(TestResources.Mp4Video, customArguments: "-headers \"Hello: World\"");
Assert.AreEqual(3, info.Duration.Seconds);
}
}
}

View file

@ -0,0 +1,57 @@

namespace FFMpegCore.Arguments
{
internal class OutputTeeArgument : IOutputArgument
{
private readonly FFMpegMultiOutputOptions _options;
public OutputTeeArgument(FFMpegMultiOutputOptions options)
{
if (options.Outputs.Count == 0)
{
throw new ArgumentException("Atleast one output must be specified.", nameof(options));
}
_options = options;
}
public string Text => $"-f tee \"{string.Join("|", _options.Outputs.Select(MapOptions))}\"";
public Task During(CancellationToken cancellationToken = default) => Task.CompletedTask;
public void Post()
{
}
public void Pre()
{
}
private static string MapOptions(FFMpegArgumentOptions option)
{
var optionPrefix = string.Empty;
if (option.Arguments.Count > 1)
{
var options = option.Arguments.Take(option.Arguments.Count - 1);
optionPrefix = $"[{string.Join(":", options.Select(MapArgument))}]";
}
var output = option.Arguments.OfType<IOutputArgument>().Single();
return $"{optionPrefix}{output.Text.Trim('"')}";
}
private static string MapArgument(IArgument argument)
{
if (argument is MapStreamArgument map)
{
return map.Text.Replace("-map ", "select=\\'") + "\\'";
}
else if (argument is BitStreamFilterArgument bitstreamFilter)
{
return bitstreamFilter.Text.Replace("-bsf:", "bsfs/").Replace(' ', '=');
}
return argument.Text.TrimStart('-').Replace(' ', '=');
}
}
}

View file

@ -6,6 +6,8 @@ public class ChapterData
public TimeSpan Start { get; private set; }
public TimeSpan End { get; private set; }
public TimeSpan Duration => End - Start;
public ChapterData(string title, TimeSpan start, TimeSpan end)
{
Title = title;

View file

@ -71,6 +71,21 @@ private FFMpegArgumentProcessor ToProcessor(IOutputArgument argument, Action<FFM
return new FFMpegArgumentProcessor(this);
}
public FFMpegArgumentProcessor OutputToTee(Action<FFMpegMultiOutputOptions> addOutputs, Action<FFMpegArgumentOptions>? addArguments = null)
{
var outputs = new FFMpegMultiOutputOptions();
addOutputs(outputs);
return ToProcessor(new OutputTeeArgument(outputs), addArguments);
}
public FFMpegArgumentProcessor MultiOutput(Action<FFMpegMultiOutputOptions> addOutputs)
{
var args = new FFMpegMultiOutputOptions();
addOutputs(args);
Arguments.AddRange(args.Arguments);
return new FFMpegArgumentProcessor(this);
}
internal void Pre()
{
foreach (var argument in Arguments.OfType<IInputOutputArgument>())

View file

@ -0,0 +1,29 @@
using FFMpegCore.Arguments;
using FFMpegCore.Pipes;
namespace FFMpegCore
{
public class FFMpegMultiOutputOptions
{
internal readonly List<FFMpegArgumentOptions> Outputs = new();
public IEnumerable<IArgument> Arguments => Outputs.SelectMany(o => o.Arguments);
public FFMpegMultiOutputOptions OutputToFile(string file, bool overwrite = true, Action<FFMpegArgumentOptions>? addArguments = null) => AddOutput(new OutputArgument(file, overwrite), addArguments);
public FFMpegMultiOutputOptions OutputToUrl(string uri, Action<FFMpegArgumentOptions>? addArguments = null) => AddOutput(new OutputUrlArgument(uri), addArguments);
public FFMpegMultiOutputOptions OutputToUrl(Uri uri, Action<FFMpegArgumentOptions>? addArguments = null) => AddOutput(new OutputUrlArgument(uri.ToString()), addArguments);
public FFMpegMultiOutputOptions OutputToPipe(IPipeSink reader, Action<FFMpegArgumentOptions>? addArguments = null) => AddOutput(new OutputPipeArgument(reader), addArguments);
public FFMpegMultiOutputOptions AddOutput(IOutputArgument argument, Action<FFMpegArgumentOptions>? addArguments)
{
var args = new FFMpegArgumentOptions();
addArguments?.Invoke(args);
args.Arguments.Add(argument);
Outputs.Add(args);
return this;
}
}
}

View file

@ -10,52 +10,52 @@ namespace FFMpegCore
{
public static class FFProbe
{
public static IMediaAnalysis Analyse(string filePath, FFOptions? ffOptions = null)
public static IMediaAnalysis Analyse(string filePath, FFOptions? ffOptions = null, string? customArguments = null)
{
ThrowIfInputFileDoesNotExist(filePath);
var processArguments = PrepareStreamAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current);
var processArguments = PrepareStreamAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current, customArguments);
var result = processArguments.StartAndWaitForExit();
ThrowIfExitCodeNotZero(result);
return ParseOutput(result);
}
public static FFProbeFrames GetFrames(string filePath, FFOptions? ffOptions = null)
public static FFProbeFrames GetFrames(string filePath, FFOptions? ffOptions = null, string? customArguments = null)
{
ThrowIfInputFileDoesNotExist(filePath);
var instance = PrepareFrameAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current);
var instance = PrepareFrameAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current, customArguments);
var result = instance.StartAndWaitForExit();
ThrowIfExitCodeNotZero(result);
return ParseFramesOutput(result);
}
public static FFProbePackets GetPackets(string filePath, FFOptions? ffOptions = null)
public static FFProbePackets GetPackets(string filePath, FFOptions? ffOptions = null, string? customArguments = null)
{
ThrowIfInputFileDoesNotExist(filePath);
var instance = PreparePacketAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current);
var instance = PreparePacketAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current, customArguments);
var result = instance.StartAndWaitForExit();
ThrowIfExitCodeNotZero(result);
return ParsePacketsOutput(result);
}
public static IMediaAnalysis Analyse(Uri uri, FFOptions? ffOptions = null)
public static IMediaAnalysis Analyse(Uri uri, FFOptions? ffOptions = null, string? customArguments = null)
{
var instance = PrepareStreamAnalysisInstance(uri.AbsoluteUri, ffOptions ?? GlobalFFOptions.Current);
var instance = PrepareStreamAnalysisInstance(uri.AbsoluteUri, ffOptions ?? GlobalFFOptions.Current, customArguments);
var result = instance.StartAndWaitForExit();
ThrowIfExitCodeNotZero(result);
return ParseOutput(result);
}
public static IMediaAnalysis Analyse(Stream stream, FFOptions? ffOptions = null)
public static IMediaAnalysis Analyse(Stream stream, FFOptions? ffOptions = null, string? customArguments = null)
{
var streamPipeSource = new StreamPipeSource(stream);
var pipeArgument = new InputPipeArgument(streamPipeSource);
var instance = PrepareStreamAnalysisInstance(pipeArgument.PipePath, ffOptions ?? GlobalFFOptions.Current);
var instance = PrepareStreamAnalysisInstance(pipeArgument.PipePath, ffOptions ?? GlobalFFOptions.Current, customArguments);
pipeArgument.Pre();
var task = instance.StartAndWaitForExitAsync();
@ -75,57 +75,57 @@ public static IMediaAnalysis Analyse(Stream stream, FFOptions? ffOptions = null)
return ParseOutput(result);
}
public static async Task<IMediaAnalysis> AnalyseAsync(string filePath, FFOptions? ffOptions = null, CancellationToken cancellationToken = default)
public static async Task<IMediaAnalysis> AnalyseAsync(string filePath, FFOptions? ffOptions = null, CancellationToken cancellationToken = default, string? customArguments = null)
{
ThrowIfInputFileDoesNotExist(filePath);
var instance = PrepareStreamAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current);
var instance = PrepareStreamAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current, customArguments);
var result = await instance.StartAndWaitForExitAsync(cancellationToken).ConfigureAwait(false);
ThrowIfExitCodeNotZero(result);
return ParseOutput(result);
}
public static FFProbeFrames GetFrames(Uri uri, FFOptions? ffOptions = null)
public static FFProbeFrames GetFrames(Uri uri, FFOptions? ffOptions = null, string? customArguments = null)
{
var instance = PrepareFrameAnalysisInstance(uri.AbsoluteUri, ffOptions ?? GlobalFFOptions.Current);
var instance = PrepareFrameAnalysisInstance(uri.AbsoluteUri, ffOptions ?? GlobalFFOptions.Current, customArguments);
var result = instance.StartAndWaitForExit();
ThrowIfExitCodeNotZero(result);
return ParseFramesOutput(result);
}
public static async Task<FFProbeFrames> GetFramesAsync(string filePath, FFOptions? ffOptions = null, CancellationToken cancellationToken = default)
public static async Task<FFProbeFrames> GetFramesAsync(string filePath, FFOptions? ffOptions = null, CancellationToken cancellationToken = default, string? customArguments = null)
{
ThrowIfInputFileDoesNotExist(filePath);
var instance = PrepareFrameAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current);
var instance = PrepareFrameAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current, customArguments);
var result = await instance.StartAndWaitForExitAsync(cancellationToken).ConfigureAwait(false);
return ParseFramesOutput(result);
}
public static async Task<FFProbePackets> GetPacketsAsync(string filePath, FFOptions? ffOptions = null, CancellationToken cancellationToken = default)
public static async Task<FFProbePackets> GetPacketsAsync(string filePath, FFOptions? ffOptions = null, CancellationToken cancellationToken = default, string? customArguments = null)
{
ThrowIfInputFileDoesNotExist(filePath);
var instance = PreparePacketAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current);
var instance = PreparePacketAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current, customArguments);
var result = await instance.StartAndWaitForExitAsync(cancellationToken).ConfigureAwait(false);
return ParsePacketsOutput(result);
}
public static async Task<IMediaAnalysis> AnalyseAsync(Uri uri, FFOptions? ffOptions = null, CancellationToken cancellationToken = default)
public static async Task<IMediaAnalysis> AnalyseAsync(Uri uri, FFOptions? ffOptions = null, CancellationToken cancellationToken = default, string? customArguments = null)
{
var instance = PrepareStreamAnalysisInstance(uri.AbsoluteUri, ffOptions ?? GlobalFFOptions.Current);
var instance = PrepareStreamAnalysisInstance(uri.AbsoluteUri, ffOptions ?? GlobalFFOptions.Current, customArguments);
var result = await instance.StartAndWaitForExitAsync(cancellationToken).ConfigureAwait(false);
ThrowIfExitCodeNotZero(result);
return ParseOutput(result);
}
public static async Task<IMediaAnalysis> AnalyseAsync(Stream stream, FFOptions? ffOptions = null, CancellationToken cancellationToken = default)
public static async Task<IMediaAnalysis> AnalyseAsync(Stream stream, FFOptions? ffOptions = null, CancellationToken cancellationToken = default, string? customArguments = null)
{
var streamPipeSource = new StreamPipeSource(stream);
var pipeArgument = new InputPipeArgument(streamPipeSource);
var instance = PrepareStreamAnalysisInstance(pipeArgument.PipePath, ffOptions ?? GlobalFFOptions.Current);
var instance = PrepareStreamAnalysisInstance(pipeArgument.PipePath, ffOptions ?? GlobalFFOptions.Current, customArguments);
pipeArgument.Pre();
var task = instance.StartAndWaitForExitAsync(cancellationToken);
@ -148,9 +148,9 @@ public static async Task<IMediaAnalysis> AnalyseAsync(Stream stream, FFOptions?
return ParseOutput(result);
}
public static async Task<FFProbeFrames> GetFramesAsync(Uri uri, FFOptions? ffOptions = null, CancellationToken cancellationToken = default)
public static async Task<FFProbeFrames> GetFramesAsync(Uri uri, FFOptions? ffOptions = null, CancellationToken cancellationToken = default, string? customArguments = null)
{
var instance = PrepareFrameAnalysisInstance(uri.AbsoluteUri, ffOptions ?? GlobalFFOptions.Current);
var instance = PrepareFrameAnalysisInstance(uri.AbsoluteUri, ffOptions ?? GlobalFFOptions.Current, customArguments);
var result = await instance.StartAndWaitForExitAsync(cancellationToken).ConfigureAwait(false);
return ParseFramesOutput(result);
}
@ -212,18 +212,18 @@ private static void ThrowIfExitCodeNotZero(IProcessResult result)
}
}
private static ProcessArguments PrepareStreamAnalysisInstance(string filePath, FFOptions ffOptions)
=> PrepareInstance($"-loglevel error -print_format json -show_format -sexagesimal -show_streams \"{filePath}\"", ffOptions);
private static ProcessArguments PrepareFrameAnalysisInstance(string filePath, FFOptions ffOptions)
=> PrepareInstance($"-loglevel error -print_format json -show_frames -v quiet -sexagesimal \"{filePath}\"", ffOptions);
private static ProcessArguments PreparePacketAnalysisInstance(string filePath, FFOptions ffOptions)
=> PrepareInstance($"-loglevel error -print_format json -show_packets -v quiet -sexagesimal \"{filePath}\"", ffOptions);
private static ProcessArguments PrepareStreamAnalysisInstance(string filePath, FFOptions ffOptions, string? customArguments)
=> PrepareInstance($"-loglevel error -print_format json -show_format -sexagesimal -show_streams -show_chapters \"{filePath}\"", ffOptions, customArguments);
private static ProcessArguments PrepareFrameAnalysisInstance(string filePath, FFOptions ffOptions, string? customArguments)
=> PrepareInstance($"-loglevel error -print_format json -show_frames -v quiet -sexagesimal \"{filePath}\"", ffOptions, customArguments);
private static ProcessArguments PreparePacketAnalysisInstance(string filePath, FFOptions ffOptions, string? customArguments)
=> PrepareInstance($"-loglevel error -print_format json -show_packets -v quiet -sexagesimal \"{filePath}\"", ffOptions, customArguments);
private static ProcessArguments PrepareInstance(string arguments, FFOptions ffOptions)
private static ProcessArguments PrepareInstance(string arguments, FFOptions ffOptions, string? customArguments)
{
FFProbeHelper.RootExceptionCheck();
FFProbeHelper.VerifyFFProbeExists(ffOptions);
var startInfo = new ProcessStartInfo(GlobalFFOptions.GetFFProbeBinaryPath(ffOptions), arguments)
var startInfo = new ProcessStartInfo(GlobalFFOptions.GetFFProbeBinaryPath(ffOptions), $"{arguments} {customArguments}")
{
StandardOutputEncoding = ffOptions.Encoding,
StandardErrorEncoding = ffOptions.Encoding,

View file

@ -11,6 +11,9 @@ public class FFProbeAnalysis
[JsonPropertyName("format")]
public Format Format { get; set; } = null!;
[JsonPropertyName("chapters")]
public List<Chapter> Chapters { get; set; } = null!;
[JsonIgnore]
public IReadOnlyList<string> ErrorData { get; set; } = new List<string>();
}
@ -129,6 +132,30 @@ public class Format : ITagsContainer
public Dictionary<string, string>? Tags { get; set; }
}
public class Chapter : ITagsContainer
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("time_base")]
public string TimeBase { get; set; } = null!;
[JsonPropertyName("start")]
public int Start { get; set; }
[JsonPropertyName("start_time")]
public string StartTime { get; set; } = null!;
[JsonPropertyName("end")]
public int End { get; set; }
[JsonPropertyName("end_time")]
public string EndTime { get; set; } = null!;
[JsonPropertyName("tags")]
public Dictionary<string, string>? Tags { get; set; }
}
public interface IDispositionContainer
{
Dictionary<string, int> Disposition { get; set; }

View file

@ -1,9 +1,12 @@
namespace FFMpegCore
using FFMpegCore.Builders.MetaData;
namespace FFMpegCore
{
public interface IMediaAnalysis
{
TimeSpan Duration { get; }
MediaFormat Format { get; }
List<ChapterData> Chapters { get; }
AudioStream? PrimaryAudioStream { get; }
VideoStream? PrimaryVideoStream { get; }
SubtitleStream? PrimarySubtitleStream { get; }

View file

@ -1,4 +1,5 @@
using System.Text.RegularExpressions;
using FFMpegCore.Builders.MetaData;
namespace FFMpegCore
{
@ -7,6 +8,7 @@ internal class MediaAnalysis : IMediaAnalysis
internal MediaAnalysis(FFProbeAnalysis analysis)
{
Format = ParseFormat(analysis.Format);
Chapters = analysis.Chapters.Select(c => ParseChapter(c)).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();
@ -28,6 +30,15 @@ private MediaFormat ParseFormat(Format analysisFormat)
};
}
private ChapterData ParseChapter(Chapter analysisChapter)
{
var title = analysisChapter.Tags.FirstOrDefault(t => t.Key == "title").Value;
var start = MediaAnalysisUtils.ParseDuration(analysisChapter.StartTime);
var end = MediaAnalysisUtils.ParseDuration(analysisChapter.EndTime);
return new ChapterData(title, start, end);
}
public TimeSpan Duration => new[]
{
Format.Duration,
@ -37,6 +48,8 @@ private MediaFormat ParseFormat(Format analysisFormat)
public MediaFormat Format { get; }
public List<ChapterData> Chapters { get; }
public AudioStream? PrimaryAudioStream => AudioStreams.OrderBy(stream => stream.Index).FirstOrDefault();
public VideoStream? PrimaryVideoStream => VideoStreams.OrderBy(stream => stream.Index).FirstOrDefault();
public SubtitleStream? PrimarySubtitleStream => SubtitleStreams.OrderBy(stream => stream.Index).FirstOrDefault();

View file

@ -30,12 +30,23 @@ private static string GetFFBinaryPath(string name, FFOptions ffOptions)
}
var target = Environment.Is64BitProcess ? "x64" : "x86";
if (Directory.Exists(Path.Combine(ffOptions.BinaryFolder, target)))
var possiblePaths = new List<string>()
{
ffName = Path.Combine(target, ffName);
Path.Combine(ffOptions.BinaryFolder, target),
ffOptions.BinaryFolder
};
foreach (var possiblePath in possiblePaths)
{
var possibleFFMpegPath = Path.Combine(possiblePath, ffName);
if (File.Exists(possibleFFMpegPath))
{
return possibleFFMpegPath;
}
}
return Path.Combine(ffOptions.BinaryFolder, ffName);
//Fall back to the assumption this tool exists in the PATH
return ffName;
}
private static FFOptions LoadFFOptions()