Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Hardware video encoding for H.264 and HEVC

KnifeLemon2a5ac9892c98
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index b6c6ca01..fb18909c 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -807,6 +807,29 @@ Same-format edges exist too, so "MP4 720p" works on MP4 files and "MP3 128k" on
for the rest. The encoders are looked up with `ffmpeg -encoders` once per FFmpeg, so a copy the user picked without
x265 or AV1 fails with a clear message instead of an FFmpeg error. x265 and SVT-AV1 log only errors
(`-x265-params log-level=error`, `SVT_LOG=1`).
+- **Hardware encoding** (*Hardware acceleration* in the video card, `MediaOptions.HardwareEncoding`; off by default and
+ for older presets, so nobody's results change without asking). H.264 and HEVC encodes (not VP9, AV1 and the
+ MPEG-style codecs, not stream copies, not pictures → video) go to the graphics chip (`Media/HardwareVideo.cs`,
+ `Media/HardwareProbe.cs`):
+
+ | System | Tried in this order |
+ |---|---|
+ | Windows | `*_nvenc` (NVIDIA), `*_qsv` (Intel Quick Sync), `*_amf` (AMD) |
+ | macOS | `*_videotoolbox` with constant quality (Apple Silicon), then with a bitrate (Intel Macs reject `-q:v`) |
+ | Linux | `*_nvenc`, then `*_vaapi` on `/dev/dri/renderD128` (`-vaapi_device`, frames uploaded with `format=nv12,hwupload`) |
+
+ FFmpeg lists encoders the computer can't run (NVENC without an NVIDIA card), so only the ones `ffmpeg -encoders`
+ lists are tried, each first with a test encode with the real options (0.1 s of `testsrc` at 256 × 144 to the null
+ muxer, 15 s limit). The first that succeeds is used; results are kept per FFmpeg executable, encoder, rate control
+ and bit depth until Filee restarts, and written to the log. Quality: *High/Balanced/Small* become quantizer 19/24/29
+ for H.264 and 23/27/31 for HEVC (one above x264's and x265's CRF: hardware encoders spend bits less wisely) as NVENC
+ `-rc vbr -cq N -b:v 0 -preset p5`, Quick Sync `-global_quality N -preset medium` (ICQ), AMF `-rc cqp -qp_p N -qp_i N−2`
+ (`-quality balanced`) and VA-API `-rc_mode CQP -qp N`; VideoToolbox gets `-q:v` 70/60/50, or on Intel Macs
+ `-b:v` from 0.14/0.09/0.05 bits per pixel per frame (× 0.65 for HEVC). 8-bit video is NV12 (H.264 High, HEVC Main);
+ 10-bit and HDR sources stay P010 HEVC Main 10 with their colour tags when the encoder passes a 10-bit test encode,
+ otherwise x265 encodes them. HEVC keeps the `hvc1` tag in MP4/M4V/MOV. When a hardware encode fails anyway (a
+ picture too large for the chip, a driver error), the partial output is deleted and the file is encoded again with
+ x264/x265; that is logged, not shown as a failure.
- DSD (DSF, DFF) decodes at 2.8 MHz or more: lossless and PCM targets get 88.2 kHz, Vorbis and WMA 44.1 kHz, the
other lossy encoders their nearest supported rate.
- Subtitle extraction takes the first text subtitle track (SubRip, ASS/SSA, WebVTT, MP4 timed text, CEA-608, …).
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index df514816..2db9973c 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -410,6 +410,8 @@
"presets.video_codec.vp9": "VP9",
"presets.video_codec.hevc": "HEVC / H.265 (smaller)",
"presets.video_codec.av1": "AV1 (smallest, slow)",
+ "presets.hardware_encoding": "Use hardware acceleration (graphics chip)",
+ "presets.hardware_encoding_hint": "Encodes H.264 and HEVC on the graphics chip.\nMuch faster and uses less power.\nSlightly lower quality at the same file size.\nWithout a usable chip, the video is encoded as usual.",
"presets.audio_codec": "Audio codec",
"presets.audio_codec.aac": "AAC",
"presets.audio_codec.alac": "ALAC (lossless)",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index 911d0f3b..db923f14 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -410,6 +410,8 @@
"presets.video_codec.vp9": "VP9",
"presets.video_codec.hevc": "HEVC / H.265 (더 작게)",
"presets.video_codec.av1": "AV1 (가장 작게, 느림)",
+ "presets.hardware_encoding": "하드웨어 가속 사용 (그래픽 칩)",
+ "presets.hardware_encoding_hint": "H.264와 HEVC를 그래픽 칩으로 인코딩해요.\n훨씬 빠르고 전력도 덜 써요.\n같은 용량이면 화질이 조금 낮아요.\n쓸 수 있는 칩이 없으면 평소처럼 인코딩해요.",
"presets.audio_codec": "오디오 코덱",
"presets.audio_codec.aac": "AAC",
"presets.audio_codec.alac": "ALAC (무손실)",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index d6f4f5b8..793f8733 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -410,6 +410,8 @@
"presets.video_codec.vp9": "VP9",
"presets.video_codec.hevc": "HEVC / H.265(更小)",
"presets.video_codec.av1": "AV1(最小,较慢)",
+ "presets.hardware_encoding": "使用硬件加速(显卡)",
+ "presets.hardware_encoding_hint": "用显卡编码 H.264 和 HEVC。\n速度快得多,也更省电。\n相同文件大小时画质略低。\n没有可用的显卡时照常编码。",
"presets.audio_codec": "音频编码",
"presets.audio_codec.aac": "AAC",
"presets.audio_codec.alac": "ALAC(无损)",
diff --git a/src/Filee.App/Services/AppHost.cs b/src/Filee.App/Services/AppHost.cs
index 5b03168f..beea6ad1 100644
--- a/src/Filee.App/Services/AppHost.cs
+++ b/src/Filee.App/Services/AppHost.cs
@@ -47,7 +47,7 @@ public static class AppHost
// Conversion engines
services.AddSingleton(_ => new EngineEnvironment(dataDir));
- services.AddSingleton(sp => EngineRegistry.CreateAll(sp.GetRequiredService<EngineEnvironment>()));
+ services.AddSingleton(sp => EngineRegistry.CreateAll(sp.GetRequiredService<EngineEnvironment>(), sp.GetRequiredService<ILoggerFactory>()));
services.AddSingleton(sp => new ConverterCatalog(sp.GetRequiredService<IReadOnlyList<IConverter>>()));
services.AddSingleton(sp => new JobQueue(
sp.GetRequiredService<ConverterCatalog>(),
diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
index 45382072..ceeaa1ac 100644
--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
@@ -94,6 +94,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
_wavFormat = WavFormats.First(f => f.Value == _edit.Media.WavFormat);
_videoCodecValue = _edit.Media.VideoCodec;
_audioCodecValue = _edit.Media.AudioCodec;
+ _hardwareEncoding = _edit.Media.HardwareEncoding;
_archiveLevel = ArchiveLevels.First(l => l.Value == _edit.Archive.Level);
_combineIntoOne = _edit.Archive.CombineIntoOne;
_traceMode = TraceModes.First(m => m.Value == _edit.Trace.Mode);
@@ -158,7 +159,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
[NotifyPropertyChangedFor(nameof(ShowImage), nameof(ShowTurnForPdf), nameof(ShowQuality), nameof(ShowTiff), nameof(ShowMultiPageTiff), nameof(ShowWebp), nameof(ShowIco),
nameof(ShowPdf), nameof(ShowPdfBuild), nameof(ShowDocument), nameof(ShowPdfSplit), nameof(ShowPdfCombine),
nameof(ShowMedia), nameof(ShowMediaQuality), nameof(ShowMaxHeight), nameof(ShowAudioBitrate), nameof(ShowRemoveAudio),
- nameof(ShowAudioChannels), nameof(ShowWav), nameof(VideoCodecs), nameof(VideoCodecChoice), nameof(ShowVideoCodec),
+ nameof(ShowAudioChannels), nameof(ShowWav), nameof(VideoCodecs), nameof(VideoCodecChoice), nameof(ShowVideoCodec), nameof(ShowHardwareEncoding),
nameof(AudioCodecs), nameof(AudioCodecChoice), nameof(ShowAudioCodec),
nameof(ShowArchive), nameof(ShowArchiveOptions), nameof(ShowExtractNote), nameof(ShowTrace))]
private Choice<string> _target;
@@ -186,6 +187,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
return;
_videoCodecValue = value.Value;
OnPropertyChanged();
+ OnPropertyChanged(nameof(ShowHardwareEncoding));
}
}
@@ -281,6 +283,9 @@ public sealed partial class PresetEditorViewModel : ObservableObject
[ObservableProperty] private Choice<int> _sampleRate;
[ObservableProperty] private Choice<WavSampleFormat> _wavFormat;
[ObservableProperty] private bool _removeAudio;
+
+ /// <summary>Encode H.264 / HEVC on the graphics chip when one works (MediaOptions.HardwareEncoding).</summary>
+ [ObservableProperty] private bool _hardwareEncoding;
[ObservableProperty] private Choice<ArchiveLevel> _archiveLevel;
[ObservableProperty] private bool _combineIntoOne;
@@ -325,6 +330,8 @@ public sealed partial class PresetEditorViewModel : ObservableObject
public bool ShowWav => TargetId is "wav" or "w64";
/// <summary>MP4, MKV, MOV and WebM can be written with HEVC or AV1 besides their usual codec.</summary>
public bool ShowVideoCodec => TargetIsVideo && VideoCodecs.Count > 1;
+ /// <summary>Hardware encoding applies to H.264 and HEVC only (not VP9, AV1, MPEG-2, …).</summary>
+ public bool ShowHardwareEncoding => TargetIsVideo && MediaCodecs.TakesHardwareEncoding(TargetId, _videoCodecValue);
/// <summary>M4A / M4B can hold Apple Lossless besides AAC.</summary>
public bool ShowAudioCodec => AudioCodecs.Count > 1;
public bool ShowMediaQuality => TargetIsLossyMedia;
@@ -413,6 +420,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
media.WavFormat = WavFormat.Value;
media.VideoCodec = MediaCodecs.Effective(TargetId, _videoCodecValue);
media.AudioCodec = MediaCodecs.Effective(TargetId, _audioCodecValue);
+ media.HardwareEncoding = HardwareEncoding;
_original.Archive.Level = ArchiveLevel.Value;
_original.Archive.CombineIntoOne = CombineIntoOne;
_original.Trace.Mode = TraceMode.Value;
diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axaml
index 01686024..27d53348 100644
--- a/src/Filee.App/Views/PresetEditorView.axaml
+++ b/src/Filee.App/Views/PresetEditorView.axaml
@@ -163,6 +163,10 @@
<ComboBox ItemsSource="{Binding WavFormats}" SelectedItem="{Binding WavFormat}" HorizontalAlignment="Stretch" />
</StackPanel>
</UniformGrid>
+ <StackPanel Spacing="2" IsVisible="{Binding ShowHardwareEncoding}">
+ <CheckBox Content="{DynamicResource presets.hardware_encoding}" IsChecked="{Binding HardwareEncoding}" />
+ <TextBlock Classes="caption" TextWrapping="Wrap" Margin="28,0,0,0" Text="{DynamicResource presets.hardware_encoding_hint}" />
+ </StackPanel>
</StackPanel>
</Border>
diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.cs
index 72550948..adc9a2f2 100644
--- a/src/Filee.Core/Presets/Preset.cs
+++ b/src/Filee.Core/Presets/Preset.cs
@@ -367,6 +367,14 @@ public sealed class MediaOptions
/// <summary>Audio codec for targets that can hold several (<see cref="MediaCodecs.AudioCodecsFor"/>).</summary>
public AudioCodec AudioCodec { get; set; } = AudioCodec.Default;
+ /// <summary>
+ /// Encode H.264 and HEVC video with the graphics chip's encoder (NVENC, Quick Sync, AMF, VideoToolbox or VA-API)
+ /// when one works on this computer, else with x264 / x265 as usual. Much faster and lighter on power, a little
+ /// larger at the same quality. Off by default (and for presets saved before it existed), so results never change
+ /// without the user asking for it.
+ /// </summary>
+ public bool HardwareEncoding { get; set; }
+
public MediaOptions Clone() => (MediaOptions)MemberwiseClone();
}
@@ -413,6 +421,20 @@ public static class MediaCodecs
public static VideoCodec Effective(string target, VideoCodec codec) =>
VideoCodecsFor(target).Contains(codec) ? codec : VideoCodec.Default;
+ /// <summary>Video targets whose usual codec is H.264 (the others have their container's own: VP9, MPEG-2, …).</summary>
+ public static IReadOnlySet<string> H264Targets { get; } = new HashSet<string> { "mp4", "m4v", "mov", "mkv", "flv", "ts", "m2ts", "3gp", "3g2" };
+
+ /// <summary>
+ /// True when <paramref name="target"/> with <paramref name="codec"/> is written as H.264 or HEVC, the codecs
+ /// <see cref="MediaOptions.HardwareEncoding"/> applies to.
+ /// </summary>
+ public static bool TakesHardwareEncoding(string target, VideoCodec codec) => Effective(target, codec) switch
+ {
+ VideoCodec.Hevc => true,
+ VideoCodec.Default => H264Targets.Contains(target),
+ _ => false,
+ };
+
/// <summary>The codec <paramref name="target"/> is written with: the chosen one if the target takes it, else Default.</summary>
public static AudioCodec Effective(string target, AudioCodec codec) =>
AudioCodecsFor(target).Contains(codec) ? codec : AudioCodec.Default;
diff --git a/src/Filee.Engines/EngineRegistry.cs b/src/Filee.Engines/EngineRegistry.cs
index 0a2e3a42..612351ed 100644
--- a/src/Filee.Engines/EngineRegistry.cs
+++ b/src/Filee.Engines/EngineRegistry.cs
@@ -19,6 +19,7 @@ using Filee.Engines.Pdf;
using Filee.Engines.Subtitles;
using Filee.Engines.Text;
using Filee.Engines.Vector;
+using Microsoft.Extensions.Logging;
namespace Filee.Engines;
@@ -30,7 +31,8 @@ public static class EngineRegistry
/// AppSettings.EnginePriority: built-in engines first, the optional downloads last. Software installed on the
/// system (Microsoft Office, a system-wide LibreOffice) is never used.
/// </summary>
- public static IReadOnlyList<IConverter> CreateAll(EngineEnvironment env) =>
+ /// <param name="loggers">The app's log; FFmpeg writes which hardware encoders work and when one failed.</param>
+ public static IReadOnlyList<IConverter> CreateAll(EngineEnvironment env, ILoggerFactory? loggers = null) =>
[
new MagickImageConverter(),
new PdfSharpConverter(),
@@ -50,7 +52,7 @@ public static class EngineRegistry
new EmlConverter(),
new DataConverter(),
new SubtitleConverter(),
- new FfmpegConverter(),
+ new FfmpegConverter(loggers?.CreateLogger<FfmpegConverter>()),
new CadConverter(),
new ModelConverter(),
new EbookConverter(),
diff --git a/src/Filee.Engines/Media/FfmpegConverter.cs b/src/Filee.Engines/Media/FfmpegConverter.cs
index 5bc2877a..787de120 100644
--- a/src/Filee.Engines/Media/FfmpegConverter.cs
+++ b/src/Filee.Engines/Media/FfmpegConverter.cs
@@ -2,26 +2,40 @@
// engines/ffmpeg): video ↔ video (H.264, HEVC, AV1, …), video → animated GIF / APNG or a still frame, audio
// extraction, subtitle extraction (the first text track as SRT / ASS / WebVTT), audio ↔ audio and GIF, APNG or a still
// picture → video, and images → HEIC (FFmpeg's HEVC encoder, Filee's own container writer).
-// Container and codec choices live in MediaEncoding, the process handling in FfmpegRunner.
+// Container and codec choices live in MediaEncoding, the process handling in FfmpegRunner, hardware encoders in
+// HardwareVideo (options) and HardwareProbe (which one works here).
using System.Collections.Concurrent;
-using System.Diagnostics;
using System.Text.RegularExpressions;
using Filee.Core.Conversion;
using Filee.Core.Formats;
using Filee.Engines.Heic;
using Filee.Engines.Infrastructure;
using Filee.Engines.Magick;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Logging.Abstractions;
namespace Filee.Engines.Media;
/// <summary>Converts video and audio files with Filee's own copy of FFmpeg.</summary>
-public sealed partial class FfmpegConverter : IConverter, IImageTransformer
+/// <param name="logger">Receives which hardware encoders work and why a hardware encode was redone in software.</param>
+public sealed partial class FfmpegConverter(ILogger? logger = null) : IConverter, IImageTransformer
{
private static readonly ConcurrentDictionary<string, string> Versions = new();
+ /// <summary><c>ffmpeg -version</c> and <c>-encoders</c> answer at once; a copy that does not is broken or hangs.</summary>
+ internal static readonly TimeSpan QueryTimeout = TimeSpan.FromSeconds(10);
+
+ private readonly ILogger _logger = logger ?? NullLogger.Instance;
+
private (string Ffmpeg, string Ffprobe)? _tools;
+ /// <summary>
+ /// Picks the hardware encoder for (ffmpeg, codec, 10-bit, encoders) instead of <see cref="HardwareProbe.SelectAsync"/>.
+ /// Tests put an encoder here that FFmpeg does not have, to see the software retry.
+ /// </summary>
+ internal Func<string, string, bool, IReadOnlySet<string>?, CancellationToken, Task<HardwareEncoder?>>? SelectHardware { get; init; }
+
public string Id => "ffmpeg";
public string DisplayName => "FFmpeg";
@@ -107,21 +121,28 @@ public sealed partial class FfmpegConverter : IConverter, IImageTransformer
? await CoverArt.PrepareAsync(ffmpeg, input, coverStream, step.To, step.WorkDirectory, cancellationToken)
: null;
+ var media = step.Preset.Media;
+ var encoders = still ? null : EncodersOf(ffmpeg);
+ // Hardware encoding (preset option): the first GPU encoder that passes its test encode, if any.
+ HardwareEncoder? hardware = null;
+ if (!still && MediaEncoding.HardwareCodec(step.To, media, info) is { } codec)
+ {
+ var tenBit = HardwareVideo.TenBit(codec, info.Video!);
+ hardware = SelectHardware is { } select
+ ? await select(ffmpeg, codec, tenBit, encoders, cancellationToken)
+ : await HardwareProbe.SelectAsync(ffmpeg, codec, tenBit, encoders, _logger, cancellationToken);
+ }
+
+ IReadOnlyList<FfmpegPass> Plan(HardwareEncoder? encoder) => still
+ ? MediaEncoding.PlanStill(input, output, step.To, media, info)
+ : MediaEncoding.Plan(input, output, step.To, media, info, step.WorkDirectory, cover, encoders, encoder);
// Throws for a missing stream before anything is written (an existing file of that name stays untouched).
- var passes = still
- ? MediaEncoding.PlanStill(input, output, step.To, step.Preset.Media, info)
- : MediaEncoding.Plan(input, output, step.To, step.Preset.Media, info, step.WorkDirectory, cover, EncodersOf(ffmpeg));
+ var passes = Plan(hardware);
var duration = still ? MediaEncoding.StillDuration : info.Duration;
try
{
- var done = 0.0;
- foreach (var pass in passes)
- {
- await RunPassAsync(ffmpeg, pass, duration, progress, done, cancellationToken);
- done += pass.Weight;
- }
- if (!File.Exists(output) || new FileInfo(output).Length == 0)
- throw new InvalidOperationException("FFmpeg did not write any output.");
+ await RunWithFallbackAsync(passes, hardware, Plan,
+ planned => RunPassesAsync(ffmpeg, planned, output, duration, progress, cancellationToken), output, _logger, cancellationToken);
}
catch
{
@@ -134,6 +155,49 @@ public sealed partial class FfmpegConverter : IConverter, IImageTransformer
return [output];
}
+ /// <summary>
+ /// Runs <paramref name="passes"/>, planned with <paramref name="hardware"/>. When a hardware encode fails (a driver
+ /// error, a picture larger than the chip encodes, …) the file is encoded again as <paramref name="plan"/> plans it
+ /// without hardware: an encoder that passed its test encode can still refuse one particular video, and the user
+ /// asked for a converted file, not for the GPU. The failure is logged, not reported. Cancellation is never retried.
+ /// </summary>
+ internal static async Task RunWithFallbackAsync(IReadOnlyList<FfmpegPass> passes, HardwareEncoder? hardware,
+ Func<HardwareEncoder?, IReadOnlyList<FfmpegPass>> plan, Func<IReadOnlyList<FfmpegPass>, Task> run, string output, ILogger logger,
+ CancellationToken cancellationToken)
+ {
+ if (hardware is null)
+ {
+ await run(passes);
+ return;
+ }
+ try
+ {
+ await run(passes);
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException && !cancellationToken.IsCancellationRequested)
+ {
+ logger.LogWarning("{File}: hardware encoder {Encoder} failed ({Reason}); encoding it again with the software encoder",
+ output, hardware.Name, ex.Message);
+ TryDelete(output);
+ // An FFmpeg without x265 says so here: the hardware encoder was the only way to write HEVC.
+ await run(plan(null));
+ }
+ }
+
+ /// <summary>Runs every pass, then checks that FFmpeg wrote something.</summary>
+ private static async Task RunPassesAsync(string ffmpeg, IReadOnlyList<FfmpegPass> passes, string output, TimeSpan? duration,
+ IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ var done = 0.0;
+ foreach (var pass in passes)
+ {
+ await RunPassAsync(ffmpeg, pass, duration, progress, done, cancellationToken);
+ done += pass.Weight;
+ }
+ if (!File.Exists(output) || new FileInfo(output).Length == 0)
+ throw new InvalidOperationException("FFmpeg did not write any output.");
+ }
+
/// <summary>Runs one pass and maps FFmpeg's position (seconds) onto this pass' share of the progress.</summary>
private static async Task RunPassAsync(string ffmpeg, FfmpegPass pass, TimeSpan? duration, IProgress<double>? progress, double done, CancellationToken cancellationToken)
{
@@ -165,26 +229,23 @@ public sealed partial class FfmpegConverter : IConverter, IImageTransformer
}
/// <summary>"9.0.2" from <c>ffmpeg -version</c>; cached per executable so re-checking the engines stays cheap.</summary>
- private static string VersionOf(string ffmpeg) =>
+ /// <exception cref="InvalidOperationException">FFmpeg does not start, fails or does not answer within <paramref name="timeout"/>.</exception>
+ internal static string VersionOf(string ffmpeg, TimeSpan? timeout = null) =>
Versions.GetOrAdd($"{ffmpeg}|{File.GetLastWriteTimeUtc(ffmpeg).Ticks}", _ =>
{
- using var process = Process.Start(new ProcessStartInfo(ffmpeg, "-hide_banner -version")
+ ProcessResult result;
+ try
{
- UseShellExecute = false,
- CreateNoWindow = true,
- RedirectStandardOutput = true,
- RedirectStandardError = true,
- }) ?? throw new InvalidOperationException("FFmpeg could not be started.");
- var firstLine = process.StandardOutput.ReadLine() ?? "";
- process.StandardOutput.ReadToEnd();
- if (!process.WaitForExit(10_000))
+ result = FfmpegRunner.RunBriefly(ffmpeg, ["-hide_banner", "-version"], timeout ?? QueryTimeout);
+ }
+ catch (TimeoutException)
{
- process.Kill(entireProcessTree: true);
throw new InvalidOperationException("FFmpeg did not start in time.");
}
- if (process.ExitCode != 0)
- throw new InvalidOperationException($"FFmpeg does not start (exit code {process.ExitCode}).");
+ if (result.ExitCode != 0)
+ throw new InvalidOperationException($"FFmpeg does not start (exit code {result.ExitCode}).");
// "ffmpeg version 9.0.2-full_build-www.gyan.dev Copyright …" → "9.0.2"
+ var firstLine = result.StandardOutput.Split('\n', 2)[0];
var match = VersionPattern().Match(firstLine);
return match.Success ? match.Groups[1].Value : firstLine.Trim();
});
@@ -198,38 +259,29 @@ public sealed partial class FfmpegConverter : IConverter, IImageTransformer
/// The encoders of <paramref name="ffmpeg"/> (<c>ffmpeg -encoders</c>), cached per executable: a copy the user
/// picked may lack x265 or SVT-AV1. Null (assume Filee's build) when the list can't be read.
/// </summary>
- private static IReadOnlySet<string>? EncodersOf(string ffmpeg) =>
+ internal static IReadOnlySet<string>? EncodersOf(string ffmpeg, TimeSpan? timeout = null) =>
Encoders.GetOrAdd($"{ffmpeg}|{File.GetLastWriteTimeUtc(ffmpeg).Ticks}", _ =>
{
try
{
- using var process = Process.Start(new ProcessStartInfo(ffmpeg, "-hide_banner -encoders")
- {
- UseShellExecute = false,
- CreateNoWindow = true,
- RedirectStandardOutput = true,
- RedirectStandardError = true,
- });
- if (process is null)
- return null;
- process.ErrorDataReceived += (_, _) => { };
- process.BeginErrorReadLine();
- var list = process.StandardOutput.ReadToEnd();
- if (!process.WaitForExit(10_000) || process.ExitCode != 0)
- return null;
- // " V....D libx265 libx265 H.265 / HEVC (codec hevc)"
- return list.Split('\n')
- .Select(line => line.Split(' ', StringSplitOptions.RemoveEmptyEntries))
- .Where(parts => parts.Length >= 2 && parts[0].Length == 6 && parts[0][0] is 'V' or 'A' or 'S')
- .Select(parts => parts[1])
- .ToHashSet(StringComparer.Ordinal);
+ var result = FfmpegRunner.RunBriefly(ffmpeg, ["-hide_banner", "-encoders"], timeout ?? QueryTimeout);
+ return result.ExitCode == 0 ? ParseEncoders(result.StandardOutput) : null;
}
- catch (Exception ex) when (ex is InvalidOperationException or System.ComponentModel.Win32Exception or IOException)
+ catch (Exception ex) when (ex is TimeoutException or InvalidOperationException or System.ComponentModel.Win32Exception or IOException)
{
return null;
}
});
+ /// <summary>The encoder names in <c>ffmpeg -encoders</c> output.</summary>
+ internal static IReadOnlySet<string> ParseEncoders(string list) =>
+ // " V....D libx265 libx265 H.265 / HEVC (codec hevc)"
+ list.Split('\n')
+ .Select(line => line.Split(' ', StringSplitOptions.RemoveEmptyEntries))
+ .Where(parts => parts.Length >= 2 && parts[0].Length == 6 && parts[0][0] is 'V' or 'A' or 'S')
+ .Select(parts => parts[1])
+ .ToHashSet(StringComparer.Ordinal);
+
private static void TryDelete(string path)
{
try
diff --git a/src/Filee.Engines/Media/FfmpegRunner.cs b/src/Filee.Engines/Media/FfmpegRunner.cs
index b4cb60b4..5c3426c3 100644
--- a/src/Filee.Engines/Media/FfmpegRunner.cs
+++ b/src/Filee.Engines/Media/FfmpegRunner.cs
@@ -108,6 +108,48 @@ internal static class FfmpegRunner
return new ProcessResult(process.ExitCode, "", stderr);
}
+ /// <summary>
+ /// Runs a short query (<c>ffmpeg -version</c>, <c>-encoders</c>) synchronously. Both streams are read in the
+ /// background, so the time limit holds even when the program hangs with its output open (reading it to the end
+ /// first would wait for the hang).
+ /// </summary>
+ /// <exception cref="TimeoutException">The program did not exit within <paramref name="timeout"/>; it was killed.</exception>
+ /// <exception cref="InvalidOperationException">The program could not be started.</exception>
+ internal static ProcessResult RunBriefly(string executable, IReadOnlyList<string> arguments, TimeSpan timeout)
+ {
+ var psi = new ProcessStartInfo(executable)
+ {
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ StandardOutputEncoding = Encoding.UTF8,
+ StandardErrorEncoding = Encoding.UTF8,
+ };
+ foreach (var argument in arguments)
+ psi.ArgumentList.Add(argument);
+
+ using var process = new Process { StartInfo = psi };
+ var stdout = new StringBuilder();
+ var stderr = new StringBuilder();
+ process.OutputDataReceived += (_, e) => { if (e.Data is not null) lock (stdout) stdout.Append(e.Data).Append('\n'); };
+ process.ErrorDataReceived += (_, e) => { if (e.Data is not null) lock (stderr) stderr.Append(e.Data).Append('\n'); };
+ if (!process.Start())
+ throw new InvalidOperationException($"Could not start {executable}.");
+ process.BeginOutputReadLine();
+ process.BeginErrorReadLine();
+ if (!process.WaitForExit(timeout))
+ {
+ Kill(process);
+ throw new TimeoutException($"{Path.GetFileName(executable)} did not finish within {timeout.TotalSeconds:0} s.");
+ }
+ // Make sure the asynchronous readers have delivered the last lines.
+ process.WaitForExit();
+ lock (stdout)
+ lock (stderr)
+ return new ProcessResult(process.ExitCode, stdout.ToString(), stderr.ToString());
+ }
+
/// <summary>
/// The position in seconds from one line of <c>-progress</c> output (<c>out_time_us=2000000</c>) or of the
/// palette pass' frame stats (<c>frame_time=2.5</c>); null for every other line.
diff --git a/src/Filee.Engines/Media/HardwareProbe.cs b/src/Filee.Engines/Media/HardwareProbe.cs
new file mode 100644
index 00000000..eaaff759
--- /dev/null
+++ b/src/Filee.Engines/Media/HardwareProbe.cs
@@ -0,0 +1,68 @@
+// Finds out which hardware video encoder works on this computer. FFmpeg lists every encoder it was built with, also
+// NVENC without an NVIDIA card or Quick Sync without an Intel GPU, so each candidate gets a tiny test encode first. The
+// result is kept per FFmpeg executable, encoder and bit depth for as long as Filee runs.
+
+using System.Collections.Concurrent;
+using Filee.Engines.Infrastructure;
+using Microsoft.Extensions.Logging;
+
+namespace Filee.Engines.Media;
+
+/// <summary>Picks the first hardware encoder whose test encode succeeds.</summary>
+internal static class HardwareProbe
+{
+ /// <summary>
+ /// A test encode takes 0.1–2 s (Quick Sync loads its runtime on the first one); a driver that hangs is given up on
+ /// after this long and the software encoder is used.
+ /// </summary>
+ public static readonly TimeSpan Timeout = TimeSpan.FromSeconds(15);
+
+ private static readonly ConcurrentDictionary<string, Lazy<Task<bool>>> Results = new();
+
+ /// <summary>
+ /// The hardware encoder to write <paramref name="codec"/> ("h264" or "hevc") with, or null when none works here
+ /// (then x264 / x265 encode as usual).
+ /// </summary>
+ /// <param name="tenBit">The video is encoded in 10 bits (HEVC Main 10): an encoder must handle that too.</param>
+ /// <param name="encoders">The encoders <paramref name="ffmpeg"/> lists; null when the list could not be read.</param>
+ public static async Task<HardwareEncoder?> SelectAsync(string ffmpeg, string codec, bool tenBit, IReadOnlySet<string>? encoders,
+ ILogger logger, CancellationToken cancellationToken)
+ {
+ var vaapi = HardwareVideo.Current == HostPlatform.Linux && File.Exists(HardwareVideo.VaapiDevice);
+ foreach (var candidate in HardwareVideo.Candidates(codec, HardwareVideo.Current, encoders, vaapi))
+ {
+ // The probe itself is not cancelled with the conversion: other conversions may be waiting for its result.
+ if (await WorksAsync(ffmpeg, candidate, tenBit, logger).WaitAsync(cancellationToken))
+ return candidate;
+ }
+ return null;
+ }
+
+ /// <summary>The cached result of the test encode of <paramref name="encoder"/> (run on first use).</summary>
+ internal static Task<bool> WorksAsync(string ffmpeg, HardwareEncoder encoder, bool tenBit, ILogger logger) =>
+ Results.GetOrAdd($"{ffmpeg}|{File.GetLastWriteTimeUtc(ffmpeg).Ticks}|{encoder.Name}|{encoder.RateControl}|{(tenBit ? 10 : 8)}",
+ _ => new Lazy<Task<bool>>(() => ProbeAsync(ffmpeg, encoder, tenBit, logger))).Value;
+
+ private static async Task<bool> ProbeAsync(string ffmpeg, HardwareEncoder encoder, bool tenBit, ILogger logger)
+ {
+ var bits = tenBit ? 10 : 8;
+ try
+ {
+ var result = await ProcessRunner.RunAsync(ffmpeg, HardwareVideo.ProbeArguments(encoder, tenBit), Timeout, CancellationToken.None);
+ if (result.ExitCode == 0)
+ {
+ logger.LogInformation("Hardware encoder {Encoder} ({RateControl}, {Bits}-bit) works", encoder.Name, encoder.RateControl, bits);
+ return true;
+ }
+ logger.LogInformation("Hardware encoder {Encoder} ({RateControl}, {Bits}-bit) is not usable: {Reason}", encoder.Name,
+ encoder.RateControl, bits, FfmpegRunner.Summarize(result.StandardError));
+ return false;
+ }
+ catch (Exception ex) when (ex is TimeoutException or InvalidOperationException or System.ComponentModel.Win32Exception or IOException)
+ {
+ logger.LogInformation("Hardware encoder {Encoder} ({RateControl}, {Bits}-bit) is not usable: {Reason}", encoder.Name,
+ encoder.RateControl, bits, ex.Message);
+ return false;
+ }
+ }
+}
diff --git a/src/Filee.Engines/Media/HardwareVideo.cs b/src/Filee.Engines/Media/HardwareVideo.cs
new file mode 100644
index 00000000..8253460c
--- /dev/null
+++ b/src/Filee.Engines/Media/HardwareVideo.cs
@@ -0,0 +1,229 @@
+// Hardware video encoders (NVENC, Quick Sync, AMF, VideoToolbox, VA-API) for H.264 and HEVC: which ones to try on
+// which system, and their FFmpeg options. Pure (no processes), so every choice is unit tested without a GPU; whether
+// an encoder actually works on this computer is found out by HardwareProbe.
+
+using System.Globalization;
+using Filee.Core.Presets;
+
+namespace Filee.Engines.Media;
+
+/// <summary>The vendor interface a hardware encoder goes through; it decides the encoder's options.</summary>
+internal enum HardwareApi
+{
+ /// <summary>NVIDIA (<c>h264_nvenc</c>, <c>hevc_nvenc</c>).</summary>
+ Nvenc,
+
+ /// <summary>Intel Quick Sync Video (<c>h264_qsv</c>, <c>hevc_qsv</c>).</summary>
+ Qsv,
+
+ /// <summary>AMD Advanced Media Framework (<c>h264_amf</c>, <c>hevc_amf</c>).</summary>
+ Amf,
+
+ /// <summary>Apple VideoToolbox (<c>h264_videotoolbox</c>, <c>hevc_videotoolbox</c>).</summary>
+ VideoToolbox,
+
+ /// <summary>Linux VA-API (<c>h264_vaapi</c>, <c>hevc_vaapi</c>): frames are uploaded to the GPU first.</summary>
+ Vaapi,
+}
+
+/// <summary>How the preset's quality reaches a hardware encoder.</summary>
+internal enum HardwareRateControl
+{
+ /// <summary>A constant quality or quantizer, like x264's CRF.</summary>
+ Quality,
+
+ /// <summary>
+ /// An average bitrate from the picture size and frame rate: VideoToolbox on Intel Macs has no constant quality mode
+ /// (FFmpeg rejects <c>-q:v</c> there).
+ /// </summary>
+ Bitrate,
+}
+
+/// <summary>The operating systems hardware encoders are chosen for.</summary>
+internal enum HostPlatform
+{
+ Windows,
+ MacOS,
+ Linux,
+ Other,
+}
+
+/// <summary>One hardware encoder of FFmpeg, with the way it is told the quality.</summary>
+/// <param name="Name">FFmpeg encoder name, e.g. <c>hevc_nvenc</c>.</param>
+internal sealed record HardwareEncoder(string Name, HardwareApi Api, HardwareRateControl RateControl = HardwareRateControl.Quality)
+{
+ /// <summary>"h264" or "hevc": the part before the underscore.</summary>
+ public string Codec => Name[..Name.IndexOf('_', StringComparison.Ordinal)];
+}
+
+/// <summary>Hardware encoder candidates and command-line options.</summary>
+internal static class HardwareVideo
+{
+ /// <summary>
+ /// The first DRM render node: the integrated or only GPU on almost every Linux system. A second GPU has
+ /// renderD129, but NVIDIA's (the usual second one) is taken through NVENC, which is tried first.
+ /// </summary>
+ public const string VaapiDevice = "/dev/dri/renderD128";
+
+ /// <summary>The system Filee runs on.</summary>
+ public static HostPlatform Current { get; } =
+ OperatingSystem.IsWindows() ? HostPlatform.Windows
+ : OperatingSystem.IsMacOS() ? HostPlatform.MacOS
+ : OperatingSystem.IsLinux() ? HostPlatform.Linux
+ : HostPlatform.Other;
+
+ /// <summary>
+ /// The hardware encoders for <paramref name="codec"/> ("h264" or "hevc") worth trying, best first. Windows:
+ /// NVIDIA, then Intel, then AMD (a laptop with an Intel chip and an NVIDIA card encodes on the card). macOS:
+ /// VideoToolbox with constant quality (Apple Silicon), then with a bitrate (Intel Macs). Linux: NVIDIA, then
+ /// VA-API when a render node exists. Only encoders the FFmpeg in use lists are tried (all of them when the list
+ /// could not be read); the probe decides which one really works.
+ /// </summary>
+ public static IReadOnlyList<HardwareEncoder> Candidates(string codec, HostPlatform platform, IReadOnlySet<string>? encoders, bool vaapiDevice)
+ {
+ if (codec is not ("h264" or "hevc"))
+ return [];
+ List<HardwareEncoder> candidates = platform switch
+ {
+ HostPlatform.Windows => [new($"{codec}_nvenc", HardwareApi.Nvenc), new($"{codec}_qsv", HardwareApi.Qsv), new($"{codec}_amf", HardwareApi.Amf)],
+ HostPlatform.MacOS =>
+ [
+ new($"{codec}_videotoolbox", HardwareApi.VideoToolbox),
+ new($"{codec}_videotoolbox", HardwareApi.VideoToolbox, HardwareRateControl.Bitrate),
+ ],
+ HostPlatform.Linux => vaapiDevice
+ ? [new($"{codec}_nvenc", HardwareApi.Nvenc), new($"{codec}_vaapi", HardwareApi.Vaapi)]
+ : [new($"{codec}_nvenc", HardwareApi.Nvenc)],
+ _ => [],
+ };
+ return encoders is null ? candidates : [.. candidates.Where(c => encoders.Contains(c.Name))];
+ }
+
+ /// <summary>
+ /// True when the video is encoded in 10 bits: HEVC keeps 10-bit and HDR sources in Main 10 (as x265 does). H.264
+ /// is always 8-bit 4:2:0, the only format every player decodes (as with x264).
+ /// </summary>
+ public static bool TenBit(string codec, VideoStreamInfo video) => codec == "hevc" && (video.IsHighBitDepth || video.IsHdr);
+
+ /// <summary>
+ /// The preset's quality on the encoders' 0–51 quantizer scale (NVENC <c>-cq</c>, Quick Sync <c>-global_quality</c>,
+ /// AMF and VA-API <c>-qp</c>): one above x264's CRF 18/23/28 for H.264 and x265's 22/26/30 for HEVC. Hardware
+ /// encoders lack x264/x265's psychovisual tuning and spend bits less wisely, so the same number gives a larger
+ /// file; one step coarser keeps the size close at a slightly lower quality.
+ /// </summary>
+ public static int Quantizer(string codec, MediaQuality quality) => codec == "hevc"
+ ? Choose(quality, 23, 27, 31)
+ : Choose(quality, 19, 24, 29);
+
+ /// <summary>VideoToolbox's constant quality (<c>-q:v</c>, 1–100, higher is better) on Apple Silicon.</summary>
+ public static int VideoToolboxQuality(MediaQuality quality) => Choose(quality, 70, 60, 50);
+
+ /// <summary>
+ /// The average bitrate (kbit/s) for VideoToolbox on Intel Macs: bits per pixel per frame of the output picture,
+ /// e.g. 1080p at 30 fps gets about 9 / 5.6 / 3.1 Mbit/s as H.264 and two thirds of that as HEVC.
+ /// </summary>
+ public static int BitrateKbps(string codec, MediaQuality quality, VideoStreamInfo video, int maxHeight)
+ {
+ double height = video.DisplayHeight > 0 ? video.DisplayHeight : 1080;
+ if (maxHeight > 0 && height > Math.Max(16, maxHeight))
+ height = Math.Max(16, maxHeight);
+ var width = height * (video.DisplayAspect > 0 && double.IsFinite(video.DisplayAspect) ? video.DisplayAspect : 16 / 9.0);
+ var fps = video.FrameRate is > 0 and <= 240 ? video.FrameRate : 30;
+ var bitsPerPixel = Choose(quality, 0.14, 0.09, 0.05) * (codec == "hevc" ? 0.65 : 1);
+ return (int)Math.Clamp(Math.Round(width * height * fps * bitsPerPixel / 1000), 300, 100_000);
+ }
+
+ /// <summary>Global options before the input: VA-API needs its device.</summary>
+ public static string[] InputArguments(HardwareEncoder encoder) =>
+ encoder.Api == HardwareApi.Vaapi ? ["-vaapi_device", VaapiDevice] : [];
+
+ /// <summary>
+ /// Appended to the video filter chain: VA-API encodes frames in GPU memory, so the scaled frames are converted to
+ /// NV12 / P010 and uploaded. The others take frames from system memory (<c>-pix_fmt</c>).
+ /// </summary>
+ public static string FilterSuffix(HardwareEncoder encoder, bool tenBit) =>
+ encoder.Api == HardwareApi.Vaapi ? $",format={(tenBit ? "p010le" : "nv12")},hwupload" : "";
+
+ /// <summary>
+ /// The encoder options for one video: rate control from the preset's quality, NV12 (8-bit) or P010 with the Main 10
+ /// profile (10-bit HEVC), the source's HDR colour tags, and the <c>hvc1</c> tag Apple players need for HEVC in
+ /// MP4/MOV.
+ /// </summary>
+ public static List<string> CodecArguments(HardwareEncoder encoder, string target, MediaQuality quality, VideoStreamInfo video, int maxHeight)
+ {
+ var codec = encoder.Codec;
+ var tenBit = TenBit(codec, video);
+ var quantizer = Text(Quantizer(codec, quality));
+ List<string> args = ["-c:v", encoder.Name];
+ switch (encoder.Api)
+ {
+ case HardwareApi.Nvenc:
+ // Constant quality inside VBR; -b:v 0 lifts NVENC's default 2 Mbit/s cap. P5 is the "slow, good quality"
+ // preset, still many times faster than x264's medium.
+ args.AddRange(["-preset", "p5", "-rc", "vbr", "-cq", quantizer, "-b:v", "0"]);
+ break;
+ case HardwareApi.Qsv:
+ // global_quality without a bitrate selects ICQ (intelligent constant quality), or CQP where the driver
+ // has no ICQ.
+ args.AddRange(["-preset", "medium", "-global_quality", quantizer]);
+ break;
+ case HardwareApi.Amf:
+ // Constant quantizer; I-frames two steps finer, as AMF's own presets do.
+ args.AddRange(["-quality", "balanced", "-rc", "cqp", "-qp_i", Text(Math.Max(0, Quantizer(codec, quality) - 2)), "-qp_p", quantizer]);
+ if (codec == "h264")
+ args.AddRange(["-qp_b", quantizer]);
+ break;
+ case HardwareApi.VideoToolbox when encoder.RateControl == HardwareRateControl.Bitrate:
+ args.AddRange(["-b:v", Text(BitrateKbps(codec, quality, video, maxHeight)) + "k"]);
+ break;
+ case HardwareApi.VideoToolbox:
+ args.AddRange(["-q:v", Text(VideoToolboxQuality(quality))]);
+ break;
+ case HardwareApi.Vaapi:
+ args.AddRange(["-rc_mode", "CQP", "-qp", quantizer]);
+ break;
+ }
+
+ if (codec == "h264")
+ args.AddRange(["-profile:v", "high"]);
+ else
+ args.AddRange(["-profile:v", tenBit ? "main10" : "main"]);
+ // VA-API's frames are already uploaded in the right format (FilterSuffix).
+ if (encoder.Api != HardwareApi.Vaapi)
+ args.AddRange(["-pix_fmt", tenBit ? "p010le" : "nv12"]);
+ if (tenBit)
+ args.AddRange(MediaEncoding.ColorArguments(video));
+ if (codec == "hevc" && target is "mp4" or "m4v" or "mov")
+ args.AddRange(["-tag:v", "hvc1"]);
+ return args;
+ }
+
+ /// <summary>The source of a probe: a tenth of a second of test pattern, three small frames.</summary>
+ private const string ProbeSource = "testsrc=size=256x144:rate=30:duration=0.1";
+
+ /// <summary>
+ /// A tiny test encode with exactly the options a real one uses (rate control, profile, pixel format), so an
+ /// encoder FFmpeg lists but the computer can't run (no GPU, old driver, no 10-bit support, no constant quality on
+ /// an Intel Mac) fails here instead of on the user's file.
+ /// </summary>
+ public static List<string> ProbeArguments(HardwareEncoder encoder, bool tenBit)
+ {
+ var picture = new VideoStreamInfo(256, 144, 1, 0, 30, PixelFormat: tenBit ? "yuv420p10le" : "yuv420p");
+ return
+ [
+ .. MediaEncoding.Common, .. InputArguments(encoder), "-f", "lavfi", "-i", ProbeSource,
+ "-vf", "null" + FilterSuffix(encoder, tenBit),
+ .. CodecArguments(encoder, "mkv", MediaQuality.Balanced, picture, 0),
+ "-f", "null", "-",
+ ];
+ }
+
+ private static T Choose<T>(MediaQuality quality, T high, T balanced, T small) => quality switch
+ {
+ MediaQuality.High => high,
+ MediaQuality.Small => small,
+ _ => balanced,
+ };
+
+ private static string Text(int value) => value.ToString(CultureInfo.InvariantCulture);
+}
diff --git a/src/Filee.Engines/Media/MediaEncoding.cs b/src/Filee.Engines/Media/MediaEncoding.cs
index ff791f17..44ac80de 100644
--- a/src/Filee.Engines/Media/MediaEncoding.cs
+++ b/src/Filee.Engines/Media/MediaEncoding.cs
@@ -141,9 +141,13 @@ internal static class MediaEncoding
/// <param name="workDirectory">Scratch folder (the GIF palette goes there).</param>
/// <param name="cover">The source's cover for targets FFmpeg can't put a picture stream into (<see cref="CoverArt"/>).</param>
/// <param name="encoders">The encoders the FFmpeg in use has (<c>ffmpeg -encoders</c>); null assumes the pinned build's.</param>
+ /// <param name="hardware">
+ /// The hardware encoder that passed its probe for <see cref="HardwareCodec"/> of this file; null encodes with x264 /
+ /// x265 (also the retry after a hardware encode failed).
+ /// </param>
/// <exception cref="InvalidOperationException">The file lacks the stream the target needs (e.g. no audio track).</exception>
public static IReadOnlyList<FfmpegPass> Plan(string input, string output, string target, MediaOptions options, MediaInfo info, string workDirectory,
- CoverExtras? cover = null, IReadOnlySet<string>? encoders = null)
+ CoverExtras? cover = null, IReadOnlySet<string>? encoders = null, HardwareEncoder? hardware = null)
{
if (target == "gif")
return AnimatedGif(input, output, options, info, workDirectory);
@@ -152,7 +156,7 @@ internal static class MediaEncoding
if (target == "png")
return [new FfmpegPass(PosterFrame(input, output, info), 1)];
if (VideoTargets.TryGetValue(target, out var video))
- return [new FfmpegPass(Video(input, output, target, video, options, info, encoders), 1)];
+ return [new FfmpegPass(Video(input, output, target, video, options, info, encoders, hardware), 1)];
if (AudioTargets.TryGetValue(target, out var audio))
return [new FfmpegPass(Audio(input, output, target, audio, options, info, cover), 1)];
if (SubtitleTargets.ContainsKey(target))
@@ -162,8 +166,19 @@ internal static class MediaEncoding
// ───────────────────────── Video ─────────────────────────
+ /// <summary>
+ /// The codec a hardware encoder would have to write for this file ("h264" or "hevc"), or null when the preset does
+ /// not ask for hardware encoding, the target is written with another codec (VP9, AV1, MPEG-2, …), or the video is
+ /// copied anyway.
+ /// </summary>
+ internal static string? HardwareCodec(string target, MediaOptions options, MediaInfo info) =>
+ options.HardwareEncoding && info.Video is { } video && VideoTargets.ContainsKey(target)
+ && MediaCodecs.TakesHardwareEncoding(target, options.VideoCodec) && !CanCopyVideo(target, video, options)
+ ? MediaCodecs.Effective(target, options.VideoCodec) == Core.Presets.VideoCodec.Hevc ? "hevc" : "h264"
+ : null;
+
private static List<string> Video(string input, string output, string target, MediaTarget spec, MediaOptions options, MediaInfo info,
- IReadOnlySet<string>? encoders)
+ IReadOnlySet<string>? encoders, HardwareEncoder? hardware)
{
var video = info.Video ?? throw new InvalidOperationException("The file has no video stream.");
// An input without sound is fine: the output simply has no audio track.
@@ -180,6 +195,13 @@ internal static class MediaEncoding
if (video.Codec == "hevc" && target is "mp4" or "m4v" or "mov")
args.AddRange(["-tag:v", "hvc1"]);
}
+ else if (hardware is not null && HardwareCodec(target, options, info) == hardware.Codec)
+ {
+ // VA-API's device is a global option, so it goes before the input.
+ args.InsertRange(Common.Length, HardwareVideo.InputArguments(hardware));
+ args.AddRange(["-vf", ScaleFilter(options.MaxHeight) + HardwareVideo.FilterSuffix(hardware, HardwareVideo.TenBit(hardware.Codec, video))]);
+ args.AddRange(HardwareVideo.CodecArguments(hardware, target, options.Quality, video, options.MaxHeight));
+ }
else
{
var pal = IsPal(video.FrameRate);
@@ -367,8 +389,14 @@ internal static class MediaEncoding
internal static string[] HighBitDepthArguments(VideoStreamInfo video)
{
var tenBit = video.IsHighBitDepth || video.IsHdr;
- List<string> args = ["-pix_fmt", tenBit ? "yuv420p10le" : "yuv420p"];
- if (tenBit && video.Color is { } color)
+ return ["-pix_fmt", tenBit ? "yuv420p10le" : "yuv420p", .. tenBit ? ColorArguments(video) : []];
+ }
+
+ /// <summary>The source's colour tags (primaries, transfer, matrix), for 10-bit and HDR encodes.</summary>
+ internal static List<string> ColorArguments(VideoStreamInfo video)
+ {
+ List<string> args = [];
+ if (video.Color is { } color)
{
if (color.Primaries is { } primaries)
args.AddRange(["-color_primaries", primaries]);
@@ -377,7 +405,7 @@ internal static class MediaEncoding
if (color.Matrix is { } matrix)
args.AddRange(["-colorspace", matrix]);
}
- return [.. args];
+ return args;
}
/// <summary><c>-r</c> for a rate, nothing when the source rate is unknown (FFmpeg then keeps its own guess).</summary>
diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs
index aabfe58b..0781d6cb 100644
--- a/tests/Filee.App.Tests/RenderTests.cs
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@ -1011,6 +1011,37 @@ public class RenderTests
Assert.Equal("600p", new PresetEditorViewModel(preset, AppHost.Get<ILocalizer>()).MaxHeight.Label);
}
+ [AvaloniaFact]
+ public void Preset_editor_offers_hardware_encoding_for_h264_and_hevc()
+ {
+ TestServices.EnsureInitialized("en");
+ var preset = new Filee.Core.Presets.Preset { TargetFormat = "mp4", Name = "Fast" };
+ var vm = new PresetEditorViewModel(preset, AppHost.Get<ILocalizer>());
+ Assert.True(vm.ShowHardwareEncoding);
+ Assert.False(vm.HardwareEncoding); // off unless asked for
+ vm.HardwareEncoding = true;
+
+ // AV1 and VP9 have no hardware path; HEVC does.
+ vm.VideoCodecChoice = vm.VideoCodecs.Single(c => c.Value == Filee.Core.Presets.VideoCodec.Av1);
+ Assert.False(vm.ShowHardwareEncoding);
+ vm.VideoCodecChoice = vm.VideoCodecs.Single(c => c.Value == Filee.Core.Presets.VideoCodec.Hevc);
+ Assert.True(vm.ShowHardwareEncoding);
+ vm.Target = vm.Targets.Single(t => t.Value == "webm");
+ Assert.False(vm.ShowHardwareEncoding);
+ vm.Target = vm.Targets.Single(t => t.Value == "avi");
+ Assert.False(vm.ShowHardwareEncoding);
+ vm.Target = vm.Targets.Single(t => t.Value == "mp3");
+ Assert.False(vm.ShowHardwareEncoding);
+ vm.Target = vm.Targets.Single(t => t.Value == "ts");
+ Assert.True(vm.ShowHardwareEncoding);
+ vm.Target = vm.Targets.Single(t => t.Value == "mov");
+ Assert.True(vm.Apply());
+ Assert.True(preset.Media.HardwareEncoding);
+ Assert.Equal(Filee.Core.Presets.VideoCodec.Hevc, preset.Media.VideoCodec);
+
+ Assert.True(new PresetEditorViewModel(preset, AppHost.Get<ILocalizer>()).HardwareEncoding);
+ }
+
[AvaloniaFact]
public void Preset_editor_offers_the_codecs_each_target_can_hold()
{
diff --git a/tests/Filee.Core.Tests/UserDataStoreTests.cs b/tests/Filee.Core.Tests/UserDataStoreTests.cs
index 36e7c4bc..2a9c4072 100644
--- a/tests/Filee.Core.Tests/UserDataStoreTests.cs
+++ b/tests/Filee.Core.Tests/UserDataStoreTests.cs
@@ -118,6 +118,34 @@ public class UserDataStoreTests
Assert.Equal("mine", reloaded.Profiles[0].PresetIds[0]);
}
+ [Fact]
+ public void Hardware_encoding_is_saved_and_stays_off_for_presets_from_before_it()
+ {
+ using var dir = new TempDir();
+ var store = new UserDataStore(dir.Path);
+ store.Load();
+ Assert.All(store.Presets, p => Assert.False(p.Media.HardwareEncoding)); // no built-in preset turns it on
+ store.Presets.Add(new Preset { Id = "fast", Name = "Fast", TargetFormat = "mp4", Media = { HardwareEncoding = true, VideoCodec = VideoCodec.Hevc } });
+ store.Presets.Add(new Preset { Id = "old", Name = "Old", TargetFormat = "mp4" });
+ store.SaveLibrary();
+
+ // A Filee from before the option saved no "hardwareEncoding".
+ var path = Path.Combine(dir.Path, "presets.json");
+ var presets = System.Text.Json.Nodes.JsonNode.Parse(File.ReadAllText(path))!.AsArray();
+ Assert.True((bool)presets.Single(p => (string?)p!["id"] == "fast")!["media"]!["hardwareEncoding"]!);
+ Assert.True(presets.Single(p => (string?)p!["id"] == "old")!["media"]!.AsObject().Remove("hardwareEncoding"));
+ File.WriteAllText(path, presets.ToJsonString());
+
+ var reloaded = new UserDataStore(dir.Path);
+ reloaded.Load();
+
+ var fast = reloaded.FindPreset("fast")!;
+ Assert.True(fast.Media.HardwareEncoding);
+ Assert.Equal(VideoCodec.Hevc, fast.Media.VideoCodec);
+ Assert.True(fast.Clone().Media.HardwareEncoding);
+ Assert.False(reloaded.FindPreset("old")!.Media.HardwareEncoding);
+ }
+
[Fact]
public void History_is_kept_until_turned_off_and_can_be_cleared()
{
diff --git a/tests/Filee.Engines.Tests/HardwareEncodingTests.cs b/tests/Filee.Engines.Tests/HardwareEncodingTests.cs
new file mode 100644
index 00000000..d9b873d4
--- /dev/null
+++ b/tests/Filee.Engines.Tests/HardwareEncodingTests.cs
@@ -0,0 +1,384 @@
+// Hardware video encoding: which encoders are tried where, their options (no GPU or FFmpeg needed), the software retry
+// when a hardware encode fails, and the time limit of FFmpeg's quick queries. Real hardware encodes run only on a
+// computer with a working GPU encoder and Filee's FFmpeg; CI has neither, so those tests skip there.
+
+using System.Diagnostics;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Infrastructure;
+using Filee.Engines.Media;
+using Microsoft.Extensions.Logging;
+
+namespace Filee.Engines.Tests;
+
+[Collection(nameof(FfmpegCollection))]
+public class HardwareEncodingTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private static readonly (string Ffmpeg, string Ffprobe)? Tools = FfmpegConverter.Locate();
+
+ private static readonly VideoStreamInfo Hd = new(1920, 1080, 1, 0, 29.97, "h264", "yuv444p");
+
+ private static readonly MediaInfo HdClip = new(TimeSpan.FromSeconds(10), Hd, new AudioStreamInfo(2, 48000, "aac"), null);
+
+ private static readonly MediaInfo HdrClip = new(TimeSpan.FromSeconds(10),
+ new VideoStreamInfo(3840, 2160, 1, 0, 30, "hevc", "yuv420p10le", new VideoColor("bt2020", "smpte2084", "bt2020nc", "tv")),
+ new AudioStreamInfo(2, 48000, "aac"), null);
+
+ private static string After(IReadOnlyList<string> args, string option) => args[args.ToList().IndexOf(option) + 1];
+
+ private static IReadOnlyList<string> Args(string target, MediaOptions options, HardwareEncoder? hardware, MediaInfo? info = null) =>
+ MediaEncoding.Plan("in.mov", "out." + target, target, options, info ?? HdClip, "work", hardware: hardware).Single().Arguments;
+
+ // ───────────────────────── Which encoders, in which order ─────────────────────────
+
+ [Fact]
+ public void Each_system_tries_its_own_encoders_best_first()
+ {
+ Assert.Equal(
+ [new HardwareEncoder("hevc_nvenc", HardwareApi.Nvenc), new("hevc_qsv", HardwareApi.Qsv), new("hevc_amf", HardwareApi.Amf)],
+ HardwareVideo.Candidates("hevc", HostPlatform.Windows, encoders: null, vaapiDevice: false));
+ Assert.Equal(
+ [new HardwareEncoder("h264_videotoolbox", HardwareApi.VideoToolbox),
+ new("h264_videotoolbox", HardwareApi.VideoToolbox, HardwareRateControl.Bitrate)],
+ HardwareVideo.Candidates("h264", HostPlatform.MacOS, encoders: null, vaapiDevice: false));
+ Assert.Equal([new HardwareEncoder("h264_nvenc", HardwareApi.Nvenc)],
+ HardwareVideo.Candidates("h264", HostPlatform.Linux, encoders: null, vaapiDevice: false));
+ Assert.Equal([new HardwareEncoder("h264_nvenc", HardwareApi.Nvenc), new("h264_vaapi", HardwareApi.Vaapi)],
+ HardwareVideo.Candidates("h264", HostPlatform.Linux, encoders: null, vaapiDevice: true));
+ Assert.Empty(HardwareVideo.Candidates("h264", HostPlatform.Other, encoders: null, vaapiDevice: true));
+ Assert.Empty(HardwareVideo.Candidates("av1", HostPlatform.Windows, encoders: null, vaapiDevice: false));
+
+ // Only what this FFmpeg was built with: a build without NVENC goes straight to Quick Sync.
+ Assert.Equal([new HardwareEncoder("h264_qsv", HardwareApi.Qsv), new("h264_amf", HardwareApi.Amf)],
+ HardwareVideo.Candidates("h264", HostPlatform.Windows, new HashSet<string> { "libx264", "h264_qsv", "h264_amf", "hevc_nvenc" }, false));
+ Assert.Empty(HardwareVideo.Candidates("hevc", HostPlatform.MacOS, new HashSet<string> { "libx265" }, false));
+
+ Assert.Equal("hevc", new HardwareEncoder("hevc_videotoolbox", HardwareApi.VideoToolbox).Codec);
+ Assert.Equal("h264", new HardwareEncoder("h264_qsv", HardwareApi.Qsv).Codec);
+ }
+
+ [Fact]
+ public void Only_h264_and_hevc_encodes_ask_for_a_hardware_encoder()
+ {
+ var on = new MediaOptions { HardwareEncoding = true };
+ Assert.Equal("h264", MediaEncoding.HardwareCodec("mp4", on, HdClip));
+ Assert.Equal("h264", MediaEncoding.HardwareCodec("ts", on, HdClip));
+ Assert.Equal("hevc", MediaEncoding.HardwareCodec("mkv", new MediaOptions { HardwareEncoding = true, VideoCodec = VideoCodec.Hevc }, HdClip));
+ // Off, another codec, or a video that is only rewrapped.
+ Assert.Null(MediaEncoding.HardwareCodec("mp4", new MediaOptions(), HdClip));
+ Assert.Null(MediaEncoding.HardwareCodec("webm", on, HdClip));
+ Assert.Null(MediaEncoding.HardwareCodec("avi", on, HdClip));
+ Assert.Null(MediaEncoding.HardwareCodec("mp4", new MediaOptions { HardwareEncoding = true, VideoCodec = VideoCodec.Av1 }, HdClip));
+ Assert.Null(MediaEncoding.HardwareCodec("mp3", on, HdClip));
+ var playable = HdClip with { Video = Hd with { PixelFormat = "yuv420p" } };
+ Assert.Null(MediaEncoding.HardwareCodec("mp4", on, playable));
+ Assert.Equal("h264", MediaEncoding.HardwareCodec("mp4", new MediaOptions { HardwareEncoding = true, Quality = MediaQuality.Small }, playable));
+
+ // The editor's list of H.264 targets is the encoder table's.
+ Assert.Equal(MediaEncoding.VideoTargets.Where(t => t.Value.VideoCodec == "libx264").Select(t => t.Key).Order(), MediaCodecs.H264Targets.Order());
+ }
+
+ // ───────────────────────── Options per encoder ─────────────────────────
+
+ [Fact]
+ public void Quality_levels_map_to_each_encoders_rate_control()
+ {
+ IReadOnlyList<string> Codec(HardwareEncoder encoder, string target, MediaQuality quality, VideoStreamInfo? video = null, int maxHeight = 0) =>
+ HardwareVideo.CodecArguments(encoder, target, quality, video ?? Hd, maxHeight);
+
+ Assert.Equal(["-c:v", "h264_nvenc", "-preset", "p5", "-rc", "vbr", "-cq", "24", "-b:v", "0", "-profile:v", "high", "-pix_fmt", "nv12"],
+ Codec(new("h264_nvenc", HardwareApi.Nvenc), "mp4", MediaQuality.Balanced));
+ Assert.Equal(["-c:v", "hevc_qsv", "-preset", "medium", "-global_quality", "23", "-profile:v", "main", "-pix_fmt", "nv12", "-tag:v", "hvc1"],
+ Codec(new("hevc_qsv", HardwareApi.Qsv), "mp4", MediaQuality.High));
+ Assert.Equal(["-c:v", "h264_amf", "-quality", "balanced", "-rc", "cqp", "-qp_i", "27", "-qp_p", "29", "-qp_b", "29", "-profile:v", "high", "-pix_fmt", "nv12"],
+ Codec(new("h264_amf", HardwareApi.Amf), "mkv", MediaQuality.Small));
+ Assert.Equal(["-c:v", "hevc_amf", "-quality", "balanced", "-rc", "cqp", "-qp_i", "25", "-qp_p", "27", "-profile:v", "main", "-pix_fmt", "nv12"],
+ Codec(new("hevc_amf", HardwareApi.Amf), "mkv", MediaQuality.Balanced));
+ Assert.Equal(["-c:v", "h264_videotoolbox", "-q:v", "60", "-profile:v", "high", "-pix_fmt", "nv12"],
+ Codec(new("h264_videotoolbox", HardwareApi.VideoToolbox), "mov", MediaQuality.Balanced));
+ Assert.Equal(["-c:v", "hevc_vaapi", "-rc_mode", "CQP", "-qp", "31", "-profile:v", "main"],
+ Codec(new("hevc_vaapi", HardwareApi.Vaapi), "mkv", MediaQuality.Small));
+
+ // Intel Macs: a bitrate from the output picture, 1080p30 H.264 Balanced ≈ 5.6 Mbit/s; less when scaled to 720p.
+ var bitrate = new HardwareEncoder("h264_videotoolbox", HardwareApi.VideoToolbox, HardwareRateControl.Bitrate);
+ Assert.Equal(["-c:v", "h264_videotoolbox", "-b:v", "5593k", "-profile:v", "high", "-pix_fmt", "nv12"],
+ Codec(bitrate, "mp4", MediaQuality.Balanced));
+ Assert.Equal("2486k", After(Codec(bitrate, "mp4", MediaQuality.Balanced, maxHeight: 720), "-b:v"));
+ Assert.True(HardwareVideo.BitrateKbps("hevc", MediaQuality.High, Hd, 0) < HardwareVideo.BitrateKbps("h264", MediaQuality.High, Hd, 0));
+ Assert.True(HardwareVideo.BitrateKbps("h264", MediaQuality.Small, Hd, 0) < HardwareVideo.BitrateKbps("h264", MediaQuality.Balanced, Hd, 0));
+ Assert.Equal(300, HardwareVideo.BitrateKbps("hevc", MediaQuality.Small, new VideoStreamInfo(64, 64, 1, 0, 5), 0));
+
+ // Coarser than the software CRF by one, finer for High than for Small.
+ Assert.Equal([19, 24, 29], new[] { MediaQuality.High, MediaQuality.Balanced, MediaQuality.Small }.Select(q => HardwareVideo.Quantizer("h264", q)));
+ Assert.Equal([23, 27, 31], new[] { MediaQuality.High, MediaQuality.Balanced, MediaQuality.Small }.Select(q => HardwareVideo.Quantizer("hevc", q)));
+ }
+
+ [Fact]
+ public void Ten_bit_and_hdr_stay_ten_bit_on_hevc_and_h264_stays_eight_bit()
+ {
+ var hdr = HdrClip.Video!;
+ var nvenc = HardwareVideo.CodecArguments(new("hevc_nvenc", HardwareApi.Nvenc), "mp4", MediaQuality.Balanced, hdr, 0);
+ Assert.Equal(("main10", "p010le", "hvc1"), (After(nvenc, "-profile:v"), After(nvenc, "-pix_fmt"), After(nvenc, "-tag:v")));
+ Assert.Equal(("bt2020", "smpte2084", "bt2020nc"), (After(nvenc, "-color_primaries"), After(nvenc, "-color_trc"), After(nvenc, "-colorspace")));
+
+ // H.264 is 8-bit 4:2:0 whatever the source, as with x264.
+ var h264 = HardwareVideo.CodecArguments(new("h264_qsv", HardwareApi.Qsv), "mp4", MediaQuality.Balanced, hdr, 0);
+ Assert.Equal(("high", "nv12"), (After(h264, "-profile:v"), After(h264, "-pix_fmt")));
+ Assert.DoesNotContain("-color_trc", h264);
+ Assert.False(HardwareVideo.TenBit("h264", hdr));
+ Assert.True(HardwareVideo.TenBit("hevc", hdr));
+ Assert.True(HardwareVideo.TenBit("hevc", Hd with { PixelFormat = "p010le" }));
+ Assert.False(HardwareVideo.TenBit("hevc", Hd));
+
+ // VA-API: 10-bit frames are uploaded as P010.
+ var vaapi = new HardwareEncoder("hevc_vaapi", HardwareApi.Vaapi);
+ Assert.Equal(",format=p010le,hwupload", HardwareVideo.FilterSuffix(vaapi, tenBit: true));
+ Assert.Equal(",format=nv12,hwupload", HardwareVideo.FilterSuffix(vaapi, tenBit: false));
+ Assert.Equal("", HardwareVideo.FilterSuffix(new("hevc_nvenc", HardwareApi.Nvenc), tenBit: true));
+ }
+
+ [Fact]
+ public void The_plan_uses_the_hardware_encoder_only_where_it_applies()
+ {
+ var on = new MediaOptions { HardwareEncoding = true };
+ var nvenc = new HardwareEncoder("h264_nvenc", HardwareApi.Nvenc);
+ var mp4 = Args("mp4", on, nvenc);
+ Assert.Equal(("h264_nvenc", "24", "copy"), (After(mp4, "-c:v"), After(mp4, "-cq"), After(mp4, "-c:a"))); // the AAC sound is kept as it is
+ Assert.Equal("scale=w='trunc(iw/2)*2':h='trunc(ih/2)*2'", After(mp4, "-vf"));
+ Assert.Equal("+faststart", After(mp4, "-movflags"));
+ Assert.DoesNotContain("-crf", mp4);
+
+ // HEVC keeps the hvc1 tag in MP4 and MOV, and the 10 bits of an HDR source.
+ var hevcOptions = new MediaOptions { HardwareEncoding = true, VideoCodec = VideoCodec.Hevc, MaxHeight = 1080 };
+ var hevc = Args("mov", hevcOptions, new HardwareEncoder("hevc_videotoolbox", HardwareApi.VideoToolbox), HdrClip);
+ Assert.Equal(("hevc_videotoolbox", "hvc1", "p010le", "main10"), (After(hevc, "-c:v"), After(hevc, "-tag:v"), After(hevc, "-pix_fmt"), After(hevc, "-profile:v")));
+ Assert.DoesNotContain("-tag:v", Args("mkv", hevcOptions, new HardwareEncoder("hevc_nvenc", HardwareApi.Nvenc), HdrClip));
+
+ // VA-API: the device before the input, the upload after the scaling.
+ var vaapi = Args("mkv", on, new HardwareEncoder("h264_vaapi", HardwareApi.Vaapi));
+ Assert.True(vaapi.ToList().IndexOf("-vaapi_device") < vaapi.ToList().IndexOf("-i"));
+ Assert.Equal(HardwareVideo.VaapiDevice, After(vaapi, "-vaapi_device"));
+ Assert.Equal("scale=w='trunc(iw/2)*2':h='trunc(ih/2)*2',format=nv12,hwupload", After(vaapi, "-vf"));
+ Assert.DoesNotContain("-pix_fmt", vaapi);
+
+ // Software when the preset doesn't ask, when the encoder is for another codec, and the copy rules stay.
+ Assert.Equal("libx264", After(Args("mp4", new MediaOptions(), nvenc), "-c:v"));
+ Assert.Equal("libx265", After(Args("mp4", new MediaOptions { HardwareEncoding = true, VideoCodec = VideoCodec.Hevc }, nvenc), "-c:v"));
+ Assert.Equal("libvpx-vp9", After(Args("webm", on, nvenc), "-c:v"));
+ var phone = HdClip with { Video = new VideoStreamInfo(1920, 1080, 1, 0, 30, "h264", "yuv420p") };
+ Assert.Equal("copy", After(Args("mp4", on, nvenc, phone), "-c:v"));
+ // A missing x265 doesn't matter while the hardware encoder writes HEVC.
+ Assert.Equal("hevc_nvenc", After(MediaEncoding.Plan("in.mov", "out.mkv", "mkv", new MediaOptions { HardwareEncoding = true, VideoCodec = VideoCodec.Hevc },
+ HdClip, "work", encoders: new HashSet<string> { "aac" }, hardware: new HardwareEncoder("hevc_nvenc", HardwareApi.Nvenc)).Single().Arguments, "-c:v"));
+ }
+
+ [Fact]
+ public void The_probe_is_a_tiny_test_encode_with_the_real_options()
+ {
+ var qsv = HardwareVideo.ProbeArguments(new HardwareEncoder("hevc_qsv", HardwareApi.Qsv), tenBit: true);
+ Assert.Equal(["-f", "lavfi", "-i", "testsrc=size=256x144:rate=30:duration=0.1"], qsv.SkipWhile(a => a != "-f").Take(4));
+ Assert.Equal(("hevc_qsv", "p010le", "main10", "27"), (After(qsv, "-c:v"), After(qsv, "-pix_fmt"), After(qsv, "-profile:v"), After(qsv, "-global_quality")));
+ Assert.Equal(["-f", "null", "-"], qsv.TakeLast(3));
+
+ var vaapi = HardwareVideo.ProbeArguments(new HardwareEncoder("h264_vaapi", HardwareApi.Vaapi), tenBit: false);
+ Assert.True(vaapi.IndexOf("-vaapi_device") < vaapi.IndexOf("-i"));
+ Assert.Equal("null,format=nv12,hwupload", After(vaapi, "-vf"));
+
+ var intelMac = HardwareVideo.ProbeArguments(new HardwareEncoder("h264_videotoolbox", HardwareApi.VideoToolbox, HardwareRateControl.Bitrate), false);
+ Assert.Contains("-b:v", intelMac);
+ Assert.DoesNotContain("-q:v", intelMac);
+ }
+
+ // ───────────────────────── Software retry ─────────────────────────
+
+ private sealed class ListLogger : ILogger
+ {
+ public List<(LogLevel Level, string Message)> Entries { get; } = [];
+
+ public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
+
+ public bool IsEnabled(LogLevel logLevel) => true;
+
+ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
+ {
+ lock (Entries)
+ Entries.Add((logLevel, formatter(state, exception)));
+ }
+ }
+
+ private static IReadOnlyList<FfmpegPass> FakePlan(HardwareEncoder? encoder) =>
+ [new FfmpegPass(["-c:v", encoder?.Name ?? "libx264"], 1)];
+
+ private static Task Fallback(HardwareEncoder? hardware, Func<IReadOnlyList<FfmpegPass>, Task> run, string output, ILogger logger,
+ CancellationToken cancellationToken) =>
+ FfmpegConverter.RunWithFallbackAsync(FakePlan(hardware), hardware, FakePlan, run, output, logger, cancellationToken);
+
+ [Fact]
+ public async Task A_failing_hardware_encode_is_redone_in_software_and_logged()
+ {
+ var output = Path.Combine(fx.NewFolder(), "out.mp4");
+ var runs = new List<string>();
+ var logger = new ListLogger();
+ Task Run(IReadOnlyList<FfmpegPass> passes)
+ {
+ var encoder = After(passes[0].Arguments, "-c:v");
+ runs.Add(encoder);
+ if (encoder != "h264_nvenc")
+ return Task.CompletedTask;
+ File.WriteAllText(output, "half-written");
+ throw new InvalidOperationException("FFmpeg failed (exit code -22): No capable devices found");
+ }
+
+ await Fallback(new HardwareEncoder("h264_nvenc", HardwareApi.Nvenc), Run, output, logger, CancellationToken.None);
+
+ Assert.Equal(["h264_nvenc", "libx264"], runs);
+ Assert.False(File.Exists(output)); // the partial hardware output is gone before the retry
+ var (level, message) = Assert.Single(logger.Entries);
+ Assert.Equal(LogLevel.Warning, level);
+ Assert.Contains("h264_nvenc", message);
+ Assert.Contains("No capable devices found", message);
+ }
+
+ [Fact]
+ public async Task Success_cancellation_and_software_failures_are_not_retried()
+ {
+ var output = Path.Combine(fx.NewFolder(), "out.mp4");
+ var logger = new ListLogger();
+ var nvenc = new HardwareEncoder("h264_nvenc", HardwareApi.Nvenc);
+
+ var runs = 0;
+ await Fallback(nvenc, _ => { runs++; return Task.CompletedTask; }, output, logger, CancellationToken.None);
+ Assert.Equal(1, runs);
+
+ using var cancelled = new CancellationTokenSource();
+ await cancelled.CancelAsync();
+ runs = 0;
+ await Assert.ThrowsAnyAsync<OperationCanceledException>(() => Fallback(nvenc,
+ _ => { runs++; throw new OperationCanceledException(cancelled.Token); }, output, logger, cancelled.Token));
+ Assert.Equal(1, runs);
+
+ // Without hardware a failure is the user's error message, as before.
+ var error = await Assert.ThrowsAsync<InvalidOperationException>(() => Fallback(null,
+ _ => throw new InvalidOperationException("FFmpeg failed"), output, logger, CancellationToken.None));
+ Assert.Equal("FFmpeg failed", error.Message);
+ // And when the software retry fails too, its error is the one reported.
+ error = await Assert.ThrowsAsync<InvalidOperationException>(() => Fallback(nvenc,
+ passes => throw new InvalidOperationException("failed with " + After(passes[0].Arguments, "-c:v")), output, logger, CancellationToken.None));
+ Assert.Equal("failed with libx264", error.Message);
+ Assert.DoesNotContain(logger.Entries, e => e.Level > LogLevel.Warning);
+ }
+
+ [Fact]
+ public async Task An_encoder_ffmpeg_does_not_have_falls_back_to_x264_in_a_real_conversion()
+ {
+ Assert.SkipUnless(Tools is not null, "FFmpeg is not installed (pwsh build/fetch-engines.ps1 -Only ffmpeg)");
+ var folder = fx.NewFolder();
+ var source = await MakeClipAsync(folder, "clip.mov");
+ var logger = new ListLogger();
+ var converter = new FfmpegConverter(logger)
+ {
+ SelectHardware = (_, codec, _, _, _) => Task.FromResult<HardwareEncoder?>(new HardwareEncoder($"{codec}_filee_missing", HardwareApi.Nvenc)),
+ };
+ Assert.True(converter.GetStatus().IsAvailable);
+
+ var outputs = await converter.ConvertAsync(Step(source, "mov", "mkv", folder, new MediaOptions { HardwareEncoding = true, Quality = MediaQuality.Small }),
+ null, CancellationToken.None);
+
+ Assert.Equal("h264", await CodecOfAsync(Assert.Single(outputs)));
+ Assert.Contains(logger.Entries, e => e.Level == LogLevel.Warning && e.Message.Contains("h264_filee_missing", StringComparison.Ordinal));
+ }
+
+ /// <summary>Runs only where a GPU encoder works (e.g. a laptop with Intel graphics); CI has none.</summary>
+ [Theory]
+ [InlineData(VideoCodec.Default, "h264")]
+ [InlineData(VideoCodec.Hevc, "hevc")]
+ public async Task A_working_hardware_encoder_writes_the_video(VideoCodec videoCodec, string codec)
+ {
+ Assert.SkipUnless(Tools is not null, "FFmpeg is not installed (pwsh build/fetch-engines.ps1 -Only ffmpeg)");
+ var ffmpeg = Tools!.Value.Ffmpeg;
+ var logger = new ListLogger();
+ var hardware = await HardwareProbe.SelectAsync(ffmpeg, codec, false, FfmpegConverter.EncodersOf(ffmpeg), logger, CancellationToken.None);
+ Assert.SkipUnless(hardware is not null, $"No {codec} hardware encoder works on this computer");
+
+ var folder = fx.NewFolder();
+ var source = await MakeClipAsync(folder, "clip.mov");
+ var converter = new FfmpegConverter(logger);
+ converter.GetStatus();
+ var outputs = await converter.ConvertAsync(Step(source, "mov", "mp4", folder,
+ new MediaOptions { HardwareEncoding = true, Quality = MediaQuality.Small, VideoCodec = videoCodec }), null, CancellationToken.None);
+
+ Assert.Equal(codec, await CodecOfAsync(Assert.Single(outputs)));
+ Assert.DoesNotContain(logger.Entries, e => e.Level == LogLevel.Warning); // no software retry
+ }
+
+ // ───────────────────────── Quick queries ─────────────────────────
+
+ [Fact]
+ public void Version_and_encoder_queries_give_up_on_an_ffmpeg_that_hangs()
+ {
+ var hanging = HangingProgram(fx.NewFolder());
+ var watch = Stopwatch.StartNew();
+ Assert.Throws<InvalidOperationException>(() => FfmpegConverter.VersionOf(hanging, TimeSpan.FromSeconds(1)));
+ Assert.Null(FfmpegConverter.EncodersOf(hanging, TimeSpan.FromSeconds(1)));
+ // Before, both read the output to its end first and waited as long as the program hung (here a minute).
+ Assert.True(watch.Elapsed < TimeSpan.FromSeconds(20), $"took {watch.Elapsed}");
+ }
+
+ [Fact]
+ public void Encoder_lists_are_read()
+ {
+ var encoders = FfmpegConverter.ParseEncoders(
+ "Encoders:\n V..... = Video\n ------\n V....D libx264 libx264 H.264 / AVC\n" +
+ " V..... h264_qsv H.264 (Intel Quick Sync Video acceleration) (codec h264)\r\n A....D aac AAC\n");
+ Assert.Contains("libx264", encoders);
+ Assert.Contains("h264_qsv", encoders);
+ Assert.Contains("aac", encoders);
+ Assert.DoesNotContain("Video", encoders);
+ }
+
+ /// <summary>A program that writes nothing and runs for a minute, keeping its output open (a hung FFmpeg).</summary>
+ private static string HangingProgram(string folder)
+ {
+ if (OperatingSystem.IsWindows())
+ {
+ var script = Path.Combine(folder, "hanging-ffmpeg.cmd");
+ File.WriteAllText(script, "@ping -n 60 127.0.0.1 >nul\r\n");
+ return script;
+ }
+ var shell = Path.Combine(folder, "hanging-ffmpeg");
+ File.WriteAllText(shell, "#!/bin/sh\nsleep 60\n");
+ File.SetUnixFileMode(shell, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
+ return shell;
+ }
+
+ // ───────────────────────── Helpers ─────────────────────────
+
+ private sealed class FolderAllocator(string folder) : IOutputAllocator
+ {
+ public string? Allocate(string extension, string? suffix = null) => Path.Combine(folder, $"out{suffix}.{extension}");
+ }
+
+ private static ConversionStep Step(string input, string from, string to, string folder, MediaOptions media) =>
+ new(input, from, to, new Preset { TargetFormat = to, Media = media }, new FolderAllocator(folder), folder);
+
+ /// <summary>A one-second 320×240 test pattern with a tone, in a yuv444p H.264 that every target re-encodes.</summary>
+ private static async Task<string> MakeClipAsync(string folder, string name)
+ {
+ var path = Path.Combine(folder, name);
+ var result = await ProcessRunner.RunAsync(Tools!.Value.Ffmpeg,
+ ["-hide_banner", "-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=320x240:rate=25:duration=1",
+ "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100:duration=1", "-c:v", "libx264", "-pix_fmt", "yuv444p", path],
+ TimeSpan.FromMinutes(1), CancellationToken.None);
+ Assert.True(result.ExitCode == 0, result.StandardError);
+ return path;
+ }
+
+ private static async Task<string> CodecOfAsync(string file)
+ {
+ var result = await ProcessRunner.RunAsync(Tools!.Value.Ffprobe,
+ ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=codec_name", "-of", "default=nw=1:nk=1", file],
+ TimeSpan.FromMinutes(1), CancellationToken.None);
+ Assert.True(result.ExitCode == 0, result.StandardError);
+ return result.StandardOutput.Trim();
+ }
+}