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.

Add HEVC and AV1 video, more audio formats and subtitle conversion

KnifeLemon6a581953267f
diff --git a/README.ko.md b/README.ko.md
index f6e5d109..c9a5d760 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -90,8 +90,9 @@
| **한글**: HWP, HWPX | PDF, PNG, DOCX, HWPX ↔ HWP, TXT, 마크다운, HTML |
| **텍스트**: TXT, 마크다운, HTML · reStructuredText, LaTeX³ | PDF, DOCX, HWPX, EPUB |
| **전자책**: EPUB, MOBI, AZW3, AZW, AZW4, FB2, CBZ, CBR, CB7, HTMLZ, TXTZ · LIT, LRF, CHM, PDB 등⁴ | PDF, EPUB, DOCX, TXT, HTML, HWPX · MOBI, AZW3⁴ |
-| **동영상**⁵: MP4, MOV, MKV, WEBM, AVI, WMV, FLV, MPEG, TS, M2TS, 3GP, OGV, VOB 등 | MP4, WEBM, MOV, MKV, AVI, GIF, MP3, M4A, 720p |
-| **오디오**⁵: MP3, M4A, AAC, WAV, FLAC, OGG, OPUS, WMA, AIFF, AMR 등 | MP3, M4A, WAV, FLAC, OGG, OPUS, AAC |
+| **동영상**⁵: MP4, MOV, MKV, WEBM, AVI, WMV, FLV, MPEG, TS, M2TS, 3GP, OGV, VOB 등 | MP4(H.264, HEVC, AV1), WEBM, MOV, MKV, AVI, GIF, MP3, M4A, 720p, 자막(SRT, ASS, WebVTT) |
+| **오디오**⁵: MP3, M4A, AAC, WAV, FLAC, OGG, OPUS, WMA, AIFF, AMR, APE, WavPack, TTA, DSD(DSF, DFF), DTS, AC3, E-AC3 등 | MP3, M4A(AAC, ALAC), WAV, FLAC, OGG, OPUS, AAC, WavPack, TTA, W64, AC3, E-AC3 |
+| **자막**: SRT, ASS/SSA, WebVTT, SAMI(SMI), LRC, TTML, MicroDVD, SCC | 서로 변환, UTF-8로 저장(CP949 한글 자막도 깨지지 않아요) |
| **압축 파일**: ZIP, 7Z, RAR, TAR, TAR.GZ, TAR.BZ2, TAR.XZ, GZ, ISO, CAB, DMG, ALZ, EGG 등 | 압축 풀기, ZIP, 7Z, TAR, TAR.GZ; 여러 파일 → ZIP 하나 |
| **CAD**: DWG, DXF | PDF, SVG, PNG, DWG ↔ DXF |
| **글꼴**: TTF, OTF, WOFF, WOFF2, EOT | 서로 변환 |
diff --git a/README.md b/README.md
index c2f73df1..8b5a6bdd 100644
--- a/README.md
+++ b/README.md
@@ -90,8 +90,9 @@ Filee shows new releases in its menu and updates itself, keeping your settings a
| **HWP**: HWP, HWPX | PDF, PNG, DOCX, HWPX ↔ HWP, TXT, Markdown, HTML |
| **Text**: TXT, Markdown, HTML · reStructuredText, LaTeX³ | PDF, DOCX, HWPX, EPUB |
| **E-books**: EPUB, MOBI, AZW3, AZW, AZW4, FB2, CBZ, CBR, CB7, HTMLZ, TXTZ · LIT, LRF, CHM, PDB, …⁴ | PDF, EPUB, DOCX, TXT, HTML, HWPX · MOBI, AZW3⁴ |
-| **Video**⁵: MP4, MOV, MKV, WEBM, AVI, WMV, FLV, MPEG, TS, M2TS, 3GP, OGV, VOB, … | MP4, WEBM, MOV, MKV, AVI, GIF, MP3, M4A, 720p |
-| **Audio**⁵: MP3, M4A, AAC, WAV, FLAC, OGG, OPUS, WMA, AIFF, AMR, … | MP3, M4A, WAV, FLAC, OGG, OPUS, AAC |
+| **Video**⁵: MP4, MOV, MKV, WEBM, AVI, WMV, FLV, MPEG, TS, M2TS, 3GP, OGV, VOB, … | MP4 (H.264, HEVC, AV1), WEBM, MOV, MKV, AVI, GIF, MP3, M4A, 720p, subtitles (SRT, ASS, WebVTT) |
+| **Audio**⁵: MP3, M4A, AAC, WAV, FLAC, OGG, OPUS, WMA, AIFF, AMR, APE, WavPack, TTA, DSD (DSF, DFF), DTS, AC3, E-AC3, … | MP3, M4A (AAC, ALAC), WAV, FLAC, OGG, OPUS, AAC, WavPack, TTA, W64, AC3, E-AC3 |
+| **Subtitles**: SRT, ASS/SSA, WebVTT, SAMI (SMI), LRC, TTML, MicroDVD, SCC | each other as UTF-8 (Korean CP949 files read correctly) |
| **Archives**: ZIP, 7Z, RAR, TAR, TAR.GZ, TAR.BZ2, TAR.XZ, GZ, ISO, CAB, DMG, ALZ, EGG, … | extract, ZIP, 7Z, TAR, TAR.GZ; any files → one ZIP |
| **CAD**: DWG, DXF | PDF, SVG, PNG, DWG ↔ DXF |
| **Fonts**: TTF, OTF, WOFF, WOFF2, EOT | each other |
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 9ca8989c..9d07aeb3 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -89,8 +89,9 @@
| **HWP**:HWP、HWPX | PDF、PNG、DOCX、HWPX ↔ HWP、TXT、Markdown、HTML |
| **文本**:TXT、Markdown、HTML · reStructuredText、LaTeX³ | PDF、DOCX、HWPX、EPUB |
| **电子书**:EPUB、MOBI、AZW3、AZW、AZW4、FB2、CBZ、CBR、CB7、HTMLZ、TXTZ · LIT、LRF、CHM、PDB 等⁴ | PDF、EPUB、DOCX、TXT、HTML、HWPX · MOBI、AZW3⁴ |
-| **视频**⁵:MP4、MOV、MKV、WEBM、AVI、WMV、FLV、MPEG、TS、M2TS、3GP、OGV、VOB 等 | MP4、WEBM、MOV、MKV、AVI、GIF、MP3、M4A、720p |
-| **音频**⁵:MP3、M4A、AAC、WAV、FLAC、OGG、OPUS、WMA、AIFF、AMR 等 | MP3、M4A、WAV、FLAC、OGG、OPUS、AAC |
+| **视频**⁵:MP4、MOV、MKV、WEBM、AVI、WMV、FLV、MPEG、TS、M2TS、3GP、OGV、VOB 等 | MP4(H.264、HEVC、AV1)、WEBM、MOV、MKV、AVI、GIF、MP3、M4A、720p、字幕(SRT、ASS、WebVTT) |
+| **音频**⁵:MP3、M4A、AAC、WAV、FLAC、OGG、OPUS、WMA、AIFF、AMR、APE、WavPack、TTA、DSD(DSF、DFF)、DTS、AC3、E-AC3 等 | MP3、M4A(AAC、ALAC)、WAV、FLAC、OGG、OPUS、AAC、WavPack、TTA、W64、AC3、E-AC3 |
+| **字幕**:SRT、ASS/SSA、WebVTT、SAMI(SMI)、LRC、TTML、MicroDVD、SCC | 互相转换,保存为 UTF-8(也能读取 CP949 韩文字幕) |
| **压缩包**:ZIP、7Z、RAR、TAR、TAR.GZ、TAR.BZ2、TAR.XZ、GZ、ISO、CAB、DMG、ALZ、EGG 等 | 解压、ZIP、7Z、TAR、TAR.GZ;多个文件 → 一个 ZIP |
| **CAD**:DWG、DXF | PDF、SVG、PNG、DWG ↔ DXF |
| **字体**:TTF、OTF、WOFF、WOFF2、EOT | 互相转换 |
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index e1434f2f..0967421d 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -22,7 +22,7 @@
│ Built in: Magick (images, RAW) · PdfSharp · Pdfium · PdfPig · Svg.Skia · ICNS │
│ HwpxWriter + DocxWriter over DocumentReaders (DOCX, XLSX, XLS, ODS, PPTX, │
│ PDF, HTML, EPUB, MOBI, FB2, HWPX, Markdown) · Spreadsheets · OOXML variants │
- │ · E-mail · E-books · CAD · Fonts │
+ │ · E-mail · E-books · CAD · Fonts · Subtitles │
│ Bundled: rhwp (HWP→PDF, HWP↔HWPX) · 7-Zip (archives) · Unhwp · Markdig │
│ Optional: FFmpeg · LibreOffice + H2Orestart · calibre · Ghostscript · Pandoc │
└────────────────────────────────────────────────────────────────────────────────────┘
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index da0fca5f..ca9ffbcc 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -21,12 +21,13 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,
| E-mail | built in (MimeKit) | **EML → HTML** (headers + body, inline pictures), **TXT**, **ZIP** (the attachments) |
| **E-books** | built in | **EPUB, MOBI/AZW/AZW3/PRC, FB2, HTMLZ, TXTZ → EPUB, HWPX (→ PDF), TXT, HTML, Markdown, FB2, HTMLZ, TXTZ**; HTML, Markdown, TXT, DOCX → EPUB/FB2/HTMLZ/TXTZ; HTML → TXT; comics CBZ/CBR/CB7/CBT/CBC → PDF, EPUB, CBZ; PDF → CBZ; AZW4 → PDF |
| CAD (ACadSharp + built-in renderer) | built in (library) | **DWG ↔ DXF**; DWG/DXF → **PDF** (vector), **SVG**, PNG, JPG, WEBP, TIFF, BMP, GIF, ICO, AVIF |
+| **Subtitles** | built in | **SRT, ASS/SSA, WebVTT, SAMI (SMI), LRC, TTML, MicroDVD, SCC → SRT, ASS, WebVTT, SAMI, LRC, TTML, MicroDVD**, always UTF-8 (Korean CP949 / EUC-KR files read correctly) |
| rhwp | bundled with the installer (`engines/rhwp`) | HWP/HWPX → PDF, **HWP → HWPX, HWPX → HWP** |
| Archives (7-Zip) | bundled with the installer (`engines/7zip`, ~2.5 MB) + built-in readers | ZIP, 7Z, RAR, TAR (+ GZ/BZ2/XZ/Z/7Z/LZ), CAB, ISO, DMG, … **→ folder, ZIP, 7Z, TAR, TAR.GZ/BZ2/XZ**; ALZ, EGG, lzip read in-process; "Compress into one archive" for any files |
| 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/ODP; HWP/HWPX → DOCX/ODT; read-only formats (see below) → PDF and their kind's editable formats |
| Pandoc | **optional download** (~42 MB, 240 MB on disk) | Markdown ↔ DOCX/ODT/RTF, DOCX/ODT/HTML/RTF → Markdown, HTML ↔ DOCX/ODT, reStructuredText and LaTeX ↔ Markdown/HTML/DOCX/ODT (and → RTF, EPUB, TXT) |
| Ghostscript | **optional download** (~20 MB, 31 MB on disk) | EPS/PS → PDF, PDF → EPS/PS, PostScript-based AI → PDF (images through PDF and PDFium) |
-| 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 and photos → MP4/WEBM/MOV, images → HEIC |
+| FFmpeg | **optional download** (~100 MB, 272 MB on disk) | **all video and audio**: video ↔ video (H.264, HEVC, AV1), video → animated GIF or a still frame, audio and subtitle extraction, audio ↔ audio (also APE, WavPack, TTA, DSD, DTS, ALAC, …), GIF and photos → MP4/WEBM/MOV, images → HEIC |
| Calibre | **optional download** (~216 MB, 660 MB on disk) | rare e-book formats: LIT, LRF, CHM, PDB, PML, RB, SNB, TCR, OEB → EPUB; EPUB → MOBI, AZW3, LIT, LRF, PDB, PML, RB, SNB, TCR |
DOCX, XLSX, XLS, ODS and PPTX → PDF need neither Microsoft Office nor LibreOffice: they are read in-process, written as HWPX
@@ -473,6 +474,32 @@ bundled with the installer), never a 7-Zip installed on the PC. It runs as a sep
LibreOffice's filter registry): Publisher, CorelDRAW and Visio open in Draw, CGM in Impress, and "SDA" files
in Draw (.sda) or Impress (.sdd). SVG and PNG export the first page.
+## Subtitles
+
+`Subtitles/SubtitleConverter.cs` (engine id `subtitle`) converts text subtitles in managed code, no FFmpeg needed.
+Every reader produces one cue model (`SubtitleModel.cs`: start, end and text with line breaks and SRT's own tags
+`<i>`, `<b>`, `<u>`, `<font color>`), every writer takes it, so any format converts to any other and to itself (an
+SRT or SAMI file in CP949 comes out as UTF-8).
+
+| Format | Read | Written |
+|---|---|---|
+| SRT | numbers optional, blank lines inside cues and missing between them, `,` or `.` before the milliseconds, `{\an8}` codes dropped | UTF-8 with BOM, CRLF, tags kept |
+| ASS / SSA | `Dialogue:` lines in the order of the `Format:` line; `\i \b \u \c`, bold/italic/underline styles, `\N`; drawings (`\p1`) and comments left out, shadow layers merged | ASS v4.00+ for 1920 × 1080, one "Default" style, override codes (SSA is read only) |
+| WebVTT | NOTE / STYLE / REGION blocks skipped, cue settings ignored, `<i> <b> <u>`, the colour classes (`<c.yellow>`), entities; voices and timestamps dropped | UTF-8, the basic colour classes, text escaped |
+| SAMI (SMI) | hand-made HTML: unquoted attributes, unclosed `<SYNC>` / `<P>`, `&nbsp` with or without `;`; of several languages (KRCC, ENCC, …) the one with the most lines | one class from the text's language (KRCC for Korean), `&nbsp;` where the screen goes blank, UTF-8 with BOM |
+| LRC | `[mm:ss.xx]` (several per line), `[ti:]`, `[offset:]`, enhanced word times dropped; a line lasts until the next one | plain text, lines joined, an empty time line where the screen goes blank |
+| TTML / DFXP | TTML 1 and the 2006 DFXP namespace; times relative to their parents; clock, frames (`ttp:frameRate`), ticks and offset times; spans and referenced styles | TTML 1 with a bottom region and tts: spans |
+| MicroDVD (.sub) | `{frame}{frame}text` with the rate of a `{1}{1}25` first line (else 23.976), `\|` between lines, `{y:i}` / `{c:$BBGGRR}`; VobSub `.sub` (pictures) and SubViewer fail with a clear message | 23.976 fps, first line states it, plain text, `{Y:i}` for all-italic cues |
+| SCC | CEA-608 caption channel 1: pop-on, paint-on and roll-up captions, row preambles, italics, special and extended characters, doubled control codes, drop-frame time codes | — |
+
+- **Encodings**: a byte order mark (UTF-8, UTF-16) or valid UTF-8 decide first, then a `charset=` / `encoding=` the
+ file declares. Otherwise CP949 when the bytes are CP949 pairs, most of them Hangul syllables of KS X 1001 and hardly
+ any with a lead byte above C8 (Chinese GBK text uses those for many common characters), then the PC's code page on
+ Chinese or Japanese Windows, else the Western one (Windows-1252 on Korean Windows). Everything is written as UTF-8.
+- Cues without an end (LRC, the last SAMI line, an unterminated SCC caption) last 4 seconds; empty cues are dropped.
+- Not kept: positions and alignment, fonts and sizes, karaoke timing, ASS animations, WebVTT regions and voices.
+- Tests (`SubtitleTests.cs`) write every input in code, CP949 and GBK bytes included.
+
## DjVu
Not supported: DjVuLibre (GPL) has no pinned, redistributable Windows build in an archive the installer can unpack.
@@ -483,9 +510,9 @@ Filee (with the GPL source offer), then an `engines.json` component and an optio
## 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 and PNG to MP4, WEBM
-and MOV.
+`Media/FfmpegConverter.cs` converts every video format to every video format, to animated GIF, to a still PNG frame,
+to every audio format (the sound track) and to SRT, ASS and WebVTT (the subtitles); every audio format to every audio
+format; and GIF and PNG 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).
@@ -506,8 +533,14 @@ Same-format edges exist too, so "MP4 720p" works on MP4 files and "MP3 128k" on
| 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 (WAV: 8/16/24/32-bit or 32-bit float; RF64 over 4 GB) · FLAC |
+ | MP4, M4V, MKV with *Video codec* HEVC · MOV with HEVC | x265 (preset medium, `hvc1` tag in MP4/M4V/MOV) + AAC |
+ | MP4, M4V, MKV, WEBM with *Video codec* AV1 | SVT-AV1 (preset 8), or libaom-av1 (cpu-used 6, row multithreading) with an FFmpeg that lacks SVT-AV1 |
+ | MP3 · M4A/M4B · AAC · OGG · OPUS · WEBA · MKA · WMA · MP2 · AC3 · E-AC3 · AMR | LAME VBR (V0/V2/V5) or CBR · AAC, or ALAC with *Audio codec* ALAC · AAC (ADTS) · Vorbis · Opus · Opus · Opus · WMA 2 · MP2 · AC-3 · E-AC-3 · AMR-NB 12.2k (8 kHz mono) |
+ | WAV · W64 · AIFF · AU · CAF · VOC · FLAC · WV · TTA | 16-bit PCM (WAV and W64: 8/16/24/32-bit or 32-bit float; WAV switches to RF64 over 4 GB, Sony Wave64 has no limit) · FLAC · WavPack (lossless) · TTA |
+ | SRT · ASS · VTT (from video) | the video's first text subtitle track, copied when it already is that format, else converted by FFmpeg |
+
+ Read only (FFmpeg's decoders): APE (Monkey's Audio), Musepack (MPC), TAK, DSF and DFF (DSD), DTS, Speex (SPX) and the
+ formats above. No encoder for them is in the build, or (DTS) only an experimental one.
- **Rewrapping instead of re-encoding.** When the target container takes the source's codecs as they are
(`MediaEncoding.Remuxable`: H.264/HEVC + AAC, ALAC, AC-3, E-AC-3 or MP3 for MP4/M4V/MOV, also ProRes and PCM for
@@ -518,12 +551,26 @@ Same-format edges exist too, so "MP4 720p" works on MP4 files and "MP3 128k" on
is needed; audio only when no bitrate or other channel count is set. Quality *Small* always re-encodes (the user
asked for a smaller file); *High* and *Balanced* only set how a stream that has to be encoded is encoded. A
stream that can't be copied is encoded as below, the other one is still copied.
-- 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; the editor offers 32 to 320 kbit/s); *RemoveAudio* drops the sound;
- *AudioChannels* (0 source, 1 mono, 2 stereo) applies to every audio target but AMR; *AudioSampleRate* (8 to
- 48 kHz) and *WavFormat* (bit depth) apply to WAV.
+- Preset options (`MediaOptions`): *Quality* picks CRF 18/23/28 (x264), 22/26/30 (x265), 26/32/40 (SVT-AV1 and
+ libaom), 24/32/38 (VP9), quantizer 2/4/7 (MPEG-4, WMV, MPEG-2), Theora 8/6/4 and the audio bitrates (e.g. AAC and
+ E-AC-3 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; the editor offers 32 to
+ 320 kbit/s); *RemoveAudio* drops the sound; *AudioChannels* (0 source, 1 mono, 2 stereo) applies to every audio
+ target but AMR; *AudioSampleRate* (8 to 48 kHz) and *WavFormat* (bit depth) apply to WAV and W64.
+- *VideoCodec* (Default, HEVC, AV1) and *AudioCodec* (Default, ALAC) pick another codec where the target takes it
+ (`MediaCodecs` in Filee.Core: HEVC for MP4/M4V/MKV/MOV, AV1 for MP4/M4V/MKV/WEBM, ALAC for M4A/M4B); for any other
+ target the usual codec is written. The presets "MP4 HEVC" (on the video donut), "MP4 AV1" and "ALAC" use them. A
+ video already in the chosen codec is copied (the rules above, with AV1 also into MP4); HEVC and AV1 keep 10 bits
+ (`yuv420p10le`, Main 10) for 10-bit and HDR sources and write their colour tags (BT.2020, PQ or HLG), 8-bit 4:2:0
+ for the rest. The encoders are looked up with `ffmpeg -encoders` once per FFmpeg, so a copy the user picked without
+ x265 or AV1 fails with a clear message instead of an FFmpeg error. x265 and SVT-AV1 log only errors
+ (`-x265-params log-level=error`, `SVT_LOG=1`).
+- 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, …).
+ A video without subtitles fails with "The video has no subtitle track."; one with only picture subtitles (Blu-ray
+ PGS, DVD, DVB) says they can't be turned into text without OCR. Video → SAMI, LRC, TTML, … goes through SRT and the
+ subtitle engine (ASS and WebVTT extraction cost 11 so SRT is the hub).
- 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
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 2828fbba..c9b0ce0c 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -78,7 +78,8 @@
"engine.cad.description": "AutoCAD drawings: DWG ↔ DXF, and both to PDF, SVG and PNG.",
"engine.archive.description": "Extracts ZIP, 7Z, RAR, TAR, ISO and more, and packs ZIP, 7Z or TAR.GZ (7-Zip).",
"engine.ebook.description": "EPUB, MOBI, AZW3, FB2 and comics (CBZ, CBR) to PDF, EPUB, DOCX and text.\nAlso documents to EPUB and PDF to CBZ.",
- "engine.ffmpeg.description": "Video and audio: MP4, MOV, MKV, WEBM, MP3, M4A, WAV, FLAC and more.\nAlso extracts sound, makes GIFs and saves images as HEIC.",
+ "engine.subtitle.description": "Subtitles: SRT, ASS/SSA, WebVTT, SAMI (SMI), LRC, TTML, MicroDVD and SCC into each other, saved as UTF-8.\nKorean SMI and SRT files in CP949 / EUC-KR read correctly.",
+ "engine.ffmpeg.description": "Video and audio: MP4, MOV, MKV, WEBM, MP3, M4A, WAV, FLAC and more.\nAlso extracts sound and subtitles, makes GIFs and saves images as HEIC.",
"engine.pandoc.description": "Markdown and HTML ↔ ODT and RTF, DOCX → Markdown\nreStructuredText and LaTeX ↔ Markdown, HTML, DOCX and ODT",
"engine.ghostscript.description": "EPS, PostScript and older Illustrator files to PDF and images; PDF to EPS and PS.",
"engine.calibre.description": "Rare e-book formats (LIT, LRF, CHM, PDB, RB…) and Kindle output (MOBI, AZW3).",
@@ -94,6 +95,7 @@
"profile.ebooks": "E-books",
"profile.video": "Video",
"profile.audio": "Audio",
+ "profile.subtitles": "Subtitles",
"profile.vector": "Vector graphics",
"profile.archives": "Archives",
"profile.cad": "CAD drawings",
@@ -108,6 +110,7 @@
"preset.long_image": "Long image",
"preset.extract": "Extract",
"preset.zip_all": "One ZIP",
+ "preset.extract_subtitles": "Extract subtitles",
"format.folder": "Folder",
"format.category.Image": "Image",
@@ -124,6 +127,7 @@
"format.category.Vector": "Vector",
"format.category.Cad": "CAD",
"format.category.Font": "Font",
+ "format.category.Subtitle": "Subtitle",
"general.title": "General",
"general.language": "Language",
@@ -354,6 +358,15 @@
"presets.wav_format.Pcm24": "24-bit",
"presets.wav_format.Pcm32": "32-bit",
"presets.wav_format.Float32": "32-bit float",
+ "presets.video_codec": "Video codec",
+ "presets.video_codec_hint": "H.264 plays everywhere.\nHEVC files are about half the size and play on most phones, TVs and recent PCs.\nAV1 is smaller still but slow to encode and needs a recent device.\nA video already in the chosen codec is only rewrapped.",
+ "presets.video_codec.h264": "H.264 (plays everywhere)",
+ "presets.video_codec.vp9": "VP9",
+ "presets.video_codec.hevc": "HEVC / H.265 (smaller)",
+ "presets.video_codec.av1": "AV1 (smallest, slow)",
+ "presets.audio_codec": "Audio codec",
+ "presets.audio_codec.aac": "AAC",
+ "presets.audio_codec.alac": "ALAC (lossless)",
"presets.group.archive": "Archive",
"presets.archive_level": "Compression",
"presets.archive_level.Store": "None (store only)",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index c0074be4..0e361d39 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -78,7 +78,8 @@
"engine.cad.description": "오토캐드 도면: DWG ↔ DXF, 그리고 둘 다 PDF, SVG, PNG로.",
"engine.archive.description": "ZIP, 7Z, RAR, TAR, ISO 등을 풀고, ZIP·7Z·TAR.GZ로 묶어요(7-Zip).",
"engine.ebook.description": "EPUB, MOBI, AZW3, FB2, 만화책(CBZ, CBR)을 PDF, EPUB, DOCX, 텍스트로 바꿔요.\n문서는 EPUB으로, PDF는 CBZ로도 만들어요.",
- "engine.ffmpeg.description": "MP4, MOV, MKV, WEBM, MP3, M4A, WAV, FLAC 등 동영상·오디오를 변환해요.\n소리 추출, GIF 만들기, 이미지 → HEIC도 해요.",
+ "engine.subtitle.description": "SRT, ASS/SSA, WebVTT, SAMI(SMI), LRC, TTML, MicroDVD, SCC 자막을 서로 바꾸고 UTF-8로 저장해요.\nCP949/EUC-KR로 된 SMI·SRT 파일도 한글이 깨지지 않아요.",
+ "engine.ffmpeg.description": "MP4, MOV, MKV, WEBM, MP3, M4A, WAV, FLAC 등 동영상·오디오를 변환해요.\n소리·자막 추출, GIF 만들기, 이미지 → HEIC도 해요.",
"engine.pandoc.description": "마크다운·HTML ↔ ODT·RTF, DOCX → 마크다운\nreStructuredText·LaTeX ↔ 마크다운·HTML·DOCX·ODT",
"engine.ghostscript.description": "EPS, 포스트스크립트, 예전 일러스트레이터 파일을 PDF와 이미지로, PDF를 EPS·PS로.",
"engine.calibre.description": "드문 전자책 형식(LIT, LRF, CHM, PDB, RB…)과 킨들용 출력(MOBI, AZW3).",
@@ -94,6 +95,7 @@
"profile.ebooks": "전자책",
"profile.video": "동영상",
"profile.audio": "오디오",
+ "profile.subtitles": "자막",
"profile.vector": "벡터 그래픽",
"profile.archives": "압축 파일",
"profile.cad": "CAD 도면",
@@ -108,6 +110,7 @@
"preset.long_image": "긴 이미지",
"preset.extract": "압축 풀기",
"preset.zip_all": "ZIP 하나로",
+ "preset.extract_subtitles": "자막 추출",
"format.folder": "폴더",
"format.category.Image": "이미지",
@@ -124,6 +127,7 @@
"format.category.Vector": "벡터",
"format.category.Cad": "CAD",
"format.category.Font": "글꼴",
+ "format.category.Subtitle": "자막",
"general.title": "일반",
"general.language": "언어",
@@ -354,6 +358,15 @@
"presets.wav_format.Pcm24": "24비트",
"presets.wav_format.Pcm32": "32비트",
"presets.wav_format.Float32": "32비트 부동소수점",
+ "presets.video_codec": "비디오 코덱",
+ "presets.video_codec_hint": "H.264는 어디서나 재생돼요.\nHEVC는 용량이 절반쯤이고 대부분의 휴대폰, TV, 최신 PC에서 재생돼요.\nAV1은 더 작지만 인코딩이 느리고 최신 기기가 필요해요.\n이미 고른 코덱인 동영상은 다시 인코딩하지 않아요.",
+ "presets.video_codec.h264": "H.264 (어디서나 재생)",
+ "presets.video_codec.vp9": "VP9",
+ "presets.video_codec.hevc": "HEVC / H.265 (더 작게)",
+ "presets.video_codec.av1": "AV1 (가장 작게, 느림)",
+ "presets.audio_codec": "오디오 코덱",
+ "presets.audio_codec.aac": "AAC",
+ "presets.audio_codec.alac": "ALAC (무손실)",
"presets.group.archive": "압축",
"presets.archive_level": "압축 수준",
"presets.archive_level.Store": "압축 안 함 (보관만)",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index 8ec41bb7..a2985f41 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -78,7 +78,8 @@
"engine.cad.description": "AutoCAD 图纸:DWG ↔ DXF,并可转为 PDF、SVG 和 PNG。",
"engine.archive.description": "解压 ZIP、7Z、RAR、TAR、ISO 等,并打包为 ZIP、7Z 或 TAR.GZ(7-Zip)。",
"engine.ebook.description": "EPUB、MOBI、AZW3、FB2 和漫画(CBZ、CBR)转为 PDF、EPUB、DOCX 和文本。\n也能把文档转为 EPUB、把 PDF 转为 CBZ。",
- "engine.ffmpeg.description": "MP4、MOV、MKV、WEBM、MP3、M4A、WAV、FLAC 等视频和音频。\n还能提取声音、制作 GIF、把图片保存为 HEIC。",
+ "engine.subtitle.description": "SRT、ASS/SSA、WebVTT、SAMI(SMI)、LRC、TTML、MicroDVD、SCC 字幕互转,保存为 UTF-8。\n也能正确读取 CP949/EUC-KR 编码的韩文字幕。",
+ "engine.ffmpeg.description": "MP4、MOV、MKV、WEBM、MP3、M4A、WAV、FLAC 等视频和音频。\n还能提取声音和字幕、制作 GIF、把图片保存为 HEIC。",
"engine.pandoc.description": "Markdown 和 HTML ↔ ODT、RTF,DOCX → Markdown\nreStructuredText、LaTeX ↔ Markdown、HTML、DOCX、ODT",
"engine.ghostscript.description": "EPS、PostScript 和旧版 Illustrator 文件转为 PDF 和图片;PDF 转为 EPS 和 PS。",
"engine.calibre.description": "少见的电子书格式(LIT、LRF、CHM、PDB、RB…)以及 Kindle 输出(MOBI、AZW3)。",
@@ -94,6 +95,7 @@
"profile.ebooks": "电子书",
"profile.video": "视频",
"profile.audio": "音频",
+ "profile.subtitles": "字幕",
"profile.vector": "矢量图形",
"profile.archives": "压缩文件",
"profile.cad": "CAD 图纸",
@@ -108,6 +110,7 @@
"preset.long_image": "长图",
"preset.extract": "解压",
"preset.zip_all": "打包成一个 ZIP",
+ "preset.extract_subtitles": "提取字幕",
"format.folder": "文件夹",
"format.category.Image": "图片",
@@ -124,6 +127,7 @@
"format.category.Vector": "矢量图",
"format.category.Cad": "CAD",
"format.category.Font": "字体",
+ "format.category.Subtitle": "字幕",
"general.title": "常规",
"general.language": "语言",
@@ -354,6 +358,15 @@
"presets.wav_format.Pcm24": "24 位",
"presets.wav_format.Pcm32": "32 位",
"presets.wav_format.Float32": "32 位浮点",
+ "presets.video_codec": "视频编码",
+ "presets.video_codec_hint": "H.264 到处都能播放。\nHEVC 文件约小一半,多数手机、电视和较新的电脑都能播放。\nAV1 更小,但编码慢,需要较新的设备。\n已是所选编码的视频只重新封装。",
+ "presets.video_codec.h264": "H.264(兼容性最好)",
+ "presets.video_codec.vp9": "VP9",
+ "presets.video_codec.hevc": "HEVC / H.265(更小)",
+ "presets.video_codec.av1": "AV1(最小,较慢)",
+ "presets.audio_codec": "音频编码",
+ "presets.audio_codec.aac": "AAC",
+ "presets.audio_codec.alac": "ALAC(无损)",
"presets.group.archive": "压缩文件",
"presets.archive_level": "压缩级别",
"presets.archive_level.Store": "不压缩(仅存储)",
diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
index b608376d..ff8450cd 100644
--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
@@ -30,7 +30,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
private static readonly HashSet<string> LossyTargets = ["jpg", "webp", "avif", "heic"];
/// <summary>Audio targets without a bitrate or quality to choose.</summary>
- private static readonly HashSet<string> LosslessAudioTargets = ["wav", "flac", "aiff"];
+ private static readonly HashSet<string> LosslessAudioTargets = ["wav", "flac", "aiff", "wv", "tta", "w64"];
private static readonly int[] MaxHeightSteps = [0, 2160, 1440, 1080, 720, 480];
// 32-64 kbit/s: speech (Opus is still clear at 32 kbit/s mono), small files.
@@ -87,6 +87,8 @@ public sealed partial class PresetEditorViewModel : ObservableObject
_audioChannels = AudioChannelChoices.FirstOrDefault(c => c.Value == _edit.Media.AudioChannels) ?? AudioChannelChoices[0];
_sampleRate = SampleRates.First(r => r.Value == _edit.Media.AudioSampleRate);
_wavFormat = WavFormats.First(f => f.Value == _edit.Media.WavFormat);
+ _videoCodecValue = _edit.Media.VideoCodec;
+ _audioCodecValue = _edit.Media.AudioCodec;
_archiveLevel = ArchiveLevels.First(l => l.Value == _edit.Archive.Level);
_combineIntoOne = _edit.Archive.CombineIntoOne;
_quality = _edit.Image.Quality;
@@ -143,10 +145,57 @@ public sealed partial class PresetEditorViewModel : ObservableObject
[NotifyPropertyChangedFor(nameof(ShowImage), nameof(ShowQuality), nameof(ShowTiff), nameof(ShowMultiPageTiff), nameof(ShowWebp), nameof(ShowIco),
nameof(ShowPdf), nameof(ShowPdfBuild), nameof(ShowDocument), nameof(ShowPdfSplit), nameof(ShowPdfCombine),
nameof(ShowMedia), nameof(ShowMediaQuality), nameof(ShowMaxHeight), nameof(ShowAudioBitrate), nameof(ShowRemoveAudio),
- nameof(ShowAudioChannels), nameof(ShowWav),
+ nameof(ShowAudioChannels), nameof(ShowWav), nameof(VideoCodecs), nameof(VideoCodecChoice), nameof(ShowVideoCodec),
+ nameof(AudioCodecs), nameof(AudioCodecChoice), nameof(ShowAudioCodec),
nameof(ShowArchive), nameof(ShowArchiveOptions), nameof(ShowExtractNote))]
private Choice<string> _target;
+ private VideoCodec _videoCodecValue;
+ private AudioCodec _audioCodecValue;
+
+ /// <summary>The video codecs the target can hold (H.264 / VP9, HEVC, AV1); one entry for most targets.</summary>
+ public IReadOnlyList<Choice<VideoCodec>> VideoCodecs =>
+ [.. MediaCodecs.VideoCodecsFor(TargetId).Select(c => new Choice<VideoCodec>(c, _loc[c switch
+ {
+ VideoCodec.Hevc => "presets.video_codec.hevc",
+ VideoCodec.Av1 => "presets.video_codec.av1",
+ _ => TargetId == "webm" ? "presets.video_codec.vp9" : "presets.video_codec.h264",
+ }]))];
+
+ /// <summary>The chosen video codec; a codec the target can't hold shows (and is saved) as its usual one.</summary>
+ public Choice<VideoCodec> VideoCodecChoice
+ {
+ get => VideoCodecs.FirstOrDefault(c => c.Value == _videoCodecValue) ?? VideoCodecs[0];
+ set
+ {
+ // The combo box clears its selection while its list is replaced.
+ if (value is null || value.Value == _videoCodecValue)
+ return;
+ _videoCodecValue = value.Value;
+ OnPropertyChanged();
+ }
+ }
+
+ /// <summary>The audio codecs the target can hold (AAC or ALAC for M4A); one entry for most targets.</summary>
+ public IReadOnlyList<Choice<AudioCodec>> AudioCodecs =>
+ [.. MediaCodecs.AudioCodecsFor(TargetId).Select(c => new Choice<AudioCodec>(c, _loc[c == AudioCodec.Alac ? "presets.audio_codec.alac" : "presets.audio_codec.aac"]))];
+
+ /// <summary>The chosen audio codec; ALAC is lossless, so it has no quality or bitrate.</summary>
+ public Choice<AudioCodec> AudioCodecChoice
+ {
+ get => AudioCodecs.FirstOrDefault(c => c.Value == _audioCodecValue) ?? AudioCodecs[0];
+ set
+ {
+ if (value is null || value.Value == _audioCodecValue)
+ return;
+ _audioCodecValue = value.Value;
+ OnPropertyChanged();
+ OnPropertyChanged(nameof(ShowMediaQuality));
+ OnPropertyChanged(nameof(ShowAudioBitrate));
+ OnPropertyChanged(nameof(ShowMedia));
+ }
+ }
+
[ObservableProperty, NotifyPropertyChangedFor(nameof(ShowPercent), nameof(ShowLongEdge), nameof(ShowWidth))]
private Choice<ResizeMode> _resize;
@@ -224,7 +273,8 @@ public sealed partial class PresetEditorViewModel : ObservableObject
private bool TargetIsImage => TargetId == BuiltInData.SameAsSource || TargetCategory == FormatCategory.Image;
private bool TargetIsVideo => TargetCategory == FormatCategory.Video;
private bool TargetIsAudio => TargetCategory == FormatCategory.Audio;
- private bool TargetIsLossyMedia => TargetIsVideo || (TargetIsAudio && !LosslessAudioTargets.Contains(TargetId));
+ private bool TargetIsLossyMedia => TargetIsVideo
+ || (TargetIsAudio && !LosslessAudioTargets.Contains(TargetId) && MediaCodecs.Effective(TargetId, _audioCodecValue) != AudioCodec.Alac);
public bool ShowImage => TargetIsImage;
public bool ShowQuality => TargetId == BuiltInData.SameAsSource || LossyTargets.Contains(TargetId);
@@ -232,19 +282,24 @@ public sealed partial class PresetEditorViewModel : ObservableObject
public bool ShowWebp => TargetId is "webp" or BuiltInData.SameAsSource;
public bool ShowMultiPageTiff => TargetId is "tiff";
public bool ShowIco => TargetId == "ico";
- /// <summary>PDF options (also used when a PDF source becomes images) mean nothing for media, archive and font targets.</summary>
- public bool ShowPdf => TargetCategory is not (FormatCategory.Video or FormatCategory.Audio or FormatCategory.Archive or FormatCategory.Font);
+ /// <summary>PDF options (also used when a PDF source becomes images) mean nothing for media, archive, font and subtitle targets.</summary>
+ public bool ShowPdf => TargetCategory is not (FormatCategory.Video or FormatCategory.Audio or FormatCategory.Archive or FormatCategory.Font
+ or FormatCategory.Subtitle);
public bool ShowPdfBuild => TargetId == "pdf";
public bool ShowPdfSplit => TargetId == "pdf";
/// <summary>PDF → a single-image format: the pages can be stacked into one tall image (TIFF and GIF keep pages).</summary>
public bool ShowPdfCombine => TargetCategory == FormatCategory.Image && TargetId is not ("tiff" or "gif" or "ico" or "icns" or "svg" or "pdf");
public bool ShowDocument => TargetId == "pdf";
- public bool ShowMedia => ShowMediaQuality || ShowMaxHeight || ShowRemoveAudio || ShowAudioChannels;
+ public bool ShowMedia => ShowMediaQuality || ShowMaxHeight || ShowRemoveAudio || ShowAudioChannels || ShowVideoCodec || ShowAudioCodec;
/// <summary>Mono / stereo for every audio target but AMR, which is mono by definition.</summary>
public bool ShowAudioChannels => TargetIsAudio && TargetId != "amr";
- /// <summary>Sample rate and sample format: WAV's PCM takes any.</summary>
- public bool ShowWav => TargetId == "wav";
+ /// <summary>Sample rate and sample format: the PCM of WAV and W64 takes any.</summary>
+ 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>M4A / M4B can hold Apple Lossless besides AAC.</summary>
+ public bool ShowAudioCodec => AudioCodecs.Count > 1;
public bool ShowMediaQuality => TargetIsLossyMedia;
public bool ShowMaxHeight => TargetIsVideo;
public bool ShowAudioBitrate => TargetIsLossyMedia;
@@ -319,6 +374,8 @@ public sealed partial class PresetEditorViewModel : ObservableObject
media.AudioChannels = AudioChannels.Value;
media.AudioSampleRate = SampleRate.Value;
media.WavFormat = WavFormat.Value;
+ media.VideoCodec = MediaCodecs.Effective(TargetId, _videoCodecValue);
+ media.AudioCodec = MediaCodecs.Effective(TargetId, _audioCodecValue);
_original.Archive.Level = ArchiveLevel.Value;
_original.Archive.CombineIntoOne = CombineIntoOne;
diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axaml
index 4f6ae7b9..b613600c 100644
--- a/src/Filee.App/Views/PresetEditorView.axaml
+++ b/src/Filee.App/Views/PresetEditorView.axaml
@@ -125,6 +125,15 @@
</Grid>
<!-- Two per row, whichever apply to the target: hidden ones leave no gap. -->
<UniformGrid Columns="2" ColumnSpacing="12" RowSpacing="10">
+ <StackPanel IsVisible="{Binding ShowVideoCodec}">
+ <TextBlock Classes="label" Text="{DynamicResource presets.video_codec}" />
+ <ComboBox ItemsSource="{Binding VideoCodecs}" SelectedItem="{Binding VideoCodecChoice}" HorizontalAlignment="Stretch"
+ ToolTip.Tip="{DynamicResource presets.video_codec_hint}" />
+ </StackPanel>
+ <StackPanel IsVisible="{Binding ShowAudioCodec}">
+ <TextBlock Classes="label" Text="{DynamicResource presets.audio_codec}" />
+ <ComboBox ItemsSource="{Binding AudioCodecs}" SelectedItem="{Binding AudioCodecChoice}" HorizontalAlignment="Stretch" />
+ </StackPanel>
<StackPanel IsVisible="{Binding ShowAudioBitrate}">
<TextBlock Classes="label" Text="{DynamicResource presets.audio_bitrate}" />
<ComboBox ItemsSource="{Binding AudioBitrates}" SelectedItem="{Binding AudioBitrate}" HorizontalAlignment="Stretch" />
diff --git a/src/Filee.Core/Formats/FileFormat.cs b/src/Filee.Core/Formats/FileFormat.cs
index c8049d3d..be5b50b9 100644
--- a/src/Filee.Core/Formats/FileFormat.cs
+++ b/src/Filee.Core/Formats/FileFormat.cs
@@ -19,6 +19,7 @@ public enum FormatCategory
Vector,
Cad,
Font,
+ Subtitle,
}
/// <summary>
diff --git a/src/Filee.Core/Formats/FormatRegistry.cs b/src/Filee.Core/Formats/FormatRegistry.cs
index 46c2be56..86108959 100644
--- a/src/Filee.Core/Formats/FormatRegistry.cs
+++ b/src/Filee.Core/Formats/FormatRegistry.cs
@@ -171,6 +171,17 @@ public static class FormatRegistry
new("mp2", "MP2", FormatCategory.Audio, ["mp2", "mpa"]),
new("dss", "DSS", FormatCategory.Audio, ["dss"], Writable: false),
new("voc", "VOC", FormatCategory.Audio, ["voc"]),
+ new("wv", "WavPack", FormatCategory.Audio, ["wv"]),
+ new("tta", "TTA", FormatCategory.Audio, ["tta"]),
+ new("w64", "W64", FormatCategory.Audio, ["w64"]),
+ new("eac3", "E-AC3", FormatCategory.Audio, ["eac3", "ec3"]),
+ new("ape", "APE", FormatCategory.Audio, ["ape"], Writable: false),
+ new("mpc", "Musepack", FormatCategory.Audio, ["mpc", "mpp", "mp+"], Writable: false),
+ new("tak", "TAK", FormatCategory.Audio, ["tak"], Writable: false),
+ new("dsf", "DSF", FormatCategory.Audio, ["dsf"], Writable: false),
+ new("dff", "DFF", FormatCategory.Audio, ["dff"], Writable: false),
+ new("dts", "DTS", FormatCategory.Audio, ["dts"], Writable: false),
+ new("spx", "Speex", FormatCategory.Audio, ["spx"], Writable: false),
// Archives
new("zip", "ZIP", FormatCategory.Archive, ["zip"]),
@@ -213,6 +224,17 @@ public static class FormatRegistry
new("woff", "WOFF", FormatCategory.Font, ["woff"]),
new("woff2", "WOFF2", FormatCategory.Font, ["woff2"]),
new("eot", "EOT", FormatCategory.Font, ["eot"]),
+
+ // Subtitles (text)
+ new("srt", "SRT", FormatCategory.Subtitle, ["srt"]),
+ new("ass", "ASS", FormatCategory.Subtitle, ["ass"]),
+ new("ssa", "SSA", FormatCategory.Subtitle, ["ssa"], Writable: false),
+ new("vtt", "WebVTT", FormatCategory.Subtitle, ["vtt"]),
+ new("smi", "SAMI", FormatCategory.Subtitle, ["smi", "sami"]),
+ new("lrc", "LRC", FormatCategory.Subtitle, ["lrc"]),
+ new("ttml", "TTML", FormatCategory.Subtitle, ["ttml", "dfxp"]),
+ new("sub", "MicroDVD", FormatCategory.Subtitle, ["sub"]),
+ new("scc", "SCC", FormatCategory.Subtitle, ["scc"], Writable: false),
];
private static readonly Dictionary<string, FileFormat> ById =
diff --git a/src/Filee.Core/Presets/BuiltInData.cs b/src/Filee.Core/Presets/BuiltInData.cs
index 65fab5c3..077bb8d0 100644
--- a/src/Filee.Core/Presets/BuiltInData.cs
+++ b/src/Filee.Core/Presets/BuiltInData.cs
@@ -74,6 +74,35 @@ public static class BuiltInData
new() { Id = "to-html", Name = "HTML", TargetFormat = "html" },
.. SpreadsheetPresets(),
.. CatalogPresets(),
+ .. CodecAndSubtitlePresets(),
+ ];
+
+ /// <summary>
+ /// HEVC / AV1 video, ALAC and the subtitle targets (added in settings schema 11, see SettingsMigrations).
+ /// </summary>
+ public static List<Preset> CodecAndSubtitlePresets() =>
+ [
+ // Video codecs and lossless audio
+ new()
+ {
+ Id = "mp4-hevc", Name = "MP4 HEVC", TargetFormat = "mp4",
+ Media = { VideoCodec = VideoCodec.Hevc }, Output = { FileNamePattern = "{name}_hevc" },
+ },
+ new()
+ {
+ Id = "mp4-av1", Name = "MP4 AV1", TargetFormat = "mp4",
+ Media = { VideoCodec = VideoCodec.Av1 }, Output = { FileNamePattern = "{name}_av1" },
+ },
+ new() { Id = "to-alac", Name = "ALAC", TargetFormat = "m4a", Media = { AudioCodec = AudioCodec.Alac } },
+
+ // Subtitles; on the video donut, SRT takes the first text subtitle track out of the video.
+ new() { Id = "extract-subtitles", NameKey = "preset.extract_subtitles", TargetFormat = "srt" },
+ new() { Id = "to-srt", Name = "SRT", TargetFormat = "srt" },
+ new() { Id = "to-vtt", Name = "WebVTT", TargetFormat = "vtt" },
+ new() { Id = "to-ass", Name = "ASS", TargetFormat = "ass" },
+ new() { Id = "to-smi", Name = "SAMI", TargetFormat = "smi" },
+ new() { Id = "to-lrc", Name = "LRC", TargetFormat = "lrc" },
+ new() { Id = "to-ttml", Name = "TTML", TargetFormat = "ttml" },
];
/// <summary>HWP as a target, through HWPX (added in settings schema 7, see SettingsMigrations).</summary>
@@ -195,7 +224,7 @@ public static class BuiltInData
PresetIds = ["to-pdf", "to-docx", "to-hwpx", "to-hwp", "to-png", "to-jpg", "to-txt", "to-md", "to-epub", "merge-pdf"],
},
TextProfile(),
- .. CatalogProfiles(),
+ .. WithSubtitleProfile(CatalogProfiles()),
new()
{
Id = "mixed", NameKey = "profile.mixed", IsFallback = true,
@@ -243,7 +272,7 @@ public static class BuiltInData
{
Id = "video", NameKey = "profile.video",
Extensions = ExtensionsOf(FormatCategory.Video),
- PresetIds = ["to-mp4", "mp4-720", "to-webm", "to-mov", "to-gif", "to-mp3", "to-mkv", "to-avi"],
+ PresetIds = ["to-mp4", "mp4-720", "mp4-hevc", "to-webm", "to-mov", "to-gif", "to-mp3", "extract-subtitles", "to-mkv", "to-avi"],
},
new()
{
@@ -277,6 +306,22 @@ public static class BuiltInData
},
];
+ /// <summary>Text subtitles: SRT, ASS, WebVTT, SAMI, LRC, ... (added in settings schema 11, after "audio").</summary>
+ public static ToolbarProfile SubtitleProfile() => new()
+ {
+ Id = "subtitles",
+ NameKey = "profile.subtitles",
+ Extensions = ExtensionsOf(FormatCategory.Subtitle),
+ PresetIds = ["to-srt", "to-vtt", "to-ass", "to-smi", "to-lrc", "to-ttml"],
+ };
+
+ /// <summary><paramref name="profiles"/> with the subtitle donut after the audio donut.</summary>
+ private static List<ToolbarProfile> WithSubtitleProfile(List<ToolbarProfile> profiles)
+ {
+ profiles.Insert(profiles.FindIndex(p => p.Id == "audio") + 1, SubtitleProfile());
+ return profiles;
+ }
+
/// <summary>Every file extension of the formats in <paramref name="category"/>.</summary>
public static List<string> ExtensionsOf(FormatCategory category) =>
FormatRegistry.Known.Where(f => f.Category == category)
diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.cs
index 8ef81e8a..c6e46b50 100644
--- a/src/Filee.Core/Presets/Preset.cs
+++ b/src/Filee.Core/Presets/Preset.cs
@@ -240,12 +240,69 @@ public sealed class MediaOptions
/// <summary>Sample rate in Hz of a WAV file (8000 … 48000); 0 keeps the source's.</summary>
public int AudioSampleRate { get; set; }
- /// <summary>How a WAV file stores its samples.</summary>
+ /// <summary>How a WAV (or W64) file stores its samples.</summary>
public WavSampleFormat WavFormat { get; set; } = WavSampleFormat.Pcm16;
+ /// <summary>
+ /// Video codec for targets that can hold several (<see cref="MediaCodecs.VideoCodecsFor"/>); targets that can't
+ /// hold the chosen one use their usual codec.
+ /// </summary>
+ public VideoCodec VideoCodec { get; set; } = VideoCodec.Default;
+
+ /// <summary>Audio codec for targets that can hold several (<see cref="MediaCodecs.AudioCodecsFor"/>).</summary>
+ public AudioCodec AudioCodec { get; set; } = AudioCodec.Default;
+
public MediaOptions Clone() => (MediaOptions)MemberwiseClone();
}
+/// <summary>Video codec of a video target. <see cref="Default"/> is the target's usual codec (H.264, VP9 for WebM, ...).</summary>
+public enum VideoCodec
+{
+ Default,
+ /// <summary>H.265 / HEVC (x265): about half the size of H.264 at the same quality.</summary>
+ Hevc,
+ /// <summary>AV1 (SVT-AV1, or libaom): smaller still, slower to encode.</summary>
+ Av1,
+}
+
+/// <summary>Audio codec of an audio target. <see cref="Default"/> is the target's usual codec (AAC for M4A, ...).</summary>
+public enum AudioCodec
+{
+ Default,
+ /// <summary>Apple Lossless in M4A / M4B.</summary>
+ Alac,
+}
+
+/// <summary>Which targets take which codecs besides their default one.</summary>
+public static class MediaCodecs
+{
+ /// <summary>The video codecs <paramref name="target"/> can be written with; only Default for most targets.</summary>
+ public static IReadOnlyList<VideoCodec> VideoCodecsFor(string target) => target switch
+ {
+ // AV1 in MP4 plays in browsers, Android and Windows; QuickTime (MOV) has no AV1 mapping.
+ "mp4" or "m4v" or "mkv" => [VideoCodec.Default, VideoCodec.Hevc, VideoCodec.Av1],
+ "mov" => [VideoCodec.Default, VideoCodec.Hevc],
+ // The WebM specification allows VP8, VP9 and AV1.
+ "webm" => [VideoCodec.Default, VideoCodec.Av1],
+ _ => [VideoCodec.Default],
+ };
+
+ /// <summary>The audio codecs <paramref name="target"/> can be written with; only Default for most targets.</summary>
+ public static IReadOnlyList<AudioCodec> AudioCodecsFor(string target) => target switch
+ {
+ "m4a" or "m4b" => [AudioCodec.Default, AudioCodec.Alac],
+ _ => [AudioCodec.Default],
+ };
+
+ /// <summary>The codec <paramref name="target"/> is written with: the chosen one if the target takes it, else Default.</summary>
+ public static VideoCodec Effective(string target, VideoCodec codec) =>
+ VideoCodecsFor(target).Contains(codec) ? codec : VideoCodec.Default;
+
+ /// <summary>The codec <paramref name="target"/> is written with: the chosen one if the target takes it, else Default.</summary>
+ public static AudioCodec Effective(string target, AudioCodec codec) =>
+ AudioCodecsFor(target).Contains(codec) ? codec : AudioCodec.Default;
+}
+
/// <summary>Sample format of a WAV file. 16-bit PCM is what every player reads (and was the only one before 1.6).</summary>
public enum WavSampleFormat
{
diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs
index 7e4f98ea..fab51c96 100644
--- a/src/Filee.Core/Settings/AppSettings.cs
+++ b/src/Filee.Core/Settings/AppSettings.cs
@@ -50,7 +50,7 @@ public sealed class DonutSettings
public sealed class AppSettings
{
/// <summary>Current schema version. Increase when the format changes and add a migration.</summary>
- public const int CurrentSchemaVersion = 10;
+ public const int CurrentSchemaVersion = 11;
public int SchemaVersion { get; set; } = CurrentSchemaVersion;
@@ -89,8 +89,8 @@ public sealed class AppSettings
public List<string> EnginePriority { get; set; } =
[
"magick", "pdfium", "pdfsharp", "rhwp", "unhwp", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer",
- "pdf-text", "email", "vector", "icns", "font", "cad", "archive", "ebook", "ffmpeg", "pandoc", "ghostscript", "calibre",
- "libreoffice",
+ "pdf-text", "email", "vector", "icns", "font", "cad", "archive", "ebook", "subtitle", "ffmpeg", "pandoc", "ghostscript",
+ "calibre", "libreoffice",
];
/// <summary>Set once the first-run welcome has been shown.</summary>
diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs
index ae92ef14..0895a148 100644
--- a/src/Filee.Core/Settings/UserDataStore.cs
+++ b/src/Filee.Core/Settings/UserDataStore.cs
@@ -252,6 +252,10 @@ internal static class SettingsMigrations
InsertBefore(settings.EnginePriority, id, "libreoffice");
}
+ // v11: built-in "subtitle" engine (SRT, ASS, WebVTT, SAMI, LRC, TTML, ...), before FFmpeg.
+ if (settings.SchemaVersion < 11)
+ InsertBefore(settings.EnginePriority, "subtitle", "ffmpeg");
+
if (settings.Triggers.Count == 0)
settings.Triggers = TriggerGesture.Defaults();
@@ -360,20 +364,52 @@ internal static class SettingsMigrations
presets.Add(BuiltInData.CreatePresets().Single(p => p.Id == "remove-background"));
changed = true;
}
+
+ // v11: HEVC / AV1 video, ALAC and the new audio formats (WavPack, TTA, APE, DSD, ...), and a subtitles donut
+ // after the audio donut. The video donut offers "MP4 HEVC" and "Extract subtitles".
+ if (from < 11)
+ changed |= AddCodecsAndSubtitles(presets, profiles);
return changed;
}
- private static bool AddCatalog(List<Preset> presets, List<ToolbarProfile> profiles)
+ private static bool AddCodecsAndSubtitles(List<Preset> presets, List<ToolbarProfile> profiles)
{
var changed = false;
- foreach (var preset in BuiltInData.CatalogPresets().Where(p => presets.All(existing => existing.Id != p.Id)))
+ foreach (var preset in BuiltInData.CodecAndSubtitlePresets().Where(p => presets.All(existing => existing.Id != p.Id)))
{
presets.Add(preset);
changed = true;
}
- var presetIds = presets.Select(p => p.Id).ToHashSet();
+ changed |= AddNewDefaultExtensions(profiles);
- // Extensions checked on a mixed-selection profile only limit that profile; they don't claim files.
+ if (profiles.All(p => p.Id != "subtitles"))
+ {
+ var claimed = profiles.Where(p => !p.IsFallback).SelectMany(p => p.Extensions).ToHashSet(StringComparer.OrdinalIgnoreCase);
+ var subtitles = BuiltInData.SubtitleProfile();
+ subtitles.Extensions = subtitles.Extensions.Where(claimed.Add).ToList();
+ if (subtitles.Extensions.Count > 0)
+ {
+ var ids = presets.Select(p => p.Id).ToHashSet();
+ subtitles.PresetIds = subtitles.PresetIds.Where(ids.Contains).ToList();
+ var audio = profiles.FindIndex(p => p.Id == "audio");
+ var insertAt = audio >= 0 ? audio + 1 : profiles.FindIndex(p => p.IsFallback);
+ profiles.Insert(insertAt < 0 ? profiles.Count : insertAt, subtitles);
+ changed = true;
+ }
+ }
+
+ changed |= Offer(presets, profiles, "video", "mp4-hevc", "mp4-720");
+ changed |= Offer(presets, profiles, "video", "extract-subtitles", "to-mp3");
+ return changed;
+ }
+
+ /// <summary>
+ /// Built-in donuts learn the extensions their defaults gained (new formats of their category), unless another
+ /// donut of the user already takes them. Extensions checked on a mixed-selection profile don't count as taken.
+ /// </summary>
+ private static bool AddNewDefaultExtensions(List<ToolbarProfile> profiles)
+ {
+ var changed = false;
var claimed = profiles.Where(p => !p.IsFallback).SelectMany(p => p.Extensions).ToHashSet(StringComparer.OrdinalIgnoreCase);
var defaults = BuiltInData.CreateProfiles().ToDictionary(p => p.Id);
foreach (var profile in profiles.Where(p => !p.IsFallback && defaults.ContainsKey(p.Id)))
@@ -384,6 +420,22 @@ internal static class SettingsMigrations
changed = true;
}
}
+ return changed;
+ }
+
+ private static bool AddCatalog(List<Preset> presets, List<ToolbarProfile> profiles)
+ {
+ var changed = false;
+ foreach (var preset in BuiltInData.CatalogPresets().Where(p => presets.All(existing => existing.Id != p.Id)))
+ {
+ presets.Add(preset);
+ changed = true;
+ }
+ var presetIds = presets.Select(p => p.Id).ToHashSet();
+
+ changed |= AddNewDefaultExtensions(profiles);
+ // Extensions checked on a mixed-selection profile only limit that profile; they don't claim files.
+ var claimed = profiles.Where(p => !p.IsFallback).SelectMany(p => p.Extensions).ToHashSet(StringComparer.OrdinalIgnoreCase);
var text = profiles.FindIndex(p => p.Id == "text");
var insertAt = text >= 0 ? text + 1 : profiles.FindIndex(p => p.IsFallback);
diff --git a/src/Filee.Engines/EngineRegistry.cs b/src/Filee.Engines/EngineRegistry.cs
index 731e3bf3..1f7e9033 100644
--- a/src/Filee.Engines/EngineRegistry.cs
+++ b/src/Filee.Engines/EngineRegistry.cs
@@ -14,6 +14,7 @@ using Filee.Engines.Magick;
using Filee.Engines.Media;
using Filee.Engines.Office;
using Filee.Engines.Pdf;
+using Filee.Engines.Subtitles;
using Filee.Engines.Text;
using Filee.Engines.Vector;
@@ -45,6 +46,7 @@ public static class EngineRegistry
new DocxWriterConverter(),
new PdfTextConverter(),
new EmlConverter(),
+ new SubtitleConverter(),
new FfmpegConverter(),
new CadConverter(),
new EbookConverter(),
diff --git a/src/Filee.Engines/Media/FfmpegConverter.cs b/src/Filee.Engines/Media/FfmpegConverter.cs
index e095bc51..5a621e6f 100644
--- a/src/Filee.Engines/Media/FfmpegConverter.cs
+++ b/src/Filee.Engines/Media/FfmpegConverter.cs
@@ -1,6 +1,7 @@
// 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 or a still picture → video, and images → HEIC (FFmpeg's HEVC encoder, Filee's own container writer).
+// engines/ffmpeg): video ↔ video (H.264, HEVC, AV1, …), video → animated GIF or a still frame, audio extraction,
+// subtitle extraction (the first text track as SRT / ASS / WebVTT), audio ↔ audio and GIF or a still picture →
+// video, and images → HEIC (FFmpeg's HEVC encoder, Filee's own container writer).
// Container and codec choices live in MediaEncoding, the process handling in FfmpegRunner.
using System.Collections.Concurrent;
@@ -30,8 +31,9 @@ public sealed partial class FfmpegConverter : IConverter
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);
+ /// Every video format (read by FFmpeg's demuxers) → every video target, animated GIF, a still PNG frame, every
+ /// audio target and SRT / ASS / WebVTT (its subtitles); every audio format → every audio target (including
+ /// itself: re-encode with another bitrate);
/// GIF and PNG → MP4, WEBM, MOV; every image ImageMagick reads → HEIC. Only formats the pinned build can write
/// are targets (see MediaEncoding).
/// </summary>
@@ -50,6 +52,10 @@ public sealed partial class FfmpegConverter : IConverter
return
[
.. from source in videos from target in videoTargets select new ConversionEdge(source, target),
+ // Subtitles out of a video. SRT is the hub to the other subtitle formats (the subtitle engine takes it on),
+ // so ASS and WebVTT cost a little more and are only taken when they are the target.
+ .. from source in videos from target in MediaEncoding.SubtitleTargets.Keys
+ select new ConversionEdge(source, target, target == "srt" ? 10 : 11),
.. videos.Select(source => new ConversionEdge(source, "gif", 15)),
.. from source in audios from target in MediaEncoding.AudioTargets.Keys select new ConversionEdge(source, target),
.. MediaEncoding.PictureToVideoTargets.Select(target => new ConversionEdge("gif", target)),
@@ -92,14 +98,14 @@ public sealed partial class FfmpegConverter : IConverter
var still = step.From == "png";
// Album art for targets FFmpeg can't put a picture stream into (Ogg, Matroska): prepared on the side.
- var cover = !still && info.CoverStreamIndex is { } coverStream
+ var cover = !still && info.CoverStreamIndex is { } coverStream && MediaEncoding.AudioTargets.ContainsKey(step.To)
? await CoverArt.PrepareAsync(ffmpeg, input, coverStream, step.To, step.WorkDirectory, cancellationToken)
: null;
// Throws for a missing stream before anything is written (an existing file of that name stays untouched).
var passes = still
? MediaEncoding.PlanStill(input, output, step.To, step.Preset.Media, info)
- : MediaEncoding.Plan(input, output, step.To, step.Preset.Media, info, step.WorkDirectory, cover);
+ : MediaEncoding.Plan(input, output, step.To, step.Preset.Media, info, step.WorkDirectory, cover, EncodersOf(ffmpeg));
var duration = still ? MediaEncoding.StillDuration : info.Duration;
try
{
@@ -181,6 +187,44 @@ public sealed partial class FfmpegConverter : IConverter
[GeneratedRegex(@"version\s+n?(\d+(?:\.\d+)+|\S+)")]
private static partial Regex VersionPattern();
+ private static readonly ConcurrentDictionary<string, IReadOnlySet<string>?> Encoders = new();
+
+ /// <summary>
+ /// The encoders of <paramref name="ffmpeg"/> (<c>ffmpeg -encoders</c>), cached per executable: a copy the user
+ /// picked may lack x265 or SVT-AV1. Null (assume Filee's build) when the list can't be read.
+ /// </summary>
+ private static IReadOnlySet<string>? EncodersOf(string ffmpeg) =>
+ Encoders.GetOrAdd($"{ffmpeg}|{File.GetLastWriteTimeUtc(ffmpeg).Ticks}", _ =>
+ {
+ try
+ {
+ using var process = Process.Start(new ProcessStartInfo(ffmpeg, "-hide_banner -encoders")
+ {
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ });
+ if (process is null)
+ return null;
+ process.ErrorDataReceived += (_, _) => { };
+ process.BeginErrorReadLine();
+ var list = process.StandardOutput.ReadToEnd();
+ if (!process.WaitForExit(10_000) || process.ExitCode != 0)
+ return null;
+ // " V....D libx265 libx265 H.265 / HEVC (codec hevc)"
+ return list.Split('\n')
+ .Select(line => line.Split(' ', StringSplitOptions.RemoveEmptyEntries))
+ .Where(parts => parts.Length >= 2 && parts[0].Length == 6 && parts[0][0] is 'V' or 'A' or 'S')
+ .Select(parts => parts[1])
+ .ToHashSet(StringComparer.Ordinal);
+ }
+ catch (Exception ex) when (ex is InvalidOperationException or System.ComponentModel.Win32Exception or IOException)
+ {
+ return null;
+ }
+ });
+
private static void TryDelete(string path)
{
try
diff --git a/src/Filee.Engines/Media/FfmpegRunner.cs b/src/Filee.Engines/Media/FfmpegRunner.cs
index b1629129..b4cb60b4 100644
--- a/src/Filee.Engines/Media/FfmpegRunner.cs
+++ b/src/Filee.Engines/Media/FfmpegRunner.cs
@@ -46,6 +46,8 @@ internal static class FfmpegRunner
};
foreach (var argument in arguments)
psi.ArgumentList.Add(argument);
+ // SVT-AV1 logs its settings to stderr, where they would bury FFmpeg's error message: errors only.
+ psi.Environment["SVT_LOG"] = "1";
using var process = new Process { StartInfo = psi };
var lastActivity = Stopwatch.GetTimestamp();
diff --git a/src/Filee.Engines/Media/MediaEncoding.cs b/src/Filee.Engines/Media/MediaEncoding.cs
index 96260289..b43b58eb 100644
--- a/src/Filee.Engines/Media/MediaEncoding.cs
+++ b/src/Filee.Engines/Media/MediaEncoding.cs
@@ -78,8 +78,31 @@ internal static class MediaEncoding
["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"),
+ // Lossless: WavPack and TTA (FFmpeg's own encoders); Sony Wave64 is WAV without the 4 GB limit.
+ ["wv"] = new("wv", null, "wavpack"),
+ ["tta"] = new("tta", null, "tta"),
+ ["w64"] = new("w64", null, "pcm_s16le"),
+ ["eac3"] = new("eac3", null, "eac3"),
};
+ /// <summary>Subtitle formats a video's first text subtitle track can be taken out as: (muxer, encoder).</summary>
+ public static IReadOnlyDictionary<string, (string Muxer, string Encoder)> SubtitleTargets { get; } = new Dictionary<string, (string, string)>
+ {
+ ["srt"] = ("srt", "srt"),
+ ["ass"] = ("ass", "ass"),
+ ["vtt"] = ("webvtt", "webvtt"),
+ };
+
+ /// <summary>
+ /// Subtitle codecs that are text (FFmpeg decodes them to text; CEA-608 captions too). Blu-ray PGS, DVD VobSub and
+ /// DVB subtitles are pictures.
+ /// </summary>
+ private static readonly HashSet<string> TextSubtitleCodecs =
+ [
+ "subrip", "srt", "ass", "ssa", "webvtt", "mov_text", "text", "microdvd", "sami", "realtext", "subviewer", "subviewer1",
+ "jacosub", "mpl2", "pjs", "vplayer", "stl", "eia_608", "ttml",
+ ];
+
/// <summary>Formats an animated GIF or a still picture (PNG) can be turned into.</summary>
public static IReadOnlyList<string> PictureToVideoTargets { get; } = ["mp4", "webm", "mov"];
@@ -117,24 +140,28 @@ internal static class MediaEncoding
/// </summary>
/// <param name="workDirectory">Scratch folder (the GIF palette goes there).</param>
/// <param name="cover">The source's cover for targets FFmpeg can't put a picture stream into (<see cref="CoverArt"/>).</param>
+ /// <param name="encoders">The encoders the FFmpeg in use has (<c>ffmpeg -encoders</c>); null assumes the pinned build's.</param>
/// <exception cref="InvalidOperationException">The file lacks the stream the target needs (e.g. no audio track).</exception>
public static IReadOnlyList<FfmpegPass> Plan(string input, string output, string target, MediaOptions options, MediaInfo info, string workDirectory,
- CoverExtras? cover = null)
+ CoverExtras? cover = null, IReadOnlySet<string>? encoders = null)
{
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)];
+ return [new FfmpegPass(Video(input, output, target, video, options, info, encoders), 1)];
if (AudioTargets.TryGetValue(target, out var audio))
return [new FfmpegPass(Audio(input, output, target, audio, options, info, cover), 1)];
+ if (SubtitleTargets.ContainsKey(target))
+ return [new FfmpegPass(Subtitles(input, output, target, 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)
+ private static List<string> Video(string input, string output, string target, MediaTarget spec, MediaOptions options, MediaInfo info,
+ IReadOnlySet<string>? encoders)
{
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.
@@ -155,7 +182,7 @@ internal static class MediaEncoding
{
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));
+ args.AddRange(VideoCodecArguments(target, VideoEncoder(target, spec.VideoCodec!, options.VideoCodec, encoders), options.Quality, video, pal));
}
if (audio is null)
@@ -195,13 +222,47 @@ internal static class MediaEncoding
/// <summary>
/// True when the video stream can be copied: the target container takes its codec in a pixel format players
/// decode, it needs no scaling down, and the preset does not ask for a small file (Small always re-encodes; High
- /// and Balanced only describe how a video that has to be encoded anyway is encoded).
+ /// and Balanced only describe how a video that has to be encoded anyway is encoded). A preset that asks for HEVC
+ /// or AV1 copies only a video in that codec (an AV1 video goes into MP4 then too).
/// </summary>
- internal static bool CanCopyVideo(string target, VideoStreamInfo video, MediaOptions options) =>
- options.Quality != MediaQuality.Small
- && Remuxable.TryGetValue(target, out var codecs) && video.Codec is { } codec && codecs.Video.Contains(codec)
- && (codec == "prores" || video.PixelFormat is { } format && PlayablePixelFormats.Contains(format))
- && !(options.MaxHeight > 0 && video.DisplayHeight > Math.Max(16, options.MaxHeight));
+ internal static bool CanCopyVideo(string target, VideoStreamInfo video, MediaOptions options)
+ {
+ if (options.Quality == MediaQuality.Small || options.MaxHeight > 0 && video.DisplayHeight > Math.Max(16, options.MaxHeight)
+ || video.Codec is not { } codec || !Remuxable.TryGetValue(target, out var codecs))
+ return false;
+ var takes = MediaCodecs.Effective(target, options.VideoCodec) switch
+ {
+ VideoCodec.Hevc => codec == "hevc",
+ VideoCodec.Av1 => codec == "av1",
+ _ => codecs.Video.Contains(codec),
+ };
+ return takes && (codec == "prores" || video.PixelFormat is { } format && PlayablePixelFormats.Contains(format));
+ }
+
+ /// <summary>
+ /// The encoder for a video that has to be encoded: the preset's codec where the target takes it (x265 for HEVC;
+ /// SVT-AV1 for AV1, libaom where an FFmpeg lacks SVT-AV1), else the target's usual one.
+ /// </summary>
+ /// <exception cref="InvalidOperationException">The FFmpeg in use has no encoder for the chosen codec.</exception>
+ internal static string VideoEncoder(string target, string defaultEncoder, VideoCodec codec, IReadOnlySet<string>? encoders)
+ {
+ bool Has(string encoder) => encoders is null || encoders.Contains(encoder);
+ switch (MediaCodecs.Effective(target, codec))
+ {
+ case VideoCodec.Hevc when Has("libx265"):
+ return "libx265";
+ case VideoCodec.Hevc:
+ throw new InvalidOperationException("This FFmpeg has no HEVC encoder (libx265). Filee's FFmpeg download has one.");
+ case VideoCodec.Av1 when Has("libsvtav1"):
+ return "libsvtav1";
+ case VideoCodec.Av1 when Has("libaom-av1"):
+ return "libaom-av1";
+ case VideoCodec.Av1:
+ throw new InvalidOperationException("This FFmpeg has no AV1 encoder (libsvtav1 or libaom-av1). Filee's FFmpeg download has one.");
+ default:
+ return defaultEncoder;
+ }
+ }
/// <summary>
/// True when the audio stream can be copied: the container takes it, no bitrate is set and the channels stay
@@ -249,6 +310,19 @@ internal static class MediaEncoding
// 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 "libx265":
+ // x265's CRF 28 looks like x264's 23 at about half the size; 22 / 26 / 30 keep High clean and Small
+ // clearly smaller than H.264 Small. Apple plays HEVC in MP4 / MOV only under the "hvc1" tag.
+ return ["-c:v", "libx265", "-preset", "medium", "-crf", Text(Choose(quality, 22, 26, 30)),
+ .. HighBitDepthArguments(video), "-x265-params", "log-level=error",
+ .. target is "mp4" or "m4v" or "mov" ? ["-tag:v", "hvc1"] : Array.Empty<string>()];
+ case "libsvtav1":
+ // SVT-AV1 preset 8: fast enough on a desktop, a little larger than the slow presets.
+ return ["-c:v", "libsvtav1", "-preset", "8", "-crf", Text(Choose(quality, 26, 32, 40)), .. HighBitDepthArguments(video)];
+ case "libaom-av1":
+ // Constant quality (-b:v 0 + CRF); cpu-used 6 with row multithreading and tiles keeps libaom bearable.
+ return ["-c:v", "libaom-av1", "-b:v", "0", "-crf", Text(Choose(quality, 26, 32, 40)), "-cpu-used", "6", "-row-mt", "1",
+ "-tiles", "2x2", .. HighBitDepthArguments(video)];
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.
@@ -283,6 +357,27 @@ internal static class MediaEncoding
}
}
+ /// <summary>
+ /// HEVC and AV1 keep 10 bits for 10-bit and HDR sources (Main 10; 8 bits would band and break HDR) and 8-bit 4:2:0
+ /// for everything else, which every player decodes. HDR colour tags (BT.2020 primaries, PQ or HLG transfer) are
+ /// written as the source has them.
+ /// </summary>
+ internal static string[] HighBitDepthArguments(VideoStreamInfo video)
+ {
+ var tenBit = video.IsHighBitDepth || video.IsHdr;
+ List<string> args = ["-pix_fmt", tenBit ? "yuv420p10le" : "yuv420p"];
+ if (tenBit && video.Color is { } color)
+ {
+ if (color.Primaries is { } primaries)
+ args.AddRange(["-color_primaries", primaries]);
+ if (color.Transfer is { } transfer)
+ args.AddRange(["-color_trc", transfer]);
+ if (color.Matrix is { } matrix)
+ args.AddRange(["-colorspace", matrix]);
+ }
+ return [.. args];
+ }
+
/// <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];
@@ -353,15 +448,24 @@ internal static class MediaEncoding
args.AddRange(["-map", $"0:{cover}", "-c:v", "copy", "-disposition:v:0", "attached_pic"]);
if (extras is { AttachmentFile: { } picture, AttachmentMime: { } mime })
args.AddRange(["-attach", picture, "-metadata:s:t", "mimetype=" + mime, "-metadata:s:t", "filename=" + Path.GetFileName(picture)]);
- var codec = target == "wav" ? WavCodec(options.WavFormat) : spec.AudioCodec;
+ var codec = AudioEncoder(target, spec.AudioCodec, options);
args.AddRange(AudioCodecArguments(target, codec, options, audio, inVideo: false));
- args.AddRange(ChannelAndRateArguments(target, codec, options));
+ args.AddRange(ChannelAndRateArguments(target, codec, options, audio.SampleRate));
args.AddRange(MetadataArguments(extras?.MetadataFile is null ? 0 : 1));
args.AddRange(ContainerArguments(target));
args.AddRange(["-f", spec.Muxer, "-progress", "pipe:1", output]);
return args;
}
+ /// <summary>
+ /// The audio encoder of a target: the PCM format the preset picks for WAV and W64, ALAC for M4A / M4B when the
+ /// preset asks for Apple Lossless, else the target's usual one.
+ /// </summary>
+ internal static string AudioEncoder(string target, string defaultEncoder, MediaOptions options) =>
+ target is "wav" or "w64" ? WavCodec(options.WavFormat)
+ : MediaCodecs.Effective(target, options.AudioCodec) == Core.Presets.AudioCodec.Alac ? "alac"
+ : defaultEncoder;
+
/// <summary>The PCM codec of a WAV sample format (little-endian, 8-bit is unsigned as WAV defines it).</summary>
internal static string WavCodec(WavSampleFormat format) => format switch
{
@@ -374,22 +478,38 @@ internal static class MediaEncoding
/// <summary>
/// Mono or stereo for any audio target (after the codec's own limits, so the user's choice wins), and the sample
- /// rate for WAV, whose PCM takes any rate. Codecs with a fixed layout (AMR is mono, 8 kHz) are left alone.
+ /// rate for WAV and W64, whose PCM takes any rate. Codecs with a fixed layout (AMR is mono, 8 kHz) are left alone.
/// </summary>
- internal static IEnumerable<string> ChannelAndRateArguments(string target, string codec, MediaOptions options)
+ /// <param name="sourceSampleRate">
+ /// The source's rate. DSD (DSF, DFF) decodes at 352.8 kHz or more: lossless and PCM targets get 88.2 kHz (the
+ /// usual rate for DSD as PCM), Vorbis and WMA 44.1 kHz; the other lossy encoders pick a rate they support.
+ /// </param>
+ internal static IEnumerable<string> ChannelAndRateArguments(string target, string codec, MediaOptions options, int sourceSampleRate = 0)
{
if (options.AudioChannels is 1 or 2 && codec != "libopencore_amrnb")
{
yield return "-ac";
yield return options.AudioChannels.ToString(CultureInfo.InvariantCulture);
}
- if (target == "wav" && options.AudioSampleRate is >= 8000 and <= 192000)
+ if (target is "wav" or "w64" && options.AudioSampleRate is >= 8000 and <= 192000)
{
yield return "-ar";
yield return options.AudioSampleRate.ToString(CultureInfo.InvariantCulture);
}
+ else if (sourceSampleRate > 192000 && (LosslessEncoders.Contains(codec) || codec.StartsWith("pcm_", StringComparison.Ordinal)))
+ {
+ yield return "-ar";
+ yield return "88200";
+ }
+ else if (sourceSampleRate > 192000 && codec is "libvorbis" or "wmav2")
+ {
+ yield return "-ar";
+ yield return "44100";
+ }
}
+ private static readonly HashSet<string> LosslessEncoders = ["flac", "alac", "wavpack", "tta"];
+
/// <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
@@ -449,6 +569,10 @@ internal static class MediaEncoding
if (requested > 0)
args.AddRange(Bitrate(Snap(requested, Ac3Bitrates), 32, 640));
break;
+ case "eac3":
+ // E-AC-3 takes any bitrate; per stereo pair 256 / 192 / 128 kbit/s like AAC.
+ args.AddRange(Bitrate(requested > 0 ? requested : Scaled(Choose(quality, 256, 192, 128), channels), 32, 6144));
+ 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"]);
@@ -479,6 +603,24 @@ internal static class MediaEncoding
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];
+ // ───────────────────────── Subtitles ─────────────────────────
+
+ /// <summary>
+ /// The first text subtitle track of a video as SRT, ASS or WebVTT (UTF-8). A track already in the target's format is
+ /// copied as it is (an ASS track keeps its styles); others are converted by FFmpeg.
+ /// </summary>
+ /// <exception cref="InvalidOperationException">The video has no subtitle track, or only picture subtitles.</exception>
+ private static List<string> Subtitles(string input, string output, string target, MediaInfo info)
+ {
+ var track = info.Subtitles.FirstOrDefault(s => s.Codec is { } codec && TextSubtitleCodecs.Contains(codec))
+ ?? throw new InvalidOperationException(info.Subtitles.Count == 0
+ ? "The video has no subtitle track."
+ : "The video's subtitles are pictures (Blu-ray PGS, DVD or DVB subtitles), not text. Picture subtitles can't be turned into text without OCR.");
+ var (muxer, encoder) = SubtitleTargets[target];
+ var same = (target, track.Codec) is ("srt", "subrip" or "srt") or ("ass", "ass") or ("vtt", "webvtt");
+ return [.. Common, "-i", input, "-map", $"0:{track.Index}", "-c:s", same ? "copy" : encoder, "-f", muxer, "-progress", "pipe:1", output];
+ }
+
// ───────────────────────── Animated GIF ─────────────────────────
/// <summary>
diff --git a/src/Filee.Engines/Media/MediaInfo.cs b/src/Filee.Engines/Media/MediaInfo.cs
index b482b8bf..e058fbac 100644
--- a/src/Filee.Engines/Media/MediaInfo.cs
+++ b/src/Filee.Engines/Media/MediaInfo.cs
@@ -15,9 +15,24 @@ namespace Filee.Engines.Media;
/// <param name="FrameRate">Average frames per second, 0 when unknown.</param>
/// <param name="Codec">FFmpeg's codec name (<c>h264</c>, <c>hevc</c>, …), null when unknown.</param>
/// <param name="PixelFormat">FFmpeg's pixel format (<c>yuv420p</c>, <c>yuv420p10le</c>, …), null when unknown.</param>
+/// <param name="Color">Colour primaries, transfer and matrix as FFmpeg names them (<c>bt2020</c>, <c>smpte2084</c>, …).</param>
internal sealed record VideoStreamInfo(int Width, int Height, double SampleAspect, int Rotation, double FrameRate,
- string? Codec = null, string? PixelFormat = null)
+ string? Codec = null, string? PixelFormat = null, VideoColor? Color = null)
{
+ /// <summary>
+ /// True for more than 8 bits per sample (yuv420p10le, p010le, yuv422p12le, …): phones' HDR video, ProRes, 10-bit
+ /// HEVC and AV1. HEVC and AV1 targets keep 10 bits for these.
+ /// </summary>
+ public bool IsHighBitDepth => PixelFormat is { } format
+ && (HighBitDepthSuffixes.Any(s => format.Contains(s, StringComparison.Ordinal))
+ || HighBitDepthPrefixes.Any(p => format.StartsWith(p, StringComparison.Ordinal)));
+
+ private static readonly string[] HighBitDepthSuffixes = ["p10", "p12", "p14", "p16"];
+ private static readonly string[] HighBitDepthPrefixes = ["p010", "p012", "p016", "p210", "p216", "p410", "p416", "y210", "y212", "v210"];
+
+ /// <summary>True for HDR video: PQ (HDR10, Dolby Vision) or HLG transfer.</summary>
+ public bool IsHdr => Color?.Transfer is "smpte2084" or "arib-std-b67";
+
/// <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;
@@ -37,6 +52,15 @@ internal sealed record VideoStreamInfo(int Width, int Height, double SampleAspec
}
}
+/// <summary>Colour description of a video stream, in FFmpeg's names; null parts are unknown.</summary>
+internal sealed record VideoColor(string? Primaries, string? Transfer, string? Matrix, string? Range);
+
+/// <summary>A subtitle stream of a file.</summary>
+/// <param name="Index">The stream's index in the file (for <c>-map 0:index</c>).</param>
+/// <param name="Codec">FFmpeg's codec name (<c>subrip</c>, <c>ass</c>, <c>mov_text</c>, <c>hdmv_pgs_subtitle</c>, …).</param>
+/// <param name="Language">The language tag (<c>kor</c>, <c>eng</c>, …), null when the file doesn't say.</param>
+internal sealed record SubtitleStreamInfo(int Index, string? Codec, string? Language);
+
/// <summary>The first audio stream of a file.</summary>
/// <param name="Codec">FFmpeg's codec name (<c>aac</c>, <c>opus</c>, …), null when unknown.</param>
internal sealed record AudioStreamInfo(int Channels, int SampleRate, string? Codec = null);
@@ -46,8 +70,13 @@ internal sealed record AudioStreamInfo(int Channels, int SampleRate, string? Cod
/// <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)
+/// <param name="SubtitleStreams">Every subtitle stream in file order, null when there is none.</param>
+internal sealed record MediaInfo(TimeSpan? Duration, VideoStreamInfo? Video, AudioStreamInfo? Audio, int? CoverStreamIndex,
+ IReadOnlyList<SubtitleStreamInfo>? SubtitleStreams = null)
{
+ /// <summary>Every subtitle stream, in file order.</summary>
+ public IReadOnlyList<SubtitleStreamInfo> Subtitles => SubtitleStreams ?? [];
+
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>
@@ -73,6 +102,7 @@ internal sealed record MediaInfo(TimeSpan? Duration, VideoStreamInfo? Video, Aud
VideoStreamInfo? video = null;
AudioStreamInfo? audio = null;
int? cover = null;
+ List<SubtitleStreamInfo> subtitles = [];
double longestStream = 0;
if (root.TryGetProperty("streams", out var streams) && streams.ValueKind == JsonValueKind.Array)
{
@@ -94,12 +124,17 @@ internal sealed record MediaInfo(TimeSpan? Duration, VideoStreamInfo? Video, Aud
RotationOf(stream),
FrameRateOf(stream),
Text(stream, "codec_name"),
- Text(stream, "pix_fmt"));
+ Text(stream, "pix_fmt"),
+ ColorOf(stream));
break;
case "audio" when audio is null:
audio = new AudioStreamInfo((int)Number(stream, "channels"), (int)Number(stream, "sample_rate"),
Text(stream, "codec_name"));
break;
+ case "subtitle":
+ subtitles.Add(new SubtitleStreamInfo((int)Number(stream, "index"), Text(stream, "codec_name"),
+ stream.TryGetProperty("tags", out var tags) ? Text(tags, "language") : null));
+ break;
}
}
}
@@ -107,7 +142,16 @@ internal sealed record MediaInfo(TimeSpan? Duration, VideoStreamInfo? Video, Aud
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);
+ return new MediaInfo(seconds > 0 ? TimeSpan.FromSeconds(seconds) : null, video, audio, cover,
+ subtitles.Count > 0 ? subtitles : null);
+ }
+
+ /// <summary>The colour tags of a video stream; null when it has none ("unknown" counts as none).</summary>
+ private static VideoColor? ColorOf(JsonElement stream)
+ {
+ string? Known(string name) => Text(stream, name) is { } value && value != "unknown" ? value : null;
+ var color = new VideoColor(Known("color_primaries"), Known("color_transfer"), Known("color_space"), Known("color_range"));
+ return color is { Primaries: null, Transfer: null, Matrix: null, Range: null } ? null : color;
}
private static bool IsAttachedPicture(JsonElement stream) =>
diff --git a/src/Filee.Engines/Subtitles/SamiReader.cs b/src/Filee.Engines/Subtitles/SamiReader.cs
new file mode 100644
index 00000000..a082c2e0
--- /dev/null
+++ b/src/Filee.Engines/Subtitles/SamiReader.cs
@@ -0,0 +1,116 @@
+// SAMI (.smi), Microsoft's HTML-like subtitle format and the usual one for Korean subtitles. Files are hand-made and
+// rarely valid HTML: <SYNC> and <P> are seldom closed, attribute values are unquoted, and one file may hold several
+// languages as classes (KRCC, ENCC, …). The text is read with regular expressions, not an HTML parser.
+
+using System.Globalization;
+using System.Text.RegularExpressions;
+
+namespace Filee.Engines.Subtitles;
+
+/// <summary>Reads SAMI subtitles.</summary>
+internal static partial class SamiReader
+{
+ /// <summary>
+ /// Reads every <c>&lt;SYNC Start=ms&gt;</c>: its text lasts until the next SYNC, and a SYNC with only
+ /// <c>&amp;nbsp;</c> clears the screen. Of several languages, the one with the most lines is read (the first
+ /// one on a tie).
+ /// </summary>
+ public static SubtitleDocument Read(string text)
+ {
+ var document = new SubtitleDocument();
+ if (Title().Match(text) is { Success: true } title && System.Net.WebUtility.HtmlDecode(title.Groups["text"].Value).Trim() is { Length: > 0 } name)
+ document.Title = name;
+
+ // Body only: the <STYLE> block's comment would otherwise look like text.
+ var body = BodyStart().Match(text) is { Success: true } start ? text[(start.Index + start.Length)..] : text;
+ body = Comment().Replace(body, "");
+ var syncs = Sync().Matches(body);
+ List<(TimeSpan Time, string Class, string Text)> entries = [];
+ for (var i = 0; i < syncs.Count; i++)
+ {
+ if (!int.TryParse(syncs[i].Groups["start"].Value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var ms))
+ continue;
+ var contentStart = syncs[i].Index + syncs[i].Length;
+ var contentEnd = i + 1 < syncs.Count ? syncs[i + 1].Index : body.Length;
+ var content = BodyEnd().Replace(body[contentStart..contentEnd], "");
+ var time = TimeSpan.FromMilliseconds(Math.Max(0, ms));
+
+ var paragraphs = Paragraph().Matches(content);
+ if (paragraphs.Count == 0)
+ {
+ entries.Add((time, "", Text(content)));
+ continue;
+ }
+ for (var p = 0; p < paragraphs.Count; p++)
+ {
+ var end = p + 1 < paragraphs.Count ? paragraphs[p + 1].Index : content.Length;
+ var paragraph = content[(paragraphs[p].Index + paragraphs[p].Length)..end];
+ var language = ClassAttribute().Match(paragraphs[p].Groups["attributes"].Value) is { Success: true } c ? c.Groups["name"].Value.ToUpperInvariant() : "";
+ entries.Add((time, language, Text(paragraph)));
+ }
+ }
+
+ // The language with the most lines; lines without a class belong to every language.
+ var chosen = entries.Where(e => e.Class.Length > 0 && SubtitleMarkup.PlainText(e.Text).Trim().Length > 0)
+ .GroupBy(e => e.Class)
+ .Select((g, order) => (g.Key, Count: g.Count(), Order: order))
+ .OrderByDescending(g => g.Count).ThenBy(g => g.Order)
+ .Select(g => g.Key)
+ .FirstOrDefault() ?? "";
+ var lines = entries.Where(e => e.Class.Length == 0 || e.Class == chosen).OrderBy(e => e.Time).ToList();
+ for (var i = 0; i < lines.Count; i++)
+ {
+ var end = i + 1 < lines.Count ? lines[i + 1].Time : lines[i].Time + SubtitleDocument.DefaultDuration;
+ // Two entries at the same time: the later one wins.
+ if (end == lines[i].Time && i + 1 < lines.Count)
+ continue;
+ document.Add(lines[i].Time, end, lines[i].Text);
+ }
+
+ if (chosen.Length > 0 && LanguageOf(text, chosen) is { } lang)
+ document.Language = lang;
+ return document;
+ }
+
+ /// <summary>The paragraph's text as cue markup: HTML whitespace rules (source line breaks are spaces), <c>&lt;br&gt;</c> breaks.</summary>
+ private static string Text(string html) =>
+ SubtitleMarkup.FromHtml(Whitespace().Replace(LooseNbsp().Replace(html, "&nbsp;"), " "), decodeEntities: true);
+
+ /// <summary>Hand-written files clear the screen with <c>&amp;nbsp</c> without the semicolon, or in capitals.</summary>
+ [GeneratedRegex("&nbsp;?", RegexOptions.IgnoreCase)]
+ private static partial Regex LooseNbsp();
+
+ /// <summary>The <c>lang:</c> of a class in the style sheet: <c>.KRCC { Name: Korean; lang: ko-KR; }</c>.</summary>
+ private static string? LanguageOf(string text, string className)
+ {
+ var rule = Regex.Match(text, @"\." + Regex.Escape(className) + @"\s*\{(?<rule>[^}]*)\}", RegexOptions.IgnoreCase);
+ return rule.Success && Lang().Match(rule.Groups["rule"].Value) is { Success: true } lang ? lang.Groups["value"].Value : null;
+ }
+
+ [GeneratedRegex(@"<title[^>]*>(?<text>.*?)</title>", RegexOptions.IgnoreCase | RegexOptions.Singleline)]
+ private static partial Regex Title();
+
+ [GeneratedRegex(@"<body[^>]*>", RegexOptions.IgnoreCase)]
+ private static partial Regex BodyStart();
+
+ [GeneratedRegex(@"</body\s*>.*|</sami\s*>.*", RegexOptions.IgnoreCase | RegexOptions.Singleline)]
+ private static partial Regex BodyEnd();
+
+ [GeneratedRegex(@"<!--.*?-->", RegexOptions.Singleline)]
+ private static partial Regex Comment();
+
+ [GeneratedRegex("""<sync\b[^>]*?start\s*=\s*["']?(?<start>-?\d+)[^>]*>""", RegexOptions.IgnoreCase)]
+ private static partial Regex Sync();
+
+ [GeneratedRegex(@"<p\b(?<attributes>[^>]*)>", RegexOptions.IgnoreCase)]
+ private static partial Regex Paragraph();
+
+ [GeneratedRegex("""class\s*=\s*["']?(?<name>[\w-]+)""", RegexOptions.IgnoreCase)]
+ private static partial Regex ClassAttribute();
+
+ [GeneratedRegex(@"lang\s*:\s*(?<value>[A-Za-z]{2,3}(?:-[A-Za-z0-9]+)*)", RegexOptions.IgnoreCase)]
+ private static partial Regex Lang();
+
+ [GeneratedRegex(@"\s+")]
+ private static partial Regex Whitespace();
+}
diff --git a/src/Filee.Engines/Subtitles/SccReader.cs b/src/Filee.Engines/Subtitles/SccReader.cs
new file mode 100644
index 00000000..79e55659
--- /dev/null
+++ b/src/Filee.Engines/Subtitles/SccReader.cs
@@ -0,0 +1,309 @@
+// Scenarist SCC: broadcast closed captions (CEA-608) as hex byte pairs with SMPTE time codes. A small 608 decoder
+// for caption channel 1 (CC1): pop-on captions (loaded off screen, shown at End Of Caption, removed at Erase
+// Displayed Memory), paint-on and roll-up captions, row addresses, italics, and the special and extended character
+// sets. Every byte pair takes one frame at 29.97 fps; control codes sent twice (as broadcasters do) count once.
+
+using System.Globalization;
+using System.Text;
+using System.Text.RegularExpressions;
+
+namespace Filee.Engines.Subtitles;
+
+/// <summary>Reads SCC closed captions.</summary>
+internal static partial class SccReader
+{
+ /// <summary>One NTSC frame: 1001/30000 s.</summary>
+ private const double FrameSeconds = 1001.0 / 30000;
+
+ public static SubtitleDocument Read(string text)
+ {
+ if (!text.TrimStart('', ' ', '\n').StartsWith("Scenarist_SCC", StringComparison.OrdinalIgnoreCase))
+ throw new InvalidDataException("This is not an SCC file (it must start with \"Scenarist_SCC V1.0\").");
+ var document = new SubtitleDocument();
+ var decoder = new Decoder(document);
+ var last = TimeSpan.Zero;
+ foreach (var line in text.Split('\n'))
+ {
+ if (TimedLine().Match(line.Trim()) is not { Success: true } match)
+ continue;
+ var start = TimeCode(match);
+ var words = match.Groups["data"].Value.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
+ for (var i = 0; i < words.Length; i++)
+ {
+ if (words[i].Length != 4 || !int.TryParse(words[i], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var word))
+ continue;
+ last = start + TimeSpan.FromSeconds(i * FrameSeconds);
+ decoder.Pair(last, (byte)((word >> 8) & 0x7F), (byte)(word & 0x7F));
+ }
+ }
+ decoder.Finish(last);
+ return document;
+ }
+
+ /// <summary>
+ /// A SMPTE time code as a time: frames counted at 30 per second (with drop-frame numbering when written with
+ /// <c>;</c>), played at 29.97.
+ /// </summary>
+ private static TimeSpan TimeCode(Match match)
+ {
+ int Part(string name) => int.Parse(match.Groups[name].Value, CultureInfo.InvariantCulture);
+ int h = Part("h"), m = Part("m"), s = Part("s"), f = Part("f");
+ long frames = ((h * 60L + m) * 60 + s) * 30 + f;
+ if (match.Groups["sep"].Value is ";" or ".")
+ {
+ var minutes = 60L * h + m;
+ frames -= 2 * (minutes - minutes / 10);
+ }
+ return TimeSpan.FromSeconds(frames * FrameSeconds);
+ }
+
+ /// <summary>A CEA-608 decoder for caption channel 1.</summary>
+ private sealed class Decoder(SubtitleDocument document)
+ {
+ private enum Mode { PopOn, PaintOn, RollUp }
+
+ private Mode _mode = Mode.PopOn;
+ private int _rollUpRows = 2;
+ private Memory _displayed = new();
+ private Memory _hidden = new();
+ private TimeSpan? _shownSince;
+ private bool _channelOne = true;
+ private (byte, byte)? _lastControl;
+
+ private Memory Target => _mode == Mode.PopOn ? _hidden : _displayed;
+
+ public void Pair(TimeSpan time, byte hi, byte lo)
+ {
+ // Padding (0x80 0x80 with parity) and XDS data (first byte 0x01–0x0F) carry no caption text.
+ if (hi < 0x10)
+ {
+ _lastControl = null;
+ return;
+ }
+ if (hi is >= 0x10 and <= 0x1F)
+ {
+ // Control codes are sent twice so a damaged one is not missed: the repeat does nothing.
+ if (_lastControl == (hi, lo))
+ {
+ _lastControl = null;
+ return;
+ }
+ _lastControl = (hi, lo);
+ Control(time, hi, lo);
+ return;
+ }
+ _lastControl = null;
+ if (!_channelOne)
+ return;
+ Character(time, hi);
+ if (lo >= 0x20)
+ Character(time, lo);
+ }
+
+ private void Control(TimeSpan time, byte hi, byte lo)
+ {
+ // Channel 2 uses the same codes with bit 3 of the first byte set; 0x15 / 0x1D misc codes are field 2.
+ var channel = hi >= 0x18 ? 2 : 1;
+ var basic = (byte)(hi & 0xF7);
+ if (basic is 0x14 or 0x15 && lo is >= 0x20 and <= 0x2F)
+ {
+ _channelOne = channel == 1 && basic == 0x14;
+ if (_channelOne)
+ Misc(time, lo);
+ return;
+ }
+ _channelOne = channel == 1;
+ if (!_channelOne)
+ return;
+
+ if (lo >= 0x40)
+ {
+ Preamble(basic, lo);
+ }
+ else if (basic == 0x11 && lo is >= 0x20 and <= 0x2F)
+ {
+ // Mid-row code: colour or italics, shown as a space.
+ Target.Append(time, " ");
+ Target.SetItalic((lo & 0x0E) == 0x0E);
+ }
+ else if (basic == 0x11 && lo is >= 0x30 and <= 0x3F)
+ {
+ Target.Append(time, Special[lo - 0x30].ToString());
+ }
+ else if (basic is 0x12 or 0x13 && lo is >= 0x20 and <= 0x3F)
+ {
+ // Extended characters replace the plain fallback character sent before them.
+ Target.Backspace();
+ Target.Append(time, (basic == 0x12 ? Extended1 : Extended2)[lo - 0x20].ToString());
+ }
+ // Tab offsets and background attributes don't change the text.
+ }
+
+ private void Misc(TimeSpan time, byte code)
+ {
+ switch (code)
+ {
+ case 0x20: // Resume Caption Loading
+ _mode = Mode.PopOn;
+ break;
+ case 0x21: // Backspace
+ Target.Backspace();
+ break;
+ case 0x24: // Delete to End of Row
+ Target.ClearRow();
+ break;
+ case 0x25 or 0x26 or 0x27: // Roll-Up 2, 3, 4 rows
+ if (_mode != Mode.RollUp)
+ Show(time, new Memory());
+ _mode = Mode.RollUp;
+ _rollUpRows = code - 0x23;
+ break;
+ case 0x29: // Resume Direct Captioning
+ _mode = Mode.PaintOn;
+ break;
+ case 0x2C: // Erase Displayed Memory
+ Show(time, new Memory());
+ break;
+ case 0x2D when _mode == Mode.RollUp: // Carriage Return: the row scrolls up
+ Show(time, _displayed.RolledUp(_rollUpRows));
+ _shownSince = null;
+ break;
+ case 0x2E: // Erase Non-displayed Memory
+ _hidden = new Memory();
+ break;
+ case 0x2F: // End Of Caption: swap memories
+ var next = _hidden;
+ _hidden = new Memory();
+ Show(time, next);
+ _mode = Mode.PopOn;
+ break;
+ }
+ }
+
+ private void Preamble(byte basic, byte lo)
+ {
+ var row = Array.IndexOf(PreambleRows, basic) is var index and >= 0
+ ? (basic == 0x10 ? 11 : PreambleFirstRow[index] + (lo >= 0x60 ? 1 : 0))
+ : 15;
+ if (_mode == Mode.RollUp)
+ row = 15; // roll-up captions always write on the base row
+ Target.MoveTo(row, italic: (lo & 0x1E) == 0x0E);
+ }
+
+ private void Character(TimeSpan time, byte code)
+ {
+ if (code < 0x20)
+ return;
+ Target.Append(time, Basic(code).ToString());
+ if (_mode != Mode.PopOn)
+ _shownSince ??= _displayed.FirstWrite;
+ }
+
+ /// <summary>Ends what is on screen (as a cue) and shows <paramref name="next"/> from now on.</summary>
+ private void Show(TimeSpan time, Memory next)
+ {
+ var shown = _shownSince ?? _displayed.FirstWrite;
+ if (shown is { } since && _displayed.Text is { Length: > 0 } text)
+ document.Add(since, time, text);
+ _displayed = next;
+ _shownSince = next.IsEmpty ? null : time;
+ }
+
+ public void Finish(TimeSpan time)
+ {
+ var since = _shownSince ?? _displayed.FirstWrite;
+ // Captions still on screen when the file ends stay for a while.
+ if (since is { } start)
+ Show(time > start + SubtitleDocument.DefaultDuration ? time : start + SubtitleDocument.DefaultDuration, new Memory());
+ }
+
+ private static char Basic(byte code) => code switch
+ {
+ 0x2A => 'á',
+ 0x5C => 'é',
+ 0x5E => 'í',
+ 0x5F => 'ó',
+ 0x60 => 'ú',
+ 0x7B => 'ç',
+ 0x7C => '÷',
+ 0x7D => 'Ñ',
+ 0x7E => 'ñ',
+ 0x7F => '█',
+ _ => (char)code,
+ };
+ }
+
+ /// <summary>Caption memory: rows of text (with italics as markup) by row number.</summary>
+ private sealed class Memory
+ {
+ private readonly SortedDictionary<int, StringBuilder> _rows = [];
+ private int _row = 15;
+ private bool _italic;
+
+ /// <summary>When the first character was written (paint-on and roll-up captions show from then).</summary>
+ public TimeSpan? FirstWrite { get; private set; }
+
+ public bool IsEmpty => _rows.Values.All(r => SubtitleMarkup.PlainText(r.ToString()).Trim().Length == 0);
+
+ public string Text => string.Join('\n', _rows.Values.Select(r => r.ToString() + (r.ToString().Contains("<i>", StringComparison.Ordinal) ? "</i>" : "")));
+
+ private StringBuilder Row => _rows.TryGetValue(_row, out var row) ? row : _rows[_row] = new StringBuilder();
+
+ public void MoveTo(int row, bool italic)
+ {
+ if (_italic)
+ Row.Append("</i>");
+ _row = row;
+ _italic = false;
+ SetItalic(italic);
+ }
+
+ public void SetItalic(bool italic)
+ {
+ if (italic != _italic)
+ Row.Append(italic ? "<i>" : "</i>");
+ _italic = italic;
+ }
+
+ public void Append(TimeSpan time, string text)
+ {
+ FirstWrite ??= time;
+ Row.Append(text);
+ }
+
+ public void Backspace()
+ {
+ var row = Row;
+ if (row.Length > 0 && row[^1] != '>')
+ row.Length--;
+ }
+
+ public void ClearRow() => _rows.Remove(_row);
+
+ /// <summary>A new memory with the last <paramref name="rows"/> − 1 rows moved up and an empty base row.</summary>
+ public Memory RolledUp(int rows)
+ {
+ var next = new Memory();
+ var kept = _rows.Where(r => SubtitleMarkup.PlainText(r.Value.ToString()).Trim().Length > 0).TakeLast(rows - 1).ToList();
+ for (var i = 0; i < kept.Count; i++)
+ next._rows[15 - kept.Count + i] = new StringBuilder(kept[i].Value.ToString());
+ return next;
+ }
+ }
+
+ /// <summary>First bytes of row preambles (channel 1) and the first of the two rows each one addresses.</summary>
+ private static readonly byte[] PreambleRows = [0x11, 0x12, 0x15, 0x16, 0x17, 0x10, 0x13, 0x14];
+ private static readonly int[] PreambleFirstRow = [1, 3, 5, 7, 9, 11, 12, 14];
+
+ /// <summary>Special characters (0x11 0x30–0x3F); 0x39 is a transparent space.</summary>
+ private const string Special = "®°½¿™¢£♪à èâêîôû";
+
+ /// <summary>Extended characters, Spanish / French / miscellaneous (0x12 0x20–0x3F).</summary>
+ private const string Extended1 = "ÁÉÓÚÜü‘¡*’—©℠•“”ÀÂÇÈÊËëÎÏïÔÙùÛ«»";
+
+ /// <summary>Extended characters, Portuguese / German / Danish (0x13 0x20–0x3F).</summary>
+ private const string Extended2 = "ÃãÍÌìÒòÕõ{}\\^_|~ÄäÖöߥ¤│Å娸┌┐└┘";
+
+ [GeneratedRegex(@"^(?<h>\d{2}):(?<m>\d{2}):(?<s>\d{2})(?<sep>[:;.,])(?<f>\d{2})\s+(?<data>.+)$")]
+ private static partial Regex TimedLine();
+}
diff --git a/src/Filee.Engines/Subtitles/SubtitleConverter.cs b/src/Filee.Engines/Subtitles/SubtitleConverter.cs
new file mode 100644
index 00000000..70e76a68
--- /dev/null
+++ b/src/Filee.Engines/Subtitles/SubtitleConverter.cs
@@ -0,0 +1,41 @@
+// Text subtitles in managed code: SRT, ASS/SSA, WebVTT, SAMI, LRC, TTML, MicroDVD and SCC are read into one cue model
+// and written as SRT, ASS, WebVTT, SAMI, LRC, TTML or MicroDVD, always as UTF-8. Korean CP949 / EUC-KR files (most
+// SAMI files) are recognised. Subtitles inside videos are taken out by FFmpeg (video → SRT / ASS / WebVTT), see
+// docs/ENGINES.md.
+
+using Filee.Core.Conversion;
+using Filee.Engines.Infrastructure;
+
+namespace Filee.Engines.Subtitles;
+
+/// <summary>Converts text subtitle formats into each other.</summary>
+public sealed class SubtitleConverter : IConverter
+{
+ public string Id => "subtitle";
+ public string DisplayName => "Subtitles (built-in)";
+ public int MaxParallelism => 0;
+
+ /// <summary>
+ /// Every subtitle format to every one Filee writes, also to itself: an SRT or SAMI file in CP949 comes out as UTF-8.
+ /// </summary>
+ public IReadOnlyList<ConversionEdge> Edges { get; } =
+ [.. from source in SubtitleReader.Formats from target in SubtitleWriter.Formats select new ConversionEdge(source, target)];
+
+ public EngineStatus GetStatus() => EngineStatus.Available("SRT, ASS, WebVTT, SAMI, LRC, TTML, MicroDVD, SCC", EngineVersions.BuiltIn);
+
+ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
+ Task.Run<IReadOnlyList<string>>(() =>
+ {
+ var document = SubtitleReader.Read(step.From, File.ReadAllBytes(step.InputPath));
+ cancellationToken.ThrowIfCancellationRequested();
+ progress?.Report(0.5);
+ var data = SubtitleWriter.Write(document, step.To);
+
+ var output = step.Output.Allocate(Core.Formats.FormatRegistry.Get(step.To).PrimaryExtension);
+ if (output is null)
+ return [];
+ File.WriteAllBytes(output, data);
+ progress?.Report(1);
+ return [output];
+ }, cancellationToken);
+}
diff --git a/src/Filee.Engines/Subtitles/SubtitleEncoding.cs b/src/Filee.Engines/Subtitles/SubtitleEncoding.cs
new file mode 100644
index 00000000..f2708505
--- /dev/null
+++ b/src/Filee.Engines/Subtitles/SubtitleEncoding.cs
@@ -0,0 +1,97 @@
+// Subtitle files come in whatever encoding their author's PC used. Korean SAMI and SRT files are usually CP949
+// (EUC-KR plus Microsoft's extra Hangul), Chinese ones GBK, Western ones Windows-1252. Filee reads them all and
+// always writes UTF-8.
+
+using System.Globalization;
+using System.Text;
+using System.Text.RegularExpressions;
+
+namespace Filee.Engines.Subtitles;
+
+/// <summary>Decodes subtitle files.</summary>
+internal static partial class SubtitleEncoding
+{
+ /// <summary>
+ /// The text of a subtitle file: by its byte order mark; as UTF-8 when the bytes are valid UTF-8; by the charset the
+ /// file declares (SAMI, TTML); as CP949 when the bytes look like Korean (EUC-KR / CP949); as the PC's code page on
+ /// Chinese and Japanese Windows; else as the PC's Western code page.
+ /// </summary>
+ public static string Decode(byte[] bytes) => Decode(bytes, CultureInfo.CurrentCulture.TextInfo.ANSICodePage);
+
+ /// <summary><see cref="Decode(byte[])"/> with the PC's ANSI code page given (for tests).</summary>
+ internal static string Decode(byte[] bytes, int ansiCodePage)
+ {
+ if (bytes is [0xEF, 0xBB, 0xBF, ..])
+ return new UTF8Encoding(false).GetString(bytes, 3, bytes.Length - 3);
+ if (bytes is [0xFF, 0xFE, ..] or [0xFE, 0xFF, ..])
+ return new StreamReader(new MemoryStream(bytes), detectEncodingFromByteOrderMarks: true).ReadToEnd();
+ // UTF-16 without a byte order mark: every other byte of ASCII text is zero.
+ if (bytes.Length >= 4 && bytes[1] == 0 && bytes[3] == 0 && bytes[0] != 0)
+ return Encoding.Unicode.GetString(bytes);
+ try
+ {
+ return new UTF8Encoding(false, throwOnInvalidBytes: true).GetString(bytes);
+ }
+ catch (DecoderFallbackException)
+ {
+ }
+
+ Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
+ if (Declared(bytes) is { } declared)
+ return declared.GetString(bytes);
+ if (LooksKorean(bytes))
+ return Encoding.GetEncoding(949).GetString(bytes);
+ if (ansiCodePage is 932 or 936 or 950)
+ return Encoding.GetEncoding(ansiCodePage).GetString(bytes);
+ return Encoding.GetEncoding(ansiCodePage is > 0 and not (949 or 1361) and not 65001 ? ansiCodePage : 1252).GetString(bytes);
+ }
+
+ /// <summary>The encoding named by <c>charset=…</c> (SAMI's HTML) or <c>encoding="…"</c> (XML) near the start.</summary>
+ private static Encoding? Declared(byte[] bytes)
+ {
+ var head = Encoding.ASCII.GetString(bytes, 0, Math.Min(bytes.Length, 2048));
+ if (DeclaredCharset().Match(head) is not { Success: true } match)
+ return null;
+ try
+ {
+ var encoding = Encoding.GetEncoding(match.Groups["name"].Value);
+ // A file claiming UTF-8 that isn't valid UTF-8 was saved by a program that lied: guess instead.
+ return encoding.CodePage is 65001 or 1200 or 1201 ? null : encoding;
+ }
+ catch (ArgumentException)
+ {
+ return null;
+ }
+ }
+
+ /// <summary>
+ /// True when the non-ASCII bytes form CP949 pairs, most of them Hangul syllables of KS X 1001 (lead byte B0–C8,
+ /// trail byte A1–FE) and hardly any with a lead byte above C8, as Korean text is. Western text decoded as CP949
+ /// gives pairs with ASCII trail bytes; Chinese GBK text uses lead bytes above C8 for a good part of its common
+ /// characters (的 B5C4 but 是 CAC7, 我 CED2, 这 D5E2), where Korean has only the rare Hanja.
+ /// </summary>
+ internal static bool LooksKorean(byte[] bytes)
+ {
+ int pairs = 0, hangul = 0, high = 0;
+ for (var i = 0; i < bytes.Length; i++)
+ {
+ var lead = bytes[i];
+ if (lead < 0x80)
+ continue;
+ if (lead is < 0x81 or > 0xFE || i + 1 >= bytes.Length)
+ return false;
+ var trail = bytes[++i];
+ if (trail is not (>= 0x41 and <= 0x5A or >= 0x61 and <= 0x7A or >= 0x81 and <= 0xFE))
+ return false;
+ pairs++;
+ if (lead is >= 0xB0 and <= 0xC8 && trail >= 0xA1)
+ hangul++;
+ else if (lead > 0xC8)
+ high++;
+ }
+ return pairs > 0 && hangul * 2 >= pairs && high * 10 <= pairs;
+ }
+
+ [GeneratedRegex("""(?:charset|encoding)\s*=\s*["']?(?<name>[A-Za-z0-9_.:-]+)""", RegexOptions.IgnoreCase)]
+ private static partial Regex DeclaredCharset();
+}
diff --git a/src/Filee.Engines/Subtitles/SubtitleModel.cs b/src/Filee.Engines/Subtitles/SubtitleModel.cs
new file mode 100644
index 00000000..c2e772d1
--- /dev/null
+++ b/src/Filee.Engines/Subtitles/SubtitleModel.cs
@@ -0,0 +1,401 @@
+// The common model every subtitle reader produces and every writer consumes: timed cues whose text uses a tiny
+// markup (line breaks plus <i>, <b>, <u> and <font color="#RRGGBB">, SRT's own tags), so styling survives between
+// formats that have it and is dropped cleanly by those that don't (LRC, MicroDVD).
+
+using System.Globalization;
+using System.Text;
+using System.Text.RegularExpressions;
+
+namespace Filee.Engines.Subtitles;
+
+/// <summary>One subtitle shown from <paramref name="Start"/> to <paramref name="End"/>.</summary>
+/// <param name="Text">Lines separated by <c>\n</c>, with the markup of <see cref="SubtitleMarkup"/>.</param>
+internal sealed record SubtitleCue(TimeSpan Start, TimeSpan End, string Text);
+
+/// <summary>A subtitle file: its cues in time order, and the title and language when the file says.</summary>
+internal sealed class SubtitleDocument
+{
+ public List<SubtitleCue> Cues { get; } = [];
+
+ public string? Title { get; set; }
+
+ /// <summary>Language tag such as <c>ko-KR</c> or <c>en</c>, when the file names one.</summary>
+ public string? Language { get; set; }
+
+ /// <summary>How long a cue without an end time (LRC, the last SAMI line) stays on screen.</summary>
+ public static readonly TimeSpan DefaultDuration = TimeSpan.FromSeconds(4);
+
+ /// <summary>Adds a cue with normalized markup; empty and zero-length cues are dropped.</summary>
+ public void Add(TimeSpan start, TimeSpan end, string text)
+ {
+ if (start < TimeSpan.Zero)
+ start = TimeSpan.Zero;
+ var normalized = SubtitleMarkup.Normalize(text);
+ if (end <= start || SubtitleMarkup.PlainText(normalized).Trim().Length == 0)
+ return;
+ Cues.Add(new SubtitleCue(start, end, normalized));
+ }
+
+ /// <summary>Puts the cues in time order (stable) and drops exact duplicates (ASS shadow layers).</summary>
+ public SubtitleDocument Finish()
+ {
+ var ordered = Cues.Distinct().OrderBy(c => c.Start).ThenBy(c => c.End).ToList();
+ Cues.Clear();
+ Cues.AddRange(ordered);
+ return this;
+ }
+
+ /// <summary>
+ /// The language of the text when the file doesn't name one: Korean, Japanese and Chinese by their scripts,
+ /// English otherwise.
+ /// </summary>
+ public string GuessLanguage()
+ {
+ if (!string.IsNullOrWhiteSpace(Language))
+ return Language;
+ int hangul = 0, kana = 0, han = 0;
+ foreach (var c in Cues.SelectMany(c => c.Text))
+ {
+ if (c is >= '가' and <= '힣' or >= 'ᄀ' and <= 'ᇿ' or >= '㄰' and <= '㆏')
+ hangul++;
+ else if (c is >= '぀' and <= 'ヿ')
+ kana++;
+ else if (c is >= '一' and <= '鿿')
+ han++;
+ }
+ if (hangul > 0 && hangul >= kana && hangul >= han / 4)
+ return "ko-KR";
+ if (kana > 0)
+ return "ja-JP";
+ return han > 0 ? "zh-CN" : "en-US";
+ }
+}
+
+/// <summary>Kinds of <see cref="MarkupToken"/>.</summary>
+internal enum MarkupKind
+{
+ Text,
+ LineBreak,
+ Open,
+ Close,
+}
+
+/// <summary>A piece of cue text: text, a line break, or the start / end of a style.</summary>
+/// <param name="Value">The text, or the style: <c>i</c>, <c>b</c>, <c>u</c> or a colour <c>#RRGGBB</c> (closed as <c>font</c>).</param>
+internal readonly record struct MarkupToken(MarkupKind Kind, string Value)
+{
+ public bool IsColor => Value.StartsWith('#');
+}
+
+/// <summary>The cue text markup: parsing, balancing, plain text and colours.</summary>
+internal static partial class SubtitleMarkup
+{
+ /// <summary>Splits normalized cue text into tokens.</summary>
+ public static List<MarkupToken> Tokens(string text)
+ {
+ List<MarkupToken> tokens = [];
+ var position = 0;
+ foreach (Match match in CanonicalTag().Matches(text))
+ {
+ AddText(tokens, text[position..match.Index]);
+ if (match.Groups["color"].Success)
+ tokens.Add(new MarkupToken(MarkupKind.Open, "#" + match.Groups["color"].Value.ToUpperInvariant()));
+ else if (match.Value == "</font>")
+ tokens.Add(new MarkupToken(MarkupKind.Close, "font"));
+ else
+ tokens.Add(new MarkupToken(match.Groups["close"].Length > 0 ? MarkupKind.Close : MarkupKind.Open, match.Groups["tag"].Value));
+ position = match.Index + match.Length;
+ }
+ AddText(tokens, text[position..]);
+ return tokens;
+ }
+
+ private static void AddText(List<MarkupToken> tokens, string text)
+ {
+ var lines = text.Split('\n');
+ for (var i = 0; i < lines.Length; i++)
+ {
+ if (i > 0)
+ tokens.Add(new MarkupToken(MarkupKind.LineBreak, ""));
+ if (lines[i].Length > 0)
+ tokens.Add(new MarkupToken(MarkupKind.Text, lines[i]));
+ }
+ }
+
+ /// <summary>
+ /// Cleans up cue text written by a reader: tags properly nested (overlapping ones are closed and reopened), unclosed
+ /// ones closed, stray closing tags and empty styles dropped, spaces at line ends and empty lines removed.
+ /// </summary>
+ public static string Normalize(string text)
+ {
+ var tokens = Tokens(text.Replace("\r\n", "\n").Replace('\r', '\n').Replace(' ', ' ').Replace('\t', ' '));
+ List<MarkupToken> balanced = [];
+ List<string> open = [];
+ foreach (var token in tokens)
+ {
+ switch (token.Kind)
+ {
+ case MarkupKind.Open when !token.IsColor && open.Contains(token.Value):
+ break; // already on
+ case MarkupKind.Open:
+ open.Add(token.Value);
+ balanced.Add(token);
+ break;
+ case MarkupKind.Close:
+ var index = open.FindLastIndex(o => Closes(token.Value, o));
+ if (index < 0)
+ break;
+ var reopen = open.Skip(index + 1).ToList();
+ for (var i = open.Count - 1; i >= index; i--)
+ balanced.Add(new MarkupToken(MarkupKind.Close, open[i].StartsWith('#') ? "font" : open[i]));
+ open.RemoveRange(index, open.Count - index);
+ foreach (var tag in reopen)
+ {
+ open.Add(tag);
+ balanced.Add(new MarkupToken(MarkupKind.Open, tag));
+ }
+ break;
+ default:
+ balanced.Add(token);
+ break;
+ }
+ }
+ for (var i = open.Count - 1; i >= 0; i--)
+ balanced.Add(new MarkupToken(MarkupKind.Close, open[i].StartsWith('#') ? "font" : open[i]));
+
+ // Lines without their surrounding spaces, empty styles removed, no empty lines.
+ var lines = Render(RemoveEmptyStyles(balanced)).Split('\n')
+ .Select(line => MultipleSpaces().Replace(line, " ").Trim())
+ .Where(line => PlainText(line).Trim().Length > 0);
+ return string.Join('\n', lines);
+ }
+
+ private static bool Closes(string close, string open) => close == "font" ? open.StartsWith('#') : close == open;
+
+ private static List<MarkupToken> RemoveEmptyStyles(List<MarkupToken> tokens)
+ {
+ var changed = true;
+ while (changed)
+ {
+ changed = false;
+ for (var i = 0; i + 1 < tokens.Count; i++)
+ {
+ if (tokens[i].Kind == MarkupKind.Open && tokens[i + 1].Kind == MarkupKind.Close)
+ {
+ tokens.RemoveRange(i, 2);
+ changed = true;
+ break;
+ }
+ }
+ }
+ return tokens;
+ }
+
+ /// <summary>Tokens back to markup text.</summary>
+ public static string Render(IEnumerable<MarkupToken> tokens)
+ {
+ var sb = new StringBuilder();
+ foreach (var token in tokens)
+ {
+ sb.Append(token.Kind switch
+ {
+ MarkupKind.Text => token.Value,
+ MarkupKind.LineBreak => "\n",
+ MarkupKind.Open when token.IsColor => $"<font color=\"{token.Value}\">",
+ MarkupKind.Open => $"<{token.Value}>",
+ _ => $"</{token.Value}>",
+ });
+ }
+ return sb.ToString();
+ }
+
+ /// <summary>The text without any markup (lines still separated by <c>\n</c>).</summary>
+ public static string PlainText(string text) =>
+ string.Concat(Tokens(text).Select(t => t.Kind switch
+ {
+ MarkupKind.Text => t.Value,
+ MarkupKind.LineBreak => "\n",
+ _ => "",
+ }));
+
+ /// <summary>
+ /// Turns HTML-like subtitle text (SRT, WebVTT, SAMI) into cue markup: <c>i</c>, <c>b</c>, <c>u</c>, font colours and
+ /// WebVTT's colour classes (<c>&lt;c.yellow&gt;</c>) are kept, <c>br</c> breaks the line, every other tag is dropped
+ /// (its text stays).
+ /// </summary>
+ /// <param name="decodeEntities">Decode <c>&amp;amp;</c>, <c>&amp;nbsp;</c>, … (WebVTT and SAMI; SRT has no entities).</param>
+ public static string FromHtml(string text, bool decodeEntities)
+ {
+ var sb = new StringBuilder();
+ var position = 0;
+ var colors = 0;
+ Stack<bool> classes = []; // WebVTT <c.yellow>: whether the class gave a colour
+ foreach (Match match in AnyTag().Matches(text))
+ {
+ AppendText(sb, text[position..match.Index], decodeEntities);
+ position = match.Index + match.Length;
+ var closing = match.Groups["close"].Length > 0;
+ var name = match.Groups["name"].Value.ToLowerInvariant();
+ if (name == "c" || name.StartsWith("c.", StringComparison.Ordinal))
+ {
+ if (closing && classes.Count > 0 && classes.Pop())
+ sb.Append("</font>");
+ else if (!closing && name.Split('.').Skip(1).Select(c => NamedColors.GetValueOrDefault(c)).FirstOrDefault(c => c is not null) is { } classColor)
+ {
+ classes.Push(true);
+ sb.Append($"<font color=\"{classColor}\">");
+ }
+ else if (!closing)
+ {
+ classes.Push(false);
+ }
+ continue;
+ }
+ switch (name)
+ {
+ case "i" or "em":
+ sb.Append(closing ? "</i>" : "<i>");
+ break;
+ case "b" or "strong":
+ sb.Append(closing ? "</b>" : "<b>");
+ break;
+ case "u":
+ sb.Append(closing ? "</u>" : "<u>");
+ break;
+ case "br":
+ sb.Append('\n');
+ break;
+ case "font" when closing:
+ if (colors > 0)
+ {
+ colors--;
+ sb.Append("</font>");
+ }
+ break;
+ case "font":
+ // A <font face=…> without colour has nothing to keep; its </font> then must not close a colour.
+ if (ColorAttribute().Match(match.Groups["attributes"].Value) is { Success: true } attribute
+ && ParseColor(attribute.Groups["value"].Value) is { } color)
+ {
+ colors++;
+ sb.Append($"<font color=\"{color}\">");
+ }
+ break;
+ }
+ }
+ AppendText(sb, text[position..], decodeEntities);
+ return sb.ToString();
+ }
+
+ private static void AppendText(StringBuilder sb, string text, bool decodeEntities)
+ {
+ if (decodeEntities)
+ text = System.Net.WebUtility.HtmlDecode(text);
+ // Bidirectional marks of WebVTT (&lrm; &rlm;) and zero-width characters carry nothing visible.
+ sb.Append(text.Replace("‎", "").Replace("‏", "").Replace("​", ""));
+ }
+
+ /// <summary>
+ /// <c>#RRGGBB</c> from <c>#rgb</c>, <c>#rrggbb</c>, <c>#rrggbbaa</c>, bare hex digits, <c>rgb(…)</c> or a colour name;
+ /// null when it can't be read.
+ /// </summary>
+ public static string? ParseColor(string value)
+ {
+ value = value.Trim().Trim('"', '\'').Trim();
+ if (value.StartsWith("rgb", StringComparison.OrdinalIgnoreCase) && value.IndexOf('(') is var open and > 0 && value.EndsWith(')'))
+ {
+ var parts = value[(open + 1)..^1].Split(',', StringSplitOptions.TrimEntries);
+ if (parts.Length >= 3 && parts.Take(3).All(p => int.TryParse(p, NumberStyles.Integer, CultureInfo.InvariantCulture, out var v) && v is >= 0 and <= 255))
+ return "#" + string.Concat(parts.Take(3).Select(p => int.Parse(p, CultureInfo.InvariantCulture).ToString("X2", CultureInfo.InvariantCulture)));
+ return null;
+ }
+ if (NamedColors.TryGetValue(value, out var named))
+ return named;
+ var hex = value.TrimStart('#');
+ if (!hex.All(Uri.IsHexDigit))
+ return null;
+ return hex.Length switch
+ {
+ 3 => "#" + string.Concat(hex.Select(c => $"{c}{c}")).ToUpperInvariant(),
+ 6 or 8 => "#" + hex[..6].ToUpperInvariant(),
+ _ => null,
+ };
+ }
+
+ /// <summary>The colour's name when it is one of the basic CSS colours (WebVTT has classes for those).</summary>
+ public static string? ColorName(string hex) =>
+ NamedColors.FirstOrDefault(pair => pair.Value == hex && pair.Key is "white" or "lime" or "cyan" or "red" or "yellow" or "magenta" or "blue" or "black").Key;
+
+ private static readonly Dictionary<string, string> NamedColors = new(StringComparer.OrdinalIgnoreCase)
+ {
+ ["white"] = "#FFFFFF",
+ ["black"] = "#000000",
+ ["red"] = "#FF0000",
+ ["lime"] = "#00FF00",
+ ["green"] = "#008000",
+ ["blue"] = "#0000FF",
+ ["yellow"] = "#FFFF00",
+ ["cyan"] = "#00FFFF",
+ ["aqua"] = "#00FFFF",
+ ["magenta"] = "#FF00FF",
+ ["fuchsia"] = "#FF00FF",
+ ["gray"] = "#808080",
+ ["grey"] = "#808080",
+ ["silver"] = "#C0C0C0",
+ ["orange"] = "#FFA500",
+ ["purple"] = "#800080",
+ ["maroon"] = "#800000",
+ ["navy"] = "#000080",
+ ["olive"] = "#808000",
+ ["teal"] = "#008080",
+ ["pink"] = "#FFC0CB",
+ };
+
+ [GeneratedRegex("""<(?<close>/?)(?<tag>i|b|u)>|<font color="#(?<color>[0-9A-Fa-f]{6})">|</font>""")]
+ private static partial Regex CanonicalTag();
+
+ [GeneratedRegex("""<\s*(?<close>/?)\s*(?<name>[^\s>/]+)(?<attributes>[^>]*)>""")]
+ private static partial Regex AnyTag();
+
+ [GeneratedRegex("""color\s*=\s*(?<value>"[^"]*"|'[^']*'|[^\s>]+)""", RegexOptions.IgnoreCase)]
+ private static partial Regex ColorAttribute();
+
+ [GeneratedRegex(" {2,}")]
+ private static partial Regex MultipleSpaces();
+}
+
+/// <summary>Time stamps in the notations of the subtitle formats.</summary>
+internal static class SubtitleTime
+{
+ /// <summary>A time from hours, minutes, seconds and a decimal fraction ("5" = 0.5 s, "045" = 45 ms).</summary>
+ public static TimeSpan From(string hours, string minutes, string seconds, string? fraction)
+ {
+ var ms = 0;
+ if (!string.IsNullOrEmpty(fraction))
+ ms = (int)Math.Round(double.Parse("0." + fraction, CultureInfo.InvariantCulture) * 1000);
+ return new TimeSpan(0, Number(hours), Number(minutes), Number(seconds), ms);
+ }
+
+ private static int Number(string text) => text.Length == 0 ? 0 : int.Parse(text, CultureInfo.InvariantCulture);
+
+ /// <summary><c>HH:MM:SS{separator}mmm</c> (SRT: comma, WebVTT and TTML: dot).</summary>
+ public static string Milliseconds(TimeSpan time, char separator)
+ {
+ var ms = (long)Math.Round(Math.Max(0, time.TotalMilliseconds));
+ return string.Create(CultureInfo.InvariantCulture, $"{ms / 3_600_000:00}:{ms / 60_000 % 60:00}:{ms / 1000 % 60:00}{separator}{ms % 1000:000}");
+ }
+
+ /// <summary><c>H:MM:SS.cc</c> (ASS).</summary>
+ public static string Centiseconds(TimeSpan time)
+ {
+ var cs = (long)Math.Round(Math.Max(0, time.TotalMilliseconds) / 10);
+ return string.Create(CultureInfo.InvariantCulture, $"{cs / 360_000}:{cs / 6000 % 60:00}:{cs / 100 % 60:00}.{cs % 100:00}");
+ }
+
+ /// <summary><c>mm:ss.cc</c> (LRC; minutes go past 99 for long recordings).</summary>
+ public static string Lrc(TimeSpan time)
+ {
+ var cs = (long)Math.Round(Math.Max(0, time.TotalMilliseconds) / 10);
+ return string.Create(CultureInfo.InvariantCulture, $"{cs / 6000:00}:{cs / 100 % 60:00}.{cs % 100:00}");
+ }
+}
diff --git a/src/Filee.Engines/Subtitles/SubtitleReader.cs b/src/Filee.Engines/Subtitles/SubtitleReader.cs
new file mode 100644
index 00000000..9f141ed6
--- /dev/null
+++ b/src/Filee.Engines/Subtitles/SubtitleReader.cs
@@ -0,0 +1,409 @@
+// Readers of the line-based text subtitle formats: SubRip (SRT), WebVTT, ASS/SSA, LRC and MicroDVD. SAMI, TTML and
+// SCC have their own files. Readers are lenient: missing blank lines, one- or two-digit fractions, comma or dot before
+// the milliseconds and stray styling codes are accepted, because subtitle files are hand-made as often as not.
+
+using System.Globalization;
+using System.Text;
+using System.Text.RegularExpressions;
+
+namespace Filee.Engines.Subtitles;
+
+/// <summary>Reads any supported subtitle format into a <see cref="SubtitleDocument"/>.</summary>
+internal static partial class SubtitleReader
+{
+ /// <summary>Format ids this engine reads.</summary>
+ public static readonly string[] Formats = ["srt", "ass", "ssa", "vtt", "smi", "lrc", "ttml", "sub", "scc"];
+
+ /// <summary>Reads a file of format <paramref name="format"/> (decoding it with <see cref="SubtitleEncoding"/>).</summary>
+ /// <exception cref="InvalidDataException">The file is not a subtitle file of that format or has no cues.</exception>
+ public static SubtitleDocument Read(string format, byte[] bytes)
+ {
+ if (format == "sub" && LooksBinary(bytes))
+ throw new InvalidDataException("This .sub file holds VobSub picture subtitles (from a DVD), not MicroDVD text. Picture subtitles can't be turned into text without OCR.");
+ var text = SubtitleEncoding.Decode(bytes).Replace("\r\n", "\n").Replace('\r', '\n');
+ var document = format switch
+ {
+ "srt" => ReadSrt(text),
+ "vtt" => ReadVtt(text),
+ "ass" or "ssa" => ReadAss(text),
+ "lrc" => ReadLrc(text),
+ "sub" => ReadMicroDvd(text),
+ "smi" => SamiReader.Read(text),
+ "ttml" => TtmlReader.Read(text),
+ "scc" => SccReader.Read(text),
+ _ => throw new NotSupportedException($"Subtitles in '{format}' can't be read."),
+ };
+ document.Finish();
+ if (document.Cues.Count == 0)
+ throw new InvalidDataException($"No subtitles were found in this file (it is empty or not a {format.ToUpperInvariant()} subtitle file).");
+ return document;
+ }
+
+ /// <summary>A NUL byte or an MPEG pack header: a VobSub .sub, not text.</summary>
+ private static bool LooksBinary(byte[] bytes) =>
+ bytes is [0x00, 0x00, 0x01, 0xBA, ..] || bytes.AsSpan(0, Math.Min(bytes.Length, 4096)).Contains((byte)0);
+
+ // ───────────────────────── SubRip ─────────────────────────
+
+ /// <summary>
+ /// SubRip: a number, <c>00:00:01,000 --> 00:00:02,500</c>, text lines, a blank line. A cue starts at every timing
+ /// line, so blank lines inside a cue's text and missing blank lines between cues don't matter.
+ /// </summary>
+ private static SubtitleDocument ReadSrt(string text)
+ {
+ var document = new SubtitleDocument();
+ var lines = text.Split('\n');
+ TimeSpan? start = null, end = null;
+ List<string> body = [];
+
+ void Flush(bool beforeNextCue)
+ {
+ if (start is null)
+ return;
+ while (body.Count > 0 && body[^1].Trim().Length == 0)
+ body.RemoveAt(body.Count - 1);
+ // The next cue's number ended up as this cue's last line.
+ if (beforeNextCue && body.Count > 0 && IsNumber(body[^1]))
+ body.RemoveAt(body.Count - 1);
+ // ASS override codes some SRT files carry ({\an8} = top of the screen) are not text.
+ var cue = AssOverride().Replace(string.Join('\n', body), "");
+ document.Add(start.Value, end!.Value, SubtitleMarkup.FromHtml(cue, decodeEntities: false));
+ }
+
+ foreach (var line in lines)
+ {
+ if (SrtTiming().Match(line) is { Success: true } timing)
+ {
+ Flush(beforeNextCue: true);
+ start = Time(timing, "s");
+ end = Time(timing, "e");
+ body = [];
+ }
+ else if (start is not null)
+ {
+ body.Add(line);
+ }
+ }
+ Flush(beforeNextCue: false);
+ return document;
+ }
+
+ private static bool IsNumber(string line) => line.Trim() is { Length: > 0 } t && t.All(char.IsAsciiDigit);
+
+ private static TimeSpan Time(Match match, string prefix) => SubtitleTime.From(
+ match.Groups[prefix + "h"].Value, match.Groups[prefix + "m"].Value, match.Groups[prefix + "s"].Value, match.Groups[prefix + "f"].Value);
+
+ // ───────────────────────── WebVTT ─────────────────────────
+
+ /// <summary>
+ /// WebVTT: a <c>WEBVTT</c> header, then blocks separated by blank lines. NOTE, STYLE and REGION blocks are skipped;
+ /// a cue is an optional id line, <c>[hh:]mm:ss.ttt --> [hh:]mm:ss.ttt [settings]</c> and its text.
+ /// </summary>
+ private static SubtitleDocument ReadVtt(string text)
+ {
+ var document = new SubtitleDocument();
+ var blocks = BlankLines().Split(text.Trim('\n', ' ', ''));
+ foreach (var block in blocks)
+ {
+ var lines = block.Split('\n');
+ var timingLine = Array.FindIndex(lines, l => l.Contains("-->", StringComparison.Ordinal));
+ if (timingLine < 0 && lines[0].StartsWith("WEBVTT", StringComparison.Ordinal))
+ {
+ // Header lines such as "Language: ko".
+ if (lines.FirstOrDefault(l => l.StartsWith("Language:", StringComparison.OrdinalIgnoreCase)) is { } language)
+ document.Language = language["Language:".Length..].Trim();
+ continue;
+ }
+ if (timingLine is < 0 or > 1 || lines[0].StartsWith("NOTE", StringComparison.Ordinal))
+ continue;
+ if (VttTiming().Match(lines[timingLine]) is not { Success: true } timing)
+ continue;
+ var cue = string.Join('\n', lines.Skip(timingLine + 1));
+ document.Add(Time(timing, "s"), Time(timing, "e"), SubtitleMarkup.FromHtml(cue, decodeEntities: true));
+ }
+ return document;
+ }
+
+ // ───────────────────────── ASS / SSA ─────────────────────────
+
+ /// <summary>
+ /// Advanced SubStation Alpha and SubStation Alpha: <c>Dialogue:</c> lines of the [Events] section in the order its
+ /// <c>Format:</c> line gives. Override codes become markup where it has them (\i, \b, \u, \c) and are dropped
+ /// otherwise; vector drawings (\p1) are no text and are left out. Bold, italic and underline styles apply too.
+ /// </summary>
+ private static SubtitleDocument ReadAss(string text)
+ {
+ var document = new SubtitleDocument();
+ var section = "";
+ string[] styleFormat = ["name", "fontname", "fontsize", "primarycolour", "secondarycolour", "outlinecolour", "backcolour", "bold", "italic", "underline"];
+ string[] eventFormat = ["layer", "start", "end", "style", "name", "marginl", "marginr", "marginv", "effect", "text"];
+ var styles = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); // name → opening markup
+
+ foreach (var raw in text.Split('\n'))
+ {
+ var line = raw.Trim().TrimStart('');
+ if (line.StartsWith('[') && line.EndsWith(']'))
+ {
+ section = line[1..^1].Trim().ToLowerInvariant();
+ continue;
+ }
+ var colon = line.IndexOf(':');
+ if (colon <= 0)
+ continue;
+ var key = line[..colon].Trim().ToLowerInvariant();
+ var value = line[(colon + 1)..].TrimStart();
+
+ if (section == "script info" && key == "title" && value.Length > 0 && value != "<untitled>")
+ document.Title = value;
+ else if (key == "format" && section.Contains("styles", StringComparison.Ordinal))
+ styleFormat = value.Split(',').Select(f => f.Trim().ToLowerInvariant()).ToArray();
+ else if (key == "format" && section == "events")
+ eventFormat = value.Split(',').Select(f => f.Trim().ToLowerInvariant()).ToArray();
+ else if (key == "style" && section.Contains("styles", StringComparison.Ordinal))
+ {
+ var fields = value.Split(',');
+ string Field(string name) => Array.IndexOf(styleFormat, name) is var i and >= 0 && i < fields.Length ? fields[i].Trim() : "";
+ static bool On(string flag) => flag is "-1" or "1";
+ var open = (On(Field("bold")) ? "<b>" : "") + (On(Field("italic")) ? "<i>" : "") + (On(Field("underline")) ? "<u>" : "");
+ styles[Field("name")] = open;
+ }
+ else if (key == "dialogue" && section == "events")
+ {
+ // The text is the last field and may itself contain commas.
+ var fields = value.Split(',', eventFormat.Length);
+ string Field(string name) => Array.IndexOf(eventFormat, name) is var i and >= 0 && i < fields.Length ? fields[i].Trim() : "";
+ if (AssTime().Match(Field("start")) is not { Success: true } start || AssTime().Match(Field("end")) is not { Success: true } end)
+ continue;
+ var textIndex = Array.IndexOf(eventFormat, "text");
+ var cueText = textIndex >= 0 && textIndex < fields.Length ? fields[textIndex] : "";
+ if (AssText(cueText) is not { } markup)
+ continue;
+ document.Add(AssTimeOf(start), AssTimeOf(end), styles.GetValueOrDefault(Field("style").TrimStart('*'), "") + markup);
+ }
+ }
+ return document;
+ }
+
+ private static TimeSpan AssTimeOf(Match match) =>
+ SubtitleTime.From(match.Groups["h"].Value, match.Groups["m"].Value, match.Groups["s"].Value, match.Groups["f"].Value);
+
+ /// <summary>ASS dialogue text as cue markup, or null for a drawing.</summary>
+ internal static string? AssText(string text)
+ {
+ var sb = new StringBuilder();
+ var position = 0;
+ var drawing = false;
+ foreach (Match block in AssOverride().Matches(text))
+ {
+ if (!drawing)
+ sb.Append(AssPlain(text[position..block.Index]));
+ position = block.Index + block.Length;
+ foreach (Match tag in AssTag().Matches(block.Value[1..^1]))
+ {
+ var name = tag.Groups["name"].Value;
+ var argument = tag.Groups["arg"].Value.Trim();
+ switch (name)
+ {
+ case "i" or "b" or "u":
+ var on = argument.Length > 0 && argument != "0" && !(name == "b" && int.TryParse(argument, out var weight) && weight is > 1 and < 600);
+ sb.Append(on ? $"<{name}>" : $"</{name}>");
+ break;
+ case "c" or "1c":
+ sb.Append("</font>");
+ if (AssColor(argument) is { } color)
+ sb.Append($"<font color=\"{color}\">");
+ break;
+ case "r":
+ sb.Append("</font></u></b></i>");
+ break;
+ case "p":
+ drawing = argument.Length > 0 && argument != "0";
+ break;
+ }
+ }
+ }
+ if (!drawing)
+ sb.Append(AssPlain(text[position..]));
+ var result = sb.ToString();
+ return SubtitleMarkup.PlainText(SubtitleMarkup.Normalize(result)).Trim().Length == 0 && text.Contains("\\p", StringComparison.Ordinal) ? null : result;
+ }
+
+ /// <summary>\N is a line break, \n a space (a break only in wrap style 2), \h a non-breaking space.</summary>
+ private static string AssPlain(string text) =>
+ text.Replace("\\N", "\n").Replace("\\n", " ").Replace("\\h", " ");
+
+ /// <summary><c>&amp;HBBGGRR&amp;</c> (ASS stores colours blue first, sometimes with alpha in front) as <c>#RRGGBB</c>.</summary>
+ private static string? AssColor(string value)
+ {
+ var hex = value.Trim('&').TrimStart('H', 'h');
+ if (hex.Length == 0 || !hex.All(Uri.IsHexDigit))
+ return null;
+ hex = hex.PadLeft(6, '0');
+ hex = hex[^6..];
+ return $"#{hex[4..6]}{hex[2..4]}{hex[..2]}".ToUpperInvariant();
+ }
+
+ // ───────────────────────── LRC ─────────────────────────
+
+ /// <summary>
+ /// LRC lyrics: <c>[mm:ss.xx]</c> time tags (several per line for repeated lines), <c>[ti:…]</c> and <c>[offset:…]</c>
+ /// tags. A line lasts until the next one; an empty line only ends the one before. Word times (<c>&lt;mm:ss.xx&gt;</c>)
+ /// of enhanced LRC are dropped.
+ /// </summary>
+ private static SubtitleDocument ReadLrc(string text)
+ {
+ var document = new SubtitleDocument();
+ var offset = TimeSpan.Zero;
+ List<(TimeSpan Time, string Text)> entries = [];
+ foreach (var raw in text.Split('\n'))
+ {
+ var line = raw.Trim().TrimStart('');
+ if (LrcMetadata().Match(line) is { Success: true } metadata)
+ {
+ var value = metadata.Groups["value"].Value.Trim();
+ switch (metadata.Groups["key"].Value.ToLowerInvariant())
+ {
+ case "ti" when value.Length > 0:
+ document.Title = value;
+ break;
+ case "la" or "lang" when value.Length > 0:
+ document.Language = value;
+ break;
+ case "offset" when int.TryParse(value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var ms):
+ // A positive offset shows the lyrics earlier.
+ offset = TimeSpan.FromMilliseconds(ms);
+ break;
+ }
+ continue;
+ }
+ var times = LrcTime().Matches(line);
+ if (times.Count == 0 || times[0].Index != 0)
+ continue;
+ // Only the tags at the start of the line are times; the rest is the lyric.
+ var count = 0;
+ for (var expected = 0; count < times.Count && times[count].Index == expected; count++)
+ expected = times[count].Index + times[count].Length;
+ var lyric = line[(times[count - 1].Index + times[count - 1].Length)..];
+ lyric = LrcWordTime().Replace(lyric, "").Trim();
+ for (var i = 0; i < count; i++)
+ {
+ var time = SubtitleTime.From("0", times[i].Groups["m"].Value, times[i].Groups["s"].Value, times[i].Groups["f"].Value);
+ entries.Add((time, lyric));
+ }
+ }
+
+ entries = [.. entries.OrderBy(e => e.Time)];
+ for (var i = 0; i < entries.Count; i++)
+ {
+ var (time, lyric) = entries[i];
+ if (lyric.Length == 0)
+ continue;
+ var end = i + 1 < entries.Count ? entries[i + 1].Time : time + SubtitleDocument.DefaultDuration;
+ document.Add(time - offset, end - offset, lyric);
+ }
+ return document;
+ }
+
+ // ───────────────────────── MicroDVD ─────────────────────────
+
+ /// <summary>The frame rate MicroDVD files are assumed to use when they don't say (the film rate of most rips).</summary>
+ internal const double MicroDvdDefaultFps = 23.976;
+
+ /// <summary>
+ /// MicroDVD: <c>{start frame}{end frame}text</c>, <c>|</c> between lines, <c>{y:i}</c>-style codes. A first line
+ /// <c>{1}{1}25</c> gives the frame rate, else <see cref="MicroDvdDefaultFps"/>.
+ /// </summary>
+ private static SubtitleDocument ReadMicroDvd(string text)
+ {
+ var document = new SubtitleDocument();
+ var fps = MicroDvdDefaultFps;
+ List<(long Start, long? End, string Text)> lines = [];
+ foreach (var raw in text.Split('\n'))
+ {
+ if (MicroDvdLine().Match(raw.Trim().TrimStart('')) is not { Success: true } match)
+ continue;
+ var start = long.Parse(match.Groups["start"].Value, CultureInfo.InvariantCulture);
+ long? end = match.Groups["end"].Length > 0 ? long.Parse(match.Groups["end"].Value, CultureInfo.InvariantCulture) : null;
+ var body = match.Groups["text"].Value;
+ if (lines.Count == 0 && start <= 1 && double.TryParse(body.Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var rate) && rate is > 1 and < 200)
+ {
+ fps = rate;
+ continue;
+ }
+ lines.Add((start, end, body));
+ }
+ if (lines.Count == 0)
+ throw new InvalidDataException("This .sub file is not a MicroDVD subtitle ({frame}{frame}text lines). SubViewer and VobSub .sub files are not supported.");
+
+ TimeSpan FrameTime(long frame) => TimeSpan.FromSeconds(frame / fps);
+ for (var i = 0; i < lines.Count; i++)
+ {
+ var (start, end, body) = lines[i];
+ var endTime = end is { } e && e > start ? FrameTime(e)
+ : i + 1 < lines.Count ? FrameTime(lines[i + 1].Start) : FrameTime(start) + SubtitleDocument.DefaultDuration;
+ document.Add(FrameTime(start), endTime, MicroDvdText(body));
+ }
+ return document;
+ }
+
+ /// <summary>MicroDVD text: <c>|</c> breaks lines; <c>{y:i}</c> styles one line, <c>{Y:i}</c> all of them; <c>{c:$BBGGRR}</c> colours.</summary>
+ private static string MicroDvdText(string body)
+ {
+ List<string> all = [];
+ List<string> lines = [];
+ foreach (var part in body.Split('|'))
+ {
+ List<string> line = [];
+ foreach (Match code in MicroDvdCode().Matches(part))
+ (char.IsUpper(code.Groups["key"].Value[0]) ? all : line).AddRange(MicroDvdStyles(code.Groups["key"].Value, code.Groups["value"].Value));
+ lines.Add(Open(line) + MicroDvdCode().Replace(part, "") + Close(line));
+ }
+ return Open(all) + string.Join("\n", lines) + Close(all);
+
+ static string Open(List<string> styles) => string.Concat(styles.Select(s => s.StartsWith('#') ? $"<font color=\"{s}\">" : $"<{s}>"));
+ static string Close(List<string> styles) => string.Concat(styles.AsEnumerable().Reverse().Select(s => s.StartsWith('#') ? "</font>" : $"</{s}>"));
+ }
+
+ /// <summary>The styles of one MicroDVD code: <c>i</c>, <c>b</c>, <c>u</c> or a colour.</summary>
+ private static IEnumerable<string> MicroDvdStyles(string key, string value) => char.ToLowerInvariant(key[0]) switch
+ {
+ 'y' => value.ToLowerInvariant().Where(c => c is 'i' or 'b' or 'u').Select(c => c.ToString()),
+ 'c' when AssColor(value.TrimStart('$')) is { } color => [color],
+ _ => [],
+ };
+
+ // ───────────────────────── Patterns ─────────────────────────
+
+ [GeneratedRegex(@"(?<sh>\d+):(?<sm>\d{1,2}):(?<ss>\d{1,2})(?:[,.:](?<sf>\d{1,3}))?\s*-+>\s*(?<eh>\d+):(?<em>\d{1,2}):(?<es>\d{1,2})(?:[,.:](?<ef>\d{1,3}))?")]
+ private static partial Regex SrtTiming();
+
+ [GeneratedRegex(@"^\s*(?:(?<sh>\d+):)?(?<sm>\d{1,2}):(?<ss>\d{2})[.,](?<sf>\d{1,3})\s+-->\s+(?:(?<eh>\d+):)?(?<em>\d{1,2}):(?<es>\d{2})[.,](?<ef>\d{1,3})")]
+ private static partial Regex VttTiming();
+
+ [GeneratedRegex(@"\n[ \t]*\n+")]
+ private static partial Regex BlankLines();
+
+ [GeneratedRegex(@"^(?<h>\d+):(?<m>\d{1,2}):(?<s>\d{1,2})(?:[.:](?<f>\d{1,3}))?$")]
+ private static partial Regex AssTime();
+
+ [GeneratedRegex(@"\{[^}]*\}")]
+ private static partial Regex AssOverride();
+
+ [GeneratedRegex(@"\\(?<name>1c|2c|3c|4c|1a|2a|3a|4a|alpha|an|fn|fs|fscx|fscy|fsp|fr[xyz]?|fe|bord|xbord|ybord|shad|xshad|yshad|be|blur|pos|move|org|clip|iclip|fad|fade|kf|ko|k|K|q|t|p|r|i|b|u|s|c|a)(?<arg>[^\\]*)")]
+ private static partial Regex AssTag();
+
+ [GeneratedRegex(@"^\[(?<key>[A-Za-z]+):(?<value>[^\]]*)\]\s*$")]
+ private static partial Regex LrcMetadata();
+
+ [GeneratedRegex(@"\[(?<m>\d+):(?<s>\d{1,2})(?:[.:](?<f>\d{1,3}))?\]")]
+ private static partial Regex LrcTime();
+
+ [GeneratedRegex(@"<\d+:\d{1,2}(?:[.:]\d{1,3})?>")]
+ private static partial Regex LrcWordTime();
+
+ [GeneratedRegex(@"^\{(?<start>\d+)\}\{(?<end>\d*)\}(?<text>.*)$")]
+ private static partial Regex MicroDvdLine();
+
+ [GeneratedRegex(@"\{(?<key>[A-Za-z]):(?<value>[^}]*)\}")]
+ private static partial Regex MicroDvdCode();
+}
diff --git a/src/Filee.Engines/Subtitles/SubtitleWriter.cs b/src/Filee.Engines/Subtitles/SubtitleWriter.cs
new file mode 100644
index 00000000..ed0dbfcb
--- /dev/null
+++ b/src/Filee.Engines/Subtitles/SubtitleWriter.cs
@@ -0,0 +1,357 @@
+// Writers of every subtitle target. All write UTF-8: SRT, ASS, SAMI and MicroDVD with a byte order mark (Windows
+// players such as PotPlayer and KMPlayer take files without one for the PC's code page), WebVTT, TTML and LRC without
+// (browsers, XML and music players expect plain UTF-8).
+
+using System.Globalization;
+using System.Text;
+using System.Xml;
+
+namespace Filee.Engines.Subtitles;
+
+/// <summary>Writes a <see cref="SubtitleDocument"/> in one of the subtitle formats.</summary>
+internal static class SubtitleWriter
+{
+ /// <summary>Format ids this engine writes.</summary>
+ public static readonly string[] Formats = ["srt", "ass", "vtt", "smi", "lrc", "ttml", "sub"];
+
+ /// <summary>The frame rate MicroDVD files are written with (stated in their first line).</summary>
+ internal const double MicroDvdFps = SubtitleReader.MicroDvdDefaultFps;
+
+ public static byte[] Write(SubtitleDocument document, string format)
+ {
+ var (text, bom) = format switch
+ {
+ "srt" => (Srt(document), true),
+ "ass" => (Ass(document), true),
+ "vtt" => (Vtt(document), false),
+ "smi" => (Sami(document), true),
+ "lrc" => (Lrc(document), false),
+ "ttml" => (Ttml(document), false),
+ "sub" => (MicroDvd(document), true),
+ _ => throw new NotSupportedException($"Subtitles can't be written as '{format}'."),
+ };
+ return [.. (bom ? Encoding.UTF8.GetPreamble() : []), .. new UTF8Encoding(false).GetBytes(text)];
+ }
+
+ // ───────────────────────── SubRip ─────────────────────────
+
+ /// <summary>SubRip keeps the markup as it is: its own tags.</summary>
+ private static string Srt(SubtitleDocument document)
+ {
+ var sb = new StringBuilder();
+ for (var i = 0; i < document.Cues.Count; i++)
+ {
+ var cue = document.Cues[i];
+ sb.Append(CultureInfo.InvariantCulture, $"{i + 1}\r\n")
+ .Append(CultureInfo.InvariantCulture, $"{SubtitleTime.Milliseconds(cue.Start, ',')} --> {SubtitleTime.Milliseconds(cue.End, ',')}\r\n")
+ .Append(cue.Text.Replace("\n", "\r\n")).Append("\r\n\r\n");
+ }
+ return sb.ToString();
+ }
+
+ // ───────────────────────── WebVTT ─────────────────────────
+
+ /// <summary>WebVTT: i / b / u tags, colours as the basic colour classes (others are dropped), text escaped.</summary>
+ private static string Vtt(SubtitleDocument document)
+ {
+ var sb = new StringBuilder("WEBVTT\n");
+ if (document.Language is { Length: > 0 } language)
+ sb.Append("Language: ").Append(language).Append('\n');
+ sb.Append('\n');
+ foreach (var cue in document.Cues)
+ {
+ sb.Append(SubtitleTime.Milliseconds(cue.Start, '.')).Append(" --> ").Append(SubtitleTime.Milliseconds(cue.End, '.')).Append('\n');
+ Stack<bool> colors = [];
+ foreach (var token in SubtitleMarkup.Tokens(cue.Text))
+ {
+ switch (token.Kind)
+ {
+ case MarkupKind.Text:
+ // "-->" would end the cue text early.
+ sb.Append(Escape(token.Value).Replace("--&gt;", "-&gt;"));
+ break;
+ case MarkupKind.LineBreak:
+ sb.Append('\n');
+ break;
+ case MarkupKind.Open when token.IsColor:
+ var name = SubtitleMarkup.ColorName(token.Value);
+ colors.Push(name is not null);
+ if (name is not null)
+ sb.Append("<c.").Append(name).Append('>');
+ break;
+ case MarkupKind.Open:
+ sb.Append('<').Append(token.Value).Append('>');
+ break;
+ case MarkupKind.Close when token.Value == "font":
+ if (colors.Count > 0 && colors.Pop())
+ sb.Append("</c>");
+ break;
+ case MarkupKind.Close:
+ sb.Append("</").Append(token.Value).Append('>');
+ break;
+ }
+ }
+ sb.Append("\n\n");
+ }
+ return sb.ToString();
+ }
+
+ private static string Escape(string text) =>
+ text.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;");
+
+ // ───────────────────────── ASS ─────────────────────────
+
+ /// <summary>
+ /// Advanced SubStation Alpha for a 1920 × 1080 picture: one "Default" style (white Arial with a black outline at the
+ /// bottom centre), markup as override codes.
+ /// </summary>
+ private static string Ass(SubtitleDocument document)
+ {
+ var sb = new StringBuilder();
+ sb.Append("[Script Info]\r\n");
+ if (document.Title is { Length: > 0 } title)
+ sb.Append("Title: ").Append(title.Replace('\n', ' ')).Append("\r\n");
+ sb.Append("ScriptType: v4.00+\r\nWrapStyle: 0\r\nScaledBorderAndShadow: yes\r\nPlayResX: 1920\r\nPlayResY: 1080\r\n\r\n");
+ sb.Append("[V4+ Styles]\r\n");
+ sb.Append("Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\r\n");
+ sb.Append("Style: Default,Arial,64,&H00FFFFFF,&H000000FF,&H00000000,&H80000000,0,0,0,0,100,100,0,0,1,3,1,2,60,60,50,1\r\n\r\n");
+ sb.Append("[Events]\r\n");
+ sb.Append("Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\r\n");
+ foreach (var cue in document.Cues)
+ {
+ sb.Append("Dialogue: 0,").Append(SubtitleTime.Centiseconds(cue.Start)).Append(',').Append(SubtitleTime.Centiseconds(cue.End))
+ .Append(",Default,,0,0,0,,").Append(AssText(cue.Text)).Append("\r\n");
+ }
+ return sb.ToString();
+ }
+
+ /// <summary>Cue markup as ASS text: \N between lines, {\i1}…{\i0}, colours as &amp;HBBGGRR&amp;.</summary>
+ internal static string AssText(string text)
+ {
+ var sb = new StringBuilder();
+ Stack<string> colors = [];
+ foreach (var token in SubtitleMarkup.Tokens(text))
+ {
+ switch (token.Kind)
+ {
+ case MarkupKind.Text:
+ // A brace would start an override block.
+ sb.Append(token.Value.Replace("{", "(").Replace("}", ")"));
+ break;
+ case MarkupKind.LineBreak:
+ sb.Append("\\N");
+ break;
+ case MarkupKind.Open when token.IsColor:
+ colors.Push(token.Value);
+ sb.Append("{\\c").Append(AssColor(token.Value)).Append('}');
+ break;
+ case MarkupKind.Open:
+ sb.Append("{\\").Append(token.Value).Append("1}");
+ break;
+ case MarkupKind.Close when token.Value == "font":
+ // Back to the colour around it, or with a bare \c to the style's colour.
+ if (colors.Count > 0)
+ colors.Pop();
+ sb.Append("{\\c").Append(colors.Count > 0 ? AssColor(colors.Peek()) : "").Append('}');
+ break;
+ case MarkupKind.Close:
+ sb.Append("{\\").Append(token.Value).Append("0}");
+ break;
+ }
+ }
+ return sb.ToString().Replace("}{", "");
+ }
+
+ private static string AssColor(string hex) => $"&H{hex[5..7]}{hex[3..5]}{hex[1..3]}&";
+
+ // ───────────────────────── SAMI ─────────────────────────
+
+ /// <summary>
+ /// SAMI with one language class (KRCC for Korean, ENCC for English, …): a SYNC per cue and an &amp;nbsp; SYNC where
+ /// the screen goes blank before the next one.
+ /// </summary>
+ private static string Sami(SubtitleDocument document)
+ {
+ var language = document.GuessLanguage();
+ var (className, languageName) = SamiClass(language);
+ var sb = new StringBuilder();
+ sb.Append("<SAMI>\r\n<HEAD>\r\n<TITLE>").Append(Escape(document.Title ?? "")).Append("</TITLE>\r\n");
+ sb.Append("<STYLE TYPE=\"text/css\">\r\n<!--\r\n");
+ sb.Append("P { margin-left: 8pt; margin-right: 8pt; margin-bottom: 2pt; margin-top: 2pt; text-align: center; font-size: 20pt; font-family: sans-serif; font-weight: normal; color: white; }\r\n");
+ sb.Append('.').Append(className).Append(" { Name: ").Append(languageName).Append("; lang: ").Append(language).Append("; SAMIType: CC; }\r\n");
+ sb.Append("-->\r\n</STYLE>\r\n</HEAD>\r\n<BODY>\r\n");
+ for (var i = 0; i < document.Cues.Count; i++)
+ {
+ var cue = document.Cues[i];
+ sb.Append(CultureInfo.InvariantCulture, $"<SYNC Start={(long)Math.Round(cue.Start.TotalMilliseconds)}><P Class={className}>");
+ sb.Append(Html(cue.Text, "<br>")).Append("\r\n");
+ var next = i + 1 < document.Cues.Count ? document.Cues[i + 1].Start : (TimeSpan?)null;
+ if (next is null || next > cue.End)
+ sb.Append(CultureInfo.InvariantCulture, $"<SYNC Start={(long)Math.Round(cue.End.TotalMilliseconds)}><P Class={className}>&nbsp;\r\n");
+ }
+ sb.Append("</BODY>\r\n</SAMI>\r\n");
+ return sb.ToString();
+ }
+
+ /// <summary>The usual SAMI class of a language ("ko-KR" → KRCC, "Korean").</summary>
+ private static (string Class, string Name) SamiClass(string language)
+ {
+ var code = language.Split('-')[0].ToLowerInvariant();
+ return code switch
+ {
+ "ko" => ("KRCC", "Korean"),
+ "en" => ("ENCC", "English"),
+ "ja" => ("JPCC", "Japanese"),
+ "zh" => ("ZHCC", "Chinese"),
+ _ => ($"{code.ToUpperInvariant()}CC", CultureName(code)),
+ };
+ }
+
+ private static string CultureName(string code)
+ {
+ try
+ {
+ return CultureInfo.GetCultureInfo(code).EnglishName;
+ }
+ catch (CultureNotFoundException)
+ {
+ return code;
+ }
+ }
+
+ /// <summary>Cue markup as HTML (SAMI): tags as they are, text escaped, <paramref name="lineBreak"/> between lines.</summary>
+ private static string Html(string text, string lineBreak) =>
+ string.Concat(SubtitleMarkup.Tokens(text).Select(token => token.Kind switch
+ {
+ MarkupKind.Text => Escape(token.Value),
+ MarkupKind.LineBreak => lineBreak,
+ MarkupKind.Open when token.IsColor => $"<font color=\"{token.Value}\">",
+ MarkupKind.Open => $"<{token.Value}>",
+ _ => $"</{token.Value}>",
+ }));
+
+ // ───────────────────────── LRC ─────────────────────────
+
+ /// <summary>
+ /// LRC: one <c>[mm:ss.xx]</c> line per cue (its lines joined), plain text, and an empty time line where the screen
+ /// goes blank before the next cue.
+ /// </summary>
+ private static string Lrc(SubtitleDocument document)
+ {
+ var sb = new StringBuilder();
+ if (document.Title is { Length: > 0 } title)
+ sb.Append("[ti:").Append(title.Replace('\n', ' ').Replace("]", ")")).Append("]\r\n");
+ for (var i = 0; i < document.Cues.Count; i++)
+ {
+ var cue = document.Cues[i];
+ var lyric = string.Join(" ", SubtitleMarkup.PlainText(cue.Text).Split('\n', StringSplitOptions.TrimEntries));
+ sb.Append('[').Append(SubtitleTime.Lrc(cue.Start)).Append(']').Append(lyric).Append("\r\n");
+ var next = i + 1 < document.Cues.Count ? document.Cues[i + 1].Start : (TimeSpan?)null;
+ if (next is null || next - cue.End >= TimeSpan.FromMilliseconds(10))
+ sb.Append('[').Append(SubtitleTime.Lrc(cue.End)).Append("]\r\n");
+ }
+ return sb.ToString();
+ }
+
+ // ───────────────────────── TTML ─────────────────────────
+
+ /// <summary>TTML 1: a bottom region, one p per cue, spans for italic / bold / underline / colour.</summary>
+ private static string Ttml(SubtitleDocument document)
+ {
+ const string Tt = "http://www.w3.org/ns/ttml";
+ const string Tts = "http://www.w3.org/ns/ttml#styling";
+ const string Ttm = "http://www.w3.org/ns/ttml#metadata";
+ var sb = new StringBuilder();
+ var settings = new XmlWriterSettings { Indent = true, NewLineChars = "\n", Encoding = new UTF8Encoding(false), OmitXmlDeclaration = true };
+ using (var xml = XmlWriter.Create(sb, settings))
+ {
+ xml.WriteStartElement("tt", Tt);
+ xml.WriteAttributeString("xmlns", "tts", null, Tts);
+ xml.WriteAttributeString("xmlns", "ttm", null, Ttm);
+ xml.WriteAttributeString("xml", "lang", null, document.GuessLanguage());
+
+ xml.WriteStartElement("head", Tt);
+ if (document.Title is { Length: > 0 } title)
+ {
+ xml.WriteStartElement("metadata", Tt);
+ xml.WriteElementString("title", Ttm, title);
+ xml.WriteEndElement();
+ }
+ xml.WriteStartElement("styling", Tt);
+ xml.WriteStartElement("style", Tt);
+ xml.WriteAttributeString("xml", "id", null, "default");
+ xml.WriteAttributeString("color", Tts, "white");
+ xml.WriteAttributeString("fontFamily", Tts, "proportionalSansSerif");
+ xml.WriteAttributeString("textAlign", Tts, "center");
+ xml.WriteEndElement();
+ xml.WriteEndElement();
+ xml.WriteStartElement("layout", Tt);
+ xml.WriteStartElement("region", Tt);
+ xml.WriteAttributeString("xml", "id", null, "bottom");
+ xml.WriteAttributeString("origin", Tts, "10% 75%");
+ xml.WriteAttributeString("extent", Tts, "80% 20%");
+ xml.WriteAttributeString("displayAlign", Tts, "after");
+ xml.WriteAttributeString("textAlign", Tts, "center");
+ xml.WriteEndElement();
+ xml.WriteEndElement();
+ xml.WriteEndElement(); // head
+
+ xml.WriteStartElement("body", Tt);
+ xml.WriteAttributeString("region", "bottom");
+ xml.WriteAttributeString("style", "default");
+ xml.WriteStartElement("div", Tt);
+ foreach (var cue in document.Cues)
+ {
+ xml.WriteStartElement("p", Tt);
+ xml.WriteAttributeString("begin", SubtitleTime.Milliseconds(cue.Start, '.'));
+ xml.WriteAttributeString("end", SubtitleTime.Milliseconds(cue.End, '.'));
+ // Written as one piece: the indenting writer would put line breaks (spaces when read) before spans.
+ xml.WriteRaw(TtmlContent(cue.Text));
+ xml.WriteFullEndElement(); // p
+ }
+ xml.WriteEndElement(); // div
+ xml.WriteEndElement(); // body
+ xml.WriteEndElement(); // tt
+ }
+ return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + sb + "\n";
+ }
+
+ /// <summary>The content of a TTML p: escaped text, <c>br</c> and <c>span</c>s with tts: styles.</summary>
+ private static string TtmlContent(string text) =>
+ string.Concat(SubtitleMarkup.Tokens(text).Select(token => token.Kind switch
+ {
+ MarkupKind.Text => Escape(token.Value),
+ MarkupKind.LineBreak => "<br />",
+ MarkupKind.Open => token.Value switch
+ {
+ "i" => "<span tts:fontStyle=\"italic\">",
+ "b" => "<span tts:fontWeight=\"bold\">",
+ "u" => "<span tts:textDecoration=\"underline\">",
+ _ => $"<span tts:color=\"{token.Value}\">",
+ },
+ _ => "</span>",
+ }));
+
+ // ───────────────────────── MicroDVD ─────────────────────────
+
+ /// <summary>
+ /// MicroDVD at <see cref="MicroDvdFps"/> frames per second (stated in the first line, as players expect): plain
+ /// text with <c>|</c> between lines; a cue that is italic throughout gets <c>{Y:i}</c>.
+ /// </summary>
+ private static string MicroDvd(SubtitleDocument document)
+ {
+ var sb = new StringBuilder();
+ sb.Append(CultureInfo.InvariantCulture, $"{{1}}{{1}}{MicroDvdFps}\r\n");
+ foreach (var cue in document.Cues)
+ {
+ var start = (long)Math.Round(cue.Start.TotalSeconds * MicroDvdFps);
+ var end = Math.Max(start + 1, (long)Math.Round(cue.End.TotalSeconds * MicroDvdFps));
+ var tokens = SubtitleMarkup.Tokens(cue.Text);
+ var italic = tokens.Count > 2 && tokens[0] is { Kind: MarkupKind.Open, Value: "i" } && tokens[^1] is { Kind: MarkupKind.Close, Value: "i" }
+ && tokens.Count(t => t.Value == "i") == 2;
+ var text = string.Join("|", SubtitleMarkup.PlainText(cue.Text).Split('\n'));
+ sb.Append(CultureInfo.InvariantCulture, $"{{{start}}}{{{end}}}{(italic ? "{Y:i}" : "")}{text.Replace("{", "(").Replace("}", ")")}\r\n");
+ }
+ return sb.ToString();
+ }
+}
diff --git a/src/Filee.Engines/Subtitles/TtmlReader.cs b/src/Filee.Engines/Subtitles/TtmlReader.cs
new file mode 100644
index 00000000..72d02457
--- /dev/null
+++ b/src/Filee.Engines/Subtitles/TtmlReader.cs
@@ -0,0 +1,177 @@
+// TTML / DFXP (W3C Timed Text): XML with <p begin=… end=…> paragraphs. Elements are matched by local name, so both
+// the TTML 1 namespace and the older DFXP one (2006/10/ttaf1) read. Times are relative to the parent's begin;
+// clock times, frames (ttp:frameRate) and offsets in h / m / s / ms / f / ticks are understood.
+
+using System.Globalization;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Xml;
+using System.Xml.Linq;
+
+namespace Filee.Engines.Subtitles;
+
+/// <summary>Reads TTML subtitles.</summary>
+internal static partial class TtmlReader
+{
+ public static SubtitleDocument Read(string text)
+ {
+ XDocument xml;
+ try
+ {
+ xml = XDocument.Parse(text, LoadOptions.PreserveWhitespace);
+ }
+ catch (XmlException ex)
+ {
+ throw new InvalidDataException("The TTML file is not valid XML: " + ex.Message, ex);
+ }
+ var root = xml.Root ?? throw new InvalidDataException("The TTML file is empty.");
+ var document = new SubtitleDocument { Language = Attribute(root, "lang") };
+ var context = new Context(
+ Number(Attribute(root, "frameRate"), 30) * Ratio(Attribute(root, "frameRateMultiplier")),
+ Number(Attribute(root, "tickRate"), 0),
+ root.Descendants().Where(e => e.Name.LocalName == "style" && Attribute(e, "id") is not null)
+ .GroupBy(e => Attribute(e, "id")!)
+ .ToDictionary(g => g.Key, g => g.First()));
+ if (context.TickRate <= 0)
+ context = context with { TickRate = context.FrameRate > 0 ? context.FrameRate : 1 };
+
+ if (root.Descendants().FirstOrDefault(e => e.Name.LocalName == "title") is { } title && title.Value.Trim().Length > 0)
+ document.Title = title.Value.Trim();
+ if (root.Elements().FirstOrDefault(e => e.Name.LocalName == "body") is { } body)
+ Visit(body, TimeSpan.Zero, null, document, context);
+ return document;
+ }
+
+ private sealed record Context(double FrameRate, double TickRate, Dictionary<string, XElement> Styles);
+
+ /// <summary>Walks body / div / p, adding each parent's begin to its children's times.</summary>
+ private static void Visit(XElement element, TimeSpan parentBegin, TimeSpan? parentEnd, SubtitleDocument document, Context context)
+ {
+ var begin = parentBegin + (Time(Attribute(element, "begin"), context) ?? TimeSpan.Zero);
+ TimeSpan? end = Time(Attribute(element, "end"), context) is { } e ? parentBegin + e
+ : Time(Attribute(element, "dur"), context) is { } d ? begin + d
+ : parentEnd;
+
+ if (element.Name.LocalName == "p")
+ {
+ var sb = new StringBuilder();
+ AppendContent(element, sb, context);
+ document.Add(begin, end ?? begin + SubtitleDocument.DefaultDuration, sb.ToString());
+ return;
+ }
+ foreach (var child in element.Elements().Where(c => c.Name.LocalName is "div" or "p"))
+ Visit(child, begin, end, document, context);
+ }
+
+ /// <summary>The text of a p or span with its styles as markup; br breaks the line.</summary>
+ private static void AppendContent(XElement element, StringBuilder sb, Context context)
+ {
+ var styles = Styles(element, context);
+ foreach (var style in styles)
+ sb.Append(style.StartsWith('#') ? $"<font color=\"{style}\">" : $"<{style}>");
+ foreach (var node in element.Nodes())
+ {
+ switch (node)
+ {
+ case XText text:
+ sb.Append(Whitespace().Replace(text.Value, " "));
+ break;
+ case XElement { Name.LocalName: "br" }:
+ sb.Append('\n');
+ break;
+ case XElement { Name.LocalName: "span" } span:
+ AppendContent(span, sb, context);
+ break;
+ }
+ }
+ foreach (var style in Enumerable.Reverse(styles))
+ sb.Append(style.StartsWith('#') ? "</font>" : $"</{style}>");
+ }
+
+ /// <summary>Italic, bold, underline and colour of an element: its own tts: attributes and the styles it references.</summary>
+ private static List<string> Styles(XElement element, Context context)
+ {
+ List<XElement> sources = [];
+ foreach (var id in (Attribute(element, "style") ?? "").Split(' ', StringSplitOptions.RemoveEmptyEntries))
+ {
+ if (context.Styles.TryGetValue(id, out var style))
+ sources.Add(style);
+ }
+ sources.Add(element);
+
+ List<string> result = [];
+ foreach (var source in sources)
+ {
+ if (Attribute(source, "fontStyle") is "italic" or "oblique" && !result.Contains("i"))
+ result.Add("i");
+ if (Attribute(source, "fontWeight") == "bold" && !result.Contains("b"))
+ result.Add("b");
+ if (Attribute(source, "textDecoration")?.Contains("underline", StringComparison.Ordinal) == true && !result.Contains("u"))
+ result.Add("u");
+ if (Attribute(source, "color") is { } value && SubtitleMarkup.ParseColor(value) is { } color && color != "#FFFFFF")
+ {
+ result.RemoveAll(s => s.StartsWith('#'));
+ result.Add(color);
+ }
+ }
+ return result;
+ }
+
+ /// <summary>An attribute by local name in any namespace (tts:color, xml:lang, ttp:frameRate, plain begin).</summary>
+ private static string? Attribute(XElement element, string localName) =>
+ element.Attributes().FirstOrDefault(a => a.Name.LocalName == localName)?.Value.Trim();
+
+ /// <summary>A TTML time expression, null when absent or unreadable.</summary>
+ internal static TimeSpan? Time(string? value, double frameRate, double tickRate) =>
+ Time(value, new Context(frameRate, tickRate, new Dictionary<string, XElement>()));
+
+ private static TimeSpan? Time(string? value, Context context)
+ {
+ if (string.IsNullOrWhiteSpace(value))
+ return null;
+ if (Clock().Match(value) is { Success: true } clock)
+ {
+ var seconds = int.Parse(clock.Groups["h"].Value, CultureInfo.InvariantCulture) * 3600.0
+ + int.Parse(clock.Groups["m"].Value, CultureInfo.InvariantCulture) * 60
+ + double.Parse(clock.Groups["s"].Value, CultureInfo.InvariantCulture);
+ if (clock.Groups["frames"].Success && context.FrameRate > 0)
+ seconds += double.Parse(clock.Groups["frames"].Value, CultureInfo.InvariantCulture) / context.FrameRate;
+ return TimeSpan.FromSeconds(seconds);
+ }
+ if (Offset().Match(value) is { Success: true } offset)
+ {
+ var number = double.Parse(offset.Groups["n"].Value, CultureInfo.InvariantCulture);
+ var seconds = offset.Groups["unit"].Value switch
+ {
+ "h" => number * 3600,
+ "m" => number * 60,
+ "ms" => number / 1000,
+ "f" => context.FrameRate > 0 ? number / context.FrameRate : 0,
+ "t" => context.TickRate > 0 ? number / context.TickRate : 0,
+ _ => number,
+ };
+ return TimeSpan.FromSeconds(seconds);
+ }
+ return null;
+ }
+
+ private static double Number(string? text, double fallback) =>
+ double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var value) && value > 0 ? value : fallback;
+
+ /// <summary><c>ttp:frameRateMultiplier="1000 1001"</c> → 0.999 (29.97 fps written as 30 × 1000/1001).</summary>
+ private static double Ratio(string? text) =>
+ text?.Split(' ', StringSplitOptions.RemoveEmptyEntries) 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) && num > 0 && den > 0
+ ? num / den
+ : 1;
+
+ [GeneratedRegex(@"^(?<h>\d+):(?<m>\d{2}):(?<s>\d{2}(?:\.\d+)?)(?::(?<frames>\d+(?:\.\d+)?))?$")]
+ private static partial Regex Clock();
+
+ [GeneratedRegex(@"^(?<n>\d+(?:\.\d+)?)(?<unit>h|ms|m|s|f|t)$")]
+ private static partial Regex Offset();
+
+ [GeneratedRegex(@"\s+")]
+ private static partial Regex Whitespace();
+}
diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs
index 4a1abc28..9dfb26af 100644
--- a/tests/Filee.App.Tests/RenderTests.cs
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@ -722,6 +722,16 @@ public class RenderTests
box.IsDropDownOpen = false;
window.Close();
+ // HEVC preset: the codec choice next to the other video options.
+ var hevc = new PresetEditorViewModel(store.FindPreset("mp4-hevc")!, loc);
+ Assert.True(hevc.ShowVideoCodec && !hevc.ShowAudioCodec);
+ Assert.Equal(Filee.Core.Presets.VideoCodec.Hevc, hevc.VideoCodecChoice.Value);
+ window = new PresetEditorWindow { DataContext = hevc, Height = 900 };
+ window.Show();
+ Pump();
+ Save(window, $"preset-codec-{suffix}.png");
+ window.Close();
+
var archive = new PresetEditorViewModel(store.FindPreset("zip-all")!, loc);
Assert.True(archive.ShowArchive && archive.ShowArchiveOptions && archive.CombineIntoOne);
Assert.False(archive.ShowMedia || archive.ShowPdf);
@@ -794,6 +804,46 @@ public class RenderTests
Assert.Equal("600p", new PresetEditorViewModel(preset, AppHost.Get<ILocalizer>()).MaxHeight.Label);
}
+ [AvaloniaFact]
+ public void Preset_editor_offers_the_codecs_each_target_can_hold()
+ {
+ TestServices.EnsureInitialized("en");
+ var preset = new Filee.Core.Presets.Preset { TargetFormat = "mp4", Name = "Codec" };
+ var vm = new PresetEditorViewModel(preset, AppHost.Get<ILocalizer>());
+ Assert.True(vm.ShowVideoCodec && !vm.ShowAudioCodec);
+ Assert.Equal([Filee.Core.Presets.VideoCodec.Default, Filee.Core.Presets.VideoCodec.Hevc, Filee.Core.Presets.VideoCodec.Av1],
+ vm.VideoCodecs.Select(c => c.Value));
+ Assert.StartsWith("H.264", vm.VideoCodecChoice.Label);
+ vm.VideoCodecChoice = vm.VideoCodecs.Single(c => c.Value == Filee.Core.Presets.VideoCodec.Hevc);
+
+ // WebM has no HEVC: its list is VP9 / AV1 and the choice shows as VP9; MKV takes HEVC again.
+ vm.Target = vm.Targets.Single(t => t.Value == "webm");
+ Assert.Equal(["VP9", "AV1 (smallest, slow)"], vm.VideoCodecs.Select(c => c.Label));
+ Assert.Equal(Filee.Core.Presets.VideoCodec.Default, vm.VideoCodecChoice.Value);
+ vm.Target = vm.Targets.Single(t => t.Value == "mkv");
+ Assert.Equal(Filee.Core.Presets.VideoCodec.Hevc, vm.VideoCodecChoice.Value);
+ vm.Target = vm.Targets.Single(t => t.Value == "avi");
+ Assert.False(vm.ShowVideoCodec);
+
+ // M4A: AAC or ALAC; ALAC is lossless, so quality and bitrate go away.
+ vm.Target = vm.Targets.Single(t => t.Value == "m4a");
+ Assert.True(vm.ShowAudioCodec && vm.ShowAudioBitrate && vm.ShowMediaQuality && !vm.ShowVideoCodec);
+ vm.AudioCodecChoice = vm.AudioCodecs.Single(c => c.Value == Filee.Core.Presets.AudioCodec.Alac);
+ Assert.False(vm.ShowAudioBitrate || vm.ShowMediaQuality);
+ Assert.True(vm.ShowMedia && vm.ShowAudioChannels);
+ Assert.True(vm.Apply());
+ Assert.Equal((Filee.Core.Presets.VideoCodec.Default, Filee.Core.Presets.AudioCodec.Alac), (preset.Media.VideoCodec, preset.Media.AudioCodec));
+
+ // New lossless targets and W64 (WAV options); subtitles have no media or PDF options.
+ vm.Target = vm.Targets.Single(t => t.Value == "wv");
+ Assert.False(vm.ShowAudioBitrate || vm.ShowAudioCodec);
+ vm.Target = vm.Targets.Single(t => t.Value == "w64");
+ Assert.True(vm.ShowWav);
+ vm.Target = vm.Targets.Single(t => t.Value == "smi");
+ Assert.False(vm.ShowMedia || vm.ShowPdf || vm.ShowImage);
+ Assert.Equal("Subtitle", vm.Target.Detail);
+ }
+
/// <summary>Shows the toolbar page (tall, so the profile card is visible) with temporarily changed profiles.</summary>
private static void WithProfiles(string language, bool dark, double height, Action<List<ToolbarProfile>> change, Action<Window, ToolbarPageViewModel> act)
{
diff --git a/tests/Filee.Core.Tests/UserDataStoreTests.cs b/tests/Filee.Core.Tests/UserDataStoreTests.cs
index cf18bdab..c8fa15c4 100644
--- a/tests/Filee.Core.Tests/UserDataStoreTests.cs
+++ b/tests/Filee.Core.Tests/UserDataStoreTests.cs
@@ -60,7 +60,7 @@ public class UserDataStoreTests
var store = new UserDataStore(dir.Path);
store.Load();
- Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "email", "vector", "icns", "font", "cad", "archive", "ebook", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);
+ Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "email", "vector", "icns", "font", "cad", "archive", "ebook", "subtitle", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);
Assert.Equal(AppSettings.CurrentSchemaVersion, store.Settings.SchemaVersion);
}
@@ -112,7 +112,7 @@ public class UserDataStoreTests
var store = new UserDataStore(dir.Path);
store.Load();
- Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "email", "vector", "icns", "font", "cad", "archive", "ebook", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);
+ Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "email", "vector", "icns", "font", "cad", "archive", "ebook", "subtitle", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);
var ids = store.Profiles.Select(p => p.Id).ToList();
Assert.Equal(ids.IndexOf("office") + 1, ids.IndexOf("spreadsheets"));
Assert.Equal(ids.IndexOf("office") + 2, ids.IndexOf("presentations"));
@@ -126,8 +126,9 @@ public class UserDataStoreTests
public void Version_5_libraries_get_the_format_catalog()
{
// As written by 1.0.x with schema 5: no catalog presets, donuts or extensions.
- var presets = BuiltInData.CreatePresets().Where(p => BuiltInData.CatalogPresets().All(c => c.Id != p.Id)).ToList();
- var catalogIds = BuiltInData.CatalogProfiles().Select(p => p.Id).ToHashSet();
+ var presets = BuiltInData.CreatePresets()
+ .Where(p => BuiltInData.CatalogPresets().Concat(BuiltInData.CodecAndSubtitlePresets()).All(c => c.Id != p.Id)).ToList();
+ var catalogIds = BuiltInData.CatalogProfiles().Select(p => p.Id).Append("subtitles").ToHashSet();
var profiles = BuiltInData.CreateProfiles().Where(p => !catalogIds.Contains(p.Id)).ToList();
profiles.Single(p => p.Id == "images").Extensions = ["png", "jpg"];
profiles.Single(p => p.Id == "pdf").PresetIds.Remove("to-docx");
@@ -140,6 +141,7 @@ public class UserDataStoreTests
var ids = profiles.Select(p => p.Id).ToList();
Assert.Equal(ids.IndexOf("text") + 1, ids.IndexOf("ebooks"));
Assert.Equal(ids.IndexOf("mixed") - 1, ids.IndexOf("fonts"));
+ Assert.Equal(ids.IndexOf("audio") + 1, ids.IndexOf("subtitles"));
Assert.Contains("cr2", profiles.Single(p => p.Id == "images").Extensions);
Assert.DoesNotContain("mp3", profiles.Single(p => p.Id == "audio").Extensions);
Assert.Contains("flac", profiles.Single(p => p.Id == "audio").Extensions);
@@ -210,6 +212,39 @@ public class UserDataStoreTests
Assert.False(SettingsMigrations.ApplyToLibrary(9, presets, profiles)); // once only
}
+ [Fact]
+ public void Version_10_libraries_get_codecs_new_audio_formats_and_a_subtitles_donut()
+ {
+ // As written by 1.11.x: no HEVC / AV1 / ALAC / subtitle presets, no subtitles donut, the video donut and the
+ // audio extensions of that time, and a donut of the user that already takes .ape.
+ var added = BuiltInData.CodecAndSubtitlePresets().Select(p => p.Id).ToHashSet();
+ var presets = BuiltInData.CreatePresets().Where(p => !added.Contains(p.Id)).ToList();
+ var profiles = BuiltInData.CreateProfiles().Where(p => p.Id != "subtitles").ToList();
+ foreach (var profile in profiles)
+ profile.PresetIds.RemoveAll(added.Contains);
+ var audio = profiles.Single(p => p.Id == "audio");
+ audio.Extensions.RemoveAll(e => e is "wv" or "tta" or "w64" or "eac3" or "ec3" or "ape" or "mpc" or "mpp" or "mp+" or "tak"
+ or "dsf" or "dff" or "dts" or "spx");
+ profiles.Insert(0, new ToolbarProfile { Id = "mine", Name = "Mine", Extensions = ["ape"] });
+
+ Assert.True(SettingsMigrations.ApplyToLibrary(10, presets, profiles));
+
+ Assert.Contains("wv", audio.Extensions);
+ Assert.Contains("dsf", audio.Extensions);
+ Assert.DoesNotContain("ape", audio.Extensions); // the user's donut keeps it
+ var ids = profiles.Select(p => p.Id).ToList();
+ Assert.Equal(ids.IndexOf("audio") + 1, ids.IndexOf("subtitles"));
+ Assert.Equal(BuiltInData.SubtitleProfile().PresetIds, profiles.Single(p => p.Id == "subtitles").PresetIds);
+ Assert.Contains("smi", profiles.Single(p => p.Id == "subtitles").Extensions);
+ Assert.Equal(BuiltInData.CreateProfiles().Single(p => p.Id == "video").PresetIds, profiles.Single(p => p.Id == "video").PresetIds);
+ Assert.Equal(VideoCodec.Hevc, presets.Single(p => p.Id == "mp4-hevc").Media.VideoCodec);
+ Assert.Equal(AudioCodec.Alac, presets.Single(p => p.Id == "to-alac").Media.AudioCodec);
+ Assert.DoesNotContain(profiles, p => p.PresetIds.Contains("to-alac") || p.PresetIds.Contains("mp4-av1"));
+ var all = profiles.SelectMany(p => p.Extensions).ToList();
+ Assert.Equal(all.Count, all.Distinct(StringComparer.OrdinalIgnoreCase).Count());
+ Assert.False(SettingsMigrations.ApplyToLibrary(10, presets, profiles)); // once only
+ }
+
[Fact]
public void Catalog_migration_ignores_extensions_checked_on_mixed_profiles()
{
diff --git a/tests/Filee.Engines.Tests/MediaTests.cs b/tests/Filee.Engines.Tests/MediaTests.cs
index d836d40a..f53b5c0f 100644
--- a/tests/Filee.Engines.Tests/MediaTests.cs
+++ b/tests/Filee.Engines.Tests/MediaTests.cs
@@ -52,6 +52,17 @@ public class MediaTests(EngineFixture fx) : IClassFixture<EngineFixture>
[InlineData("png", "mov")]
[InlineData("rm", "mp4")]
[InlineData("dss", "mp3")]
+ [InlineData("ape", "flac")]
+ [InlineData("wv", "mp3")]
+ [InlineData("tta", "wv")]
+ [InlineData("mpc", "m4a")]
+ [InlineData("tak", "flac")]
+ [InlineData("dsf", "wav")]
+ [InlineData("dff", "flac")]
+ [InlineData("dts", "eac3")]
+ [InlineData("spx", "ogg")]
+ [InlineData("wav", "w64")]
+ [InlineData("mkv", "eac3")]
public void Media_conversions_take_one_ffmpeg_step(string from, string to)
{
var route = Planner().Plan(from, to);
@@ -212,6 +223,98 @@ public class MediaTests(EngineFixture fx) : IClassFixture<EngineFixture>
Assert.Equal("copy", After(Args("mov", new MediaOptions { AudioChannels = 2 }, phone), "-c:a"));
}
+ [Fact]
+ public void Hevc_and_av1_presets_encode_with_x265_and_svt_av1()
+ {
+ var hevc = Args("mp4", new MediaOptions { VideoCodec = VideoCodec.Hevc });
+ Assert.Equal(("libx265", "26", "yuv420p", "hvc1"), (After(hevc, "-c:v"), After(hevc, "-crf"), After(hevc, "-pix_fmt"), After(hevc, "-tag:v")));
+ Assert.Equal("log-level=error", After(hevc, "-x265-params"));
+ Assert.Equal("aac", After(hevc, "-c:a"));
+ Assert.Equal(("22", "30"), (After(Args("mkv", new MediaOptions { VideoCodec = VideoCodec.Hevc, Quality = MediaQuality.High }), "-crf"),
+ After(Args("mkv", new MediaOptions { VideoCodec = VideoCodec.Hevc, Quality = MediaQuality.Small }), "-crf")));
+ Assert.DoesNotContain("-tag:v", Args("mkv", new MediaOptions { VideoCodec = VideoCodec.Hevc }));
+
+ var av1 = Args("mp4", new MediaOptions { VideoCodec = VideoCodec.Av1 });
+ Assert.Equal(("libsvtav1", "8", "32"), (After(av1, "-c:v"), After(av1, "-preset"), After(av1, "-crf")));
+ var webm = Args("webm", new MediaOptions { VideoCodec = VideoCodec.Av1 });
+ Assert.Equal(("libsvtav1", "libopus"), (After(webm, "-c:v"), After(webm, "-c:a")));
+
+ // Targets that can't hold the codec keep their own: WebM has no HEVC, QuickTime no AV1, AVI neither.
+ Assert.Equal("libvpx-vp9", After(Args("webm", new MediaOptions { VideoCodec = VideoCodec.Hevc }), "-c:v"));
+ Assert.Equal("libx264", After(Args("mov", new MediaOptions { VideoCodec = VideoCodec.Av1 }), "-c:v"));
+ Assert.Equal("mpeg4", After(Args("avi", new MediaOptions { VideoCodec = VideoCodec.Hevc }), "-c:v"));
+ }
+
+ [Fact]
+ public void Av1_falls_back_to_libaom_and_a_missing_encoder_is_reported()
+ {
+ var info = new MediaInfo(TimeSpan.FromSeconds(10), Hd, new AudioStreamInfo(2, 48000), null);
+ IReadOnlyList<string> Plan(VideoCodec codec, params string[] encoders) => MediaEncoding.Plan("in.mov", "out.mkv", "mkv",
+ new MediaOptions { VideoCodec = codec }, info, "work", encoders: encoders.ToHashSet()).Single().Arguments;
+
+ var aom = Plan(VideoCodec.Av1, "libaom-av1", "libx264", "aac");
+ Assert.Equal(("libaom-av1", "0", "32", "6"), (After(aom, "-c:v"), After(aom, "-b:v"), After(aom, "-crf"), After(aom, "-cpu-used")));
+ Assert.Contains("AV1 encoder", Assert.Throws<InvalidOperationException>(() => Plan(VideoCodec.Av1, "libx264")).Message);
+ Assert.Contains("HEVC encoder", Assert.Throws<InvalidOperationException>(() => Plan(VideoCodec.Hevc, "libx264")).Message);
+ // A video already in the codec needs no encoder at all.
+ var hevcSource = info with { Video = Hd with { Codec = "hevc", PixelFormat = "yuv420p" } };
+ Assert.Equal("copy", After(MediaEncoding.Plan("in.mov", "out.mkv", "mkv", new MediaOptions { VideoCodec = VideoCodec.Hevc }, hevcSource, "work",
+ encoders: new HashSet<string>()).Single().Arguments, "-c:v"));
+ }
+
+ [Fact]
+ public void Ten_bit_and_hdr_sources_stay_ten_bit_and_matching_codecs_are_copied()
+ {
+ var hlg = new VideoColor("bt2020", "arib-std-b67", "bt2020nc", "tv");
+ var phone = new MediaInfo(TimeSpan.FromSeconds(10), new VideoStreamInfo(3840, 2160, 1, 0, 30, "hevc", "yuv420p10le", hlg),
+ new AudioStreamInfo(2, 48000, "aac"), null);
+
+ // HEVC asked for, HEVC given: rewrapped, 10-bit HDR untouched.
+ Assert.Equal("copy", After(Args("mp4", new MediaOptions { VideoCodec = VideoCodec.Hevc }, phone), "-c:v"));
+ // AV1 asked for: encoded in 10 bits with the HDR tags.
+ var av1 = Args("mkv", new MediaOptions { VideoCodec = VideoCodec.Av1 }, phone);
+ Assert.Equal(("libsvtav1", "yuv420p10le"), (After(av1, "-c:v"), After(av1, "-pix_fmt")));
+ Assert.Equal(("bt2020", "arib-std-b67", "bt2020nc"), (After(av1, "-color_primaries"), After(av1, "-color_trc"), After(av1, "-colorspace")));
+ // Scaled down: re-encoded, still 10 bits.
+ var small = Args("mp4", new MediaOptions { VideoCodec = VideoCodec.Hevc, MaxHeight = 1080 }, phone);
+ Assert.Equal(("libx265", "yuv420p10le"), (After(small, "-c:v"), After(small, "-pix_fmt")));
+
+ // An H.264 source with HEVC asked for is encoded; an AV1 source with AV1 asked for goes into MP4 as it is.
+ var h264 = phone with { Video = new VideoStreamInfo(1920, 1080, 1, 0, 30, "h264", "yuv420p") };
+ var hevc = Args("mp4", new MediaOptions { VideoCodec = VideoCodec.Hevc }, h264);
+ Assert.Equal(("libx265", "yuv420p"), (After(hevc, "-c:v"), After(hevc, "-pix_fmt")));
+ Assert.DoesNotContain("-color_trc", hevc);
+ var av1Source = phone with { Video = new VideoStreamInfo(1920, 1080, 1, 0, 30, "av1", "yuv420p") };
+ Assert.Equal("copy", After(Args("mp4", new MediaOptions { VideoCodec = VideoCodec.Av1 }, av1Source), "-c:v"));
+ Assert.Equal("libx264", After(Args("mp4", info: av1Source), "-c:v")); // H.264 stays the default for MP4
+
+ Assert.True(new VideoStreamInfo(1, 1, 1, 0, 0, PixelFormat: "p010le").IsHighBitDepth);
+ Assert.True(new VideoStreamInfo(1, 1, 1, 0, 0, PixelFormat: "yuv422p12le").IsHighBitDepth);
+ Assert.False(new VideoStreamInfo(1, 1, 1, 0, 0, PixelFormat: "yuvj420p").IsHighBitDepth);
+ }
+
+ [Fact]
+ public void Lossless_and_new_audio_targets_get_their_encoders()
+ {
+ var alac = Args("m4a", new MediaOptions { AudioCodec = AudioCodec.Alac, AudioBitrateKbps = 128 });
+ Assert.Equal(("alac", "ipod"), (After(alac, "-c:a"), After(alac, "-f")));
+ Assert.DoesNotContain("-b:a", alac);
+ Assert.Equal("libmp3lame", After(Args("mp3", new MediaOptions { AudioCodec = AudioCodec.Alac }), "-c:a")); // ALAC is for M4A only
+ Assert.Equal(("wavpack", "wv"), (After(Args("wv"), "-c:a"), After(Args("wv"), "-f")));
+ Assert.Equal(("tta", "tta"), (After(Args("tta"), "-c:a"), After(Args("tta"), "-f")));
+ var w64 = Args("w64", new MediaOptions { WavFormat = WavSampleFormat.Pcm24, AudioSampleRate = 48000 });
+ Assert.Equal(("pcm_s24le", "48000", "w64"), (After(w64, "-c:a"), After(w64, "-ar"), After(w64, "-f")));
+ Assert.Equal(("eac3", "576k"), (After(Args("eac3"), "-c:a"), After(Args("eac3"), "-b:a"))); // 192k per pair × 3 (5.1)
+
+ // DSD (2.8 MHz) becomes 88.2 kHz PCM for lossless targets; lossy encoders choose their own rate.
+ var dsd = new MediaInfo(TimeSpan.FromSeconds(10), null, new AudioStreamInfo(2, 2_822_400, "dsd_lsbf_planar"), null);
+ Assert.Equal("88200", After(Args("flac", info: dsd), "-ar"));
+ Assert.Equal("88200", After(Args("wav", info: dsd), "-ar"));
+ Assert.Equal("16000", After(Args("wav", new MediaOptions { AudioSampleRate = 16000 }, dsd), "-ar"));
+ Assert.Equal("44100", After(Args("ogg", info: dsd), "-ar"));
+ Assert.DoesNotContain("-ar", Args("mp3", info: dsd));
+ }
+
[Fact]
public void Dvd_and_dv_frames_are_letterboxed_into_the_nearest_tv_shape()
{
@@ -314,7 +417,8 @@ public class MediaTests(EngineFixture fx) : IClassFixture<EngineFixture>
"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 } }
+ "disposition": { "attached_pic": 1 } },
+ { "index": 3, "codec_name": "subrip", "codec_type": "subtitle", "tags": { "language": "kor" } }
],
"format": { "duration": "12.480000" }
}
@@ -326,6 +430,7 @@ public class MediaTests(EngineFixture fx) : IClassFixture<EngineFixture>
Assert.Equal(1920, info.Video.DisplayHeight);
Assert.Equal(new AudioStreamInfo(2, 48000, "aac"), info.Audio);
Assert.Equal(2, info.CoverStreamIndex);
+ Assert.Equal([new SubtitleStreamInfo(3, "subrip", "kor")], info.Subtitles);
var raw = MediaInfo.Parse("""{ "streams": [ { "index": 0, "codec_type": "audio", "channels": 1, "sample_rate": "8000" } ], "format": {} }""");
Assert.Null(raw.Duration);
@@ -481,6 +586,55 @@ public class MediaTests(EngineFixture fx) : IClassFixture<EngineFixture>
Assert.Empty(failures);
}
+ [Fact]
+ public async Task Hevc_and_av1_presets_write_those_codecs_and_keep_ten_bits()
+ {
+ SkipUnlessInstalled();
+ var folder = fx.NewFolder();
+ var h264 = await MakeClipAsync(folder, "clip.mp4", seconds: 1, size: "320x240");
+ // A 10-bit HLG source, like a phone's HDR video.
+ var hdr = await MakeClipAsync(folder, "hdr.mkv", seconds: 1, size: "320x240",
+ extra: ["-c:v", "libx265", "-pix_fmt", "yuv420p10le",
+ "-x265-params", "colorprim=bt2020:transfer=arib-std-b67:colormatrix=bt2020nc:log-level=error"]);
+
+ async Task<JsonElement> VideoOf(string file)
+ {
+ var result = await ProcessRunner.RunAsync(Tools!.Value.Ffprobe,
+ ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=codec_name,codec_tag_string,pix_fmt,color_transfer", "-of", "json", file],
+ TimeSpan.FromMinutes(1), CancellationToken.None);
+ return JsonDocument.Parse(result.StandardOutput).RootElement.GetProperty("streams")[0].Clone();
+ }
+
+ var hevc = await VideoOf(await ConvertAsync(h264, "mp4", new MediaOptions { VideoCodec = VideoCodec.Hevc }));
+ Assert.Equal(("hevc", "hvc1", "yuv420p"), (hevc.GetProperty("codec_name").GetString(), hevc.GetProperty("codec_tag_string").GetString(), hevc.GetProperty("pix_fmt").GetString()));
+
+ var av1 = await VideoOf(await ConvertAsync(hdr, "mp4", new MediaOptions { VideoCodec = VideoCodec.Av1 }));
+ Assert.Equal(("av1", "yuv420p10le", "arib-std-b67"), (av1.GetProperty("codec_name").GetString(), av1.GetProperty("pix_fmt").GetString(), av1.GetProperty("color_transfer").GetString()));
+
+ var webm = await VideoOf(await ConvertAsync(h264, "webm", new MediaOptions { VideoCodec = VideoCodec.Av1, Quality = MediaQuality.Small }));
+ Assert.Equal("av1", webm.GetProperty("codec_name").GetString());
+ }
+
+ [Fact]
+ public async Task Alac_speex_and_dts_are_written_and_read()
+ {
+ SkipUnlessInstalled();
+ var folder = fx.NewFolder();
+ var tone = await MakeToneAsync(folder, "tone.wav");
+ var alac = await ProbeAsync(await ConvertAsync(tone, "m4a", new MediaOptions { AudioCodec = AudioCodec.Alac }));
+ Assert.Equal("alac", alac.Audio?.Codec);
+ Assert.InRange(alac.Duration, 1.9, 2.1);
+
+ // Formats Filee only reads, made with FFmpeg's own encoders (DTS's is experimental), then converted.
+ var spx = Path.Combine(folder, "voice.spx");
+ await RunAsync(Tools!.Value.Ffmpeg, ["-hide_banner", "-nostdin", "-v", "error", "-y", "-i", tone, "-ar", "16000", "-ac", "1", "-c:a", "libspeex", "-f", "ogg", spx]);
+ var dts = Path.Combine(folder, "surround.dts");
+ await RunAsync(Tools.Value.Ffmpeg, ["-hide_banner", "-nostdin", "-v", "error", "-y", "-i", tone, "-ar", "48000", "-c:a", "dca", "-strict", "-2", "-f", "dts", dts]);
+ Assert.Equal("pcm_s16le", (await ProbeAsync(await ConvertAsync(spx, "wav"))).Audio?.Codec);
+ Assert.Equal("flac", (await ProbeAsync(await ConvertAsync(dts, "flac"))).Audio?.Codec);
+ Assert.Equal("wavpack", (await ProbeAsync(await ConvertAsync(dts, "wv"))).Audio?.Codec);
+ }
+
[Fact]
public async Task An_iphone_hdr_mov_is_rewrapped_into_mp4_without_re_encoding()
{
diff --git a/tests/Filee.Engines.Tests/SubtitleTests.cs b/tests/Filee.Engines.Tests/SubtitleTests.cs
new file mode 100644
index 00000000..fa012e27
--- /dev/null
+++ b/tests/Filee.Engines.Tests/SubtitleTests.cs
@@ -0,0 +1,447 @@
+// Text subtitles with the built-in subtitle engine: every reader and writer, Korean CP949 / EUC-KR detection, and
+// subtitle extraction from videos with FFmpeg (only when Filee's FFmpeg is installed). Inputs are written by the tests.
+
+using System.Text;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Infrastructure;
+using Filee.Engines.Media;
+using Filee.Engines.Subtitles;
+
+namespace Filee.Engines.Tests;
+
+[Collection(nameof(FfmpegCollection))]
+public class SubtitleTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private static readonly Encoding Cp949;
+ private static readonly Encoding Gbk;
+
+ static SubtitleTests()
+ {
+ Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
+ Cp949 = Encoding.GetEncoding(949);
+ Gbk = Encoding.GetEncoding(936);
+ }
+
+ private static SubtitleDocument Read(string format, string text) => SubtitleReader.Read(format, new UTF8Encoding(false).GetBytes(text));
+
+ private static string Write(SubtitleDocument document, string format)
+ {
+ var bytes = SubtitleWriter.Write(document, format);
+ return new UTF8Encoding(false).GetString(bytes).TrimStart('');
+ }
+
+ private static TimeSpan Ms(int ms) => TimeSpan.FromMilliseconds(ms);
+
+ // ───────────────────────── Routes ─────────────────────────
+
+ [Theory]
+ [InlineData("srt", "smi")]
+ [InlineData("smi", "srt")]
+ [InlineData("smi", "smi")] // CP949 → UTF-8
+ [InlineData("ass", "vtt")]
+ [InlineData("ssa", "srt")]
+ [InlineData("vtt", "ttml")]
+ [InlineData("lrc", "srt")]
+ [InlineData("ttml", "srt")]
+ [InlineData("sub", "srt")]
+ [InlineData("scc", "vtt")]
+ public void Subtitles_convert_in_one_built_in_step(string from, string to)
+ {
+ var route = fx.Catalog.CreatePlanner([]).Plan(from, to);
+ Assert.NotNull(route);
+ Assert.Equal("subtitle", Assert.Single(route.Steps).Converter.Id);
+ }
+
+ [Fact]
+ public void Video_subtitles_come_out_through_ffmpeg_and_srt()
+ {
+ var planner = fx.Catalog.CreatePlanner(["ffmpeg"]);
+ Assert.Equal([("ffmpeg", "mkv", "srt")], planner.Plan("mkv", "srt")!.Steps.Select(s => (s.Converter.Id, s.From, s.To)));
+ Assert.Equal([("ffmpeg", "mp4", "ass")], planner.Plan("mp4", "ass")!.Steps.Select(s => (s.Converter.Id, s.From, s.To)));
+ Assert.Equal([("ffmpeg", "mkv", "srt"), ("subtitle", "srt", "smi")],
+ planner.Plan("mkv", "smi")!.Steps.Select(s => (s.Converter.Id, s.From, s.To)));
+ // Subtitles never become video, and audio has no subtitles.
+ Assert.Null(planner.Plan("srt", "mp4"));
+ Assert.Null(planner.Plan("mp3", "srt"));
+ }
+
+ // ───────────────────────── Encodings ─────────────────────────
+
+ [Fact]
+ public void Korean_cp949_text_is_recognised_and_other_code_pages_are_not_taken_for_it()
+ {
+ const string korean = "안녕하세요. 오늘 날씨가 좋네요! 똠방각하";
+ Assert.True(SubtitleEncoding.LooksKorean(Cp949.GetBytes(korean)));
+ Assert.Equal(korean, SubtitleEncoding.Decode(Cp949.GetBytes(korean), ansiCodePage: 1252));
+ Assert.Equal(korean, SubtitleEncoding.Decode(Cp949.GetBytes(korean), ansiCodePage: 936)); // also on Chinese Windows
+
+ const string chinese = "我是一个学生,这是我的字幕文件。你好吗?";
+ Assert.False(SubtitleEncoding.LooksKorean(Gbk.GetBytes(chinese)));
+ Assert.Equal(chinese, SubtitleEncoding.Decode(Gbk.GetBytes(chinese), ansiCodePage: 936));
+
+ const string french = "Café, déjà vu à l'été";
+ var latin1 = Encoding.GetEncoding(1252).GetBytes(french);
+ Assert.False(SubtitleEncoding.LooksKorean(latin1));
+ Assert.Equal(french, SubtitleEncoding.Decode(latin1, ansiCodePage: 1252));
+ Assert.Equal(french, SubtitleEncoding.Decode(latin1, ansiCodePage: 949)); // Korean Windows: still Western
+
+ // Byte order marks and UTF-16.
+ Assert.Equal("가나", SubtitleEncoding.Decode([0xEF, 0xBB, 0xBF, .. Encoding.UTF8.GetBytes("가나")]));
+ Assert.Equal("가나", SubtitleEncoding.Decode([.. Encoding.Unicode.GetPreamble(), .. Encoding.Unicode.GetBytes("가나")]));
+ Assert.Equal("Hi there", SubtitleEncoding.Decode(Encoding.Unicode.GetBytes("Hi there")));
+ }
+
+ [Fact]
+ public async Task A_cp949_sami_file_becomes_a_utf8_srt_with_the_korean_class()
+ {
+ var folder = fx.NewFolder();
+ var smi = Path.Combine(folder, "영화.smi");
+ // As Korean SAMI files usually are: CP949, unquoted attributes, unclosed tags, two languages, &nbsp; clears.
+ File.WriteAllBytes(smi, Cp949.GetBytes("""
+ <SAMI>
+ <HEAD>
+ <TITLE>영화 자막</TITLE>
+ <STYLE TYPE="text/css">
+ <!--
+ P { margin-left:8pt; margin-right:8pt; text-align:center; }
+ .KRCC { Name:한국어; lang:ko-KR; SAMIType:CC; }
+ .ENCC { Name:English; lang:en-US; SAMIType:CC; }
+ -->
+ </STYLE>
+ </HEAD>
+ <BODY>
+ <SYNC Start=1000><P Class=KRCC>안녕하세요,<br><font color="#ffff00">반가워요</font>
+ <SYNC Start=1000><P Class=ENCC>Hello
+ <SYNC Start=2500><P Class=KRCC>&nbsp;
+ <SYNC Start=3000><P Class=KRCC><i>두 번째
+ 줄입니다</i>
+ <SYNC Start=4200><P Class=KRCC>&nbsp
+ <SYNC Start=5000><P Class=KRCC>세 번째 &amp; 마지막
+ </BODY>
+ </SAMI>
+ """));
+
+ var job = await fx.ConvertAsync([smi], new Preset { TargetFormat = "srt" });
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ var bytes = File.ReadAllBytes(job.Outputs.Single());
+ Assert.Equal(Encoding.UTF8.GetPreamble(), bytes[..3]);
+ var srt = Encoding.UTF8.GetString(bytes[3..]);
+ Assert.Equal("""
+ 1
+ 00:00:01,000 --> 00:00:02,500
+ 안녕하세요,
+ <font color="#FFFF00">반가워요</font>
+
+ 2
+ 00:00:03,000 --> 00:00:04,200
+ <i>두 번째 줄입니다</i>
+
+ 3
+ 00:00:05,000 --> 00:00:09,000
+ 세 번째 & 마지막
+
+
+ """.ReplaceLineEndings("\r\n"), srt);
+ }
+
+ // ───────────────────────── Readers ─────────────────────────
+
+ [Fact]
+ public void Srt_is_read_leniently()
+ {
+ // A blank line inside a cue, a missing blank line, a dot before the milliseconds, a {\an8} code, stray tags.
+ var document = Read("srt", "1\r\n00:00:01,000 --> 00:00:02,000\r\n<i>First</i> line\r\n\r\nstill the first\r\n\r\n2\r\n" +
+ "00:00:03.5 --> 00:00:04,250\r\n{\\an8}<b>Second</b> <span>cue</span>\r\n3\r\n00:00:05,000 --> 00:00:06,000\r\nThird 2024\r\n");
+ Assert.Equal(
+ [
+ new SubtitleCue(Ms(1000), Ms(2000), "<i>First</i> line\nstill the first"),
+ new SubtitleCue(Ms(3500), Ms(4250), "<b>Second</b> cue"),
+ new SubtitleCue(Ms(5000), Ms(6000), "Third 2024"),
+ ], document.Cues);
+ }
+
+ [Fact]
+ public void WebVtt_cues_settings_entities_and_voices_are_read()
+ {
+ var document = Read("vtt", """
+ WEBVTT
+ Language: ko
+
+ NOTE This is a comment
+ with two lines
+
+ STYLE
+ ::cue { color: yellow }
+
+ intro
+ 00:01.000 --> 00:02.500 align:start position:10%
+ <v Mary>Hi &amp; <i>welcome</i></v>
+ <c.yellow>&lt;3</c>
+
+ 01:00:00.000 --> 01:00:01.000
+ <00:00:01.500>Karaoke
+ """);
+ Assert.Equal("ko", document.Language);
+ Assert.Equal(
+ [
+ new SubtitleCue(Ms(1000), Ms(2500), "Hi & <i>welcome</i>\n<font color=\"#FFFF00\"><3</font>"),
+ new SubtitleCue(TimeSpan.FromHours(1), TimeSpan.FromHours(1) + Ms(1000), "Karaoke"),
+ ], document.Cues);
+ }
+
+ [Fact]
+ public void Ass_dialogue_override_codes_and_styles_are_read()
+ {
+ var document = Read("ass", """
+ [Script Info]
+ Title: Test show
+ ScriptType: v4.00+
+
+ [V4+ Styles]
+ Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
+ Style: Default,Arial,20,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,2,2,10,10,10,1
+ Style: Thoughts,Arial,20,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,-1,0,0,100,100,0,0,1,2,2,2,10,10,10,1
+
+ [Events]
+ Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
+ Dialogue: 0,0:00:02.00,0:00:03.50,Default,,0,0,0,,{\an8\pos(10,10)}Hello, {\i1}world{\i0}!\NSecond {\c&H00FFFF&}yellow{\c} line
+ Comment: 0,0:00:02.00,0:00:03.50,Default,,0,0,0,,Not shown
+ Dialogue: 0,0:00:01.00,0:00:01.50,Thoughts,,0,0,0,,I think\h so
+ Dialogue: 1,0:00:01.00,0:00:01.50,Thoughts,,0,0,0,,I think\h so
+ Dialogue: 0,0:00:04.00,0:00:05.00,Default,,0,0,0,,{\p1}m 0 0 l 100 0 100 100 0 100{\p0}
+ """);
+ Assert.Equal("Test show", document.Title);
+ Assert.Equal(
+ [
+ new SubtitleCue(Ms(1000), Ms(1500), "<i>I think so</i>"), // the italic style, shadow layer merged
+ new SubtitleCue(Ms(2000), Ms(3500), "Hello, <i>world</i>!\nSecond <font color=\"#FFFF00\">yellow</font> line"),
+ ], document.Cues);
+ }
+
+ [Fact]
+ public void Lrc_lines_last_until_the_next_one()
+ {
+ var document = Read("lrc", """
+ [ti:Song]
+ [ar:Singer]
+ [offset:+500]
+ [00:10.00]First <00:10.50>line
+ [00:12.30][00:20.00]Chorus
+ [00:15.00]
+ [00:25.5]Last
+ """);
+ Assert.Equal("Song", document.Title);
+ Assert.Equal(
+ [
+ new SubtitleCue(Ms(9500), Ms(11800), "First line"),
+ new SubtitleCue(Ms(11800), Ms(14500), "Chorus"),
+ new SubtitleCue(Ms(19500), Ms(25000), "Chorus"),
+ new SubtitleCue(Ms(25000), Ms(29000), "Last"),
+ ], document.Cues);
+ }
+
+ [Fact]
+ public void Ttml_times_spans_and_styles_are_read()
+ {
+ var document = Read("ttml", """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <tt xmlns="http://www.w3.org/ns/ttml" xmlns:tts="http://www.w3.org/ns/ttml#styling"
+ xmlns:ttp="http://www.w3.org/ns/ttml#parameter" xml:lang="en" ttp:frameRate="25" ttp:tickRate="10000000">
+ <head><styling><style xml:id="it" tts:fontStyle="italic"/></styling></head>
+ <body>
+ <div begin="10s">
+ <p begin="00:00:01.000" end="00:00:02.000">Line one<br/>line <span tts:fontWeight="bold">two</span></p>
+ <p begin="00:00:03:05" dur="25f" style="it">Frames</p>
+ <p begin="50000000t" end="60000000t"><span tts:color="#ff0000">Red</span> ticks</p>
+ </div>
+ </body>
+ </tt>
+ """);
+ Assert.Equal("en", document.Language);
+ Assert.Equal(
+ [
+ new SubtitleCue(Ms(11000), Ms(12000), "Line one\nline <b>two</b>"),
+ new SubtitleCue(Ms(13200), Ms(14200), "<i>Frames</i>"),
+ new SubtitleCue(Ms(15000), Ms(16000), "<font color=\"#FF0000\">Red</font> ticks"),
+ ], document.Cues);
+ }
+
+ [Fact]
+ public void MicroDvd_frames_use_the_rate_in_the_first_line()
+ {
+ var document = Read("sub", "{1}{1}25\n{25}{50}{y:i}Hello|world\n{75}{100}{c:$0000FF}Red\n");
+ Assert.Equal(
+ [
+ new SubtitleCue(Ms(1000), Ms(2000), "<i>Hello</i>\nworld"),
+ new SubtitleCue(Ms(3000), Ms(4000), "<font color=\"#FF0000\">Red</font>"),
+ ], document.Cues);
+
+ var vobsub = Assert.Throws<InvalidDataException>(() => SubtitleReader.Read("sub", [0x00, 0x00, 0x01, 0xBA, 0x44, 0x00]));
+ Assert.Contains("VobSub", vobsub.Message);
+ Assert.Contains("MicroDVD", Assert.Throws<InvalidDataException>(() => Read("sub", "[INFORMATION]\n00:00:01.00,00:00:02.00\nSubViewer")).Message);
+ }
+
+ [Fact]
+ public void Scc_pop_on_and_roll_up_captions_are_decoded()
+ {
+ // Pop-on: load "Hello" (with parity bits) and "Café" off screen, show at End Of Caption, erase two seconds later.
+ // Then roll-up with two rows. Control codes are sent twice, as broadcasters do.
+ var document = Read("scc", """
+ Scenarist_SCC V1.0
+
+ 00:00:01:00 9420 9420 94ae 94ae 9452 9452 c8e5 ecec ef80 9470 9470 4361 665c 942f 942f
+
+ 00:00:03:00 942c 942c
+
+ 00:00:05:00 9425 9425 9470 9470 4f6e 6521 94ad 94ad 5477 6f21
+
+ 00:00:07:00 942c 942c
+ """);
+ var frame = 1001.0 / 30000;
+ Assert.Equal(3, document.Cues.Count);
+ Assert.Equal("Hello\nCafé", document.Cues[0].Text);
+ Assert.Equal(30 * frame + 13 * frame, document.Cues[0].Start.TotalSeconds, 3); // the End Of Caption pair
+ Assert.Equal(90 * frame, document.Cues[0].End.TotalSeconds, 3);
+ Assert.Equal("One!", document.Cues[1].Text);
+ Assert.Equal("One!\nTwo!", document.Cues[2].Text); // the first row scrolled up
+ Assert.Equal(210 * frame, document.Cues[^1].End.TotalSeconds, 3);
+ Assert.Contains("SCC", Assert.Throws<InvalidDataException>(() => Read("scc", "00:00:01:00 9420")).Message);
+ }
+
+ [Fact]
+ public void Empty_files_fail_with_a_clear_message() =>
+ Assert.Contains("No subtitles", Assert.Throws<InvalidDataException>(() => Read("srt", "\n\n")).Message);
+
+ // ───────────────────────── Writers ─────────────────────────
+
+ private static SubtitleDocument Sample()
+ {
+ var document = new SubtitleDocument { Title = "Sample" };
+ document.Add(Ms(1000), Ms(2500), "<i>Hello</i> & <b>bye</b>\n<font color=\"#FFFF00\">yellow</font> 1 < 2");
+ document.Add(Ms(2500), Ms(4000), "다음 줄");
+ document.Add(Ms(6000), Ms(7000), "Last one");
+ return document.Finish();
+ }
+
+ [Fact]
+ public void Every_format_writes_the_cues_with_its_own_markup()
+ {
+ var document = Sample();
+ Assert.Contains("00:00:01,000 --> 00:00:02,500\r\n<i>Hello</i> & <b>bye</b>\r\n<font color=\"#FFFF00\">yellow</font> 1 < 2", Write(document, "srt"));
+
+ var vtt = Write(document, "vtt");
+ Assert.StartsWith("WEBVTT\n\n00:00:01.000 --> 00:00:02.500\n<i>Hello</i> &amp; <b>bye</b>\n<c.yellow>yellow</c> 1 &lt; 2\n\n", vtt);
+
+ var ass = Write(document, "ass");
+ Assert.Contains("Title: Sample", ass);
+ Assert.Contains(@"Dialogue: 0,0:00:01.00,0:00:02.50,Default,,0,0,0,,{\i1}Hello{\i0} & {\b1}bye{\b0}\N{\c&H00FFFF&}yellow{\c} 1 < 2", ass);
+ Assert.Equal("a (b)", SubtitleWriter.AssText("a {b}")); // a brace would start an override block
+
+ var sami = Write(document, "smi");
+ Assert.Contains(".KRCC { Name: Korean; lang: ko-KR; SAMIType: CC; }", sami);
+ Assert.Contains("<SYNC Start=1000><P Class=KRCC><i>Hello</i> &amp; <b>bye</b><br><font color=\"#FFFF00\">yellow</font> 1 &lt; 2\r\n<SYNC Start=2500>", sami);
+ Assert.Contains("<SYNC Start=4000><P Class=KRCC>&nbsp;\r\n<SYNC Start=6000>", sami); // gap: the screen is cleared
+
+ Assert.Equal("[ti:Sample]\r\n[00:01.00]Hello & bye yellow 1 < 2\r\n[00:02.50]다음 줄\r\n[00:04.00]\r\n[00:06.00]Last one\r\n[00:07.00]\r\n",
+ Write(document, "lrc"));
+
+ var ttml = Write(document, "ttml");
+ Assert.Contains("""<p begin="00:00:01.000" end="00:00:02.500"><span tts:fontStyle="italic">Hello</span> &amp; <span tts:fontWeight="bold">bye</span><br /><span tts:color="#FFFF00">yellow</span> 1 &lt; 2</p>""", ttml);
+
+ Assert.StartsWith("{1}{1}23.976\r\n{24}{60}Hello & bye|yellow 1 < 2\r\n", Write(document, "sub"));
+ }
+
+ [Theory]
+ [InlineData("srt")]
+ [InlineData("vtt")]
+ [InlineData("ass")]
+ [InlineData("smi")]
+ [InlineData("ttml")]
+ public void Formats_with_styles_read_back_what_they_write(string format)
+ {
+ var document = Sample();
+ var back = SubtitleReader.Read(format, SubtitleWriter.Write(document, format));
+ // WebVTT keeps only the basic colours, which "yellow" is.
+ Assert.Equal(document.Cues, back.Cues);
+ }
+
+ [Theory]
+ [InlineData("lrc")]
+ [InlineData("sub")]
+ public void Plain_formats_read_back_the_text_and_times(string format)
+ {
+ var document = Sample();
+ var back = SubtitleReader.Read(format, SubtitleWriter.Write(document, format));
+ Assert.Equal(document.Cues.Select(c => SubtitleMarkup.PlainText(c.Text).Replace("\n", format == "lrc" ? " " : "\n")),
+ back.Cues.Select(c => c.Text));
+ var tolerance = format == "sub" ? 45 : 10; // a frame at 23.976 fps, a hundredth of a second
+ Assert.All(document.Cues.Zip(back.Cues), pair => Assert.InRange(Math.Abs((pair.First.Start - pair.Second.Start).TotalMilliseconds), 0, tolerance));
+ }
+
+ // ───────────────────────── Extraction from video (FFmpeg) ─────────────────────────
+
+ private static readonly (string Ffmpeg, string Ffprobe)? Tools = FfmpegConverter.Locate();
+
+ private static void SkipUnlessFfmpeg() =>
+ Assert.SkipUnless(Tools is not null, "FFmpeg is not installed (pwsh build/fetch-engines.ps1 -Only ffmpeg)");
+
+ /// <summary>A 2-second clip with the given subtitle file muxed in (or none).</summary>
+ private static async Task<string> MakeVideoAsync(string folder, string name, string? subtitles, params string[] codec)
+ {
+ var path = Path.Combine(folder, name);
+ List<string> args = ["-hide_banner", "-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=160x120:rate=25:duration=2"];
+ if (subtitles is not null)
+ args.AddRange(["-i", subtitles, "-map", "0:v", "-map", "1:s"]);
+ args.AddRange(["-c:v", "libx264", "-pix_fmt", "yuv420p", .. codec, path]);
+ var result = await ProcessRunner.RunAsync(Tools!.Value.Ffmpeg, args, TimeSpan.FromMinutes(1), CancellationToken.None);
+ Assert.True(result.ExitCode == 0, result.StandardError);
+ return path;
+ }
+
+ [Fact]
+ public async Task The_first_text_subtitle_track_of_a_video_is_extracted()
+ {
+ SkipUnlessFfmpeg();
+ var folder = fx.NewFolder();
+ var srt = Path.Combine(folder, "track.srt");
+ File.WriteAllText(srt, "1\n00:00:00,500 --> 00:00:01,500\n<i>자막</i> 하나\n\n2\n00:00:01,600 --> 00:00:01,900\nTwo\n", new UTF8Encoding(false));
+ var mkv = await MakeVideoAsync(folder, "movie.mkv", srt, "-c:s", "srt");
+ var mp4 = await MakeVideoAsync(folder, "movie.mp4", srt, "-c:s", "mov_text");
+ var silent = await MakeVideoAsync(folder, "plain.mp4", null);
+
+ var job = await fx.ConvertAsync([mkv], new Preset { TargetFormat = "srt" });
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ var extracted = SubtitleReader.Read("srt", File.ReadAllBytes(job.Outputs.Single()));
+ Assert.Equal([new SubtitleCue(Ms(500), Ms(1500), "<i>자막</i> 하나"), new SubtitleCue(Ms(1600), Ms(1900), "Two")], extracted.Cues);
+
+ // MP4 timed text → WebVTT, and a video → SAMI through SRT.
+ job = await fx.ConvertAsync([mp4], new Preset { TargetFormat = "vtt" });
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ Assert.Equal(["자막 하나", "Two"], SubtitleReader.Read("vtt", File.ReadAllBytes(job.Outputs.Single())).Cues.Select(c => SubtitleMarkup.PlainText(c.Text)));
+ job = await fx.ConvertAsync([mkv], new Preset { TargetFormat = "smi" });
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ Assert.Contains("<P Class=KRCC><i>자막</i> 하나", File.ReadAllText(job.Outputs.Single()));
+
+ // A video without subtitles says so.
+ job = await fx.ConvertAsync([silent], new Preset { TargetFormat = "srt" });
+ Assert.Equal(JobState.Failed, job.State);
+ Assert.Contains("no subtitle track", job.Files.Single().ErrorDetail);
+ Assert.Empty(Directory.GetFiles(folder, "plain*.srt"));
+ }
+
+ [Fact]
+ public void Picture_subtitles_are_refused_with_a_clear_message()
+ {
+ var info = new MediaInfo(TimeSpan.FromSeconds(1), new VideoStreamInfo(1920, 1080, 1, 0, 24), null, null,
+ [new SubtitleStreamInfo(2, "hdmv_pgs_subtitle", "kor")]);
+ var error = Assert.Throws<InvalidOperationException>(() => MediaEncoding.Plan("in.mkv", "out.srt", "srt", new MediaOptions(), info, "work"));
+ Assert.Contains("pictures", error.Message);
+
+ var both = info with { SubtitleStreams = [new SubtitleStreamInfo(2, "hdmv_pgs_subtitle", "kor"), new SubtitleStreamInfo(3, "ass", "eng")] };
+ var args = MediaEncoding.Plan("in.mkv", "out.ass", "ass", new MediaOptions(), both, "work").Single().Arguments;
+ Assert.Equal(["-map", "0:3", "-c:s", "copy", "-f", "ass"], args.SkipWhile(a => a != "-map").Take(6));
+ args = MediaEncoding.Plan("in.mkv", "out.srt", "srt", new MediaOptions(), both, "work").Single().Arguments;
+ Assert.Equal(["-map", "0:3", "-c:s", "srt", "-f", "srt"], args.SkipWhile(a => a != "-map").Take(6));
+ }
+}