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 encoding for AV1: NVENC, Quick Sync, AMF and VA-API

KnifeLemon2b739fb364e2
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index f2d7d6a3..be3582b8 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -1286,28 +1286,37 @@ format, and FFmpeg reads what the file holds, so a `.dat` with no video in it fa
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
+ for older presets, so nobody's results change without asking). H.264, HEVC and AV1 encodes (not VP9 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`) |
+ | macOS | `*_videotoolbox` with constant quality (Apple Silicon), then with a bitrate (Intel Macs reject `-q:v`); none for AV1 (VideoToolbox has no AV1 encoder) |
| 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.
+ AV1 encodes only on recent chips: NVIDIA RTX 40 and newer (`av1_nvenc`), Intel Arc and Core Ultra (Meteor Lake) and
+ newer (`av1_qsv`), AMD RDNA 3 and newer (`av1_amf`), and VA-API drivers that offer it; on older ones the test
+ encode fails and SVT-AV1 encodes as before. 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
+ ("Hardware encoder av1_qsv (Quality, 8-bit) works" / "is not usable: …"). 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). AV1 has other
+ scales: NVENC's `-cq` is AV1's 0–63 quantizer and gets 28/34/42 (two above SVT-AV1's CRF 26/32/40); AMF and VA-API
+ take the 0–255 quantizer index, four times that (112/136/168: AMF `-qp_p`/`-qp_b` N, `-qp_i` N−8; VA-API
+ `-rc_mode CQP -global_quality N`, as `av1_vaapi` has no `-qp`); Quick Sync's ICQ is 1–51 for AV1 too and gets
+ HEVC's 23/27/31. 8-bit video is NV12 (H.264 High, HEVC Main, AV1 Main); 10-bit and HDR sources stay P010 (HEVC Main
+ 10, 10-bit AV1 Main) with their colour tags when the encoder passes a 10-bit test encode, otherwise x265 / SVT-AV1
+ encode them. AV1 gets no `-profile:v` (every encoder picks Main; `av1_nvenc` has no such option) and no tag (`av01`
+ in MP4/M4V, as written to MKV and WebM). HEVC keeps the `hvc1` tag in MP4/M4V/MOV. GOP length and B-frames are
+ left to each encoder's defaults, as for H.264 and HEVC. 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/SVT-AV1; 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/ar.json b/src/Filee.App/Assets/i18n/ar.json
index 9fe342a7..7b802907 100644
--- a/src/Filee.App/Assets/i18n/ar.json
+++ b/src/Filee.App/Assets/i18n/ar.json
@@ -549,7 +549,7 @@
"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.hardware_encoding_hint": "ترميز H.264 وHEVC وAV1 باستخدام معالج الرسوميات.\nأسرع بكثير وأقل استهلاكًا للطاقة.\nالجودة أقل قليلًا عند حجم الملف نفسه.\nعند عدم توفر معالج مناسب (يتطلب AV1 معالجًا حديثًا)، يُرمَّز الفيديو بالطريقة المعتادة.",
"presets.audio_codec": "ترميز الصوت",
"presets.audio_codec.aac": "AAC",
"presets.audio_codec.alac": "ALAC (دون فقدان)",
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 287c59be..41af4e18 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -564,7 +564,7 @@
"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.hardware_encoding_hint": "Encodes H.264, HEVC and AV1 on the graphics chip.\nMuch faster and uses less power.\nSlightly lower quality at the same file size.\nWithout a usable chip (AV1 needs a recent one), 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/es.json b/src/Filee.App/Assets/i18n/es.json
index 31599ceb..51bafa19 100644
--- a/src/Filee.App/Assets/i18n/es.json
+++ b/src/Filee.App/Assets/i18n/es.json
@@ -549,7 +549,7 @@
"presets.video_codec.hevc": "HEVC / H.265 (más pequeño)",
"presets.video_codec.av1": "AV1 (el más pequeño, lento)",
"presets.hardware_encoding": "Usar aceleración por hardware (chip gráfico)",
- "presets.hardware_encoding_hint": "Codifica H.264 y HEVC en el chip gráfico.\nMucho más rápido y consume menos energía.\nCalidad ligeramente inferior con el mismo tamaño de archivo.\nSin un chip compatible, el vídeo se codifica de la forma habitual.",
+ "presets.hardware_encoding_hint": "Codifica H.264, HEVC y AV1 en el chip gráfico.\nMucho más rápido y consume menos energía.\nCalidad ligeramente inferior con el mismo tamaño de archivo.\nSin un chip compatible (AV1 necesita uno reciente), el vídeo se codifica de la forma habitual.",
"presets.audio_codec": "Códec de audio",
"presets.audio_codec.aac": "AAC",
"presets.audio_codec.alac": "ALAC (sin pérdida)",
diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json
index 2beeacf5..fd3fb0c3 100644
--- a/src/Filee.App/Assets/i18n/hi.json
+++ b/src/Filee.App/Assets/i18n/hi.json
@@ -549,7 +549,7 @@
"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.hardware_encoding_hint": "H.264, HEVC और AV1 को ग्राफ़िक्स चिप पर एन्कोड करता है।\nबहुत तेज़ है और कम बिजली लगती है।\nउसी फ़ाइल साइज़ पर क्वालिटी थोड़ी कम होती है।\nउपयोगी चिप न होने पर (AV1 के लिए नई चिप चाहिए) वीडियो सामान्य तरीके से एन्कोड होता है।",
"presets.audio_codec": "ऑडियो कोडेक",
"presets.audio_codec.aac": "AAC",
"presets.audio_codec.alac": "ALAC (लॉसलेस)",
diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json
index aec6e700..2af48274 100644
--- a/src/Filee.App/Assets/i18n/ja.json
+++ b/src/Filee.App/Assets/i18n/ja.json
@@ -549,7 +549,7 @@
"presets.video_codec.hevc": "HEVC / H.265(小さめ)",
"presets.video_codec.av1": "AV1(最小、変換に時間がかかる)",
"presets.hardware_encoding": "ハードウェアアクセラレーションを使う(GPU)",
- "presets.hardware_encoding_hint": "GPUでH.264とHEVCにエンコードします。\n大幅に速くなり、消費電力も抑えられます。\n同じファイルサイズでは、画質がわずかに低くなります。\n利用可能なGPUがない場合は、通常の方法でエンコードします。",
+ "presets.hardware_encoding_hint": "GPUでH.264、HEVC、AV1にエンコードします。\n大幅に速くなり、消費電力も抑えられます。\n同じファイルサイズでは、画質がわずかに低くなります。\n利用可能なGPUがない場合(AV1には新しいGPUが必要です)は、通常の方法でエンコードします。",
"presets.audio_codec": "音声コーデック",
"presets.audio_codec.aac": "AAC",
"presets.audio_codec.alac": "ALAC(可逆圧縮)",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index ca975504..5073c1c5 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -564,7 +564,7 @@
"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.hardware_encoding_hint": "H.264, HEVC, AV1을 그래픽 칩으로 인코딩해요.\n훨씬 빠르고 전력도 덜 써요.\n같은 용량이면 화질이 조금 낮아요.\n쓸 수 있는 칩이 없으면(AV1은 최신 칩이 필요해요) 평소처럼 인코딩해요.",
"presets.audio_codec": "오디오 코덱",
"presets.audio_codec.aac": "AAC",
"presets.audio_codec.alac": "ALAC (무손실)",
diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json
index 5ed832fa..fa2815f3 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -564,7 +564,7 @@
"presets.video_codec.hevc": "HEVC / H.265 (mniejszy)",
"presets.video_codec.av1": "AV1 (najmniejszy, wolny)",
"presets.hardware_encoding": "Użyj akceleracji sprzętowej (karta graficzna)",
- "presets.hardware_encoding_hint": "Koduje H.264 i HEVC na karcie graficznej.\nZnacznie szybciej i przy mniejszym zużyciu energii.\nNieco niższa jakość przy tym samym rozmiarze pliku.\nBez obsługiwanej karty wideo jest kodowane jak zwykle.",
+ "presets.hardware_encoding_hint": "Koduje H.264, HEVC i AV1 na karcie graficznej.\nZnacznie szybciej i przy mniejszym zużyciu energii.\nNieco niższa jakość przy tym samym rozmiarze pliku.\nBez obsługiwanej karty (AV1 wymaga nowszej) wideo jest kodowane jak zwykle.",
"presets.audio_codec": "Kodek audio",
"presets.audio_codec.aac": "AAC",
"presets.audio_codec.alac": "ALAC (bezstratny)",
diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json
index 7c2d633f..15ee4bed 100644
--- a/src/Filee.App/Assets/i18n/ru.json
+++ b/src/Filee.App/Assets/i18n/ru.json
@@ -564,7 +564,7 @@
"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.hardware_encoding_hint": "Кодирует H.264, HEVC и AV1 на видеочипе.\nНамного быстрее и тратит меньше энергии.\nКачество чуть ниже при том же размере файла.\nЕсли подходящего чипа нет (для AV1 нужен современный), видео кодируется как обычно.",
"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 762bb381..d31067a4 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -564,7 +564,7 @@
"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.hardware_encoding_hint": "用显卡编码 H.264、HEVC 和 AV1。\n速度快得多,也更省电。\n相同文件大小时画质略低。\n没有可用的显卡时(AV1 需要较新的显卡)照常编码。",
"presets.audio_codec": "音频编码",
"presets.audio_codec.aac": "AAC",
"presets.audio_codec.alac": "ALAC(无损)",
diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
index 6ddb748a..ffed1f9a 100644
--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
@@ -406,7 +406,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
[ObservableProperty] private Choice<WavSampleFormat> _wavFormat;
[ObservableProperty] private bool _removeAudio;
- /// <summary>Encode H.264 / HEVC on the graphics chip when one works (MediaOptions.HardwareEncoding).</summary>
+ /// <summary>Encode H.264 / HEVC / AV1 on the graphics chip when one works (MediaOptions.HardwareEncoding).</summary>
[ObservableProperty] private bool _hardwareEncoding;
[ObservableProperty] private Choice<ArchiveLevel> _archiveLevel;
[ObservableProperty] private bool _combineIntoOne;
@@ -501,7 +501,7 @@ 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>
+ /// <summary>Hardware encoding applies to H.264, HEVC and AV1 only (not VP9, 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;
diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.cs
index bf80d026..ed631510 100644
--- a/src/Filee.Core/Presets/Preset.cs
+++ b/src/Filee.Core/Presets/Preset.cs
@@ -470,10 +470,10 @@ public sealed class MediaOptions
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.
+ /// Encode H.264, HEVC and AV1 video with the graphics chip's encoder (NVENC, Quick Sync, AMF, VideoToolbox or VA-API;
+ /// AV1 only on recent chips and not on a Mac) when one works on this computer, else with x264 / x265 / SVT-AV1 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; }
@@ -607,12 +607,12 @@ public static class MediaCodecs
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
+ /// True when <paramref name="target"/> with <paramref name="codec"/> is written as H.264, HEVC or AV1, 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.Hevc or VideoCodec.Av1 => true,
VideoCodec.Default => H264Targets.Contains(target),
_ => false,
};
diff --git a/src/Filee.Engines/Media/FfmpegConverter.cs b/src/Filee.Engines/Media/FfmpegConverter.cs
index d68d8334..dd7f8a26 100644
--- a/src/Filee.Engines/Media/FfmpegConverter.cs
+++ b/src/Filee.Engines/Media/FfmpegConverter.cs
@@ -252,7 +252,7 @@ public sealed partial class FfmpegConverter(ILogger? logger = null) : IConverter
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.
+ // An FFmpeg without x265 or an AV1 encoder says so here: the hardware encoder was its only way to write it.
await run(plan(null));
}
}
diff --git a/src/Filee.Engines/Media/HardwareProbe.cs b/src/Filee.Engines/Media/HardwareProbe.cs
index eaaff759..79f0f875 100644
--- a/src/Filee.Engines/Media/HardwareProbe.cs
+++ b/src/Filee.Engines/Media/HardwareProbe.cs
@@ -20,10 +20,10 @@ internal static class HardwareProbe
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).
+ /// The hardware encoder to write <paramref name="codec"/> ("h264", "hevc" or "av1") with, or null when none works
+ /// here (then x264 / x265 / SVT-AV1 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="tenBit">The video is encoded in 10 bits (HEVC Main 10, 10-bit AV1): 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)
diff --git a/src/Filee.Engines/Media/HardwareVideo.cs b/src/Filee.Engines/Media/HardwareVideo.cs
index 8253460c..5c2edf55 100644
--- a/src/Filee.Engines/Media/HardwareVideo.cs
+++ b/src/Filee.Engines/Media/HardwareVideo.cs
@@ -1,5 +1,5 @@
-// 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
+// Hardware video encoders (NVENC, Quick Sync, AMF, VideoToolbox, VA-API) for H.264, HEVC and AV1: 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;
@@ -10,19 +10,19 @@ 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>
+ /// <summary>NVIDIA (<c>h264_nvenc</c>, <c>hevc_nvenc</c>, <c>av1_nvenc</c> from the RTX 40 series on).</summary>
Nvenc,
- /// <summary>Intel Quick Sync Video (<c>h264_qsv</c>, <c>hevc_qsv</c>).</summary>
+ /// <summary>Intel Quick Sync Video (<c>h264_qsv</c>, <c>hevc_qsv</c>, <c>av1_qsv</c> from Arc and Core Ultra on).</summary>
Qsv,
- /// <summary>AMD Advanced Media Framework (<c>h264_amf</c>, <c>hevc_amf</c>).</summary>
+ /// <summary>AMD Advanced Media Framework (<c>h264_amf</c>, <c>hevc_amf</c>, <c>av1_amf</c> from RDNA 3 on).</summary>
Amf,
- /// <summary>Apple VideoToolbox (<c>h264_videotoolbox</c>, <c>hevc_videotoolbox</c>).</summary>
+ /// <summary>Apple VideoToolbox (<c>h264_videotoolbox</c>, <c>hevc_videotoolbox</c>; no AV1 encoder).</summary>
VideoToolbox,
- /// <summary>Linux VA-API (<c>h264_vaapi</c>, <c>hevc_vaapi</c>): frames are uploaded to the GPU first.</summary>
+ /// <summary>Linux VA-API (<c>h264_vaapi</c>, <c>hevc_vaapi</c>, <c>av1_vaapi</c>): frames are uploaded to the GPU first.</summary>
Vaapi,
}
@@ -52,7 +52,7 @@ internal enum HostPlatform
/// <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>
+ /// <summary>"h264", "hevc" or "av1": the part before the underscore.</summary>
public string Codec => Name[..Name.IndexOf('_', StringComparison.Ordinal)];
}
@@ -73,19 +73,21 @@ internal static class HardwareVideo
: HostPlatform.Other;
/// <summary>
- /// The hardware encoders for <paramref name="codec"/> ("h264" or "hevc") worth trying, best first. Windows:
+ /// The hardware encoders for <paramref name="codec"/> ("h264", "hevc" or "av1") 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.
+ /// VideoToolbox with constant quality (Apple Silicon), then with a bitrate (Intel Macs); none for AV1, which
+ /// VideoToolbox can't encode. 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, so a
+ /// chip too old for AV1 (before the RTX 40 series, Arc and Core Ultra, RDNA 3) leaves AV1 to SVT-AV1.
/// </summary>
public static IReadOnlyList<HardwareEncoder> Candidates(string codec, HostPlatform platform, IReadOnlySet<string>? encoders, bool vaapiDevice)
{
- if (codec is not ("h264" or "hevc"))
+ if (codec is not ("h264" or "hevc" or "av1"))
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 when codec == "av1" => [],
HostPlatform.MacOS =>
[
new($"{codec}_videotoolbox", HardwareApi.VideoToolbox),
@@ -100,21 +102,34 @@ internal static class HardwareVideo
}
/// <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).
+ /// True when the video is encoded in 10 bits: HEVC and AV1 keep 10-bit and HDR sources in 10 bits (HEVC Main 10, AV1
+ /// Main), as x265 and SVT-AV1 do. 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);
+ public static bool TenBit(string codec, VideoStreamInfo video) => codec is "hevc" or "av1" && (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.
+ /// file; one step coarser keeps the size close at a slightly lower quality. AV1 gets HEVC's numbers: only Quick
+ /// Sync takes this scale for AV1 (its ICQ is 1–51 for every codec, 26 by default as for HEVC).
/// </summary>
- public static int Quantizer(string codec, MediaQuality quality) => codec == "hevc"
+ public static int Quantizer(string codec, MediaQuality quality) => codec is "hevc" or "av1"
? Choose(quality, 23, 27, 31)
: Choose(quality, 19, 24, 29);
+ /// <summary>
+ /// The preset's quality on AV1's 0–63 quantizer scale (NVENC <c>-cq</c>), the scale of SVT-AV1's CRF: two above its
+ /// 26/32/40, about the one step coarser H.264 and HEVC get, on AV1's finer scale.
+ /// </summary>
+ public static int Av1Quantizer(MediaQuality quality) => Choose(quality, 28, 34, 42);
+
+ /// <summary>
+ /// <see cref="Av1Quantizer"/> on AV1's 0–255 quantizer index (<c>base_q_idx</c>), which AMF (<c>-qp_p</c>) and VA-API
+ /// (<c>-global_quality</c>) take: quantizer q is index 4q, as AV1 encoders map their CRF.
+ /// </summary>
+ public static int Av1QIndex(MediaQuality quality) => Av1Quantizer(quality) * 4;
+
/// <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);
@@ -145,13 +160,14 @@ internal static class HardwareVideo
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.
+ /// The encoder options for one video: rate control from the preset's quality, NV12 (8-bit) or P010 (10-bit HEVC
+ /// Main 10 and AV1), the source's HDR colour tags, and the <c>hvc1</c> tag Apple players need for HEVC in MP4/MOV.
+ /// AV1 needs no tag (<c>av01</c> in MP4; MKV and WebM have none).
/// </summary>
public static List<string> CodecArguments(HardwareEncoder encoder, string target, MediaQuality quality, VideoStreamInfo video, int maxHeight)
{
var codec = encoder.Codec;
+ var av1 = codec == "av1";
var tenBit = TenBit(codec, video);
var quantizer = Text(Quantizer(codec, quality));
List<string> args = ["-c:v", encoder.Name];
@@ -159,14 +175,19 @@ internal static class HardwareVideo
{
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"]);
+ // preset, still many times faster than x264's medium. AV1's -cq is on its own 0–63 scale.
+ args.AddRange(["-preset", "p5", "-rc", "vbr", "-cq", av1 ? Text(Av1Quantizer(quality)) : 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 when av1:
+ // AV1 takes the quantizer index (0–255): I-frames the same two steps finer, B-frames like P-frames.
+ var index = Av1QIndex(quality);
+ args.AddRange(["-quality", "balanced", "-rc", "cqp", "-qp_i", Text(index - 8), "-qp_p", Text(index), "-qp_b", Text(index)]);
+ 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]);
@@ -179,14 +200,19 @@ internal static class HardwareVideo
case HardwareApi.VideoToolbox:
args.AddRange(["-q:v", Text(VideoToolboxQuality(quality))]);
break;
+ case HardwareApi.Vaapi when av1:
+ // av1_vaapi has no -qp: the constant quantizer index comes from -global_quality.
+ args.AddRange(["-rc_mode", "CQP", "-global_quality", Text(Av1QIndex(quality))]);
+ break;
case HardwareApi.Vaapi:
args.AddRange(["-rc_mode", "CQP", "-qp", quantizer]);
break;
}
+ // AV1's Main profile covers 8- and 10-bit 4:2:0 and every encoder picks it itself (av1_nvenc has no -profile).
if (codec == "h264")
args.AddRange(["-profile:v", "high"]);
- else
+ else if (codec == "hevc")
args.AddRange(["-profile:v", tenBit ? "main10" : "main"]);
// VA-API's frames are already uploaded in the right format (FilterSuffix).
if (encoder.Api != HardwareApi.Vaapi)
diff --git a/src/Filee.Engines/Media/MediaEncoding.cs b/src/Filee.Engines/Media/MediaEncoding.cs
index 9336056f..be71f1a5 100644
--- a/src/Filee.Engines/Media/MediaEncoding.cs
+++ b/src/Filee.Engines/Media/MediaEncoding.cs
@@ -143,7 +143,7 @@ internal static class MediaEncoding
/// <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).
+ /// x265 / SVT-AV1 (also the retry after a hardware encode failed).
/// </param>
/// <param name="animationSpeed">Playback speed of an animated GIF or APNG (ImageOptions.PlaybackSpeed); 1 keeps the video's.</param>
/// <exception cref="InvalidOperationException">The file lacks the stream the target needs (e.g. no audio track).</exception>
@@ -211,14 +211,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
+ /// The codec a hardware encoder would have to write for this file ("h264", "hevc" or "av1"), or null when the preset
+ /// does not ask for hardware encoding, the target is written with another codec (VP9, 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"
+ ? MediaCodecs.Effective(target, options.VideoCodec) switch
+ {
+ VideoCodec.Hevc => "hevc",
+ VideoCodec.Av1 => "av1",
+ _ => "h264",
+ }
: null;
private static List<string> Video(string input, string output, string target, MediaTarget spec, MediaOptions options, MediaInfo info,
diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs
index 255fc915..ba664bf4 100644
--- a/tests/Filee.App.Tests/RenderTests.cs
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@ -1613,7 +1613,7 @@ public class RenderTests
}
[AvaloniaFact]
- public void Preset_editor_offers_hardware_encoding_for_h264_and_hevc()
+ public void Preset_editor_offers_hardware_encoding_for_h264_hevc_and_av1()
{
TestServices.EnsureInitialized("en");
var preset = new Filee.Core.Presets.Preset { TargetFormat = "mp4", Name = "Fast" };
@@ -1622,9 +1622,9 @@ public class RenderTests
Assert.False(vm.HardwareEncoding); // off unless asked for
vm.HardwareEncoding = true;
- // AV1 and VP9 have no hardware path; HEVC does.
+ // HEVC and AV1 have a hardware path; VP9 (WebM's usual codec) has none.
vm.VideoCodecChoice = vm.VideoCodecs.Single(c => c.Value == Filee.Core.Presets.VideoCodec.Av1);
- Assert.False(vm.ShowHardwareEncoding);
+ Assert.True(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");
@@ -1641,6 +1641,12 @@ public class RenderTests
Assert.Equal(Filee.Core.Presets.VideoCodec.Hevc, preset.Media.VideoCodec);
Assert.True(new PresetEditorViewModel(preset, AppHost.Get<ILocalizer>()).HardwareEncoding);
+
+ // WebM written as AV1 (the "MP4 AV1" kind of preset, in WebM) offers it too.
+ var webm = new PresetEditorViewModel(new Filee.Core.Presets.Preset { TargetFormat = "webm", Name = "AV1" }, AppHost.Get<ILocalizer>());
+ Assert.False(webm.ShowHardwareEncoding);
+ webm.VideoCodecChoice = webm.VideoCodecs.Single(c => c.Value == Filee.Core.Presets.VideoCodec.Av1);
+ Assert.True(webm.ShowHardwareEncoding);
}
[AvaloniaFact]
diff --git a/tests/Filee.Engines.Tests/HardwareEncodingTests.cs b/tests/Filee.Engines.Tests/HardwareEncodingTests.cs
index d9b873d4..040fd890 100644
--- a/tests/Filee.Engines.Tests/HardwareEncodingTests.cs
+++ b/tests/Filee.Engines.Tests/HardwareEncodingTests.cs
@@ -46,7 +46,7 @@ public class HardwareEncodingTests(EngineFixture fx) : IClassFixture<EngineFixtu
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));
+ Assert.Empty(HardwareVideo.Candidates("vp9", 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)],
@@ -55,20 +55,49 @@ public class HardwareEncodingTests(EngineFixture fx) : IClassFixture<EngineFixtu
Assert.Equal("hevc", new HardwareEncoder("hevc_videotoolbox", HardwareApi.VideoToolbox).Codec);
Assert.Equal("h264", new HardwareEncoder("h264_qsv", HardwareApi.Qsv).Codec);
+ Assert.Equal("av1", new HardwareEncoder("av1_qsv", HardwareApi.Qsv).Codec);
}
[Fact]
- public void Only_h264_and_hevc_encodes_ask_for_a_hardware_encoder()
+ public void Av1_tries_nvidia_intel_and_amd_and_stays_on_the_cpu_on_a_mac()
+ {
+ Assert.Equal(
+ [new HardwareEncoder("av1_nvenc", HardwareApi.Nvenc), new("av1_qsv", HardwareApi.Qsv), new("av1_amf", HardwareApi.Amf)],
+ HardwareVideo.Candidates("av1", HostPlatform.Windows, encoders: null, vaapiDevice: false));
+ Assert.Equal([new HardwareEncoder("av1_nvenc", HardwareApi.Nvenc), new("av1_vaapi", HardwareApi.Vaapi)],
+ HardwareVideo.Candidates("av1", HostPlatform.Linux, encoders: null, vaapiDevice: true));
+ Assert.Equal([new HardwareEncoder("av1_nvenc", HardwareApi.Nvenc)],
+ HardwareVideo.Candidates("av1", HostPlatform.Linux, encoders: null, vaapiDevice: false));
+ // VideoToolbox has no AV1 encoder: SVT-AV1 encodes, even with an FFmpeg that lists one by that name.
+ Assert.Empty(HardwareVideo.Candidates("av1", HostPlatform.MacOS, encoders: null, vaapiDevice: false));
+ Assert.Empty(HardwareVideo.Candidates("av1", HostPlatform.MacOS, new HashSet<string> { "av1_videotoolbox" }, false));
+ Assert.Empty(HardwareVideo.Candidates("av1", HostPlatform.Other, encoders: null, vaapiDevice: true));
+
+ // Only what this FFmpeg lists: an older build with H.264/HEVC Quick Sync but no av1_qsv tries nothing.
+ Assert.Equal([new HardwareEncoder("av1_qsv", HardwareApi.Qsv)],
+ HardwareVideo.Candidates("av1", HostPlatform.Windows, new HashSet<string> { "libsvtav1", "av1_qsv", "hevc_nvenc", "h264_amf" }, false));
+ Assert.Empty(HardwareVideo.Candidates("av1", HostPlatform.Windows, new HashSet<string> { "libsvtav1", "h264_qsv", "hevc_qsv" }, false));
+ }
+
+ [Fact]
+ public void Only_h264_hevc_and_av1_encodes_ask_for_a_hardware_encoder()
{
var on = new MediaOptions { HardwareEncoding = true };
+ var av1 = new MediaOptions { HardwareEncoding = true, VideoCodec = VideoCodec.Av1 };
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));
+ Assert.Equal("av1", MediaEncoding.HardwareCodec("mp4", av1, HdClip));
+ Assert.Equal("av1", MediaEncoding.HardwareCodec("m4v", av1, HdClip));
+ Assert.Equal("av1", MediaEncoding.HardwareCodec("mkv", av1, HdClip));
+ Assert.Equal("av1", MediaEncoding.HardwareCodec("webm", av1, HdClip));
// Off, another codec, or a video that is only rewrapped.
Assert.Null(MediaEncoding.HardwareCodec("mp4", new MediaOptions(), HdClip));
+ Assert.Null(MediaEncoding.HardwareCodec("mp4", new MediaOptions { VideoCodec = VideoCodec.Av1 }, 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.Equal("h264", MediaEncoding.HardwareCodec("mov", av1, HdClip)); // MOV has no AV1: H.264 as usual
+ Assert.Null(MediaEncoding.HardwareCodec("mp4", av1, HdClip with { Video = Hd with { Codec = "av1", PixelFormat = "yuv420p" } }));
Assert.Null(MediaEncoding.HardwareCodec("mp3", on, HdClip));
var playable = HdClip with { Video = Hd with { PixelFormat = "yuv420p" } };
Assert.Null(MediaEncoding.HardwareCodec("mp4", on, playable));
@@ -113,6 +142,49 @@ public class HardwareEncodingTests(EngineFixture fx) : IClassFixture<EngineFixtu
Assert.Equal([23, 27, 31], new[] { MediaQuality.High, MediaQuality.Balanced, MediaQuality.Small }.Select(q => HardwareVideo.Quantizer("hevc", q)));
}
+ [Fact]
+ public void Av1_gets_each_encoders_own_quality_scale()
+ {
+ IReadOnlyList<string> Codec(string name, HardwareApi api, string target, MediaQuality quality) =>
+ HardwareVideo.CodecArguments(new HardwareEncoder(name, api), target, quality, Hd, 0);
+
+ // NVENC: AV1's 0–63 quantizer, two above SVT-AV1's CRF 26/32/40.
+ Assert.Equal(["-c:v", "av1_nvenc", "-preset", "p5", "-rc", "vbr", "-cq", "34", "-b:v", "0", "-pix_fmt", "nv12"],
+ Codec("av1_nvenc", HardwareApi.Nvenc, "mp4", MediaQuality.Balanced));
+ // Quick Sync: ICQ is 1–51 for AV1 as for HEVC.
+ Assert.Equal(["-c:v", "av1_qsv", "-preset", "medium", "-global_quality", "23", "-pix_fmt", "nv12"],
+ Codec("av1_qsv", HardwareApi.Qsv, "mkv", MediaQuality.High));
+ // AMF and VA-API: the 0–255 quantizer index, four times the quantizer.
+ Assert.Equal(["-c:v", "av1_amf", "-quality", "balanced", "-rc", "cqp", "-qp_i", "160", "-qp_p", "168", "-qp_b", "168", "-pix_fmt", "nv12"],
+ Codec("av1_amf", HardwareApi.Amf, "webm", MediaQuality.Small));
+ Assert.Equal(["-c:v", "av1_vaapi", "-rc_mode", "CQP", "-global_quality", "136"],
+ Codec("av1_vaapi", HardwareApi.Vaapi, "mkv", MediaQuality.Balanced));
+
+ Assert.Equal([28, 34, 42], new[] { MediaQuality.High, MediaQuality.Balanced, MediaQuality.Small }.Select(HardwareVideo.Av1Quantizer));
+ Assert.Equal([112, 136, 168], new[] { MediaQuality.High, MediaQuality.Balanced, MediaQuality.Small }.Select(HardwareVideo.Av1QIndex));
+ Assert.Equal([23, 27, 31], new[] { MediaQuality.High, MediaQuality.Balanced, MediaQuality.Small }.Select(q => HardwareVideo.Quantizer("av1", q)));
+ // Every value inside the range each encoder accepts (NVENC -cq 0–63, AMF/VA-API 0–255, Quick Sync ICQ 1–51).
+ foreach (var quality in new[] { MediaQuality.High, MediaQuality.Balanced, MediaQuality.Small })
+ {
+ Assert.InRange(HardwareVideo.Av1Quantizer(quality), 1, 63);
+ Assert.InRange(HardwareVideo.Av1QIndex(quality) - 8, 0, 255);
+ Assert.InRange(HardwareVideo.Av1QIndex(quality), 0, 255);
+ Assert.InRange(HardwareVideo.Quantizer("av1", quality), 1, 51);
+ }
+
+ // No profile (each encoder picks Main; av1_nvenc has no -profile) and no tag, in MP4 as in MKV and WebM.
+ foreach (var (name, api) in new[] { ("av1_nvenc", HardwareApi.Nvenc), ("av1_qsv", HardwareApi.Qsv), ("av1_amf", HardwareApi.Amf), ("av1_vaapi", HardwareApi.Vaapi) })
+ {
+ foreach (var target in new[] { "mp4", "m4v", "mkv", "webm" })
+ {
+ var args = Codec(name, api, target, MediaQuality.Balanced);
+ Assert.DoesNotContain("-profile:v", args);
+ Assert.DoesNotContain("-tag:v", args);
+ Assert.DoesNotContain("-qp", args);
+ }
+ }
+ }
+
[Fact]
public void Ten_bit_and_hdr_stay_ten_bit_on_hevc_and_h264_stays_eight_bit()
{
@@ -130,6 +202,15 @@ public class HardwareEncodingTests(EngineFixture fx) : IClassFixture<EngineFixtu
Assert.True(HardwareVideo.TenBit("hevc", Hd with { PixelFormat = "p010le" }));
Assert.False(HardwareVideo.TenBit("hevc", Hd));
+ // AV1 keeps 10 bits as SVT-AV1 does: P010 with the colour tags, no profile to name.
+ var av1 = HardwareVideo.CodecArguments(new("av1_qsv", HardwareApi.Qsv), "mp4", MediaQuality.Balanced, hdr, 0);
+ Assert.Equal("p010le", After(av1, "-pix_fmt"));
+ Assert.Equal(("bt2020", "smpte2084", "bt2020nc"), (After(av1, "-color_primaries"), After(av1, "-color_trc"), After(av1, "-colorspace")));
+ Assert.DoesNotContain("-profile:v", av1);
+ Assert.True(HardwareVideo.TenBit("av1", hdr));
+ Assert.False(HardwareVideo.TenBit("av1", Hd));
+ Assert.Equal("nv12", After(HardwareVideo.CodecArguments(new("av1_nvenc", HardwareApi.Nvenc), "mkv", MediaQuality.Balanced, Hd, 0), "-pix_fmt"));
+
// 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));
@@ -172,6 +253,36 @@ public class HardwareEncodingTests(EngineFixture fx) : IClassFixture<EngineFixtu
HdClip, "work", encoders: new HashSet<string> { "aac" }, hardware: new HardwareEncoder("hevc_nvenc", HardwareApi.Nvenc)).Single().Arguments, "-c:v"));
}
+ [Fact]
+ public void The_plan_writes_av1_on_the_gpu_into_mp4_mkv_and_webm()
+ {
+ var av1 = new MediaOptions { HardwareEncoding = true, VideoCodec = VideoCodec.Av1 };
+ var qsv = new HardwareEncoder("av1_qsv", HardwareApi.Qsv);
+ var mp4 = Args("mp4", av1, qsv);
+ Assert.Equal(("av1_qsv", "27", "nv12", "+faststart"), (After(mp4, "-c:v"), After(mp4, "-global_quality"), After(mp4, "-pix_fmt"), After(mp4, "-movflags")));
+ Assert.DoesNotContain("-tag:v", mp4);
+ Assert.DoesNotContain("-crf", mp4);
+
+ // WebM: the GPU writes the video, the sound becomes Opus as usual.
+ var webm = Args("webm", av1, new HardwareEncoder("av1_nvenc", HardwareApi.Nvenc));
+ Assert.Equal(("av1_nvenc", "34", "libopus", "webm"), (After(webm, "-c:v"), After(webm, "-cq"), After(webm, "-c:a"), After(webm, "-f")));
+
+ // 10-bit HDR stays 10-bit; VA-API uploads it as P010.
+ var vaapi = Args("mkv", av1, new HardwareEncoder("av1_vaapi", HardwareApi.Vaapi), HdrClip);
+ Assert.Equal(("av1_vaapi", "136", "scale=w='trunc(iw/2)*2':h='trunc(ih/2)*2',format=p010le,hwupload"),
+ (After(vaapi, "-c:v"), After(vaapi, "-global_quality"), After(vaapi, "-vf")));
+ Assert.True(vaapi.ToList().IndexOf("-vaapi_device") < vaapi.ToList().IndexOf("-i"));
+
+ // Without a working encoder (or with one for another codec) SVT-AV1 encodes as before.
+ Assert.Equal("libsvtav1", After(Args("mp4", av1, null), "-c:v"));
+ Assert.Equal("libsvtav1", After(Args("mp4", av1, new HardwareEncoder("hevc_qsv", HardwareApi.Qsv)), "-c:v"));
+ Assert.Equal("h264_qsv", After(Args("mp4", new MediaOptions { HardwareEncoding = true }, new HardwareEncoder("h264_qsv", HardwareApi.Qsv)), "-c:v"));
+ Assert.Equal("libx264", After(Args("mp4", new MediaOptions { HardwareEncoding = true }, qsv), "-c:v"));
+ // A missing SVT-AV1 doesn't matter while the hardware encoder writes AV1.
+ Assert.Equal("av1_amf", After(MediaEncoding.Plan("in.mov", "out.mkv", "mkv", av1, HdClip, "work", encoders: new HashSet<string> { "aac" },
+ hardware: new HardwareEncoder("av1_amf", HardwareApi.Amf)).Single().Arguments, "-c:v"));
+ }
+
[Fact]
public void The_probe_is_a_tiny_test_encode_with_the_real_options()
{
@@ -187,6 +298,11 @@ public class HardwareEncodingTests(EngineFixture fx) : IClassFixture<EngineFixtu
var intelMac = HardwareVideo.ProbeArguments(new HardwareEncoder("h264_videotoolbox", HardwareApi.VideoToolbox, HardwareRateControl.Bitrate), false);
Assert.Contains("-b:v", intelMac);
Assert.DoesNotContain("-q:v", intelMac);
+
+ // AV1 is probed with its own options, 10-bit too: a chip without AV1 (or without 10-bit AV1) fails here.
+ var av1 = HardwareVideo.ProbeArguments(new HardwareEncoder("av1_qsv", HardwareApi.Qsv), tenBit: true);
+ Assert.Equal(("av1_qsv", "p010le", "27"), (After(av1, "-c:v"), After(av1, "-pix_fmt"), After(av1, "-global_quality")));
+ Assert.Equal(["-f", "null", "-"], av1.TakeLast(3));
}
// ───────────────────────── Software retry ─────────────────────────
@@ -292,6 +408,7 @@ public class HardwareEncodingTests(EngineFixture fx) : IClassFixture<EngineFixtu
[Theory]
[InlineData(VideoCodec.Default, "h264")]
[InlineData(VideoCodec.Hevc, "hevc")]
+ [InlineData(VideoCodec.Av1, "av1")]
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)");
@@ -311,6 +428,27 @@ public class HardwareEncodingTests(EngineFixture fx) : IClassFixture<EngineFixtu
Assert.DoesNotContain(logger.Entries, e => e.Level == LogLevel.Warning); // no software retry
}
+ /// <summary>
+ /// With the real probe: where a chip encodes AV1 the GPU writes it, elsewhere (CI, an older chip such as Intel Iris
+ /// Xe) the probes fail quietly and SVT-AV1 does. Either way the file is AV1 and no hardware encode had to be redone.
+ /// </summary>
+ [Fact]
+ public async Task An_av1_preset_with_hardware_encoding_writes_av1_with_or_without_a_capable_chip()
+ {
+ 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);
+ Assert.True(converter.GetStatus().IsAvailable);
+
+ var outputs = await converter.ConvertAsync(Step(source, "mov", "mp4", folder,
+ new MediaOptions { HardwareEncoding = true, Quality = MediaQuality.Small, VideoCodec = VideoCodec.Av1 }), null, CancellationToken.None);
+
+ Assert.Equal("av1", await CodecOfAsync(Assert.Single(outputs)));
+ Assert.DoesNotContain(logger.Entries, e => e.Level == LogLevel.Warning);
+ }
+
// ───────────────────────── Quick queries ─────────────────────────
[Fact]