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.

Convert video and audio with an optional FFmpeg engine

KnifeLemon70f186a50966
diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md
index 05fb3bc0..d35dbe13 100644
--- a/THIRD-PARTY-NOTICES.md
+++ b/THIRD-PARTY-NOTICES.md
@@ -40,6 +40,7 @@ Downloaded from their official release pages when the user chooses to install th
| H2Orestart (HWP/HWPX import for LibreOffice) | GPL-3.0 | https://github.com/ebandal/H2Orestart |
| Eclipse Temurin JRE (for H2Orestart) | GPL-2.0 with Classpath Exception | https://adoptium.net |
| Pandoc | GPL-2.0-or-later | https://github.com/jgm/pandoc |
+| FFmpeg 9.0.2 (gyan.dev "full_build-shared" Windows build; ffmpeg.exe, ffprobe.exe and their libraries, incl. x264, x265, libvpx, LAME, Opus, Vorbis, Theora, OpenCORE AMR) | GPL-3.0-or-later (the build is configured with `--enable-gpl --enable-version3`); FFmpeg itself LGPL-2.1-or-later | https://ffmpeg.org, build: https://www.gyan.dev/ffmpeg/builds/ (source: https://github.com/GyanD/codexffmpeg) |
These programs run as separate processes. Their source code is available from the linked projects.
diff --git a/build/fetch-engines.ps1 b/build/fetch-engines.ps1
index 932fa812..408a21a9 100644
--- a/build/fetch-engines.ps1
+++ b/build/fetch-engines.ps1
@@ -12,6 +12,7 @@
jre/ Eclipse Temurin JRE 21 (GPLv2 + Classpath Exception), used by H2Orestart
rhwp/ rhwp command line (MIT), HWP/HWPX -> PDF
pandoc/ Pandoc (GPL-2.0-or-later, separate program), Markdown/HTML and MD/HTML/ODT/RTF -> HWPX
+ ffmpeg/ FFmpeg (GPL-3.0 build, separate program), video and audio; bin/ffmpeg.exe + bin/ffprobe.exe
Every download is pinned to a version and verified with SHA-256 (src/Filee.Engines/Infrastructure/engines.json,
shared with the app). Downloads are cached in build/.cache.
@@ -114,6 +115,15 @@ if ('pandoc' -in $selected) {
if (-not (Test-Path (Join-Path $Destination 'pandoc\pandoc.exe'))) { throw 'pandoc.exe not found in the archive.' }
}
+if ('ffmpeg' -in $selected) {
+ # Same layout as the app's installer: the archive's single top folder is dropped, the programs stay in bin/.
+ $zip = Get-Engine 'ffmpeg'
+ Expand-Flat $zip (Join-Path $Destination 'ffmpeg')
+ foreach ($exe in 'ffmpeg.exe', 'ffprobe.exe') {
+ if (-not (Test-Path (Join-Path $Destination "ffmpeg\bin\$exe"))) { throw "$exe not found in the archive." }
+ }
+}
+
if ('jre' -in $selected) {
$zip = Get-Engine 'jre'
Expand-Flat $zip (Join-Path $Destination 'jre')
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 15adb4d1..47cb9f63 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -15,6 +15,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,
| rhwp | bundled with the installer (`engines/rhwp`) | HWP/HWPX → PDF, **HWP → HWPX, HWPX → HWP** |
| LibreOffice + H2Orestart + Java | **optional download** (~420 MB, 1.3 GB on disk) | older and rare formats only: DOC, XLS, PPT, RTF and OpenDocument → PDF and to each other, output as DOCX/ODT/ODS; HWP/HWPX → DOCX/ODT |
| Pandoc | **optional download** (~42 MB, 240 MB on disk) | Markdown ↔ DOCX/ODT/RTF, DOCX/ODT/HTML/RTF → Markdown, HTML ↔ DOCX/ODT |
+| FFmpeg | **optional download** (~100 MB, 272 MB on disk) | **all video and audio**: video ↔ video, video → animated GIF or a still frame, audio extraction, audio ↔ audio, GIF → MP4/WEBM/MOV |
DOCX, XLSX and PPTX → PDF need neither Microsoft Office nor LibreOffice: they are read in-process, written as HWPX
and rendered by rhwp. LibreOffice's cost is set so the built-in route always wins where one exists.
@@ -103,3 +104,47 @@ through the HWPX writer and then rhwp.
fails when two conversions share a profile).
- HWP/HWPX import comes from the H2Orestart extension, which is written in Java; Filee points LibreOffice at the
downloaded JRE (`-env:UNO_JAVA_JFW_JREHOME`).
+
+## FFmpeg
+
+`Media/FfmpegConverter.cs` converts every video format to every video format, to animated GIF, to a still PNG frame
+and to every audio format (the sound track); every audio format to every audio format; and GIF to MP4, WEBM and MOV.
+Same-format edges exist too, so "MP4 720p" works on MP4 files and "MP3 128k" on MP3 files.
+
+- The download is the gyan.dev **9.0.2 "full_build-shared"** Windows build (GPL-3.0, run as a separate program).
+ It is smaller than the "essentials" build (100 vs 115 MB download, 272 vs 329 MB on disk, because ffmpeg.exe and
+ ffprobe.exe share their libraries) and has a superset of its encoders. It links only Windows system DLLs; GPU
+ and Vulkan libraries are loaded only if present. Being over 60 MB, it is offered but not ticked on first run.
+- Container and codecs per target (`Media/MediaEncoding.cs`, every encoder checked with `ffmpeg -encoders`):
+
+ | Target | Written as |
+ |---|---|
+ | MP4, M4V, MOV, MKV, FLV, TS, M2TS, 3GP, 3G2 | H.264 (x264, preset medium, yuv420p) + AAC; MP4/M4V/MOV/3GP/3G2 with the index at the front (`+faststart`) |
+ | WEBM | VP9 (constant quality, speed 4, row multithreading) + Opus |
+ | AVI | MPEG-4 part 2 tagged XVID + CBR MP3 |
+ | WMV | WMV 8 (wmv2) + WMA 2 |
+ | MPG | MPEG-2 program stream: MPEG-2 video + MP2 |
+ | VOB | DVD-Video: 720×480 at 29.97 fps (NTSC) or 720×576 at 25 fps (PAL, for 25/50 fps sources), letterboxed into 4:3 or 16:9, AC-3 at 48 kHz, DVD mux rate |
+ | OGV | Theora + Vorbis |
+ | DV | DV25 with the same NTSC/PAL frames as VOB, 48 kHz stereo PCM |
+ | MXF | OP1a with long-GOP MPEG-2 + 48 kHz PCM |
+ | GIF | two passes: palettegen over the whole clip, then paletteuse; 15/12/10 fps and at most 640/480/320 px wide (High/Balanced/Small) |
+ | MP3 · M4A/M4B · AAC · OGG · OPUS · WEBA · MKA · WMA · MP2 · AC3 · AMR | LAME VBR (V0/V2/V5) or CBR · AAC · AAC (ADTS) · Vorbis · Opus · Opus · Opus · WMA 2 · MP2 · AC-3 · AMR-NB 12.2k (8 kHz mono) |
+ | WAV · AIFF · AU · CAF · VOC · FLAC | 16-bit PCM (RF64 for WAV over 4 GB) · FLAC |
+
+- Preset options (`MediaOptions`): *Quality* picks CRF 18/23/28 (x264), 24/32/38 (VP9), quantizer 2/4/7 (MPEG-4,
+ WMV, MPEG-2), Theora 8/6/4 and the audio bitrates (e.g. AAC 256/192/128 kbit/s per stereo pair); *MaxHeight*
+ scales down only, keeps the aspect ratio and even sizes; *AudioBitrateKbps* overrides the audio bitrate (snapped to
+ the MP3/MP2/AC-3 bitrate tables); *RemoveAudio* drops the sound.
+- The first video stream (cover pictures excluded) and the first audio stream are converted; files without sound
+ still convert to video. Title, artist and other tags and chapters are kept, album art too for MP3, M4A, M4B and
+ FLAC. Portrait phone videos are turned upright. Odd sizes are evened out, frame rates that MPEG-2/MXF/MPEG-4 part 2
+ cannot store are converted, and channels WMA or AMR cannot hold are mixed down.
+- Progress comes from `-progress` (position ÷ duration from ffprobe); the GIF palette pass reports per-frame stats of
+ a discarded copy of its frames. Cancelling kills the process tree and deletes the partial output. There is no
+ time limit, but FFmpeg is stopped when it reports nothing for 10 minutes. At most two conversions run at a time
+ (FFmpeg's encoders use every core themselves).
+- Video → PNG writes one still frame (a tenth into the video, where the picture has usually faded in); the image
+ engines turn it into JPG, WEBP, PDF, …. The GIF edge costs more, so these routes never go through an animated GIF
+ of the whole video. Images and PDFs → MP4/WEBM/MOV are possible through GIF (a slideshow of the PDF's pages, a
+ single frame for a photo).
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index ca855ad4..75df9fb9 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -240,6 +240,8 @@
"engines.package.libreoffice.description": "Only needed for older and less common formats: DOC, XLS, PPT and OpenDocument files, conversions to DOCX, ODT and ODS, and HWP → DOCX (includes the H2Orestart filter and Java). DOCX, XLSX, PPTX and CSV convert without it.",
"engines.package.pandoc.name": "Pandoc (HTML and Markdown ↔ Word)",
"engines.package.pandoc.description": "Markdown ↔ DOCX, ODT and RTF, and HTML, ODT and RTF → HWPX. Markdown → PDF, HWPX, HTML and TXT, and DOCX → HWPX work without it.",
+ "engines.package.ffmpeg.name": "FFmpeg (video and audio)",
+ "engines.package.ffmpeg.description": "Video ↔ video (MP4, MOV, MKV, WEBM, AVI, WMV and more), video → animated GIF or a still image, sound from videos (→ MP3, M4A, WAV …), audio ↔ audio (MP3, M4A, FLAC, WAV, OGG, OPUS and more) and GIF → MP4, WEBM, MOV. Only needed for video and audio.",
"engines.package.size": "Download {0} · {1} on disk",
"engines.install": "Install",
"engines.cancel": "Cancel",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index c45e8822..d05c6559 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -240,6 +240,8 @@
"engines.package.libreoffice.description": "오래되었거나 흔하지 않은 형식에만 필요해요: DOC·XLS·PPT·OpenDocument 파일, DOCX·ODT·ODS로 변환, HWP → DOCX (H2Orestart 필터와 Java 포함). DOCX·XLSX·PPTX·CSV는 없어도 변환돼요.",
"engines.package.pandoc.name": "Pandoc (HTML·마크다운 ↔ 워드)",
"engines.package.pandoc.description": "마크다운 ↔ DOCX·ODT·RTF 변환과 HTML·ODT·RTF → HWPX 변환을 추가합니다. 마크다운 → PDF·HWPX·HTML·TXT와 DOCX → HWPX는 없어도 됩니다.",
+ "engines.package.ffmpeg.name": "FFmpeg (동영상·오디오)",
+ "engines.package.ffmpeg.description": "동영상 ↔ 동영상(MP4·MOV·MKV·WEBM·AVI·WMV 등), 동영상 → 움직이는 GIF·정지 이미지, 동영상에서 소리 추출(→ MP3·M4A·WAV 등), 오디오 ↔ 오디오(MP3·M4A·FLAC·WAV·OGG·OPUS 등), GIF → MP4·WEBM·MOV 변환을 추가해요. 동영상과 오디오에만 필요해요.",
"engines.package.size": "다운로드 {0} · 설치 후 {1}",
"engines.install": "설치",
"engines.cancel": "취소",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index de9260d8..13eb21b7 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -240,6 +240,8 @@
"engines.package.libreoffice.description": "仅用于较旧或不常见的格式:DOC、XLS、PPT 和 OpenDocument 文件,转换为 DOCX、ODT 和 ODS,以及 HWP → DOCX(含 H2Orestart 过滤器和 Java)。DOCX、XLSX、PPTX 和 CSV 无需它即可转换。",
"engines.package.pandoc.name": "Pandoc(HTML 与 Markdown ↔ Word)",
"engines.package.pandoc.description": "支持 Markdown ↔ DOCX、ODT、RTF,以及 HTML、ODT、RTF → HWPX。Markdown → PDF、HWPX、HTML、TXT 和 DOCX → HWPX 无需此引擎。",
+ "engines.package.ffmpeg.name": "FFmpeg(视频和音频)",
+ "engines.package.ffmpeg.description": "支持视频 ↔ 视频(MP4、MOV、MKV、WEBM、AVI、WMV 等)、视频 → GIF 动图或静态图片、从视频提取声音(→ MP3、M4A、WAV 等)、音频 ↔ 音频(MP3、M4A、FLAC、WAV、OGG、OPUS 等)以及 GIF → MP4、WEBM、MOV。仅视频和音频转换需要它。",
"engines.package.size": "下载 {0} · 占用 {1}",
"engines.install": "安装",
"engines.cancel": "取消",
diff --git a/src/Filee.App/ViewModels/EngineSetupViewModel.cs b/src/Filee.App/ViewModels/EngineSetupViewModel.cs
index 04e564f6..f78dd4a1 100644
--- a/src/Filee.App/ViewModels/EngineSetupViewModel.cs
+++ b/src/Filee.App/ViewModels/EngineSetupViewModel.cs
@@ -20,13 +20,16 @@ public sealed partial class EngineSetupViewModel : ObservableObject
_loc = loc;
foreach (var package in Packages)
{
- // LibreOffice is large and only needed for older formats (DOC, XLS, PPT, OpenDocument): offered, not
- // pre-selected.
- package.Selected = !package.IsInstalled && package.Package.Id != "libreoffice";
+ // Large downloads are offered, not pre-selected: LibreOffice is only needed for older formats (DOC, XLS,
+ // PPT, OpenDocument), FFmpeg (~100 MB) only for video and audio.
+ package.Selected = !package.IsInstalled && Filee.Engines.Infrastructure.EngineDownloads.DownloadSize(package.Package) < PreselectLimit;
package.PropertyChanged += OnPackageChanged;
}
}
+ /// <summary>Packages whose download is smaller than this (bytes) are ticked on first run.</summary>
+ public const long PreselectLimit = 60_000_000;
+
public IReadOnlyList<EnginePackageState> Packages => _downloads.Packages;
/// <summary>Installation was started from this window (checkboxes lock, progress shows).</summary>
diff --git a/src/Filee.Engines/EngineRegistry.cs b/src/Filee.Engines/EngineRegistry.cs
index 31b45a74..8ae5c311 100644
--- a/src/Filee.Engines/EngineRegistry.cs
+++ b/src/Filee.Engines/EngineRegistry.cs
@@ -5,6 +5,7 @@ using Filee.Engines.Hwp;
using Filee.Engines.Hwp.Hwpx;
using Filee.Engines.Infrastructure;
using Filee.Engines.Magick;
+using Filee.Engines.Media;
using Filee.Engines.Office;
using Filee.Engines.Pdf;
using Filee.Engines.Text;
@@ -29,6 +30,7 @@ public static class EngineRegistry
new MarkdownConverter(),
new SpreadsheetConverter(),
new HwpxConverter(),
+ new FfmpegConverter(),
new PandocConverter(),
new LibreOfficeConverter(env),
];
diff --git a/src/Filee.Engines/Infrastructure/EngineDownloads.cs b/src/Filee.Engines/Infrastructure/EngineDownloads.cs
index ace46435..400a4c01 100644
--- a/src/Filee.Engines/Infrastructure/EngineDownloads.cs
+++ b/src/Filee.Engines/Infrastructure/EngineDownloads.cs
@@ -28,6 +28,7 @@ public static class EngineDownloads
[
new("libreoffice", ["libreoffice", "h2orestart", "jre"], 1_265_000_000, ["libreoffice"]),
new("pandoc", ["pandoc"], 236_000_000, ["pandoc"]),
+ new("ffmpeg", ["ffmpeg"], 272_000_000, ["ffmpeg"]),
];
/// <summary>Total download size of a package in bytes.</summary>
diff --git a/src/Filee.Engines/Infrastructure/engines.json b/src/Filee.Engines/Infrastructure/engines.json
index 02d25ed7..750472a0 100644
--- a/src/Filee.Engines/Infrastructure/engines.json
+++ b/src/Filee.Engines/Infrastructure/engines.json
@@ -35,6 +35,13 @@
"sha256": "CBEA23BC37861361BBC534BC0675E5BC67B36F712072490F82A9BF410D7C04D8",
"size": 606257,
"kind": "oxt"
+ },
+ "ffmpeg": {
+ "version": "9.0.2",
+ "url": "https://github.com/GyanD/codexffmpeg/releases/download/9.0.2/ffmpeg-9.0.2-full_build-shared.zip",
+ "sha256": "8D31E162F1616E37AAB3FA2DB991B97E1B8DBEB1C8465FD81A81BE16FF91B328",
+ "size": 99899672,
+ "kind": "zip"
}
}
}
diff --git a/src/Filee.Engines/Media/FfmpegConverter.cs b/src/Filee.Engines/Media/FfmpegConverter.cs
new file mode 100644
index 00000000..10cedc05
--- /dev/null
+++ b/src/Filee.Engines/Media/FfmpegConverter.cs
@@ -0,0 +1,176 @@
+// Video and audio conversion with FFmpeg (GPL-3.0 build, an optional download run as a separate program in
+// engines/ffmpeg): video ↔ video, video → animated GIF or a still frame, audio extraction, audio ↔ audio and
+// GIF → video.
+// Container and codec choices live in MediaEncoding, the process handling in FfmpegRunner.
+
+using System.Collections.Concurrent;
+using System.Diagnostics;
+using System.Text.RegularExpressions;
+using Filee.Core.Conversion;
+using Filee.Core.Formats;
+using Filee.Engines.Infrastructure;
+
+namespace Filee.Engines.Media;
+
+/// <summary>Converts video and audio files with Filee's own copy of FFmpeg.</summary>
+public sealed partial class FfmpegConverter : IConverter
+{
+ private static readonly ConcurrentDictionary<string, string> Versions = new();
+
+ private (string Ffmpeg, string Ffprobe)? _tools;
+
+ public string Id => "ffmpeg";
+ public string DisplayName => "FFmpeg";
+
+ /// <summary>FFmpeg's encoders use every core themselves; two runs keep the CPU busy between files.</summary>
+ public int MaxParallelism => 2;
+
+ public IReadOnlyList<ConversionEdge> Edges { get; } = BuildEdges();
+
+ /// <summary>
+ /// Every video format (read by FFmpeg's demuxers) → every video target, animated GIF, a still PNG frame and every
+ /// audio target; every audio format → every audio target (including itself: re-encode with another bitrate);
+ /// GIF → MP4, WEBM, MOV. Only formats the pinned build can write are targets (see MediaEncoding).
+ /// </summary>
+ /// <remarks>
+ /// The GIF edge costs more (slow, 256 colours), so video → JPG / PDF / TIFF … goes through the still frame
+ /// (video → PNG → image engines) and never renders an animated GIF of a whole film just to take one frame of it.
+ /// </remarks>
+ private static List<ConversionEdge> BuildEdges()
+ {
+ var videos = FormatRegistry.Known.Where(f => f.Category == FormatCategory.Video).Select(f => f.Id).ToList();
+ var audios = FormatRegistry.Known.Where(f => f.Category == FormatCategory.Audio).Select(f => f.Id);
+ var videoTargets = MediaEncoding.VideoTargets.Keys.Concat(MediaEncoding.AudioTargets.Keys).Append("png").ToList();
+ return
+ [
+ .. from source in videos from target in videoTargets select new ConversionEdge(source, target),
+ .. videos.Select(source => new ConversionEdge(source, "gif", 15)),
+ .. from source in audios from target in MediaEncoding.AudioTargets.Keys select new ConversionEdge(source, target),
+ .. MediaEncoding.GifToVideoTargets.Select(target => new ConversionEdge("gif", target)),
+ ];
+ }
+
+ public EngineStatus GetStatus()
+ {
+ _tools = Locate();
+ if (_tools is not { } tools)
+ return EngineStatus.Unavailable("engine.reason.not_installed");
+ try
+ {
+ return EngineStatus.Available($"{tools.Ffmpeg} (FFmpeg {VersionOf(tools.Ffmpeg)})");
+ }
+ catch (Exception ex) when (ex is InvalidOperationException or System.ComponentModel.Win32Exception or IOException)
+ {
+ // Present but broken, e.g. a DLL next to ffmpeg.exe is missing.
+ return EngineStatus.Unavailable("engine.reason.error", ex.Message);
+ }
+ }
+
+ public async Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ var (ffmpeg, ffprobe) = _tools ?? Locate() ?? throw new InvalidOperationException("FFmpeg was not found.");
+ var input = Path.GetFullPath(step.InputPath);
+ var info = await MediaInfo.ProbeAsync(ffprobe, input, cancellationToken);
+ progress?.Report(0.02);
+
+ var output = step.Output.Allocate(FormatRegistry.Get(step.To).PrimaryExtension);
+ if (output is null)
+ return [];
+
+ // Throws for a missing stream before anything is written (an existing file of that name stays untouched).
+ var passes = MediaEncoding.Plan(input, output, step.To, step.Preset.Media, info, step.WorkDirectory);
+ try
+ {
+ var done = 0.0;
+ foreach (var pass in passes)
+ {
+ await RunPassAsync(ffmpeg, pass, info.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.");
+ }
+ catch
+ {
+ // Never leave a half-written file where the user expects a finished one.
+ TryDelete(output);
+ throw;
+ }
+
+ progress?.Report(1);
+ return [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)
+ {
+ var total = duration?.TotalSeconds ?? 0;
+ Action<double>? onPosition = progress is null || total <= 0
+ ? null
+ : seconds => progress.Report(0.02 + 0.97 * (done + pass.Weight * Math.Clamp(seconds / total, 0, 1)));
+
+ ProcessResult result;
+ // Without a duration (raw streams) there is nothing to measure against: show an estimate instead.
+ using (total <= 0 ? ProgressEstimate.Start(progress, TimeSpan.FromSeconds(20), 0.02 + 0.97 * done, 0.02 + 0.97 * (done + pass.Weight)) : null)
+ result = await FfmpegRunner.RunAsync(ffmpeg, pass.Arguments, onPosition, cancellationToken);
+
+ if (result.ExitCode != 0)
+ {
+ var reason = FfmpegRunner.Summarize(result.StandardError);
+ throw new InvalidOperationException($"FFmpeg failed (exit code {result.ExitCode}){(reason.Length > 0 ? ": " + reason : ".")}");
+ }
+ }
+
+ /// <summary>
+ /// Filee's own FFmpeg (engines/ffmpeg, downloaded on demand; the programs are in its bin folder), never one
+ /// found elsewhere on the system.
+ /// </summary>
+ internal static (string Ffmpeg, string Ffprobe)? Locate()
+ {
+ if (EngineEnvironment.FindBundled("ffmpeg") is not { } folder)
+ return null;
+ var suffix = OperatingSystem.IsWindows() ? ".exe" : "";
+ var ffmpeg = EngineEnvironment.FirstExisting(Path.Combine(folder, "bin", "ffmpeg" + suffix), Path.Combine(folder, "ffmpeg" + suffix));
+ var ffprobe = EngineEnvironment.FirstExisting(Path.Combine(folder, "bin", "ffprobe" + suffix), Path.Combine(folder, "ffprobe" + suffix));
+ return ffmpeg is null || ffprobe is null ? null : (ffmpeg, ffprobe);
+ }
+
+ /// <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) =>
+ Versions.GetOrAdd($"{ffmpeg}|{File.GetLastWriteTimeUtc(ffmpeg).Ticks}", _ =>
+ {
+ using var process = Process.Start(new ProcessStartInfo(ffmpeg, "-hide_banner -version")
+ {
+ 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))
+ {
+ 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}).");
+ // "ffmpeg version 9.0.2-full_build-www.gyan.dev Copyright …" → "9.0.2"
+ var match = VersionPattern().Match(firstLine);
+ return match.Success ? match.Groups[1].Value : firstLine.Trim();
+ });
+
+ [GeneratedRegex(@"version\s+n?(\d+(?:\.\d+)+|\S+)")]
+ private static partial Regex VersionPattern();
+
+ private static void TryDelete(string path)
+ {
+ try
+ {
+ if (File.Exists(path))
+ File.Delete(path);
+ }
+ catch (IOException) { }
+ catch (UnauthorizedAccessException) { }
+ }
+}
diff --git a/src/Filee.Engines/Media/FfmpegRunner.cs b/src/Filee.Engines/Media/FfmpegRunner.cs
new file mode 100644
index 00000000..b1629129
--- /dev/null
+++ b/src/Filee.Engines/Media/FfmpegRunner.cs
@@ -0,0 +1,160 @@
+// Runs ffmpeg.exe and turns its machine-readable progress output into a position in seconds. Unlike ProcessRunner
+// there is no overall timeout (a feature film legitimately encodes for an hour); a process that stops reporting
+// for a long time is treated as hung and killed, and cancellation always kills the whole process tree.
+
+using System.Diagnostics;
+using System.Globalization;
+using System.Text;
+using Filee.Engines.Infrastructure;
+
+namespace Filee.Engines.Media;
+
+/// <summary>Starts FFmpeg with live progress, a stall watchdog and cancellation.</summary>
+internal static class FfmpegRunner
+{
+ /// <summary>
+ /// FFmpeg reports its progress every half second while it works, so this long without a single line means it
+ /// is stuck (e.g. on a stalled network share).
+ /// </summary>
+ public static readonly TimeSpan DefaultStallTimeout = TimeSpan.FromMinutes(10);
+
+ private static readonly TimeSpan WatchInterval = TimeSpan.FromSeconds(1);
+ private const int KeptErrorLines = 40;
+
+ /// <summary>Key of the per-frame stats line the GIF palette pass writes (seconds, see MediaEncoding).</summary>
+ public const string FrameTimeKey = "frame_time";
+
+ /// <summary>
+ /// Runs ffmpeg with <paramref name="arguments"/> and waits for it to exit.
+ /// </summary>
+ /// <param name="onPosition">Called with the output position in seconds whenever FFmpeg reports one.</param>
+ /// <param name="stallTimeout">How long FFmpeg may stay silent before it is killed; <see cref="DefaultStallTimeout"/> when null.</param>
+ /// <returns>Exit code and the last lines FFmpeg wrote to stderr (its error messages).</returns>
+ public static async Task<ProcessResult> RunAsync(
+ string ffmpeg, IReadOnlyList<string> arguments, Action<double>? onPosition, CancellationToken cancellationToken,
+ TimeSpan? stallTimeout = null)
+ {
+ var psi = new ProcessStartInfo(ffmpeg)
+ {
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ StandardOutputEncoding = Encoding.UTF8,
+ StandardErrorEncoding = Encoding.UTF8,
+ WorkingDirectory = Path.GetDirectoryName(ffmpeg) ?? "",
+ };
+ foreach (var argument in arguments)
+ psi.ArgumentList.Add(argument);
+
+ using var process = new Process { StartInfo = psi };
+ var lastActivity = Stopwatch.GetTimestamp();
+ var errors = new Queue<string>();
+ process.OutputDataReceived += (_, e) =>
+ {
+ if (e.Data is null)
+ return;
+ Volatile.Write(ref lastActivity, Stopwatch.GetTimestamp());
+ if (ParsePosition(e.Data) is { } seconds)
+ onPosition?.Invoke(seconds);
+ };
+ process.ErrorDataReceived += (_, e) =>
+ {
+ if (e.Data is null)
+ return;
+ Volatile.Write(ref lastActivity, Stopwatch.GetTimestamp());
+ lock (errors)
+ {
+ errors.Enqueue(e.Data);
+ if (errors.Count > KeptErrorLines)
+ errors.Dequeue();
+ }
+ };
+
+ if (!process.Start())
+ throw new InvalidOperationException($"Could not start {ffmpeg}.");
+ process.BeginOutputReadLine();
+ process.BeginErrorReadLine();
+
+ var limit = stallTimeout ?? DefaultStallTimeout;
+ try
+ {
+ var exited = process.WaitForExitAsync(cancellationToken);
+ while (!exited.IsCompleted)
+ {
+ await Task.WhenAny(exited, Task.Delay(WatchInterval, cancellationToken));
+ cancellationToken.ThrowIfCancellationRequested();
+ if (!exited.IsCompleted && Stopwatch.GetElapsedTime(Volatile.Read(ref lastActivity)) > limit)
+ {
+ Kill(process);
+ throw new TimeoutException($"FFmpeg stopped responding (no progress for {limit.TotalMinutes:0} minutes) and was stopped.");
+ }
+ }
+ await exited;
+ }
+ catch (OperationCanceledException)
+ {
+ Kill(process);
+ throw;
+ }
+
+ // Make sure the asynchronous readers have delivered the last lines.
+ process.WaitForExit();
+ string stderr;
+ lock (errors)
+ stderr = string.Join(Environment.NewLine, errors);
+ return new ProcessResult(process.ExitCode, "", stderr);
+ }
+
+ /// <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.
+ /// </summary>
+ internal static double? ParsePosition(string line)
+ {
+ var separator = line.IndexOf('=');
+ if (separator <= 0)
+ return null;
+ var key = line.AsSpan(0, separator);
+ var value = line.AsSpan(separator + 1).Trim();
+ if (key.SequenceEqual("out_time_us"))
+ return long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var microseconds) && microseconds >= 0
+ ? microseconds / 1_000_000.0
+ : null; // "N/A" before the first frame
+ if (key.SequenceEqual(FrameTimeKey))
+ return double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var seconds) && seconds >= 0 && double.IsFinite(seconds)
+ ? seconds
+ : null;
+ return null;
+ }
+
+ /// <summary>A short, readable version of FFmpeg's error output: its last distinct lines, without log prefixes.</summary>
+ internal static string Summarize(string stderr)
+ {
+ var lines = stderr.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
+ .Select(StripPrefix)
+ .Where(l => l.Length > 0)
+ .Distinct()
+ .TakeLast(3);
+ return string.Join(" ", lines);
+ }
+
+ /// <summary>"[aost#0:1/wmav2 @ 0000012a] too many channels" → "too many channels".</summary>
+ private static string StripPrefix(string line)
+ {
+ while (line.StartsWith('[') && line.IndexOf("] ", StringComparison.Ordinal) is var end and > 0)
+ line = line[(end + 2)..].TrimStart();
+ return line;
+ }
+
+ private static void Kill(Process process)
+ {
+ try
+ {
+ if (!process.HasExited)
+ process.Kill(entireProcessTree: true);
+ }
+ catch (InvalidOperationException) { }
+ catch (System.ComponentModel.Win32Exception) { }
+ }
+}
diff --git a/src/Filee.Engines/Media/MediaEncoding.cs b/src/Filee.Engines/Media/MediaEncoding.cs
new file mode 100644
index 00000000..d1ad97b5
--- /dev/null
+++ b/src/Filee.Engines/Media/MediaEncoding.cs
@@ -0,0 +1,457 @@
+// Which container and codecs Filee writes for every video and audio format, and the FFmpeg command lines for them.
+// Pure (no processes), so the choices are unit tested without FFmpeg. Every encoder and muxer used here was checked
+// against the pinned FFmpeg build (engines.json: `ffmpeg -encoders` / `ffmpeg -muxers`).
+
+using System.Globalization;
+using Filee.Core.Presets;
+
+namespace Filee.Engines.Media;
+
+/// <summary>How one target format is written.</summary>
+/// <param name="Muxer">FFmpeg container name (<c>-f</c>), always given explicitly: some extensions are ambiguous.</param>
+/// <param name="VideoCodec">FFmpeg video encoder, null for audio-only formats.</param>
+/// <param name="AudioCodec">FFmpeg audio encoder.</param>
+internal sealed record MediaTarget(string Muxer, string? VideoCodec, string AudioCodec);
+
+/// <summary>One run of ffmpeg.</summary>
+/// <param name="Arguments">Command line after the executable.</param>
+/// <param name="Weight">Share of the whole conversion's progress (the passes of one conversion add up to 1).</param>
+internal sealed record FfmpegPass(IReadOnlyList<string> Arguments, double Weight);
+
+/// <summary>Encoding choices and command lines.</summary>
+internal static class MediaEncoding
+{
+ /// <summary>
+ /// Video formats Filee writes. H.264 + AAC wherever the container allows it: it plays on every browser, phone,
+ /// TV and editor. The other containers get the codecs their players expect.
+ /// </summary>
+ public static IReadOnlyDictionary<string, MediaTarget> VideoTargets { get; } = new Dictionary<string, MediaTarget>
+ {
+ ["mp4"] = new("mp4", "libx264", "aac"),
+ // Apple's M4V is MP4 (FFmpeg's "m4v" muxer would write a raw MPEG-4 part 2 stream instead).
+ ["m4v"] = new("mp4", "libx264", "aac"),
+ ["mov"] = new("mov", "libx264", "aac"),
+ ["mkv"] = new("matroska", "libx264", "aac"),
+ ["flv"] = new("flv", "libx264", "aac"),
+ ["ts"] = new("mpegts", "libx264", "aac"),
+ ["m2ts"] = new("mpegts", "libx264", "aac"), // + 192-byte Blu-ray packets, see ContainerArguments
+ ["3gp"] = new("3gp", "libx264", "aac"),
+ ["3g2"] = new("3g2", "libx264", "aac"),
+ // The WebM specification allows only VP8/VP9/AV1 with Vorbis/Opus.
+ ["webm"] = new("webm", "libvpx-vp9", "libopus"),
+ // MPEG-4 part 2 tagged XVID + CBR MP3: what DVD players, old TVs and Windows' built-in codecs read in AVI.
+ ["avi"] = new("avi", "mpeg4", "libmp3lame"),
+ ["wmv"] = new("asf", "wmv2", "wmav2"),
+ // MPEG-2 program stream ("vob" is FFmpeg's plain MPEG-2 PS muxer; "mpeg" would write an MPEG-1 system stream).
+ ["mpg"] = new("vob", "mpeg2video", "mp2"),
+ // DVD-Video compliant: 720×480 NTSC / 720×576 PAL, AC-3, DVD mux rate and navigation packets.
+ ["vob"] = new("dvd", "mpeg2video", "ac3"),
+ ["ogv"] = new("ogg", "libtheora", "libvorbis"),
+ // DV has fixed frame sizes and rates (see DvdOrDvFilter) and 48 kHz PCM.
+ ["dv"] = new("dv", "dvvideo", "pcm_s16le"),
+ // MXF OP1a with long-GOP MPEG-2 (XDCAM style) and 48 kHz PCM: what broadcast and editing tools import.
+ ["mxf"] = new("mxf", "mpeg2video", "pcm_s16le"),
+ };
+
+ /// <summary>Audio formats Filee writes (also the targets of audio extraction from video).</summary>
+ public static IReadOnlyDictionary<string, MediaTarget> AudioTargets { get; } = new Dictionary<string, MediaTarget>
+ {
+ ["mp3"] = new("mp3", null, "libmp3lame"),
+ // The iPod muxer writes the M4A/M4B brands iTunes and phones expect.
+ ["m4a"] = new("ipod", null, "aac"),
+ ["m4b"] = new("ipod", null, "aac"),
+ ["aac"] = new("adts", null, "aac"),
+ ["wav"] = new("wav", null, "pcm_s16le"),
+ ["flac"] = new("flac", null, "flac"),
+ ["ogg"] = new("ogg", null, "libvorbis"),
+ ["opus"] = new("opus", null, "libopus"),
+ ["wma"] = new("asf", null, "wmav2"),
+ ["aiff"] = new("aiff", null, "pcm_s16be"),
+ ["ac3"] = new("ac3", null, "ac3"),
+ // AMR-NB (OpenCORE): 8 kHz mono speech, what phones record voice memos in.
+ ["amr"] = new("amr", null, "libopencore_amrnb"),
+ ["au"] = new("au", null, "pcm_s16be"),
+ // CAF with big-endian linear PCM, the variant Apple's own tools write by default.
+ ["caf"] = new("caf", null, "pcm_s16be"),
+ ["weba"] = new("webm", null, "libopus"),
+ ["mka"] = new("matroska", null, "libopus"),
+ ["mp2"] = new("mp2", null, "mp2"),
+ // 16-bit PCM in an extended block: exact sample rate (8-bit blocks can only approximate it).
+ ["voc"] = new("voc", null, "pcm_s16le"),
+ };
+
+ /// <summary>Formats an animated GIF can be turned into.</summary>
+ public static IReadOnlyList<string> GifToVideoTargets { get; } = ["mp4", "webm", "mov"];
+
+ /// <summary>Audio targets that can carry a cover picture (album art) copied from the source.</summary>
+ private static readonly HashSet<string> CoverTargets = ["mp3", "m4a", "m4b", "flac"];
+
+ /// <summary>
+ /// Frame rates MPEG-2 (and MXF, which only knows broadcast rates) can signal exactly. Other rates are
+ /// converted to the nearest one by dropping or repeating frames.
+ /// </summary>
+ private static readonly (int Num, int Den)[] BroadcastRates =
+ [(24000, 1001), (24, 1), (25, 1), (30000, 1001), (30, 1), (50, 1), (60000, 1001), (60, 1)];
+
+ /// <summary>Container metadata that describes the source file, not the content: not copied.</summary>
+ private static readonly string[] SourceOnlyTags = ["major_brand", "minor_version", "compatible_brands"];
+
+ /// <summary>Global arguments of every run: no banner, no keyboard input, only errors on stderr, overwrite.</summary>
+ private static readonly string[] Common = ["-hide_banner", "-nostdin", "-nostats", "-v", "error", "-y"];
+
+ /// <summary>
+ /// The ffmpeg runs that convert <paramref name="input"/> into <paramref name="output"/> in format
+ /// <paramref name="target"/>.
+ /// </summary>
+ /// <param name="workDirectory">Scratch folder (the GIF palette goes there).</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)
+ {
+ if (target == "gif")
+ return AnimatedGif(input, output, options, info, workDirectory);
+ 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), 1)];
+ if (AudioTargets.TryGetValue(target, out var audio))
+ return [new FfmpegPass(Audio(input, output, target, audio, options, info), 1)];
+ throw new NotSupportedException($"FFmpeg cannot write '{target}'.");
+ }
+
+ // ───────────────────────── Video ─────────────────────────
+
+ private static List<string> Video(string input, string output, string target, MediaTarget spec, MediaOptions options, MediaInfo info)
+ {
+ 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.
+ var audio = options.RemoveAudio ? null : info.Audio;
+
+ List<string> args = [.. Common, "-i", input, "-map", "0:V:0"];
+ if (audio is not null)
+ args.AddRange(["-map", "0:a:0"]);
+
+ var pal = IsPal(video.FrameRate);
+ args.AddRange(["-vf", target is "vob" or "dv" ? DvdOrDvFilter(video, pal) : ScaleFilter(options.MaxHeight)]);
+ args.AddRange(VideoCodecArguments(target, spec.VideoCodec!, options.Quality, video, pal));
+
+ if (audio is null)
+ args.Add("-an");
+ else
+ args.AddRange(AudioCodecArguments(target, spec.AudioCodec, options, audio, inVideo: true));
+
+ args.AddRange(MetadataArguments());
+ args.AddRange(ContainerArguments(target));
+ // Sparse or late-starting streams (subtitles-like audio) otherwise fail with "too many packets buffered".
+ args.AddRange(["-max_muxing_queue_size", "4096", "-f", spec.Muxer, "-progress", "pipe:1", output]);
+ return args;
+ }
+
+ /// <summary>
+ /// Scales down to <paramref name="maxHeight"/> (never up) keeping the aspect ratio, and makes both sides even,
+ /// which 4:2:0 encoders require (an odd-sized GIF or phone video would otherwise fail).
+ /// </summary>
+ internal static string ScaleFilter(int maxHeight) => maxHeight > 0
+ ? $"scale=w=-2:h='trunc(min(ih,{Math.Max(16, maxHeight)})/2)*2'"
+ : "scale=w='trunc(iw/2)*2':h='trunc(ih/2)*2'";
+
+ /// <summary>
+ /// DVD and DV frames are always 720×480 (NTSC) or 720×576 (PAL), shown at 4:3 or 16:9 through the pixel aspect.
+ /// The picture is fitted into whichever of the two is closer to its own shape, with black bars for the rest.
+ /// </summary>
+ internal static string DvdOrDvFilter(VideoStreamInfo video, bool pal)
+ {
+ var height = pal ? 576 : 480;
+ var aspect = video.DisplayAspect;
+ var wide = aspect >= 1.55; // between 4:3 (1.33) and 16:9 (1.78)
+ var frameAspect = wide ? 16 / 9.0 : 4 / 3.0;
+ var (w, h) = aspect > frameAspect
+ ? (720, Even(height * frameAspect / aspect))
+ : (Even(720 * aspect / frameAspect), height);
+ return $"scale={w}:{h},pad=720:{height}:(ow-iw)/2:(oh-ih)/2:black,setdar={(wide ? "16/9" : "4/3")}";
+ }
+
+ /// <summary>PAL (25 fps) for 25/50 fps sources, NTSC (29.97 fps) for everything else.</summary>
+ internal static bool IsPal(double fps) => Math.Abs(fps - 25) < 0.5 || Math.Abs(fps - 50) < 1 || Math.Abs(fps - 12.5) < 0.3;
+
+ private static IEnumerable<string> VideoCodecArguments(string target, string codec, MediaQuality quality, VideoStreamInfo video, bool pal)
+ {
+ // Constant quantizer for the MPEG-style codecs: 2 is the best useful value, 4 good, 7 visibly compressed.
+ var quantizer = Text(Choose(quality, 2, 4, 7));
+ switch (codec)
+ {
+ case "libx264":
+ // CRF 18 is visually lossless, 23 is x264's default, 28 is clearly smaller. Preset medium is x264's
+ // default speed/size balance; yuv420p (8-bit 4:2:0) is the only format every H.264 decoder plays.
+ return ["-c:v", "libx264", "-preset", "medium", "-crf", Text(Choose(quality, 18, 23, 28)), "-pix_fmt", "yuv420p"];
+ case "libvpx-vp9":
+ // Constant quality mode (-b:v 0 + CRF). Row multithreading and speed 4 keep VP9 usable on a desktop:
+ // the slower speeds gain little size for several times the encoding time.
+ return ["-c:v", "libvpx-vp9", "-b:v", "0", "-crf", Text(Choose(quality, 24, 32, 38)), "-row-mt", "1",
+ "-deadline", "good", "-cpu-used", "4", "-pix_fmt", "yuv420p"];
+ case "mpeg4":
+ // GOP 250 because the encoder's default of 12 bloats files. The frame rate is fixed because MPEG-4
+ // part 2 cannot store the fine time bases of phone videos.
+ return ["-c:v", "mpeg4", "-tag:v", "XVID", "-q:v", quantizer, "-g", "250", "-bf", "2",
+ "-pix_fmt", "yuv420p", .. FrameRate(NearestRate(video.FrameRate))];
+ case "wmv2":
+ return ["-c:v", "wmv2", "-q:v", quantizer, "-g", "250", "-pix_fmt", "yuv420p",
+ .. FrameRate(NearestRate(video.FrameRate))];
+ case "libtheora":
+ // Theora quality 0-10.
+ return ["-c:v", "libtheora", "-q:v", Text(Choose(quality, 8, 6, 4)), "-pix_fmt", "yuv420p",
+ .. FrameRate(NearestRate(video.FrameRate))];
+ case "mpeg2video" when target == "vob":
+ // DVD-Video limits: peak 9.8 Mbit/s for video + audio, 1.8 Mbit VBV buffer, GOP of 15 (PAL) / 18 (NTSC).
+ return ["-c:v", "mpeg2video", "-b:v", Text(Choose(quality, 8000, 6000, 4000)) + "k", "-maxrate", "9000k",
+ "-minrate", "0", "-bufsize", "1835k", "-g", pal ? "15" : "18", "-bf", "2", "-pix_fmt", "yuv420p",
+ "-r", pal ? "25" : "30000/1001"];
+ case "mpeg2video":
+ // mpg and mxf: constant quantizer, broadcast GOP of 15 and a frame rate MPEG-2 can signal.
+ return ["-c:v", "mpeg2video", "-q:v", quantizer, "-g", "15", "-bf", "2", "-pix_fmt", "yuv420p",
+ "-r", BroadcastRate(video.FrameRate)];
+ case "dvvideo":
+ // DV is fixed at 25 Mbit/s: NTSC samples colour 4:1:1, PAL 4:2:0.
+ return ["-c:v", "dvvideo", "-pix_fmt", pal ? "yuv420p" : "yuv411p", "-r", pal ? "25" : "30000/1001"];
+ default:
+ throw new NotSupportedException(codec);
+ }
+ }
+
+ /// <summary><c>-r</c> for a rate, nothing when the source rate is unknown (FFmpeg then keeps its own guess).</summary>
+ private static string[] FrameRate(string? rate) => rate is null ? [] : ["-r", rate];
+
+ /// <summary>
+ /// The source rate as a simple fraction: exact NTSC/film/PAL rates are kept, anything else (variable frame rate
+ /// phone videos report averages like 29.87) is rounded to whole frames per second.
+ /// </summary>
+ internal static string? NearestRate(double fps)
+ {
+ if (fps <= 0)
+ return null;
+ foreach (var (num, den) in BroadcastRates)
+ {
+ if (Math.Abs(fps - (double)num / den) < 0.01)
+ return den == 1 ? num.ToString(CultureInfo.InvariantCulture) : $"{num}/{den}";
+ }
+ return Math.Clamp((int)Math.Round(fps), 1, 120).ToString(CultureInfo.InvariantCulture);
+ }
+
+ /// <summary>The broadcast rate closest to <paramref name="fps"/> (PAL's 25 when unknown).</summary>
+ internal static string BroadcastRate(double fps)
+ {
+ if (fps <= 0)
+ return "25";
+ var (num, den) = BroadcastRates.MinBy(r => Math.Abs(fps - (double)r.Num / r.Den));
+ return den == 1 ? num.ToString(CultureInfo.InvariantCulture) : $"{num}/{den}";
+ }
+
+ private static IEnumerable<string> ContainerArguments(string target) => target switch
+ {
+ // Moves the index to the front so playback (and web streaming) can start before the file is loaded.
+ "mp4" or "m4v" or "mov" or "3gp" or "3g2" or "m4a" or "m4b" => ["-movflags", "+faststart"],
+ // Blu-ray / AVCHD transport stream: 192-byte packets with timestamps.
+ "m2ts" => ["-mpegts_m2ts_mode", "1"],
+ // DVD program stream: 10.08 Mbit/s mux rate and 2 KB sectors.
+ "vob" => ["-muxrate", "10080000", "-packetsize", "2048"],
+ // ID3v2.3 is what Windows Explorer and most car stereos read (FFmpeg writes 2.4 by default).
+ "mp3" => ["-id3v2_version", "3"],
+ // WAV is limited to 4 GB; long recordings switch to RF64 automatically.
+ "wav" => ["-rf64", "auto"],
+ _ => [],
+ };
+
+ private static IEnumerable<string> MetadataArguments()
+ {
+ // Keep title, artist, dates, … (chapters are kept by default); an empty value removes a tag.
+ yield return "-map_metadata";
+ yield return "0";
+ foreach (var tag in SourceOnlyTags)
+ {
+ yield return "-metadata";
+ yield return tag + "=";
+ }
+ }
+
+ // ───────────────────────── Audio ─────────────────────────
+
+ private static List<string> Audio(string input, string output, string target, MediaTarget spec, MediaOptions options, MediaInfo info)
+ {
+ var audio = info.Audio ?? throw new InvalidOperationException("The file has no audio track.");
+ List<string> args = [.. Common, "-i", input, "-map", "0:a:0"];
+ if (info.CoverStreamIndex is { } cover && CoverTargets.Contains(target))
+ args.AddRange(["-map", $"0:{cover}", "-c:v", "copy", "-disposition:v:0", "attached_pic"]);
+ args.AddRange(AudioCodecArguments(target, spec.AudioCodec, options, audio, inVideo: false));
+ args.AddRange(MetadataArguments());
+ args.AddRange(ContainerArguments(target));
+ args.AddRange(["-f", spec.Muxer, "-progress", "pipe:1", output]);
+ return args;
+ }
+
+ /// <summary>
+ /// Encoder options for one audio codec. <see cref="MediaOptions.AudioBitrateKbps"/> wins when set (clamped to
+ /// what the codec accepts); otherwise the quality picks a bitrate or VBR level. Lossless and PCM codecs ignore
+ /// both. Channel counts the codec cannot store are mixed down.
+ /// </summary>
+ private static List<string> AudioCodecArguments(string target, string codec, MediaOptions options, AudioStreamInfo audio, bool inVideo)
+ {
+ var quality = options.Quality;
+ var requested = options.AudioBitrateKbps;
+ var channels = audio.Channels > 0 ? audio.Channels : 2;
+ List<string> args = ["-c:a", codec];
+
+ switch (codec)
+ {
+ case "aac":
+ // Per stereo pair: 256 kbit/s is transparent, 192 excellent, 128 fine for speech and small files.
+ args.AddRange(Bitrate(requested > 0 ? requested : Scaled(Choose(quality, 256, 192, 128), channels), 16, 256 * channels));
+ break;
+ case "libopus":
+ // Opus is transparent at about 128 kbit/s for stereo; 64 is still good for music.
+ args.AddRange(Bitrate(requested > 0 ? requested : Scaled(Choose(quality, 160, 128, 64), channels), 6, 256 * channels));
+ break;
+ case "libmp3lame" when requested > 0 || inVideo:
+ // Constant bitrate (variable-bitrate MP3 confuses AVI players' audio sync) from the MP3 bitrate table.
+ args.AddRange(Bitrate(Snap(requested > 0 ? requested : Choose(quality, 256, 192, 128), Mp3Bitrates), 32, 320));
+ break;
+ case "libmp3lame":
+ // LAME's VBR presets: V0 ≈ 245, V2 ≈ 190, V5 ≈ 130 kbit/s.
+ args.AddRange(["-q:a", Text(Choose(quality, 0, 2, 5))]);
+ break;
+ case "libvorbis" when requested > 0:
+ args.AddRange(Bitrate(requested, 32, 500));
+ break;
+ case "libvorbis":
+ // Vorbis quality 6 ≈ 192, 4 ≈ 128, 2 ≈ 96 kbit/s.
+ args.AddRange(["-q:a", Text(Choose(quality, 6, 4, 2))]);
+ break;
+ case "wmav2":
+ // WMA 2 stores at most two channels.
+ args.AddRange(Bitrate(requested > 0 ? requested : Choose(quality, 192, 128, 96), 32, 320));
+ if (channels > 2)
+ args.AddRange(["-ac", "2"]);
+ break;
+ case "mp2":
+ // Layer II allows only the bitrates of its table, and those only at 32 kHz or more.
+ args.AddRange(Bitrate(Snap(requested > 0 ? requested : Choose(quality, 320, 224, 160), Mp2Bitrates), 32, 384));
+ if (audio.SampleRate is > 0 and < 32000)
+ args.AddRange(["-ar", "32000"]);
+ break;
+ case "ac3" when target == "vob":
+ // DVD audio is 48 kHz; 448 kbit/s is the DVD maximum for 5.1, 192 the usual stereo rate.
+ args.AddRange(Bitrate(Snap(requested > 0 ? requested : channels > 2 ? 448 : 192, Ac3Bitrates), 64, 448));
+ args.AddRange(["-ar", "48000"]);
+ break;
+ case "ac3":
+ // Without a bitrate the encoder picks the standard rate for the channel layout (192k stereo, 448k 5.1).
+ if (requested > 0)
+ args.AddRange(Bitrate(Snap(requested, Ac3Bitrates), 32, 640));
+ break;
+ case "libopencore_amrnb":
+ // AMR-NB is defined for 8 kHz mono only; 12.2 kbit/s is its best mode.
+ args.AddRange(["-ar", "8000", "-ac", "1", "-b:a", "12.2k"]);
+ break;
+ case "pcm_s16le" when target is "dv":
+ args.AddRange(["-ar", "48000", "-ac", "2"]);
+ break;
+ case "pcm_s16le" when target is "mxf":
+ // MXF (SMPTE 377) carries 48 kHz audio only.
+ args.AddRange(["-ar", "48000"]);
+ break;
+ case "pcm_s16le" when target is "voc" && channels > 2:
+ args.AddRange(["-ac", "2"]);
+ break;
+ }
+ return args;
+ }
+
+ /// <summary>Bitrate for a stereo pair scaled to the channel count (mono gets half, 5.1 three times as much).</summary>
+ private static int Scaled(int stereoKbps, int channels) => stereoKbps * Math.Clamp(channels, 1, 8) / 2;
+
+ private static string[] Bitrate(int kbps, int min, int max) => ["-b:a", Text(Math.Clamp(kbps, min, Math.Max(min, max))) + "k"];
+
+ /// <summary>The largest allowed bitrate not above <paramref name="kbps"/> (the smallest one if all are above).</summary>
+ internal static int Snap(int kbps, int[] allowed) => allowed.Where(a => a <= kbps).DefaultIfEmpty(allowed[0]).Max();
+
+ private static readonly int[] Mp3Bitrates = [32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320];
+ private static readonly int[] Mp2Bitrates = [32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384];
+ private static readonly int[] Ac3Bitrates = [32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448, 512, 576, 640];
+
+ // ───────────────────────── Animated GIF ─────────────────────────
+
+ /// <summary>
+ /// Animated GIF in two passes: the first finds the 256 colours that suit the whole clip best (palettegen), the
+ /// second maps every frame to them (paletteuse). A single pass with a fixed palette looks banded; generating
+ /// the palette in the same run would keep every frame in memory until the end. Frame rate and width are limited
+ /// by the quality setting because GIF stores every frame uncompressed-ish and grows fast.
+ /// </summary>
+ private static List<FfmpegPass> AnimatedGif(string input, string output, MediaOptions options, MediaInfo info, string workDirectory)
+ {
+ var video = info.Video ?? throw new InvalidOperationException("The file has no video stream.");
+ var quality = options.Quality;
+ var chain = GifFrames(video, options.MaxHeight, fps: Choose(quality, 15, 12, 10), maxWidth: Choose(quality, 640, 480, 320));
+ var palette = Path.Combine(workDirectory, $"palette-{Guid.NewGuid():N}.png");
+ var colors = Choose(quality, 256, 256, 128);
+ // Error diffusion looks best; ordered (Bayer) dithering compresses much better because it does not flicker.
+ var dither = Choose(quality, "sierra2_4a", "bayer:bayer_scale=4", "bayer:bayer_scale=5");
+
+ // Pass 1 reports no output time until the palette is written at the very end, so a second, discarded copy
+ // of the frames goes to a null output whose per-frame stats (frame_time=<seconds>) serve as progress.
+ List<string> first =
+ [
+ .. Common, "-i", input,
+ "-filter_complex", $"[0:V:0]{chain},split[a][b];[a]palettegen=max_colors={colors}[palette]",
+ "-map", "[palette]", "-frames:v", "1", "-update", "1", "-f", "image2", palette,
+ "-map", "[b]", "-stats_enc_pre", "pipe:1", "-stats_enc_pre_fmt", FfmpegRunner.FrameTimeKey + "={t}", "-f", "null", "-",
+ ];
+ List<string> second =
+ [
+ .. Common, "-i", input, "-i", palette,
+ "-filter_complex", $"[0:V:0]{chain}[frames];[frames][1:v]paletteuse=dither={dither}:diff_mode=rectangle[gif]",
+ "-map", "[gif]", "-loop", "0", "-f", "gif", "-progress", "pipe:1", output,
+ ];
+ return [new FfmpegPass(first, 0.4), new FfmpegPass(second, 0.6)];
+ }
+
+ /// <summary>Frame rate, square pixels and size of the GIF frames (never upscaled).</summary>
+ private static string GifFrames(VideoStreamInfo video, int maxHeight, int fps, int maxWidth)
+ {
+ var height = maxHeight > 0 ? $"'min(ih,{Math.Max(16, maxHeight)})'" : "ih";
+ return $"fps={fps},{SquarePixels(video)}scale=w='min(iw,{maxWidth})':h={height}:force_original_aspect_ratio=decrease:flags=lanczos";
+ }
+
+ /// <summary>Images have no pixel aspect ratio: anamorphic video (DV, DVD) is stretched to square pixels first.</summary>
+ private static string SquarePixels(VideoStreamInfo video) =>
+ Math.Abs(video.SampleAspect - 1) > 0.01 ? "scale=w='trunc(iw*sar/2)*2':h=ih,setsar=1," : "";
+
+ // ───────────────────────── Still frame ─────────────────────────
+
+ /// <summary>
+ /// One full-size PNG frame from a tenth into the video (the first frames are often black), the start for video →
+ /// image conversions (the image engines take it from there). Without this edge the route planner would reach
+ /// images through an animated GIF of the whole video.
+ /// </summary>
+ private static List<string> PosterFrame(string input, string output, MediaInfo info)
+ {
+ var video = info.Video ?? throw new InvalidOperationException("The file has no video stream.");
+ var seconds = (info.Duration?.TotalSeconds ?? 0) / 10;
+ return
+ [
+ .. Common, "-ss", seconds.ToString("0.###", CultureInfo.InvariantCulture), "-i", input, "-map", "0:V:0",
+ "-vf", SquarePixels(video) + "null", "-frames:v", "1", "-update", "1", "-c:v", "png", "-f", "image2",
+ "-progress", "pipe:1", output,
+ ];
+ }
+
+ // ───────────────────────── Helpers ─────────────────────────
+
+ 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);
+
+ private static int Even(double value) => Math.Max(2, (int)Math.Round(value / 2) * 2);
+}
diff --git a/src/Filee.Engines/Media/MediaInfo.cs b/src/Filee.Engines/Media/MediaInfo.cs
new file mode 100644
index 00000000..6472d02b
--- /dev/null
+++ b/src/Filee.Engines/Media/MediaInfo.cs
@@ -0,0 +1,160 @@
+// What the FFmpeg engine needs to know about a media file before encoding it (duration, first video and audio
+// stream, cover picture), read from ffprobe's JSON output.
+
+using System.Globalization;
+using System.Text.Json;
+using Filee.Engines.Infrastructure;
+
+namespace Filee.Engines.Media;
+
+/// <summary>The first real video stream of a file (cover pictures are not counted).</summary>
+/// <param name="Width">Coded width in pixels.</param>
+/// <param name="Height">Coded height in pixels.</param>
+/// <param name="SampleAspect">Pixel aspect ratio (1 for square pixels, 8/9 for NTSC DV 4:3, ...).</param>
+/// <param name="Rotation">Display rotation in degrees from the display matrix (phones record portrait video this way).</param>
+/// <param name="FrameRate">Average frames per second, 0 when unknown.</param>
+internal sealed record VideoStreamInfo(int Width, int Height, double SampleAspect, int Rotation, double FrameRate)
+{
+ /// <summary>True when the picture is shown turned by 90° (FFmpeg rotates it upright while decoding).</summary>
+ public bool IsRotated => Math.Abs(Rotation % 180) == 90;
+
+ /// <summary>Width ÷ height as the picture is displayed: pixel aspect and rotation applied.</summary>
+ public double DisplayAspect
+ {
+ get
+ {
+ if (Width <= 0 || Height <= 0)
+ return 16 / 9.0;
+ var aspect = Width * SampleAspect / Height;
+ return IsRotated ? 1 / aspect : aspect;
+ }
+ }
+}
+
+/// <summary>The first audio stream of a file.</summary>
+internal sealed record AudioStreamInfo(int Channels, int SampleRate);
+
+/// <summary>Summary of a media file.</summary>
+/// <param name="Duration">Playing time, null when the container does not say (raw streams).</param>
+/// <param name="Video">First video stream that is not a cover picture, if any.</param>
+/// <param name="Audio">First audio stream, if any.</param>
+/// <param name="CoverStreamIndex">Index of an embedded cover picture (JPEG or PNG) such as album art, if any.</param>
+internal sealed record MediaInfo(TimeSpan? Duration, VideoStreamInfo? Video, AudioStreamInfo? Audio, int? CoverStreamIndex)
+{
+ private static readonly TimeSpan ProbeTimeout = TimeSpan.FromMinutes(1);
+
+ /// <summary>Runs ffprobe on <paramref name="input"/>; throws with FFmpeg's message when the file cannot be read.</summary>
+ public static async Task<MediaInfo> ProbeAsync(string ffprobe, string input, CancellationToken cancellationToken)
+ {
+ var result = await ProcessRunner.RunAsync(ffprobe,
+ ["-hide_banner", "-v", "error", "-print_format", "json", "-show_format", "-show_streams", input],
+ ProbeTimeout, cancellationToken);
+ if (result.ExitCode != 0)
+ {
+ var reason = FfmpegRunner.Summarize(result.StandardError);
+ throw new InvalidOperationException($"FFmpeg cannot read this file{(reason.Length > 0 ? ": " + reason : ".")}");
+ }
+ return Parse(result.StandardOutput);
+ }
+
+ /// <summary>Parses the output of <c>ffprobe -print_format json -show_format -show_streams</c>.</summary>
+ public static MediaInfo Parse(string json)
+ {
+ using var document = JsonDocument.Parse(json);
+ var root = document.RootElement;
+
+ VideoStreamInfo? video = null;
+ AudioStreamInfo? audio = null;
+ int? cover = null;
+ double longestStream = 0;
+ if (root.TryGetProperty("streams", out var streams) && streams.ValueKind == JsonValueKind.Array)
+ {
+ foreach (var stream in streams.EnumerateArray())
+ {
+ longestStream = Math.Max(longestStream, Number(stream, "duration"));
+ switch (Text(stream, "codec_type"))
+ {
+ case "video" when IsAttachedPicture(stream):
+ // Album art and thumbnails: kept for audio targets that can hold a cover, never encoded as video.
+ if (cover is null && Text(stream, "codec_name") is "mjpeg" or "png")
+ cover = (int)Number(stream, "index");
+ break;
+ case "video" when video is null:
+ video = new VideoStreamInfo(
+ (int)Number(stream, "width"),
+ (int)Number(stream, "height"),
+ Ratio(Text(stream, "sample_aspect_ratio"), ':') is var sar and > 0 ? sar : 1,
+ RotationOf(stream),
+ FrameRateOf(stream));
+ break;
+ case "audio" when audio is null:
+ audio = new AudioStreamInfo((int)Number(stream, "channels"), (int)Number(stream, "sample_rate"));
+ break;
+ }
+ }
+ }
+
+ var seconds = root.TryGetProperty("format", out var format) ? Number(format, "duration") : 0;
+ if (seconds <= 0)
+ seconds = longestStream;
+ return new MediaInfo(seconds > 0 ? TimeSpan.FromSeconds(seconds) : null, video, audio, cover);
+ }
+
+ private static bool IsAttachedPicture(JsonElement stream) =>
+ stream.TryGetProperty("disposition", out var disposition)
+ && disposition.TryGetProperty("attached_pic", out var attached)
+ && attached.ValueKind == JsonValueKind.Number && attached.GetInt32() == 1;
+
+ /// <summary>Average frame rate; the nominal rate when the average is missing or nonsense (e.g. "0/0").</summary>
+ private static double FrameRateOf(JsonElement stream)
+ {
+ var average = Ratio(Text(stream, "avg_frame_rate"), '/');
+ if (average is > 0 and < 1000)
+ return average;
+ var nominal = Ratio(Text(stream, "r_frame_rate"), '/');
+ return nominal is > 0 and < 1000 ? nominal : 0;
+ }
+
+ /// <summary>Rotation from the display matrix side data, or the older "rotate" tag.</summary>
+ private static int RotationOf(JsonElement stream)
+ {
+ if (stream.TryGetProperty("side_data_list", out var sideData) && sideData.ValueKind == JsonValueKind.Array)
+ {
+ foreach (var item in sideData.EnumerateArray())
+ {
+ if (item.TryGetProperty("rotation", out var rotation) && rotation.ValueKind == JsonValueKind.Number)
+ return (int)Math.Round(rotation.GetDouble());
+ }
+ }
+ return stream.TryGetProperty("tags", out var tags) && int.TryParse(Text(tags, "rotate"), out var rotate) ? rotate : 0;
+ }
+
+ private static string? Text(JsonElement element, string name) =>
+ element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null;
+
+ /// <summary>ffprobe writes most numbers as strings ("2.000000"), some as JSON numbers.</summary>
+ private static double Number(JsonElement element, string name)
+ {
+ if (!element.TryGetProperty(name, out var value))
+ return 0;
+ if (value.ValueKind == JsonValueKind.Number)
+ return value.GetDouble();
+ return value.ValueKind == JsonValueKind.String
+ && double.TryParse(value.GetString(), NumberStyles.Float, CultureInfo.InvariantCulture, out var number)
+ && double.IsFinite(number)
+ ? number
+ : 0;
+ }
+
+ /// <summary>"30000/1001" → 29.97, "16:9" → 1.78; 0 for missing or invalid values.</summary>
+ private static double Ratio(string? text, char separator)
+ {
+ var parts = text?.Split(separator);
+ return parts is [var n, var d]
+ && double.TryParse(n, NumberStyles.Float, CultureInfo.InvariantCulture, out var num)
+ && double.TryParse(d, NumberStyles.Float, CultureInfo.InvariantCulture, out var den)
+ && den > 0
+ ? num / den
+ : 0;
+ }
+}
diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs
index 6810f317..1a8b72b3 100644
--- a/tests/Filee.App.Tests/RenderTests.cs
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@ -66,8 +66,10 @@ public class RenderTests
window.Show();
Pump();
- // Everything not installed is offered; all but the large LibreOffice pre-selected.
- Assert.All(vm.Packages.Where(p => !p.IsInstalled), p => Assert.Equal(p.Package.Id != "libreoffice", p.Selected));
+ // Everything not installed is offered; small downloads are pre-selected, the large LibreOffice and FFmpeg not.
+ Assert.All(vm.Packages.Where(p => !p.IsInstalled), p => Assert.Equal(
+ Filee.Engines.Infrastructure.EngineDownloads.DownloadSize(p.Package) < EngineSetupViewModel.PreselectLimit, p.Selected));
+ Assert.DoesNotContain(vm.Packages, p => p.Package.Id is "libreoffice" or "ffmpeg" && p.Selected);
Assert.Equal(vm.Packages.Any(p => p.Selected && p.CanInstall), vm.InstallCommand.CanExecute(null));
Save(window, $"engine-setup-{language}.png");
window.Close();
diff --git a/tests/Filee.Engines.Tests/MediaTests.cs b/tests/Filee.Engines.Tests/MediaTests.cs
new file mode 100644
index 00000000..f8aab33e
--- /dev/null
+++ b/tests/Filee.Engines.Tests/MediaTests.cs
@@ -0,0 +1,653 @@
+// Video and audio with FFmpeg: routes, command-line choices (no FFmpeg needed) and real conversions, which run only
+// when Filee's FFmpeg is installed (`pwsh build/fetch-engines.ps1 -Only ffmpeg`; CI does not install it). Inputs are
+// generated by FFmpeg itself (test pattern + sine tone) and every output is checked with ffprobe.
+
+using System.Diagnostics;
+using System.Globalization;
+using System.Text.Json;
+using Filee.Core.Conversion;
+using Filee.Core.Formats;
+using Filee.Core.Presets;
+using Filee.Engines.Infrastructure;
+using Filee.Engines.Media;
+
+namespace Filee.Engines.Tests;
+
+/// <summary>
+/// FFmpeg keeps every core busy: its tests run on their own, so timing-sensitive tests of other classes (progress
+/// estimates) are not starved meanwhile.
+/// </summary>
+[CollectionDefinition(nameof(FfmpegCollection), DisableParallelization = true)]
+public sealed class FfmpegCollection;
+
+[Collection(nameof(FfmpegCollection))]
+public class MediaTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private static readonly (string Ffmpeg, string Ffprobe)? Tools = FfmpegConverter.Locate();
+
+ private static void SkipUnlessInstalled() =>
+ Assert.SkipUnless(Tools is not null, "FFmpeg is not installed (pwsh build/fetch-engines.ps1 -Only ffmpeg)");
+
+ // ───────────────────────── Routes (no FFmpeg needed) ─────────────────────────
+
+ /// <summary>A planner that treats FFmpeg as installed, so these tests also run where it is not.</summary>
+ private RoutePlanner Planner() => fx.Catalog.CreatePlanner(["ffmpeg"]);
+
+ [Theory]
+ [InlineData("mp4", "webm")]
+ [InlineData("mov", "mp4")]
+ [InlineData("mkv", "mp4")]
+ [InlineData("avi", "mp4")]
+ [InlineData("mp4", "mp4")] // re-encode, e.g. the "MP4 720p" preset
+ [InlineData("mp4", "gif")]
+ [InlineData("mp4", "mp3")]
+ [InlineData("webm", "m4a")]
+ [InlineData("wav", "mp3")]
+ [InlineData("flac", "mp3")]
+ [InlineData("mp3", "mp3")] // re-encode, e.g. "MP3 128k"
+ [InlineData("m4a", "wav")]
+ [InlineData("amr", "mp3")]
+ [InlineData("gif", "mp4")]
+ [InlineData("gif", "webm")]
+ [InlineData("rm", "mp4")]
+ [InlineData("dss", "mp3")]
+ public void Media_conversions_take_one_ffmpeg_step(string from, string to)
+ {
+ var route = Planner().Plan(from, to);
+ Assert.NotNull(route);
+ var step = Assert.Single(route.Steps);
+ Assert.Equal("ffmpeg", step.Converter.Id);
+ }
+
+ [Theory]
+ [InlineData("mp4", "jpg", "magick")]
+ [InlineData("mkv", "webp", "magick")]
+ [InlineData("mov", "pdf", "pdfsharp")]
+ public void Video_to_images_goes_through_one_still_frame_not_an_animated_gif(string from, string to, string imageEngine)
+ {
+ var route = Planner().Plan(from, to);
+ Assert.NotNull(route);
+ Assert.Equal([("ffmpeg", from, "png"), (imageEngine, "png", to)], route.Steps.Select(s => (s.Converter.Id, s.From, s.To)));
+ }
+
+ [Fact]
+ public void Every_writable_video_and_audio_format_is_a_target()
+ {
+ // A new format in the catalog must get an encoding (or a documented reason why not) in MediaEncoding.
+ Assert.Equal(
+ FormatRegistry.Known.Where(f => f.Category == FormatCategory.Video && f.Writable).Select(f => f.Id).Order(),
+ MediaEncoding.VideoTargets.Keys.Order());
+ Assert.Equal(
+ FormatRegistry.Known.Where(f => f.Category == FormatCategory.Audio && f.Writable).Select(f => f.Id).Order(),
+ MediaEncoding.AudioTargets.Keys.Order());
+ }
+
+ [Fact]
+ public void Audio_is_never_turned_into_video_and_ffmpeg_is_unavailable_until_installed()
+ {
+ var planner = Planner();
+ Assert.Null(planner.Plan("mp3", "mp4"));
+ Assert.Null(planner.Plan("wav", "gif"));
+
+ var ffmpeg = fx.Converters.Single(c => c.Id == "ffmpeg");
+ Assert.Equal(Tools is not null, ffmpeg.GetStatus().IsAvailable);
+ if (Tools is null)
+ Assert.Equal("engine.reason.not_installed", ffmpeg.GetStatus().ReasonKey);
+ }
+
+ // ───────────────────────── Command lines (no FFmpeg needed) ─────────────────────────
+
+ private static readonly VideoStreamInfo Hd = new(1920, 1080, 1, 0, 29.97);
+
+ private static IReadOnlyList<string> Args(string target, MediaOptions? options = null, MediaInfo? info = null) =>
+ MediaEncoding.Plan("in.mkv", "out." + target, target, options ?? new MediaOptions(),
+ info ?? new MediaInfo(TimeSpan.FromSeconds(10), Hd, new AudioStreamInfo(6, 44100), null), "work").Single().Arguments;
+
+ private static string After(IReadOnlyList<string> args, string option) => args[args.ToList().IndexOf(option) + 1];
+
+ [Fact]
+ public void Quality_bitrate_and_size_options_reach_the_encoders()
+ {
+ var mp4 = Args("mp4", new MediaOptions { Quality = MediaQuality.High, MaxHeight = 720 });
+ Assert.Equal("libx264", After(mp4, "-c:v"));
+ Assert.Equal("18", After(mp4, "-crf"));
+ Assert.Equal("scale=w=-2:h='trunc(min(ih,720)/2)*2'", After(mp4, "-vf"));
+ Assert.Equal("+faststart", After(mp4, "-movflags"));
+ Assert.Equal("768k", After(mp4, "-b:a")); // 256k per stereo pair × 3 pairs (5.1)
+ Assert.Equal("mp4", After(mp4, "-f"));
+
+ var webm = Args("webm", new MediaOptions { Quality = MediaQuality.Small, RemoveAudio = true });
+ Assert.Equal(["-b:v", "0", "-crf", "38"], webm.SkipWhile(a => a != "-b:v").Take(4));
+ Assert.Contains("-an", webm);
+ Assert.DoesNotContain("0:a:0", webm);
+
+ var mp3 = Args("mp3", new MediaOptions { AudioBitrateKbps = 130 });
+ Assert.Equal("128k", After(mp3, "-b:a")); // snapped to the MP3 bitrate table
+ Assert.DoesNotContain("-q:a", mp3);
+ Assert.Equal("2", After(Args("mp3"), "-q:a")); // VBR V2 by default
+
+ Assert.Equal("2", After(Args("wma"), "-ac")); // WMA holds two channels at most
+ Assert.Equal("8000", After(Args("amr"), "-ar"));
+ Assert.Equal("30000/1001", After(Args("mpg"), "-r"));
+ Assert.Equal("448k", After(Args("vob"), "-b:a")); // DVD 5.1
+ }
+
+ [Fact]
+ public void Dvd_and_dv_frames_are_letterboxed_into_the_nearest_tv_shape()
+ {
+ // 16:9 source: fills the anamorphic 16:9 NTSC frame.
+ Assert.Equal("scale=720:480,pad=720:480:(ow-iw)/2:(oh-ih)/2:black,setdar=16/9", MediaEncoding.DvdOrDvFilter(Hd, pal: false));
+ // 4:3 source at PAL.
+ Assert.Equal("scale=720:576,pad=720:576:(ow-iw)/2:(oh-ih)/2:black,setdar=4/3",
+ MediaEncoding.DvdOrDvFilter(new VideoStreamInfo(640, 480, 1, 0, 25), pal: true));
+ // Cinemascope 2.39:1: 16:9 frame with bars above and below.
+ Assert.Equal("scale=720:358,pad=720:480:(ow-iw)/2:(oh-ih)/2:black,setdar=16/9",
+ MediaEncoding.DvdOrDvFilter(new VideoStreamInfo(1920, 804, 1, 0, 24), pal: false));
+ // Portrait phone video (landscape pixels + 90° rotation): 4:3 frame with bars left and right.
+ Assert.Equal("scale=304:480,pad=720:480:(ow-iw)/2:(oh-ih)/2:black,setdar=4/3",
+ MediaEncoding.DvdOrDvFilter(new VideoStreamInfo(1920, 1080, 1, -90, 30), pal: false));
+
+ Assert.True(MediaEncoding.IsPal(25));
+ Assert.True(MediaEncoding.IsPal(50));
+ Assert.False(MediaEncoding.IsPal(29.97));
+ Assert.False(MediaEncoding.IsPal(0));
+ }
+
+ [Theory]
+ [InlineData(29.97003, "30000/1001", "30000/1001")]
+ [InlineData(25, "25", "25")]
+ [InlineData(29.87, "30", "30000/1001")]
+ [InlineData(15, "15", "24000/1001")]
+ [InlineData(0, null, "25")]
+ public void Frame_rates_are_made_encodable(double fps, string? nearest, string broadcast)
+ {
+ Assert.Equal(nearest, MediaEncoding.NearestRate(fps));
+ Assert.Equal(broadcast, MediaEncoding.BroadcastRate(fps));
+ }
+
+ [Fact]
+ public void Gif_uses_a_palette_pass_and_limits_size()
+ {
+ var passes = MediaEncoding.Plan("in.mp4", "out.gif", "gif", new MediaOptions { MaxHeight = 200 },
+ new MediaInfo(TimeSpan.FromSeconds(3), Hd, null, null), "work");
+ Assert.Equal(2, passes.Count);
+ Assert.Equal(1, passes.Sum(p => p.Weight), 6);
+ var first = passes[0].Arguments;
+ var palette = After(first, "image2");
+ Assert.StartsWith(Path.Combine("work", "palette-"), palette);
+ Assert.Contains("palettegen", After(first, "-filter_complex"));
+ var second = passes[1].Arguments;
+ Assert.Equal(palette, second[second.ToList().LastIndexOf("-i") + 1]);
+ Assert.Contains("fps=12,scale=w='min(iw,480)':h='min(ih,200)'", After(second, "-filter_complex"));
+ Assert.Contains("paletteuse", After(second, "-filter_complex"));
+ }
+
+ [Fact]
+ public void Missing_streams_are_reported_clearly()
+ {
+ var silent = new MediaInfo(TimeSpan.FromSeconds(1), Hd, null, null);
+ var noVideo = new MediaInfo(TimeSpan.FromSeconds(1), null, new AudioStreamInfo(2, 48000), null);
+ Assert.Equal("The file has no audio track.", Assert.Throws<InvalidOperationException>(() => Args("mp3", info: silent)).Message);
+ Assert.Equal("The file has no video stream.", Assert.Throws<InvalidOperationException>(() => Args("mp4", info: noVideo)).Message);
+ // Video without sound converts to video without an audio track.
+ Assert.Contains("-an", Args("mkv", info: silent));
+ }
+
+ [Fact]
+ public void Probe_output_is_parsed()
+ {
+ const string json = """
+ {
+ "streams": [
+ { "index": 0, "codec_name": "h264", "codec_type": "video", "width": 1920, "height": 1080,
+ "sample_aspect_ratio": "1:1", "r_frame_rate": "30/1", "avg_frame_rate": "30000/1001",
+ "disposition": { "attached_pic": 0 }, "side_data_list": [ { "side_data_type": "Display Matrix", "rotation": -90 } ] },
+ { "index": 1, "codec_name": "aac", "codec_type": "audio", "channels": 2, "sample_rate": "48000", "duration": "12.5" },
+ { "index": 2, "codec_name": "mjpeg", "codec_type": "video", "width": 300, "height": 300,
+ "disposition": { "attached_pic": 1 } }
+ ],
+ "format": { "duration": "12.480000" }
+ }
+ """;
+ var info = MediaInfo.Parse(json);
+ Assert.Equal(12.48, info.Duration!.Value.TotalSeconds, 3);
+ Assert.Equal(new VideoStreamInfo(1920, 1080, 1, -90, 30000 / 1001.0), info.Video);
+ Assert.Equal(9 / 16.0, info.Video!.DisplayAspect, 3);
+ Assert.Equal(new AudioStreamInfo(2, 48000), info.Audio);
+ Assert.Equal(2, info.CoverStreamIndex);
+
+ var raw = MediaInfo.Parse("""{ "streams": [ { "index": 0, "codec_type": "audio", "channels": 1, "sample_rate": "8000" } ], "format": {} }""");
+ Assert.Null(raw.Duration);
+ Assert.Null(raw.Video);
+ }
+
+ [Fact]
+ public void Ffmpeg_progress_and_errors_are_read()
+ {
+ Assert.Equal(2.5, FfmpegRunner.ParsePosition("out_time_us=2500000"));
+ Assert.Null(FfmpegRunner.ParsePosition("out_time_us=N/A"));
+ Assert.Equal(1.25, FfmpegRunner.ParsePosition("frame_time=1.25"));
+ Assert.Null(FfmpegRunner.ParsePosition("progress=continue"));
+ Assert.Equal("too many channels: got 6, need 2 or fewer Error while opening encoder",
+ FfmpegRunner.Summarize("[wmav2 @ 000001e0] too many channels: got 6, need 2 or fewer\r\n" +
+ "[aost#0:1/wmav2 @ 000001e0] [enc:wmav2 @ 000001e0] Error while opening encoder\r\n"));
+ }
+
+ // ───────────────────────── Real conversions ─────────────────────────
+
+ /// <summary>Writes a test clip with FFmpeg: moving test pattern (+ a 440 Hz tone unless <paramref name="audio"/> is false).</summary>
+ private static async Task<string> MakeClipAsync(string folder, string name, double seconds = 2, string size = "320x240", int fps = 25,
+ bool audio = true, int channels = 2, params string[] extra)
+ {
+ var path = Path.Combine(folder, name);
+ List<string> args =
+ [
+ "-hide_banner", "-nostdin", "-v", "error", "-y",
+ "-f", "lavfi", "-i", $"testsrc2=size={size}:rate={fps}:duration={seconds.ToString(CultureInfo.InvariantCulture)}",
+ ];
+ if (audio)
+ args.AddRange(["-f", "lavfi", "-i", $"sine=frequency=440:sample_rate=44100:duration={seconds.ToString(CultureInfo.InvariantCulture)}",
+ "-ac", channels.ToString(CultureInfo.InvariantCulture)]);
+ args.AddRange(extra);
+ args.Add(path);
+ await RunAsync(Tools!.Value.Ffmpeg, args);
+ return path;
+ }
+
+ /// <summary>A WAV tone (44.1 kHz stereo).</summary>
+ private static async Task<string> MakeToneAsync(string folder, string name, double seconds = 2)
+ {
+ var path = Path.Combine(folder, name);
+ await RunAsync(Tools!.Value.Ffmpeg, ["-hide_banner", "-nostdin", "-v", "error", "-y", "-f", "lavfi",
+ "-i", $"sine=frequency=440:sample_rate=44100:duration={seconds.ToString(CultureInfo.InvariantCulture)}", "-ac", "2", path]);
+ return path;
+ }
+
+ private static async Task RunAsync(string exe, IEnumerable<string> args)
+ {
+ var result = await ProcessRunner.RunAsync(exe, args, TimeSpan.FromMinutes(2), CancellationToken.None);
+ Assert.True(result.ExitCode == 0, result.StandardError);
+ }
+
+ /// <summary>What ffprobe sees in a file.</summary>
+ private sealed record Probed(double Duration, List<Track> Streams)
+ {
+ public Track? Video => Streams.FirstOrDefault(s => s.Type == "video" && !s.Cover);
+ public Track? Audio => Streams.FirstOrDefault(s => s.Type == "audio");
+ }
+
+ private sealed record Track(string Type, string Codec, int Width, int Height, int Channels, int SampleRate, long BitRate, bool Cover, int Frames);
+
+ private static async Task<Probed> ProbeAsync(string path)
+ {
+ var result = await ProcessRunner.RunAsync(Tools!.Value.Ffprobe,
+ ["-v", "error", "-count_frames", "-print_format", "json", "-show_format", "-show_streams", path],
+ TimeSpan.FromMinutes(1), CancellationToken.None);
+ Assert.True(result.ExitCode == 0, $"ffprobe {path}: {result.StandardError}");
+ using var json = JsonDocument.Parse(result.StandardOutput);
+ static string S(JsonElement e, string name) => e.TryGetProperty(name, out var v) ? v.ToString() : "";
+ static long N(JsonElement e, string name) => long.TryParse(S(e, name), out var n) ? n : 0;
+ var streams = json.RootElement.GetProperty("streams").EnumerateArray().Select(s => new Track(
+ S(s, "codec_type"), S(s, "codec_name"), (int)N(s, "width"), (int)N(s, "height"), (int)N(s, "channels"),
+ (int)N(s, "sample_rate"), N(s, "bit_rate"),
+ s.TryGetProperty("disposition", out var d) && d.TryGetProperty("attached_pic", out var a) && a.GetInt32() == 1,
+ (int)N(s, "nb_read_frames"))).ToList();
+ var duration = double.TryParse(S(json.RootElement.GetProperty("format"), "duration"), NumberStyles.Float, CultureInfo.InvariantCulture, out var d2) ? d2 : 0;
+ return new Probed(duration, streams);
+ }
+
+ private async Task<string> ConvertAsync(string input, string target, MediaOptions? media = null)
+ {
+ var preset = new Preset { TargetFormat = target, Media = media ?? new MediaOptions() };
+ var job = await fx.ConvertAsync([input], preset);
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ var output = Assert.Single(job.Outputs);
+ Assert.Equal("." + FormatRegistry.Get(target).PrimaryExtension, Path.GetExtension(output));
+ return output;
+ }
+
+ /// <summary>ffprobe's codec name for each encoder Filee uses.</summary>
+ private static string Decoded(string encoder) => encoder switch
+ {
+ "libx264" => "h264",
+ "libvpx-vp9" => "vp9",
+ "libtheora" => "theora",
+ "libopus" => "opus",
+ "libmp3lame" => "mp3",
+ "libvorbis" => "vorbis",
+ "libopencore_amrnb" => "amr_nb",
+ _ => encoder,
+ };
+
+ [Theory]
+ [InlineData("webm")]
+ [InlineData("mov")]
+ [InlineData("mkv")]
+ [InlineData("avi")]
+ public async Task Mp4_converts_to_other_video_formats(string target)
+ {
+ SkipUnlessInstalled();
+ var source = await MakeClipAsync(fx.NewFolder(), "clip.mp4");
+ var probed = await ProbeAsync(await ConvertAsync(source, target));
+
+ var spec = MediaEncoding.VideoTargets[target];
+ Assert.Equal(Decoded(spec.VideoCodec!), probed.Video?.Codec);
+ Assert.Equal(Decoded(spec.AudioCodec), probed.Audio?.Codec);
+ Assert.Equal((320, 240), (probed.Video!.Width, probed.Video.Height));
+ Assert.InRange(probed.Duration, 1.7, 2.4);
+ }
+
+ [Fact]
+ public async Task Every_target_format_is_written_with_the_planned_codecs()
+ {
+ SkipUnlessInstalled();
+ var folder = fx.NewFolder();
+ var source = await MakeClipAsync(folder, "all.mp4", seconds: 1, size: "160x120");
+ var failures = new System.Collections.Concurrent.ConcurrentBag<string>();
+ var targets = MediaEncoding.VideoTargets.Concat(MediaEncoding.AudioTargets).ToList();
+ await Parallel.ForEachAsync(targets, new ParallelOptions { MaxDegreeOfParallelism = 3 }, async (entry, _) =>
+ {
+ var (target, spec) = entry;
+ try
+ {
+ var probed = await ProbeAsync(await ConvertAsync(source, target));
+ if (spec.VideoCodec is not null && probed.Video?.Codec != Decoded(spec.VideoCodec))
+ failures.Add($"{target}: video {probed.Video?.Codec}");
+ if (spec.VideoCodec is null && probed.Video is not null)
+ failures.Add($"{target}: unexpected video stream");
+ if (probed.Audio?.Codec != Decoded(spec.AudioCodec))
+ failures.Add($"{target}: audio {probed.Audio?.Codec}");
+ if (probed.Duration is < 0.7 or > 1.5)
+ failures.Add($"{target}: duration {probed.Duration}");
+ if (target is "vob" or "dv" && probed.Video is { } frame && (frame.Width, frame.Height) != (720, 576)) // 25 fps source = PAL
+ failures.Add($"{target}: frame {frame.Width}×{frame.Height}");
+ }
+ catch (Exception ex)
+ {
+ failures.Add($"{target}: {ex.Message}");
+ }
+ });
+ Assert.Empty(failures);
+ }
+
+ [Fact]
+ public async Task Video_becomes_an_animated_gif_and_back()
+ {
+ SkipUnlessInstalled();
+ var source = await MakeClipAsync(fx.NewFolder(), "anim.mp4", size: "640x360");
+ var gif = await ConvertAsync(source, "gif");
+ var probed = await ProbeAsync(gif);
+ Assert.Equal("gif", probed.Video?.Codec);
+ Assert.Equal((480, 270), (probed.Video!.Width, probed.Video.Height)); // Balanced: at most 480 px wide
+ Assert.InRange(probed.Video.Frames, 20, 30); // 2 s at 12 fps
+ Assert.Null(probed.Audio);
+
+ // GIF → MP4.
+ var mp4 = await ProbeAsync(await ConvertAsync(gif, "mp4"));
+ Assert.Equal("h264", mp4.Video?.Codec);
+ Assert.Equal((480, 270), (mp4.Video!.Width, mp4.Video.Height));
+ Assert.InRange(mp4.Duration, 1.5, 2.5);
+ }
+
+ [Fact]
+ public async Task Video_gives_a_still_frame_for_images()
+ {
+ SkipUnlessInstalled();
+ var folder = fx.NewFolder();
+ // Anamorphic 4:3 DV-style video: 720×480 pixels that are shown narrower than they are stored.
+ var source = await MakeClipAsync(folder, "still.mkv", seconds: 3, size: "720x480", extra: ["-vf", "setsar=8/9"]);
+
+ var png = await ProbeAsync(await ConvertAsync(source, "png"));
+ Assert.Equal("png", png.Video?.Codec);
+ Assert.Equal((640, 480), (png.Video!.Width, png.Video.Height)); // square pixels
+
+ var jpg = await ConvertAsync(source, "jpg");
+ using var image = new ImageMagick.MagickImage(jpg);
+ Assert.Equal((640u, 480u), (image.Width, image.Height));
+ }
+
+ [Fact]
+ public async Task Odd_sized_surround_video_is_encoded_everywhere()
+ {
+ SkipUnlessInstalled();
+ // 321×241 at 15 fps with 6 channels: odd sizes, a rate MPEG-2 cannot store and more channels than WMA/MP3 hold.
+ var source = await MakeClipAsync(fx.NewFolder(), "odd.mkv", size: "320x240", fps: 15, channels: 6,
+ extra: ["-vf", "pad=321:241", "-c:v", "libx264", "-pix_fmt", "yuv444p", "-c:a", "aac"]);
+ foreach (var target in new[] { "mp4", "wmv", "mpg", "avi", "wma", "mp3" })
+ {
+ var probed = await ProbeAsync(await ConvertAsync(source, target));
+ Assert.NotNull(probed.Audio);
+ if (probed.Video is { } video)
+ Assert.Equal((320, 240), (video.Width, video.Height));
+ }
+ }
+
+ [Theory]
+ [InlineData("mp3", "mp3")]
+ [InlineData("flac", "flac")]
+ [InlineData("ogg", "vorbis")]
+ [InlineData("opus", "opus")]
+ [InlineData("m4a", "aac")]
+ public async Task Wav_converts_to_audio_formats(string target, string codec)
+ {
+ SkipUnlessInstalled();
+ var source = await MakeToneAsync(fx.NewFolder(), "tone.wav");
+ var probed = await ProbeAsync(await ConvertAsync(source, target));
+ Assert.Equal(codec, probed.Audio?.Codec);
+ Assert.Equal(2, probed.Audio!.Channels);
+ Assert.Null(probed.Video);
+ Assert.InRange(probed.Duration, 1.8, 2.3);
+ }
+
+ [Fact]
+ public async Task Audio_is_extracted_from_video()
+ {
+ SkipUnlessInstalled();
+ var source = await MakeClipAsync(fx.NewFolder(), "talk.mp4");
+ var probed = await ProbeAsync(await ConvertAsync(source, "mp3"));
+ Assert.Equal("mp3", Assert.Single(probed.Streams).Codec);
+ Assert.InRange(probed.Duration, 1.8, 2.3);
+ }
+
+ [Fact]
+ public async Task Max_height_scales_down_only()
+ {
+ SkipUnlessInstalled();
+ var folder = fx.NewFolder();
+ var hd = await MakeClipAsync(folder, "hd.mp4", seconds: 1, size: "1920x1080", audio: false);
+ var probed = await ProbeAsync(await ConvertAsync(hd, "mp4", new MediaOptions { MaxHeight = 720 }));
+ Assert.Equal((1280, 720), (probed.Video!.Width, probed.Video.Height));
+
+ var small = await MakeClipAsync(folder, "small.mp4", seconds: 1, size: "320x240", audio: false);
+ probed = await ProbeAsync(await ConvertAsync(small, "mp4", new MediaOptions { MaxHeight = 720 }));
+ Assert.Equal((320, 240), (probed.Video!.Width, probed.Video.Height));
+ }
+
+ [Fact]
+ public async Task Portrait_phone_video_is_rotated_upright()
+ {
+ SkipUnlessInstalled();
+ var folder = fx.NewFolder();
+ var landscape = await MakeClipAsync(folder, "landscape.mp4", seconds: 1, size: "640x360");
+ // Like a phone: landscape pixels plus a display matrix that turns them by 90°.
+ var phone = Path.Combine(folder, "phone.mp4");
+ await RunAsync(Tools!.Value.Ffmpeg, ["-hide_banner", "-nostdin", "-v", "error", "-y", "-display_rotation", "90", "-i", landscape, "-c", "copy", phone]);
+
+ var probed = await ProbeAsync(await ConvertAsync(phone, "webm", new MediaOptions { MaxHeight = 320 }));
+ Assert.Equal((180, 320), (probed.Video!.Width, probed.Video.Height));
+ }
+
+ [Fact]
+ public async Task Remove_audio_and_audio_bitrate_options_apply()
+ {
+ SkipUnlessInstalled();
+ var folder = fx.NewFolder();
+ var source = await MakeClipAsync(folder, "options.mp4");
+
+ var muted = await ProbeAsync(await ConvertAsync(source, "mp4", new MediaOptions { RemoveAudio = true }));
+ Assert.NotNull(muted.Video);
+ Assert.Null(muted.Audio);
+
+ var tone = await MakeToneAsync(folder, "bitrate.wav");
+ var mp3 = await ProbeAsync(await ConvertAsync(tone, "mp3", new MediaOptions { AudioBitrateKbps = 128 }));
+ Assert.Equal(128_000, mp3.Audio!.BitRate);
+ var m4a = await ProbeAsync(await ConvertAsync(tone, "m4a", new MediaOptions { AudioBitrateKbps = 96 }));
+ Assert.InRange(m4a.Audio!.BitRate, 70_000, 110_000);
+ }
+
+ [Fact]
+ public async Task Video_without_sound_converts_but_has_no_audio_to_extract()
+ {
+ SkipUnlessInstalled();
+ var source = await MakeClipAsync(fx.NewFolder(), "silent.mp4", audio: false);
+ var probed = await ProbeAsync(await ConvertAsync(source, "webm"));
+ Assert.Equal("vp9", probed.Video?.Codec);
+ Assert.Null(probed.Audio);
+
+ var job = await fx.ConvertAsync([source], new Preset { TargetFormat = "mp3" });
+ var file = Assert.Single(job.Files);
+ Assert.Equal(FileState.Failed, file.State);
+ Assert.Contains("no audio track", file.ErrorDetail);
+ Assert.Empty(Directory.GetFiles(Path.GetDirectoryName(source)!, "*.mp3"));
+ }
+
+ [Fact]
+ public async Task Cover_art_and_tags_are_kept()
+ {
+ SkipUnlessInstalled();
+ var folder = fx.NewFolder();
+ var cover = Path.Combine(folder, "cover.png");
+ await RunAsync(Tools!.Value.Ffmpeg, ["-hide_banner", "-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=200x200", "-frames:v", "1", cover]);
+ var song = Path.Combine(folder, "song.mp3");
+ await RunAsync(Tools.Value.Ffmpeg, ["-hide_banner", "-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "sine=duration=2", "-i", cover,
+ "-map", "0:a", "-map", "1:v", "-c:v", "copy", "-disposition:v:0", "attached_pic", "-metadata", "title=노래 제목", song]);
+
+ foreach (var target in new[] { "flac", "m4a" })
+ {
+ var output = await ConvertAsync(song, target);
+ var probed = await ProbeAsync(output);
+ Assert.Contains(probed.Streams, s => s.Cover && s.Codec == "png");
+ var tags = await ProcessRunner.RunAsync(Tools.Value.Ffprobe, ["-v", "error", "-show_entries", "format_tags=title,major_brand", "-of", "json", output],
+ TimeSpan.FromMinutes(1), CancellationToken.None);
+ Assert.Contains("노래 제목", tags.StandardOutput);
+ }
+ }
+
+ // ───────────────────────── Progress and cancellation ─────────────────────────
+
+ private sealed class FolderAllocator(string folder) : IOutputAllocator
+ {
+ public List<string> Allocated { get; } = [];
+
+ public string? Allocate(string extension, string? suffix = null)
+ {
+ var path = Path.Combine(folder, $"out{suffix}.{extension}");
+ Allocated.Add(path);
+ return path;
+ }
+ }
+
+ /// <summary>Records every reported value synchronously (Progress&lt;T&gt; would post to the thread pool).</summary>
+ private sealed class Recorder(Action<double>? onReport = null) : IProgress<double>
+ {
+ public List<double> Values { get; } = [];
+
+ public void Report(double value)
+ {
+ lock (Values)
+ Values.Add(value);
+ onReport?.Invoke(value);
+ }
+ }
+
+ private static ConversionStep Step(string input, string from, string to, string folder, MediaOptions? media = null) =>
+ new(input, from, to, new Preset { TargetFormat = to, Media = media ?? new MediaOptions() }, new FolderAllocator(folder), folder);
+
+ [Fact]
+ public async Task Progress_rises_while_ffmpeg_works()
+ {
+ SkipUnlessInstalled();
+ var folder = fx.NewFolder();
+ // Long enough for several of FFmpeg's half-second progress reports.
+ var source = await MakeClipAsync(folder, "long.mp4", seconds: 40, size: "640x360", extra: ["-c:v", "libx264", "-preset", "ultrafast"]);
+ var converter = new FfmpegConverter();
+ Assert.True(converter.GetStatus().IsAvailable);
+
+ var recorder = new Recorder();
+ var outputs = await converter.ConvertAsync(Step(source, "mp4", "mkv", folder, new MediaOptions { Quality = MediaQuality.High }), recorder, CancellationToken.None);
+
+ Assert.True(File.Exists(Assert.Single(outputs)));
+ var values = recorder.Values.ToList();
+ Assert.Equal(1, values[^1]);
+ Assert.True(values.Zip(values.Skip(1)).All(p => p.First <= p.Second), string.Join(", ", values));
+ Assert.True(values.Count(v => v is > 0.02 and < 1) >= 3, string.Join(", ", values));
+ }
+
+ [Fact]
+ public async Task Gif_palette_pass_reports_progress_too()
+ {
+ SkipUnlessInstalled();
+ var folder = fx.NewFolder();
+ var source = await MakeClipAsync(folder, "gifprogress.mp4", seconds: 30, size: "640x360", audio: false, extra: ["-c:v", "libx264", "-preset", "ultrafast"]);
+ var recorder = new Recorder();
+ var converter = new FfmpegConverter();
+ converter.GetStatus();
+ await converter.ConvertAsync(Step(source, "mp4", "gif", folder, new MediaOptions { Quality = MediaQuality.Small }), recorder, CancellationToken.None);
+ // The palette pass covers the first 40 %: values inside it prove its progress is read.
+ Assert.Contains(recorder.Values, v => v is > 0.05 and < 0.4);
+ }
+
+ [Fact]
+ public async Task Cancelling_kills_ffmpeg_and_removes_the_partial_output()
+ {
+ SkipUnlessInstalled();
+ var folder = fx.NewFolder();
+ var source = await MakeClipAsync(folder, "cancel.mp4", seconds: 60, size: "1280x720", extra: ["-c:v", "libx264", "-preset", "ultrafast"]);
+ using var cancellation = new CancellationTokenSource();
+ var recorder = new Recorder(v =>
+ {
+ if (v > 0.05)
+ cancellation.Cancel();
+ });
+ var converter = new FfmpegConverter();
+ converter.GetStatus();
+ var step = Step(source, "mp4", "webm", folder, new MediaOptions { Quality = MediaQuality.High });
+ cancellation.CancelAfter(TimeSpan.FromSeconds(30)); // in case no progress arrives at all
+ var watch = Stopwatch.StartNew();
+
+ await Assert.ThrowsAnyAsync<OperationCanceledException>(() => converter.ConvertAsync(step, recorder, cancellation.Token));
+
+ Assert.True(watch.Elapsed < TimeSpan.FromSeconds(60), "VP9 encoding of the whole clip should not have finished");
+ var output = Assert.Single(((FolderAllocator)step.Output).Allocated);
+ Assert.False(File.Exists(output));
+ // No FFmpeg of ours is left running (it would keep the CPU busy and the output locked).
+ var deadline = Stopwatch.StartNew();
+ while (RunningFfmpeg(Tools!.Value.Ffmpeg) && deadline.Elapsed < TimeSpan.FromSeconds(10))
+ await Task.Delay(200, TestContext.Current.CancellationToken);
+ Assert.False(RunningFfmpeg(Tools.Value.Ffmpeg));
+ }
+
+ /// <summary>
+ /// True if a process started from <paramref name="exe"/> is running (tests of this class run one at a time, so
+ /// it can only be the one that should have been killed).
+ /// </summary>
+ private static bool RunningFfmpeg(string exe)
+ {
+ foreach (var process in Process.GetProcessesByName(Path.GetFileNameWithoutExtension(exe)))
+ {
+ using (process)
+ {
+ try
+ {
+ if (!process.HasExited && string.Equals(process.MainModule?.FileName, exe, StringComparison.OrdinalIgnoreCase))
+ return true;
+ }
+ catch (Exception ex) when (ex is InvalidOperationException or System.ComponentModel.Win32Exception)
+ {
+ // Exited meanwhile or belongs to another user: not ours.
+ }
+ }
+ }
+ return false;
+ }
+}