From bb20411164688757f9c349dc114d8657ccb92134 Mon Sep 17 00:00:00 2001 From: yusufmntm Date: Wed, 2 Dec 2026 19:12:54 +0300 Subject: [PATCH] feat(subtitles): Blu-ray picture subtitles (.sup) to SRT and ASS with OCR Filee didn't open .sup files, and picture subtitles can only become text through OCR (#1872). Filee already has Tesseract (and Apple Vision on macOS). PgsReader reads the PGS segments (compositions, windows, palettes, run-length objects split over several segments, epochs, palette-only updates) and yields each caption with its times as soon as it ends, so a film's worth of bitmaps never sits in memory at once. SubtitleOcr turns each object into dark text on white (padded, doubled when small), reads them in batches through Tesseract's list-file mode (one picture per call if a batch can't be split), cleans the lines (CJK spaces as in #691) and writes SRT or text with SubtitleWriter; ASS, WebVTT and the rest follow through SRT. Vision gets the same edges. .sup is a read-only Specialist subtitle format in the video-pro field, learned by the subtitles donut in schema 112. Subtitle presets show the OCR language picker (without the OCR switch) in an OCR card of its own. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- docs/ENGINES.md | 13 +- src/Filee.App/Assets/i18n/ar.json | 2 + src/Filee.App/Assets/i18n/bn-BD.json | 2 + src/Filee.App/Assets/i18n/de.json | 2 + src/Filee.App/Assets/i18n/en.json | 2 + src/Filee.App/Assets/i18n/es.json | 2 + src/Filee.App/Assets/i18n/fa.json | 2 + src/Filee.App/Assets/i18n/fr.json | 2 + src/Filee.App/Assets/i18n/hi.json | 2 + src/Filee.App/Assets/i18n/id.json | 2 + src/Filee.App/Assets/i18n/it.json | 2 + src/Filee.App/Assets/i18n/ja.json | 2 + src/Filee.App/Assets/i18n/ko.json | 2 + src/Filee.App/Assets/i18n/mn.json | 2 + src/Filee.App/Assets/i18n/ne.json | 2 + src/Filee.App/Assets/i18n/pl.json | 2 + src/Filee.App/Assets/i18n/pt-BR.json | 2 + src/Filee.App/Assets/i18n/pt-PT.json | 2 + src/Filee.App/Assets/i18n/ru.json | 2 + src/Filee.App/Assets/i18n/th.json | 2 + src/Filee.App/Assets/i18n/tr.json | 2 + src/Filee.App/Assets/i18n/vi.json | 2 + src/Filee.App/Assets/i18n/zh-CN.json | 2 + src/Filee.App/Assets/i18n/zh-TW.json | 2 + .../ViewModels/PresetEditorViewModel.cs | 14 +- src/Filee.App/Views/PresetEditorView.axaml | 95 +-- src/Filee.Core/Formats/FormatFields.cs | 4 +- src/Filee.Core/Formats/FormatRegistry.cs | 2 + .../Gallery/SharedPresetVersions.cs | 1 + src/Filee.Core/Settings/AppSettings.cs | 2 +- src/Filee.Core/Settings/UserDataStore.cs | 3 + src/Filee.Engines/EngineRegistry.cs | 2 +- src/Filee.Engines/Ocr/SubtitleOcr.cs | 348 +++++++++++ src/Filee.Engines/Ocr/TesseractConverter.cs | 46 +- src/Filee.Engines/Ocr/VisionConverter.cs | 58 +- src/Filee.Engines/Pdf/PdfDocumentReader.cs | 2 +- src/Filee.Engines/Subtitles/PgsReader.cs | 444 +++++++++++++ tests/Filee.App.Tests/RenderTests.cs | 21 + tests/Filee.Core.Tests/FormatFieldsTests.cs | 8 +- tests/Filee.Core.Tests/OcrRouteTests.cs | 28 + tests/Filee.Core.Tests/SupFormatTests.cs | 51 ++ tests/Filee.Engines.Tests/PgsTests.cs | 583 ++++++++++++++++++ 43 files changed, 1706 insertions(+), 67 deletions(-) create mode 100644 src/Filee.Engines/Ocr/SubtitleOcr.cs create mode 100644 src/Filee.Engines/Subtitles/PgsReader.cs create mode 100644 tests/Filee.Core.Tests/SupFormatTests.cs create mode 100644 tests/Filee.Engines.Tests/PgsTests.cs diff --git a/README.md b/README.md index 61493db45..956b626a0 100644 --- a/README.md +++ b/README.md @@ -183,7 +183,7 @@ To undo it, remove the entries in Windows Security → App & browser control → | **E-books**: EPUB, KEPUB, MOBI, AZW3, AZW, AZW4, FB2, CBZ, CBR, CB7, HTMLZ, TXTZ
LIT, LRF, CHM, PDB, …⁴ | PDF, EPUB, KEPUB (Kobo), DOCX, TXT, HTML, HWPX
MOBI, AZW3⁴ | | **Video**⁵: MP4, MOV, MKV, WEBM, AVI, WMV, FLV, MPEG, Video CD (DAT), TS, M2TS, 3GP, OGV, VOB, …;
Wisenet WAVE / Nx Witness exports (NOV), DVD-Video disc images (ISO: choose the title, audio and subtitle tracks) read | MP4 (H.264, HEVC, AV1), WEBM, MOV, MKV, AVI, GIF, APNG, WEBP, MP3, M4A, 720p, split into parts;
subtitle tracks kept (MKV, MP4, MOV, WebM);
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, …;
tracker modules (XM, IT, S3M) read | MP3, M4A (AAC, ALAC), M4R (iPhone ringtone), WAV, FLAC, OGG, OPUS, AAC, WavPack, TTA, W64, AC3, E-AC3 | -| **Subtitles**: SRT, ASS/SSA, WebVTT, SAMI (SMI), LRC, KRC, TTML, MicroDVD, SCC | each other as UTF-8 (Korean CP949 files read correctly) | +| **Subtitles**: SRT, ASS/SSA, WebVTT, SAMI (SMI), LRC, KRC, TTML, MicroDVD, SCC;
Blu-ray picture subtitles (SUP) read (with OCR) | each other as UTF-8 (Korean CP949 files read correctly);
SUP → SRT, ASS, WebVTT and the other text formats (with OCR) | | **Archives**: ZIP, ANSYS Workbench (WBPZ), 7Z, RAR, TAR, TAR.GZ, TAR.BZ2, TAR.XZ, TAR.ZST, GZ, ZST, ISO, CAB, DMG, ALZ, EGG, Garry's Mod addon (GMA), Valve pak (VPK), files packed into a Source map (BSP), …;
JAR, NuGet (NUPKG), Android packages (APKS, XAPK, APKM, AAB), Adobe extensions (ZXP), Windows app packages (MSIX, APPX), BIN/CUE (one data track) read | extract, ZIP, 7Z, TAR, TAR.GZ, GMA;
any files → one ZIP; folders → ZIP, ISO (Joliet or UDF 2.01), GMA; BIN/CUE → ISO | | **CAD**: DWG, DXF
Gerber PCB layers (GBR, GTL, GBL, GTO, …) read;
G-code of 3D printers and CNC machines (GCODE, GCO, NGC) read | PDF, SVG, PNG, DWG ↔ DXF;
G-code → toolpath (from above or isometric) or the slicer's preview | | **Fonts**: TTF, OTF, WOFF, WOFF2, EOT;
FON (Windows bitmap fonts) read | each other;
FON → one font per size | diff --git a/docs/ENGINES.md b/docs/ENGINES.md index 6952c9af2..3201ad49f 100644 --- a/docs/ENGINES.md +++ b/docs/ENGINES.md @@ -28,7 +28,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status, | **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; ZIP → CBZ, RAR → CBR (copied as they are); AZW4 → PDF; **EPUB ↔ KEPUB** (Kobo) | | CAD (ACadSharp + built-in renderer) | built in (library) | **DWG ↔ DXF**; DWG/DXF → **PDF** (vector), **SVG**, PNG, JPG, WEBP, TIFF, BMP, GIF, ICO, AVIF | | G-code | built in | **G-code (3D printers, CNC machines) → PDF** (vector), **SVG**, PNG, JPG, WEBP, TIFF, …: the toolpath from above or isometric, or the preview the slicer saved in the file | -| **Subtitles** | built in | **SRT, ASS/SSA, WebVTT, SAMI (SMI), LRC, KuGou KRC, TTML, MicroDVD, SCC → SRT, ASS, WebVTT, SAMI, LRC, TTML, MicroDVD, TXT**, always UTF-8 (Korean CP949 / EUC-KR files read correctly) | +| **Subtitles** | built in | **SRT, ASS/SSA, WebVTT, SAMI (SMI), LRC, KuGou KRC, TTML, MicroDVD, SCC → SRT, ASS, WebVTT, SAMI, LRC, TTML, MicroDVD, TXT**, always UTF-8 (Korean CP949 / EUC-KR files read correctly); **Blu-ray picture subtitles (`.sup`)** read by Filee's own PGS reader, text recognized with Tesseract or Apple Vision (see *Text recognition (OCR)*) | | Color palettes | built in | **PAL (RIFF, JASC-PAL or a raw 768-byte palette), GIMP GPL, Adobe ACT → GPL, ACT**, a list of HEX codes (**TXT, JSON**) or a **swatch (SVG**; → PNG, JPG, PDF from there), see [below](#color-palettes-pal-gpl-act) | | 3D models (SharpGLTF for glTF) | built in (library) | **GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY ↔ each other**; FBX, 3DS → each of them; → PNG, JPG, … (an isometric preview) | | Pictures to 3D relief | built in | **PNG, JPG, WEBP, … (every picture ImageMagick reads) → GLB, glTF, STL, OBJ, 3MF, PLY**: a relief, brighter areas higher | @@ -38,8 +38,8 @@ Filee chooses engines automatically. Settings → *Engines* shows their status, | 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; FODT, OpenDocument templates (OTT, OTS, OTP) and XLT out; SVG → EMF/WMF/ODG, a PDF page → SVG | | Pandoc | **optional download** (~42 MB, 240 MB on disk) | Markdown ↔ DOCX/ODT/RTF, DOCX/ODT/HTML/RTF → Markdown, HTML ↔ DOCX/ODT, markup languages (reStructuredText, LaTeX, Org, AsciiDoc, Typst, MediaWiki, DocBook, Jupyter, Textile, man, OPML) ↔ Markdown/HTML/DOCX/ODT and each other (and → RTF, EPUB, TXT), Markdown and markup → PPTX slides | | Ghostscript | **optional download** (~20 MB, 31 MB on disk) | EPS/PS → PDF, PDF → EPS/PS, PostScript-based AI/AIT → PDF (images through PDF and PDFium); smaller PDFs when a preset asks for it; PDF/A-2b for PDF/A presets; renders CMYK PDF/AI pages for CMYK JPG/TIFF | -| Tesseract | **optional download** (~50 MB, 160 MB on disk; each language 0.4–10 MB when first used) | **text recognition (OCR)**: scans and pictures → searchable PDF, and their text into DOCX, TXT, Markdown and HWPX ("Recognize text" in the preset, see below) | -| Apple Vision | part of macOS (Mac only) | **text recognition (OCR) on a Mac**, the same step as Tesseract without a download; Tesseract reads the languages Vision doesn't (see "Apple Vision on macOS") | +| Tesseract | **optional download** (~50 MB, 160 MB on disk; each language 0.4–10 MB when first used) | **text recognition (OCR)**: scans and pictures → searchable PDF, and their text into DOCX, TXT, Markdown and HWPX ("Recognize text" in the preset, see below); **Blu-ray picture subtitles (`.sup`) → SRT, ASS, WebVTT, … and TXT** | +| Apple Vision | part of macOS (Mac only) | **text recognition (OCR) on a Mac**, the same step as Tesseract without a download (scans, pictures and Blu-ray `.sup` subtitles); Tesseract reads the languages Vision doesn't (see "Apple Vision on macOS") | | FFmpeg | **optional download** (~100 MB, 272 MB on disk) | **all video and audio**: video ↔ video (H.264, HEVC, AV1), video → animated GIF / APNG / WebP, a still frame or every frame, audio and subtitle extraction, audio ↔ audio (also APE, WavPack, TTA, DSD, DTS, ALAC, …), GIF, APNG and photos → MP4/WEBM/MOV, Live / Motion Photos → their video, a clip of a video → an iPhone Live Photo or Android Motion Photo (experimental), images → HEIC, clips or audio files joined into one, pictures → a slideshow MP4, a video split into parts every so often or into equal parts (copied, not encoded), copies without metadata (see "Media tools") | | 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; e-books → PDF (ranked above the HWPX writer, see below) | | WeasyPrint | **optional download** (Windows only for now; ~32 MB, 65 MB on disk) | **HTML, Markdown, EML, MSG, MHTML → PDF** laid out as a browser prints them (headings, tables, bold, Arabic and Indic shaping), instead of the built-in route; nothing changes without it (see below) | @@ -2622,6 +2622,11 @@ languages in the text" says to add only what the text has. - The language data is copied into the job's folder and passed with `--tessdata-dir`, so a system Tesseract reads only Filee's pinned files; `-c tessedit_create_pdf=1` replaces the `pdf` config file that lives in Tesseract's own tessdata folder. +- **Blu-ray picture subtitles (`.sup`, issue #1872)**: Filee's own PGS reader (`Subtitles/PgsReader.cs`) decodes the + timed bitmaps and palettes, prepares each object as dark text on white (`Ocr/SubtitleOcr.cs`), and runs Tesseract in + batches (or Apple Vision on macOS) in the preset's `PdfOptions.OcrLanguage` to produce SRT or TXT (and through the + subtitle engine into ASS, WebVTT, SAMI, LRC, TTML and MicroDVD). Unlike PDF/image OCR, `.sup` always needs OCR so its + edges are ordinary routes and subtitle presets show the OCR language picker directly. ### Apple Vision on macOS @@ -2639,6 +2644,8 @@ Tesseract and is registered before it, so the route planner takes it; on Windows The preset editor shows no download size for the languages Vision reads, unless such a language among the chosen ones sends them all to Tesseract, and its hint names Apple Vision. - PDFs go page by page exactly like Tesseract's (`TesseractConverter.RecognizePdfAsync`, at most two pages at a time). + Blu-ray `.sup` subtitles share the same `SubtitleOcr` pipeline as Tesseract, recognizing each prepared caption bitmap + through `VNRecognizeTextRequest`. A JPEG picture goes into the PDF as it is, other pictures (and a JPEG that EXIF turns) as an upright PNG; every page of a TIFF becomes a page. The page size comes from the picture's resolution, 300 dpi when it has none. - Each page is the picture with the recognized words as invisible text (`OcrPdfWriter`, render mode 3): one font diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.json index f92287a03..a26ef4a83 100644 --- a/src/Filee.App/Assets/i18n/ar.json +++ b/src/Filee.App/Assets/i18n/ar.json @@ -127,6 +127,7 @@ "error.crop_same_frame": "للفيديو هذا الشكل بالفعل، فلا يوجد ما يُقتص", "error.ocr_language_download": "تعذّر تنزيل لغة التعرّف الضوئي OCR", "error.ocr_needs_tesseract": "لا يستطيع Apple Vision قراءة هذه اللغة. ثبّت Tesseract من الإعدادات ← المحركات", + "error.sup_no_captions": "لا يحتوي هذا الملف على ترجمة Blu-ray (.sup) يمكن لـ Filee قراءتها.", "error.too_many_frames": "عدد الإطارات كبير جدًا لحفظها كصور. زِد قيمة «كل إطار رقم N»", "error.too_many_pictures": "عدد الصور كبير جدًا لفيديو واحد، قسّمها على عدة فيديوهات", "error.too_many_parts": "عدد الأجزاء كبير جدًا لفيديو واحد، اختر أجزاء أطول", @@ -1130,6 +1131,7 @@ "presets.ocr_hint": "يصبح نص المستندات الممسوحة والصور قابلًا للبحث والتحرير. يتطلب Tesseract (الإعدادات ← المحركات).\nتبقى الصفحات التي تحتوي على نص كما هي.", "presets.ocr_hint_macos": "يصبح نص المستندات الممسوحة والصور قابلًا للبحث والتحرير بأداة التعرّف على النص المدمجة في macOS (Apple Vision). اللغات التي لا تقرؤها تتطلب Tesseract (الإعدادات ← المحركات).\nتبقى الصفحات التي تحتوي على نص كما هي.", "presets.ocr_language": "لغة النص", + "presets.ocr_language_subtitles": "لغة الترجمة، لقراءة الترجمات المصوّرة (.sup).", "presets.ocr_language_size": "تنزيل {0}", "presets.ocr_more_languages": "لغات أخرى في النص", "presets.ocr_add_language": "إضافة لغة", diff --git a/src/Filee.App/Assets/i18n/bn-BD.json b/src/Filee.App/Assets/i18n/bn-BD.json index 9b1ee35b5..1c64a6246 100644 --- a/src/Filee.App/Assets/i18n/bn-BD.json +++ b/src/Filee.App/Assets/i18n/bn-BD.json @@ -141,6 +141,7 @@ "error.crop_same_frame": "ভিডিওটি ইতিমধ্যে এই আকারের, তাই ক্রপ করার কিছু নেই", "error.ocr_language_download": "OCR ভাষা ডাউনলোড করা যায়নি", "error.ocr_needs_tesseract": "Apple Vision এই ভাষা পড়তে পারে না। সেটিংস → ইঞ্জিন-এ Tesseract ইনস্টল করুন", + "error.sup_no_captions": "এই ফাইলে Filee পড়তে পারে এমন কোনো Blu-ray সাবটাইটেল (.sup) নেই।", "error.too_many_frames": "ছবি হিসেবে সংরক্ষণ করার জন্য ফ্রেমের সংখ্যা খুব বেশি, \"প্রতি N-তম ফ্রেম\" বাড়ান", "error.too_many_pictures": "একটি ভিডিওর জন্য ছবির সংখ্যা খুব বেশি, এগুলোকে কয়েক ভাগে ভাগ করুন", "error.too_many_parts": "একটি ভিডিওর জন্য ভাগের সংখ্যা খুব বেশি, আরও লম্বা ভাগ বেছে নিন", @@ -1129,6 +1130,7 @@ "presets.ocr_hint": "স্ক্যান এবং ছবি এমন টেক্সট পায় যা আপনি অনুসন্ধান ও সম্পাদনা করতে পারেন। Tesseract প্রয়োজন (সেটিংস → ইঞ্জিন)।\nযেসব পৃষ্ঠায় ইতিমধ্যে টেক্সট রয়েছে সেগুলো অপরিবর্তিত থাকে।", "presets.ocr_hint_macos": "macOS-এর নিজস্ব টেক্সট শনাক্তকরণ (Apple Vision) দিয়ে স্ক্যান এবং ছবি অনুসন্ধানযোগ্য ও সম্পাদনাযোগ্য টেক্সট পায়। যেসব ভাষা এটি পড়তে পারে না সেগুলোর জন্য Tesseract প্রয়োজন (সেটিংস → ইঞ্জিন)।\nযেসব পৃষ্ঠায় ইতিমধ্যে টেক্সট রয়েছে সেগুলো অপরিবর্তিত থাকে।", "presets.ocr_language": "টেক্সটের ভাষা", + "presets.ocr_language_subtitles": "ছবির সাবটাইটেল (.sup) পড়ার জন্য সাবটাইটেলের ভাষা।", "presets.ocr_language_size": "{0} ডাউনলোড", "presets.ocr_more_languages": "টেক্সটে থাকা অন্যান্য ভাষা", "presets.ocr_add_language": "একটি ভাষা যোগ করুন", diff --git a/src/Filee.App/Assets/i18n/de.json b/src/Filee.App/Assets/i18n/de.json index 548f0cfff..1adb8f942 100644 --- a/src/Filee.App/Assets/i18n/de.json +++ b/src/Filee.App/Assets/i18n/de.json @@ -127,6 +127,7 @@ "error.crop_same_frame": "Das Video hat dieses Format schon. Es gibt nichts zuzuschneiden", "error.ocr_language_download": "Die OCR-Sprache konnte nicht heruntergeladen werden", "error.ocr_needs_tesseract": "Apple Vision kann diese Sprache nicht lesen. Installiere Tesseract unter Einstellungen → Module", + "error.sup_no_captions": "Diese Datei enthält keine Blu-ray-Untertitel (.sup), die Filee lesen kann.", "error.too_many_frames": "Zu viele Einzelbilder zum Speichern. Erhöhe den Wert für „Jedes n-te Einzelbild“", "error.too_many_pictures": "Zu viele Bilder für ein Video. Teile sie auf mehrere Videos auf", "error.too_many_parts": "Zu viele Teile für ein Video. Wähle längere Teile", @@ -1130,6 +1131,7 @@ "presets.ocr_hint": "Scans und Bilder erhalten durchsuchbaren und bearbeitbaren Text. Benötigt Tesseract (Einstellungen → Module).\nSeiten, die bereits Text enthalten, bleiben unverändert.", "presets.ocr_hint_macos": "Scans und Bilder erhalten durchsuchbaren und bearbeitbaren Text mit der Texterkennung von macOS (Apple Vision). Nicht unterstützte Sprachen benötigen Tesseract (Einstellungen → Module).\nSeiten, die bereits Text enthalten, bleiben unverändert.", "presets.ocr_language": "Sprache des Textes", + "presets.ocr_language_subtitles": "Sprache der Untertitel zum Lesen von Bilduntertiteln (.sup).", "presets.ocr_language_size": "{0} Download", "presets.ocr_more_languages": "Weitere Sprachen im Text", "presets.ocr_add_language": "Sprache hinzufügen", diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json index e1329a14c..4204edb4c 100644 --- a/src/Filee.App/Assets/i18n/en.json +++ b/src/Filee.App/Assets/i18n/en.json @@ -133,6 +133,7 @@ "error.crop_same_frame": "The video already has this shape, so there's nothing to crop", "error.ocr_language_download": "Couldn't download the OCR language", "error.ocr_needs_tesseract": "Apple Vision can't read this language. Install Tesseract in Settings → Engines", + "error.sup_no_captions": "This file holds no Blu-ray subtitles (.sup) Filee can read.", "error.too_many_frames": "Too many frames to save as pictures, raise \"Every Nth frame\"", "error.too_many_pictures": "Too many pictures for one video, split them into several", "error.too_many_parts": "Too many parts for one video, choose longer parts", @@ -1145,6 +1146,7 @@ "presets.ocr_hint": "Scans and pictures get text you can search and edit. Needs Tesseract (Settings → Engines).\nPages that already have text stay as they are.", "presets.ocr_hint_macos": "Scans and pictures get text you can search and edit, with macOS's own text recognition (Apple Vision). Languages it can't read need Tesseract (Settings → Engines).\nPages that already have text stay as they are.", "presets.ocr_language": "Language of the text", + "presets.ocr_language_subtitles": "Language of the subtitles, for reading picture subtitles (.sup).", "presets.ocr_language_size": "{0} download", "presets.ocr_more_languages": "Other languages in the text", "presets.ocr_add_language": "Add a language", diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json index 64965177a..b895b2a96 100644 --- a/src/Filee.App/Assets/i18n/es.json +++ b/src/Filee.App/Assets/i18n/es.json @@ -127,6 +127,7 @@ "error.crop_same_frame": "El vídeo ya tiene esta forma, así que no hay nada que recortar", "error.ocr_language_download": "No se pudo descargar el idioma de OCR", "error.ocr_needs_tesseract": "Apple Vision no puede leer este idioma. Instala Tesseract en Ajustes → Motores", + "error.sup_no_captions": "Este archivo no contiene subtítulos Blu-ray (.sup) que Filee pueda leer.", "error.too_many_frames": "Demasiados fotogramas para guardar como imágenes; aumenta «Cada N fotogramas»", "error.too_many_pictures": "Demasiadas imágenes para un vídeo; divídelas en varios", "error.too_many_parts": "Demasiadas partes para un vídeo; elige partes más largas", @@ -1130,6 +1131,7 @@ "presets.ocr_hint": "Los escaneos e imágenes tendrán texto que se puede buscar y editar. Requiere Tesseract (Ajustes → Motores).\nLas páginas que ya tienen texto no cambian.", "presets.ocr_hint_macos": "Los escaneos e imágenes tendrán texto que se puede buscar y editar, con el reconocimiento de texto propio de macOS (Apple Vision). Los idiomas que no lee requieren Tesseract (Ajustes → Motores).\nLas páginas que ya tienen texto no cambian.", "presets.ocr_language": "Idioma del texto", + "presets.ocr_language_subtitles": "Idioma de los subtítulos, para leer subtítulos de imagen (.sup).", "presets.ocr_language_size": "Descarga de {0}", "presets.ocr_more_languages": "Otros idiomas del texto", "presets.ocr_add_language": "Añadir un idioma", diff --git a/src/Filee.App/Assets/i18n/fa.json b/src/Filee.App/Assets/i18n/fa.json index 675a1d56b..d99ad7b26 100644 --- a/src/Filee.App/Assets/i18n/fa.json +++ b/src/Filee.App/Assets/i18n/fa.json @@ -141,6 +141,7 @@ "error.crop_same_frame": "ویدیو از قبل دارای این ابعاد است، بنابراین چیزی برای برش وجود ندارد", "error.ocr_language_download": "امکان دانلود زبان OCR وجود نداشت", "error.ocr_needs_tesseract": "قابلیت Apple Vision نمی‌تواند این زبان را بخواند. Tesseract را در تنظیمات ← موتورها نصب کنید", + "error.sup_no_captions": "این فایل هیچ زیرنویس Blu-ray (.sup) قابل خواندن توسط Filee ندارد.", "error.too_many_frames": "تعداد فریم‌ها برای ذخیره به عنوان تصویر بیش از حد زیاد است، مقدار «هر چند فریم یک بار» را افزایش دهید", "error.too_many_pictures": "تعداد تصاویر برای یک ویدیو بیش از حد زیاد است، آن‌ها را به چند بخش تقسیم کنید", "error.too_many_parts": "تعداد بخش‌ها برای یک ویدیو بیش از حد زیاد است، بخش‌های بلندتری انتخاب کنید", @@ -1129,6 +1130,7 @@ "presets.ocr_hint": "متن را از تصاویر و اسناد اسکن‌شده می‌خواند و آن را در لایه مخفی روی صفحات PDF قرار می‌دهد تا بتوان متن را جستجو یا کپی کرد.", "presets.ocr_hint_macos": "اسکن‌ها و تصاویر دارای متن قابل جستجو و ویرایش می‌شوند، با استفاده از تشخیص متن خود macOS (Apple Vision). زبان‌هایی که قادر به خواندن آن‌ها نیست به Tesseract نیاز دارند (تنظیمات → موتورها).\nصفحاتی که از قبل متن دارند همان‌طور که هستند باقی می‌مانند.", "presets.ocr_language": "زبان سند", + "presets.ocr_language_subtitles": "زبان زیرنویس‌ها، برای خواندن زیرنویس‌های تصویری (.sup).", "presets.ocr_language_size": "{0} دانلود", "presets.ocr_more_languages": "زبان‌های دیگر در متن", "presets.ocr_add_language": "افزودن زبان", diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.json index 9790f2c20..1a5d9be4d 100644 --- a/src/Filee.App/Assets/i18n/fr.json +++ b/src/Filee.App/Assets/i18n/fr.json @@ -133,6 +133,7 @@ "error.crop_same_frame": "La vidéo a déjà ce format, il n'y a rien à recadrer", "error.ocr_language_download": "Impossible de télécharger la langue de l'OCR", "error.ocr_needs_tesseract": "Apple Vision ne lit pas cette langue. Installez Tesseract dans Paramètres → Moteurs", + "error.sup_no_captions": "Ce fichier ne contient aucun sous-titre Blu-ray (.sup) que Filee peut lire.", "error.too_many_frames": "Trop d'images à enregistrer, augmentez « Une image sur N »", "error.too_many_pictures": "Trop d'images pour une seule vidéo, répartissez-les en plusieurs", "error.too_many_parts": "Trop de parties pour une seule vidéo, choisissez des parties plus longues", @@ -1145,6 +1146,7 @@ "presets.ocr_hint": "Le texte des numérisations et des images devient consultable et modifiable. Nécessite Tesseract (Paramètres → Moteurs).\nLes pages qui ont déjà du texte restent telles quelles.", "presets.ocr_hint_macos": "Le texte des numérisations et des images devient consultable et modifiable grâce à la reconnaissance de texte intégrée à macOS (Apple Vision). Les langues qu'elle ne lit pas nécessitent Tesseract (Paramètres → Moteurs).\nLes pages qui ont déjà du texte restent telles quelles.", "presets.ocr_language": "Langue du texte", + "presets.ocr_language_subtitles": "Langue des sous-titres, pour lire les sous-titres image (.sup).", "presets.ocr_language_size": "Téléchargement de {0}", "presets.ocr_more_languages": "Autres langues du texte", "presets.ocr_add_language": "Ajouter une langue", diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json index 4b36d6a69..f89806500 100644 --- a/src/Filee.App/Assets/i18n/hi.json +++ b/src/Filee.App/Assets/i18n/hi.json @@ -127,6 +127,7 @@ "error.crop_same_frame": "वीडियो पहले से इसी आकार का है, इसलिए क्रॉप करने को कुछ नहीं है", "error.ocr_language_download": "OCR भाषा डाउनलोड नहीं हो सकी", "error.ocr_needs_tesseract": "Apple Vision यह भाषा नहीं पढ़ सकता। सेटिंग्स → इंजन में Tesseract इंस्टॉल करें", + "error.sup_no_captions": "इस फ़ाइल में कोई Blu-ray सबटाइटल (.sup) नहीं हैं जिन्हें Filee पढ़ सके।", "error.too_many_frames": "तस्वीरों के रूप में सहेजने के लिए बहुत ज़्यादा फ़्रेम हैं, \"हर Nवाँ फ़्रेम\" बढ़ाएँ", "error.too_many_pictures": "एक वीडियो के लिए तस्वीरें बहुत ज़्यादा हैं, इन्हें कई हिस्सों में बाँटें", "error.too_many_parts": "एक वीडियो के लिए हिस्से बहुत ज़्यादा हैं, लंबे हिस्से चुनें", @@ -1130,6 +1131,7 @@ "presets.ocr_hint": "स्कैन और तस्वीरों का टेक्स्ट खोजने और बदलने योग्य बनता है। Tesseract चाहिए (सेटिंग्स → इंजन)।\nजिन पेजों में पहले से टेक्स्ट है वे वैसे ही रहते हैं।", "presets.ocr_hint_macos": "macOS की अपनी टेक्स्ट पहचान (Apple Vision) से स्कैन और तस्वीरों का टेक्स्ट खोजने और बदलने योग्य बनता है। जो भाषाएँ यह नहीं पढ़ सकता, उनके लिए Tesseract चाहिए (सेटिंग्स → इंजन)।\nजिन पेजों में पहले से टेक्स्ट है वे वैसे ही रहते हैं।", "presets.ocr_language": "टेक्स्ट की भाषा", + "presets.ocr_language_subtitles": "चित्र सबटाइटल (.sup) पढ़ने के लिए सबटाइटल की भाषा।", "presets.ocr_language_size": "{0} डाउनलोड", "presets.ocr_more_languages": "टेक्स्ट की अन्य भाषाएँ", "presets.ocr_add_language": "भाषा जोड़ें", diff --git a/src/Filee.App/Assets/i18n/id.json b/src/Filee.App/Assets/i18n/id.json index cefb4462e..0e8813ac9 100644 --- a/src/Filee.App/Assets/i18n/id.json +++ b/src/Filee.App/Assets/i18n/id.json @@ -127,6 +127,7 @@ "error.crop_same_frame": "Video sudah berbentuk ini, jadi tidak ada yang perlu dipangkas", "error.ocr_language_download": "Tidak dapat mengunduh paket bahasa OCR", "error.ocr_needs_tesseract": "Apple Vision tidak dapat membaca bahasa ini. Pasang Tesseract di Pengaturan → Engine", + "error.sup_no_captions": "File ini tidak berisi takarir Blu-ray (.sup) yang dapat dibaca Filee.", "error.too_many_frames": "Terlalu banyak bingkai untuk disimpan sebagai gambar, naikkan nilai \"Setiap bingkai ke-N\"", "error.too_many_pictures": "Terlalu banyak gambar untuk satu video, bagi menjadi beberapa video", "error.too_many_parts": "Terlalu banyak bagian untuk satu video, pilih bagian yang lebih panjang", @@ -1130,6 +1131,7 @@ "presets.ocr_hint": "Hasil pindai dan gambar mendapatkan lapisan teks yang dapat dicari dan disalin. Memerlukan Tesseract (Pengaturan → Engine).\nHalaman yang sudah memiliki teks dibiarkan apa adanya.", "presets.ocr_hint_macos": "Hasil pindai dan gambar mendapatkan teks yang dapat dicari dan disalin dengan pengenal teks bawaan macOS (Apple Vision). Bahasa yang tidak didukungnya memerlukan Tesseract (Pengaturan → Engine).\nHalaman yang sudah memiliki teks dibiarkan apa adanya.", "presets.ocr_language": "Bahasa teks", + "presets.ocr_language_subtitles": "Bahasa takarir, untuk membaca takarir gambar (.sup).", "presets.ocr_language_size": "Unduhan {0}", "presets.ocr_more_languages": "Bahasa lain dalam teks", "presets.ocr_add_language": "Tambah bahasa", diff --git a/src/Filee.App/Assets/i18n/it.json b/src/Filee.App/Assets/i18n/it.json index 551dd814b..733c265d6 100644 --- a/src/Filee.App/Assets/i18n/it.json +++ b/src/Filee.App/Assets/i18n/it.json @@ -126,6 +126,7 @@ "error.crop_same_frame": "Il video ha già questa forma, quindi non c'è niente da ritagliare", "error.ocr_language_download": "Impossibile scaricare la lingua OCR", "error.ocr_needs_tesseract": "Apple Vision non riesce a leggere questa lingua. Installa Tesseract in Impostazioni → Motori", + "error.sup_no_captions": "Questo file non contiene sottotitoli Blu-ray (.sup) che Filee può leggere.", "error.too_many_frames": "Troppi fotogrammi da salvare come immagini, aumenta “Ogni N-esimo fotogramma”", "error.too_many_pictures": "Troppe immagini per un solo video, dividile in più video", "error.too_many_parts": "Troppe parti per un solo video, scegli parti più lunghe", @@ -1129,6 +1130,7 @@ "presets.ocr_hint": "Scansioni e immagini ottengono testo ricercabile e modificabile. Richiede Tesseract (Impostazioni → Motori).\nLe pagine che hanno già testo restano come sono.", "presets.ocr_hint_macos": "Scansioni e immagini ottengono testo ricercabile e modificabile, con il riconoscimento testo di macOS (Apple Vision). Le lingue che non riesce a leggere richiedono Tesseract (Impostazioni → Motori).\nLe pagine che hanno già testo restano come sono.", "presets.ocr_language": "Lingua del testo", + "presets.ocr_language_subtitles": "Lingua dei sottotitoli, per leggere i sottotitoli immagine (.sup).", "presets.ocr_language_size": "Download di {0}", "presets.ocr_more_languages": "Altre lingue nel testo", "presets.ocr_add_language": "Aggiungi una lingua", diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json index ac0e19acd..fa336a20a 100644 --- a/src/Filee.App/Assets/i18n/ja.json +++ b/src/Filee.App/Assets/i18n/ja.json @@ -127,6 +127,7 @@ "error.crop_same_frame": "動画はすでにこの形のため、トリミングするものがありません", "error.ocr_language_download": "OCR の言語データをダウンロードできませんでした", "error.ocr_needs_tesseract": "Apple Vision はこの言語を読めません。「設定」→「変換エンジン」で Tesseract をインストールしてください", + "error.sup_no_captions": "このファイルには Filee が読み取れる Blu-ray 字幕 (.sup) が含まれていません。", "error.too_many_frames": "画像として保存するフレーム数が多すぎます。「Nフレームごと」の値を大きくしてください", "error.too_many_pictures": "1本の動画にするには画像が多すぎます。いくつかに分けてください", "error.too_many_parts": "1本の動画を分けるにはパートが多すぎます。もっと長いパートにしてください", @@ -1130,6 +1131,7 @@ "presets.ocr_hint": "スキャンや画像の文字を検索・編集できるようにします。Tesseract が必要です(「設定」→「変換エンジン」)。\nすでにテキストがあるページはそのままです。", "presets.ocr_hint_macos": "スキャンや画像の文字を、macOS 標準の文字認識(Apple Vision)で検索・編集できるようにします。読めない言語には Tesseract が必要です(「設定」→「変換エンジン」)。\nすでにテキストがあるページはそのままです。", "presets.ocr_language": "テキストの言語", + "presets.ocr_language_subtitles": "画像字幕 (.sup) を読み取るための字幕の言語。", "presets.ocr_language_size": "{0} をダウンロード", "presets.ocr_more_languages": "テキストに含まれる他の言語", "presets.ocr_add_language": "言語を追加", diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json index 8b9700458..86e1bc5f2 100644 --- a/src/Filee.App/Assets/i18n/ko.json +++ b/src/Filee.App/Assets/i18n/ko.json @@ -133,6 +133,7 @@ "error.crop_same_frame": "영상이 이미 이 비율이라 잘라낼 것이 없어요", "error.ocr_language_download": "OCR 언어 데이터를 내려받지 못했어요", "error.ocr_needs_tesseract": "Apple Vision은 이 언어를 읽지 못해요. 설정 → 변환 엔진에서 Tesseract를 설치해 주세요", + "error.sup_no_captions": "이 파일에는 Filee가 읽을 수 있는 Blu-ray 자막(.sup)이 없습니다.", "error.too_many_frames": "프레임이 너무 많아요. 'N번째 프레임마다' 값을 늘려 주세요", "error.too_many_pictures": "한 동영상에 넣기엔 사진이 너무 많아요. 여러 번에 나눠 주세요", "error.too_many_parts": "한 동영상을 나누기엔 부분이 너무 많아요. 더 길게 나눠 주세요", @@ -1145,6 +1146,7 @@ "presets.ocr_hint": "스캔본과 사진의 글자를 검색하고 편집할 수 있게 돼요. Tesseract가 필요해요(설정 → 변환 엔진).\n이미 텍스트가 있는 페이지는 그대로 둬요.", "presets.ocr_hint_macos": "스캔본과 사진의 글자를 macOS에 들어 있는 문자 인식(Apple Vision)으로 검색하고 편집할 수 있게 돼요. Apple Vision이 못 읽는 언어는 Tesseract가 필요해요(설정 → 변환 엔진).\n이미 텍스트가 있는 페이지는 그대로 둬요.", "presets.ocr_language": "텍스트 언어", + "presets.ocr_language_subtitles": "그림 자막(.sup)을 읽을 때 사용할 자막 언어입니다.", "presets.ocr_language_size": "{0} 내려받기", "presets.ocr_more_languages": "텍스트에 함께 있는 다른 언어", "presets.ocr_add_language": "언어 추가", diff --git a/src/Filee.App/Assets/i18n/mn.json b/src/Filee.App/Assets/i18n/mn.json index 7db9b5ca9..22e5bb09e 100644 --- a/src/Filee.App/Assets/i18n/mn.json +++ b/src/Filee.App/Assets/i18n/mn.json @@ -126,6 +126,7 @@ "error.crop_same_frame": "Видео аль хэдийн ийм харьцаатай байгаа тул тайрах зүйл алга", "error.ocr_language_download": "OCR хэлийг татаж чадсангүй", "error.ocr_needs_tesseract": "Apple Vision энэ хэлийг уншиж чадахгүй. Тохиргоо → Хөдөлгүүрүүд хэсгээс Tesseract суулгана уу", + "error.sup_no_captions": "Энэ файлд Filee уншиж чадах Blu-ray хадмал (.sup) байхгүй байна.", "error.too_many_frames": "Зураг болгон хадгалахад кадр хэт олон байна, \"N кадр тутамд\" утгыг ихэсгэнэ үү", "error.too_many_pictures": "Нэг видеонд зураг хэт олон байна, хэд хэдэн хэсэгт хуваана уу", "error.too_many_parts": "Нэг видеонд хуваах хэсэг хэт олон байна, илүү урт хугацаа сонгоно уу", @@ -1129,6 +1130,7 @@ "presets.ocr_hint": "Скан болон зургууд хайлт хийх, засах боломжтой тексттэй болно. Tesseract шаардлагатай (Тохиргоо → Хөдөлгүүрүүд).\nАль хэдийн тексттэй хуудсууд хэвээр үлдэнэ.", "presets.ocr_hint_macos": "macOS-ийн өөрийн текст таних системээр (Apple Vision) скан болон зургууд хайлт хийх, засах боломжтой тексттэй болно. Уншиж чадахгүй хэлэнд Tesseract шаардлагатай (Тохиргоо → Хөдөлгүүрүүд).\nАль хэдийн тексттэй хуудсууд хэвээр үлдэнэ.", "presets.ocr_language": "Текстийн хэл", + "presets.ocr_language_subtitles": "Зургийн хадмал (.sup) уншихад ашиглах хадмалын хэл.", "presets.ocr_language_size": "{0} татах", "presets.ocr_more_languages": "Текст дэх бусад хэлүүд", "presets.ocr_add_language": "Хэл нэмэх", diff --git a/src/Filee.App/Assets/i18n/ne.json b/src/Filee.App/Assets/i18n/ne.json index 56c2faff1..7ef62ac6b 100644 --- a/src/Filee.App/Assets/i18n/ne.json +++ b/src/Filee.App/Assets/i18n/ne.json @@ -126,6 +126,7 @@ "error.images_only": "केवल छविहरूमा मात्र काम गर्छ", "error.ocr_language_download": "OCR भाषा डाउनलोड गर्न सकिएन", "error.ocr_needs_tesseract": "Apple Vision ले यो भाषा पढ्न सक्दैन। सेटिङहरू → इन्जिनहरूमा Tesseract स्थापना गर्नुहोस्", + "error.sup_no_captions": "यो फाइलमा Filee ले पढ्न सक्ने कुनै Blu-ray उपशीर्षक (.sup) छैन।", "error.no_transparency": "यो ढाँचामा पारदर्शिता हुँदैन, त्यसैले काट्नुपर्ने केही छैन", "error.no_black_bars": "कालो पट्टी भेटिएन, त्यसैले क्रप गर्न केही छैन", "error.crop_same_frame": "भिडियो पहिले नै यही आकारको छ, त्यसैले क्रप गर्न केही छैन", @@ -1126,6 +1127,7 @@ "presets.ocr_hint": "स्क्यान र तस्बिरको पाठ खोज्न र सम्पादन गर्न मिल्ने हुन्छ। Tesseract चाहिन्छ (सेटिङहरू → इन्जिनहरू)।\nपहिले नै पाठ भएका पृष्ठ जस्ताको तस्तै रहन्छन्।", "presets.ocr_hint_macos": "macOS को आफ्नै पाठ पहिचान (Apple Vision) ले स्क्यान र तस्बिरको पाठ खोज्न र सम्पादन गर्न मिल्ने हुन्छ। यसले पढ्न नसक्ने भाषाका लागि Tesseract चाहिन्छ (सेटिङहरू → इन्जिनहरू)।\nपहिले नै पाठ भएका पृष्ठ जस्ताको तस्तै रहन्छन्।", "presets.ocr_language": "पाठको भाषा", + "presets.ocr_language_subtitles": "तस्वीर उपशीर्षक (.sup) पढ्नका लागि उपशीर्षकको भाषा।", "presets.ocr_language_size": "{0} डाउनलोड", "presets.ocr_more_languages": "पाठका अन्य भाषाहरू", "presets.ocr_add_language": "भाषा थप्नुहोस्", diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json index 838c7dcda..1f578a0fe 100644 --- a/src/Filee.App/Assets/i18n/pl.json +++ b/src/Filee.App/Assets/i18n/pl.json @@ -135,6 +135,7 @@ "error.crop_same_frame": "Film ma już ten kształt, więc nie ma czego kadrować", "error.ocr_language_download": "Nie udało się pobrać języka OCR", "error.ocr_needs_tesseract": "Apple Vision nie czyta tego języka. Zainstaluj Tesseract w Ustawienia → Silniki", + "error.sup_no_captions": "Ten plik nie zawiera napisów Blu-ray (.sup), które Filee może odczytać.", "error.too_many_frames": "Za dużo klatek do zapisania jako obrazy, zwiększ „Co N-ta klatka”", "error.too_many_pictures": "Za dużo zdjęć na jedno wideo, podziel je na kilka", "error.too_many_parts": "Za dużo części na jedno wideo, wybierz dłuższe części", @@ -1145,6 +1146,7 @@ "presets.ocr_hint": "Tekst skanów i obrazów da się przeszukiwać i edytować. Wymaga Tesseract (Ustawienia → Silniki).\nStrony, które mają już tekst, pozostają bez zmian.", "presets.ocr_hint_macos": "Tekst skanów i obrazów da się przeszukiwać i edytować dzięki wbudowanemu rozpoznawaniu tekstu macOS (Apple Vision). Języki, których nie czyta, wymagają Tesseract (Ustawienia → Silniki).\nStrony, które mają już tekst, pozostają bez zmian.", "presets.ocr_language": "Język tekstu", + "presets.ocr_language_subtitles": "Język napisów do odczytu napisów obrazkowych (.sup).", "presets.ocr_language_size": "Pobieranie {0}", "presets.ocr_more_languages": "Inne języki w tekście", "presets.ocr_add_language": "Dodaj język", diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.json index 0c8197280..d8b729343 100644 --- a/src/Filee.App/Assets/i18n/pt-BR.json +++ b/src/Filee.App/Assets/i18n/pt-BR.json @@ -135,6 +135,7 @@ "error.crop_same_frame": "O vídeo já tem esse formato, então não há nada para recortar", "error.ocr_language_download": "Não foi possível baixar o idioma do OCR", "error.ocr_needs_tesseract": "O Apple Vision não lê este idioma. Instale o Tesseract em Configurações → Motores", + "error.sup_no_captions": "Este arquivo não contém legendas Blu-ray (.sup) que o Filee consiga ler.", "error.too_many_frames": "Quadros demais para salvar como imagens. Aumente “A cada N quadros”", "error.too_many_pictures": "Imagens demais para um vídeo; divida-as em vários", "error.too_many_parts": "Partes demais para um vídeo; escolha partes mais longas", @@ -1145,6 +1146,7 @@ "presets.ocr_hint": "Digitalizações e imagens ganham texto que pode ser pesquisado e editado. Requer o Tesseract (Configurações → Motores).\nPáginas que já têm texto ficam como estão.", "presets.ocr_hint_macos": "Digitalizações e imagens ganham texto que pode ser pesquisado e editado, com o reconhecimento de texto do próprio macOS (Apple Vision). Idiomas que ele não lê precisam do Tesseract (Configurações → Motores).\nPáginas que já têm texto ficam como estão.", "presets.ocr_language": "Idioma do texto", + "presets.ocr_language_subtitles": "Idioma das legendas, para ler legendas em imagem (.sup).", "presets.ocr_language_size": "Download de {0}", "presets.ocr_more_languages": "Outros idiomas no texto", "presets.ocr_add_language": "Adicionar um idioma", diff --git a/src/Filee.App/Assets/i18n/pt-PT.json b/src/Filee.App/Assets/i18n/pt-PT.json index 932e0c1d7..c70d762f1 100644 --- a/src/Filee.App/Assets/i18n/pt-PT.json +++ b/src/Filee.App/Assets/i18n/pt-PT.json @@ -135,6 +135,7 @@ "error.crop_same_frame": "O vídeo já tem esta forma, por isso não há nada para recortar", "error.ocr_language_download": "Não foi possível descarregar os dados do idioma para OCR", "error.ocr_needs_tesseract": "O Apple Vision não consegue ler este idioma. Instala o Tesseract em Definições → Motores", + "error.sup_no_captions": "Este ficheiro não contém legendas Blu-ray (.sup) que o Filee consiga ler.", "error.too_many_frames": "Há demasiados fotogramas para guardar como imagens. Aumenta o valor de «A cada N fotogramas»", "error.too_many_pictures": "Há demasiadas imagens para um só vídeo. Divide-as em vários vídeos", "error.too_many_parts": "Há demasiadas partes para um só vídeo. Escolhe partes mais longas", @@ -1145,6 +1146,7 @@ "presets.ocr_hint": "As digitalizações e imagens passam a ter texto que podes pesquisar e editar. Requer o Tesseract (Definições → Motores).\nAs páginas que já têm texto mantêm-se.", "presets.ocr_hint_macos": "As digitalizações e imagens passam a ter texto que podes pesquisar e editar, com o reconhecimento de texto do macOS (Apple Vision). Os idiomas que não consegue ler requerem o Tesseract (Definições → Motores).\nAs páginas que já têm texto mantêm-se.", "presets.ocr_language": "Idioma do texto", + "presets.ocr_language_subtitles": "Idioma das legendas, para ler legendas em imagem (.sup).", "presets.ocr_language_size": "Transferência de {0}", "presets.ocr_more_languages": "Outros idiomas no texto", "presets.ocr_add_language": "Adicionar um idioma", diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json index 57d987d7d..bbc369dfe 100644 --- a/src/Filee.App/Assets/i18n/ru.json +++ b/src/Filee.App/Assets/i18n/ru.json @@ -135,6 +135,7 @@ "error.crop_same_frame": "У видео уже такая форма, обрезать нечего", "error.ocr_language_download": "Не удалось скачать язык для OCR", "error.ocr_needs_tesseract": "Apple Vision не читает этот язык. Установите Tesseract в разделе «Настройки → Движки»", + "error.sup_no_captions": "В этом файле нет субтитров Blu-ray (.sup), которые Filee может прочитать.", "error.too_many_frames": "Слишком много кадров для сохранения картинками — увеличьте «Каждый N-й кадр»", "error.too_many_pictures": "Слишком много картинок для одного видео — разделите их на несколько", "error.too_many_parts": "Слишком много частей для одного видео — выберите части подлиннее", @@ -1145,6 +1146,7 @@ "presets.ocr_hint": "Текст сканов и изображений можно будет искать и редактировать. Нужен Tesseract (Настройки → Движки).\nСтраницы, где уже есть текст, не меняются.", "presets.ocr_hint_macos": "Текст сканов и изображений можно будет искать и редактировать с помощью встроенного в macOS распознавания текста (Apple Vision). Для языков, которые оно не читает, нужен Tesseract (Настройки → Движки).\nСтраницы, где уже есть текст, не меняются.", "presets.ocr_language": "Язык текста", + "presets.ocr_language_subtitles": "Язык субтитров для распознавания графических субтитров (.sup).", "presets.ocr_language_size": "Загрузка {0}", "presets.ocr_more_languages": "Другие языки в тексте", "presets.ocr_add_language": "Добавить язык", diff --git a/src/Filee.App/Assets/i18n/th.json b/src/Filee.App/Assets/i18n/th.json index 23582240f..6953f5746 100644 --- a/src/Filee.App/Assets/i18n/th.json +++ b/src/Filee.App/Assets/i18n/th.json @@ -124,6 +124,7 @@ "error.images_only": "ใช้ได้กับไฟล์รูปภาพเท่านั้น", "error.ocr_language_download": "ดาวน์โหลดภาษาสำหรับ OCR ไม่ได้", "error.ocr_needs_tesseract": "Apple Vision อ่านภาษานี้ไม่ได้ ติดตั้ง Tesseract ได้ในการตั้งค่า → เครื่องมือแปลงไฟล์", + "error.sup_no_captions": "ไฟล์นี้ไม่มีซับไตเติล Blu-ray (.sup) ที่ Filee อ่านได้", "error.no_transparency": "ฟอร์แมตนี้ไม่มีความโปร่งใส จึงไม่มีขอบให้ตัดออก", "error.no_black_bars": "ไม่พบแถบดำ จึงไม่มีอะไรให้ครอบตัด", "error.crop_same_frame": "วิดีโอมีสัดส่วนนี้อยู่แล้ว จึงไม่มีอะไรให้ครอบตัด", @@ -1130,6 +1131,7 @@ "presets.ocr_hint": "ข้อความในภาพสแกนและรูปภาพจะค้นหาและแก้ไขได้ ต้องใช้ Tesseract (การตั้งค่า → เครื่องมือแปลงไฟล์)\nหน้าที่มีข้อความอยู่แล้วจะคงไว้ตามเดิม", "presets.ocr_hint_macos": "ข้อความในภาพสแกนและรูปภาพจะค้นหาและแก้ไขได้ด้วยระบบรู้จำข้อความในตัวของ macOS (Apple Vision) ภาษาที่อ่านไม่ได้ต้องใช้ Tesseract (การตั้งค่า → เครื่องมือแปลงไฟล์)\nหน้าที่มีข้อความอยู่แล้วจะคงไว้ตามเดิม", "presets.ocr_language": "ภาษาของข้อความ", + "presets.ocr_language_subtitles": "ภาษาของซับไตเติล สำหรับอ่านซับไตเติลแบบภาพ (.sup)", "presets.ocr_language_size": "ดาวน์โหลด {0}", "presets.ocr_more_languages": "ภาษาอื่นในข้อความ", "presets.ocr_add_language": "เพิ่มภาษา", diff --git a/src/Filee.App/Assets/i18n/tr.json b/src/Filee.App/Assets/i18n/tr.json index 4d25269f4..4d577713d 100644 --- a/src/Filee.App/Assets/i18n/tr.json +++ b/src/Filee.App/Assets/i18n/tr.json @@ -127,6 +127,7 @@ "error.crop_same_frame": "Video zaten bu biçimde, kırpılacak bir şey yok", "error.ocr_language_download": "OCR dili indirilemedi", "error.ocr_needs_tesseract": "Apple Vision bu dili okuyamıyor. Ayarlar → Dönüştürme motorları bölümünden Tesseract kurun", + "error.sup_no_captions": "Bu dosyada Filee'nin okuyabileceği Blu-ray altyazısı (.sup) yok.", "error.too_many_frames": "Görsel olarak kaydedilecek çok fazla kare var; “Her N'inci kare” değerini artırın", "error.too_many_pictures": "Tek video için çok fazla görsel var; birkaç gruba bölün", "error.too_many_parts": "Tek video için çok fazla parça var; daha uzun parçalar seçin", @@ -1130,6 +1131,7 @@ "presets.ocr_hint": "Tarama ve görsellere aranabilir ve düzenlenebilir metin eklenir. Tesseract gerektirir (Ayarlar → Dönüştürme motorları).\nZaten metin içeren sayfalar olduğu gibi kalır.", "presets.ocr_hint_macos": "Tarama ve görsellere macOS'un kendi metin tanımasıyla (Apple Vision) aranabilir ve düzenlenebilir metin eklenir. Okuyamadığı diller için Tesseract gerekir (Ayarlar → Dönüştürme motorları).\nZaten metin içeren sayfalar olduğu gibi kalır.", "presets.ocr_language": "Metnin dili", + "presets.ocr_language_subtitles": "Resim altyazılarını (.sup) okumak için altyazı dili.", "presets.ocr_language_size": "{0} indirme", "presets.ocr_more_languages": "Metindeki diğer diller", "presets.ocr_add_language": "Dil ekle", diff --git a/src/Filee.App/Assets/i18n/vi.json b/src/Filee.App/Assets/i18n/vi.json index 58b642f35..cd546de86 100644 --- a/src/Filee.App/Assets/i18n/vi.json +++ b/src/Filee.App/Assets/i18n/vi.json @@ -133,6 +133,7 @@ "error.crop_same_frame": "Video đã có khung hình này nên không có gì để cắt", "error.ocr_language_download": "Không thể tải xuống ngôn ngữ OCR", "error.ocr_needs_tesseract": "Apple Vision không đọc được ngôn ngữ này. Hãy cài Tesseract trong Cài đặt → Bộ xử lý", + "error.sup_no_captions": "Tệp này không có phụ đề Blu-ray (.sup) mà Filee có thể đọc.", "error.too_many_frames": "Quá nhiều khung hình để lưu thành ảnh, hãy tăng “Mỗi khung hình thứ N”", "error.too_many_pictures": "Quá nhiều ảnh cho một video, hãy chia thành nhiều video", "error.too_many_parts": "Quá nhiều phần cho một video, hãy chọn phần dài hơn", @@ -1145,6 +1146,7 @@ "presets.ocr_hint": "Bản quét và ảnh sẽ có văn bản để tìm kiếm và chỉnh sửa. Cần Tesseract (Cài đặt → Bộ xử lý).\nTrang đã có văn bản được giữ nguyên.", "presets.ocr_hint_macos": "Bản quét và ảnh sẽ có văn bản để tìm kiếm và chỉnh sửa, bằng tính năng nhận dạng văn bản của chính macOS (Apple Vision). Ngôn ngữ mà macOS không đọc được cần Tesseract (Cài đặt → Bộ xử lý).\nTrang đã có văn bản được giữ nguyên.", "presets.ocr_language": "Ngôn ngữ của văn bản", + "presets.ocr_language_subtitles": "Ngôn ngữ của phụ đề, dùng để đọc phụ đề hình ảnh (.sup).", "presets.ocr_language_size": "Tải xuống {0}", "presets.ocr_more_languages": "Các ngôn ngữ khác trong văn bản", "presets.ocr_add_language": "Thêm ngôn ngữ", diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json index 502793043..ee5136fbb 100644 --- a/src/Filee.App/Assets/i18n/zh-CN.json +++ b/src/Filee.App/Assets/i18n/zh-CN.json @@ -133,6 +133,7 @@ "error.crop_same_frame": "视频已经是这个比例,没有可裁剪的内容", "error.ocr_language_download": "无法下载 OCR 语言数据", "error.ocr_needs_tesseract": "Apple Vision 无法识别此语言。请在“设置 → 转换引擎”中安装 Tesseract", + "error.sup_no_captions": "此文件不包含 Filee 可以读取的蓝光字幕 (.sup)。", "error.too_many_frames": "帧数太多,请调大“每 N 帧”", "error.too_many_pictures": "图片太多,无法放进一个视频,请分成几次", "error.too_many_parts": "一个视频分的段数太多,请把每段设长一些", @@ -1145,6 +1146,7 @@ "presets.ocr_hint": "让扫描件和图片中的文字可以搜索和编辑。需要 Tesseract(设置 → 转换引擎)。\n已有文字的页面保持不变。", "presets.ocr_hint_macos": "使用 macOS 自带的文字识别(Apple Vision),让扫描件和图片中的文字可以搜索和编辑。它无法识别的语言需要 Tesseract(设置 → 转换引擎)。\n已有文字的页面保持不变。", "presets.ocr_language": "文字的语言", + "presets.ocr_language_subtitles": "用于识别图像字幕 (.sup) 的字幕语言。", "presets.ocr_language_size": "下载 {0}", "presets.ocr_more_languages": "文字中的其他语言", "presets.ocr_add_language": "添加语言", diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.json index f7cae7363..21bfbf17a 100644 --- a/src/Filee.App/Assets/i18n/zh-TW.json +++ b/src/Filee.App/Assets/i18n/zh-TW.json @@ -133,6 +133,7 @@ "error.crop_same_frame": "影片已經是這個比例,沒有可裁剪的內容", "error.ocr_language_download": "無法下載 OCR 語言資料", "error.ocr_needs_tesseract": "Apple Vision 無法辨識此語言。請在「設定 → 轉換引擎」中安裝 Tesseract", + "error.sup_no_captions": "此檔案不包含 Filee 可以讀取的藍光字幕 (.sup)。", "error.too_many_frames": "影格數太多,請調大「每 N 個影格」", "error.too_many_pictures": "圖片太多,無法放進同一部影片,請分成幾次", "error.too_many_parts": "一部影片分的段數太多,請把每段設長一些", @@ -1145,6 +1146,7 @@ "presets.ocr_hint": "讓掃描檔和圖片中的文字可以搜尋和編輯。需要 Tesseract(設定 → 轉換引擎)。\n已有文字的頁面保持不變。", "presets.ocr_hint_macos": "使用 macOS 內建的文字辨識(Apple Vision),讓掃描檔和圖片中的文字可以搜尋和編輯。它無法辨識的語言需要 Tesseract(設定 → 轉換引擎)。\n已有文字的頁面保持不變。", "presets.ocr_language": "文字的語言", + "presets.ocr_language_subtitles": "用於辨識影像字幕 (.sup) 的字幕語言。", "presets.ocr_language_size": "下載 {0}", "presets.ocr_more_languages": "文字中的其他語言", "presets.ocr_add_language": "新增語言", diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs index 6022410b0..2ab1cfa38 100644 --- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs +++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs @@ -577,7 +577,8 @@ public async Task TestTranslationAsync() nameof(ShowZipResult), nameof(ShowPdf), nameof(ShowPdfBuild), nameof(ShowSourceBookmarks), nameof(ShowMergePaper), nameof(ShowMergePaperSettings), nameof(ShowDocument), nameof(ShowLeaveOutPictures), nameof(ShowPdfSplit), nameof(ShowPageGroups), nameof(ShowPdfCombine), nameof(ShowAskPages), nameof(ShowAskPagesHint), nameof(ShowAskCompressionImage), nameof(ShowAskCompressionMedia), nameof(ShowAskCompressionPdf), - nameof(ShowPdfCompression), nameof(ShowPdfCompressionOptions), nameof(ShowSheets), nameof(ShowOcr), nameof(ShowPageSize), nameof(ShowPdfTablesNote), nameof(ShowMergedCells), + nameof(ShowPdfCompression), nameof(ShowPdfCompressionOptions), nameof(ShowSheets), nameof(ShowOcr), nameof(ShowOcrSection), + nameof(ShowOcrLanguage), nameof(ShowSubtitleOcrLanguage), nameof(ShowPageSize), nameof(ShowPdfTablesNote), nameof(ShowMergedCells), nameof(ShowMedia), nameof(ShowMediaQuality), nameof(ShowMaxHeight), nameof(ShowVideoMaxSize), nameof(ShowAudioBitrate), nameof(ShowRemoveAudio), nameof(ShowVideoSplit), nameof(ShowVideoParts), nameof(ShowAudioChannels), nameof(ShowWav), nameof(VideoCodecs), nameof(VideoCodecChoice), nameof(ShowVideoCodec), nameof(ShowHardwareEncoding), nameof(ShowTurnUpright), nameof(ShowCaption), @@ -920,7 +921,7 @@ partial void OnPdfPasswordChanged(string value) /// Recognize the text of scans and pictures (PdfOptions.Ocr), in . [ObservableProperty] - [NotifyPropertyChangedFor(nameof(ShowPdfSplit), nameof(ShowPageGroups), nameof(ShowPdfCompression), nameof(ShowPdfCompressionOptions), nameof(ShowPageSize))] + [NotifyPropertyChangedFor(nameof(ShowPdfSplit), nameof(ShowPageGroups), nameof(ShowPdfCompression), nameof(ShowPdfCompressionOptions), nameof(ShowPageSize), nameof(ShowOcrLanguage))] private bool _ocr; /// @@ -1286,6 +1287,15 @@ partial void OnUpscaleTileSizeChanged(Choice? oldValue, Choice newValu /// Text from scans goes into the formats Filee writes from a PDF's text itself (PdfOptions.OcrTargets). public bool ShowOcr => !IsTool && PdfOptions.OcrTargets.Contains(TargetId); + /// Subtitle targets read picture subtitles (.sup) with OCR, so the language picker is shown without a switch. + public bool ShowSubtitleOcrLanguage => !IsTool && TargetCategory == FormatCategory.Subtitle; + + /// OCR language rows: shown when PDF/document OCR is switched on, or always for subtitle targets. + public bool ShowOcrLanguage => (ShowOcr && Ocr) || ShowSubtitleOcrLanguage; + + /// Shows the OCR card when either the document OCR switch or the subtitle OCR language picker applies. + public bool ShowOcrSection => ShowOcr || ShowSubtitleOcrLanguage; + /// PDF → a single-image format: the pages can be stacked into one tall image (TIFF, GIF, APNG and MNG keep pages). public bool ShowPdfCombine => TargetCategory == FormatCategory.Image && TargetId is not ("tiff" or "gif" or "apng" or "mng" or "ico" or "cur" or "icns" or "svg" or "pdf"); diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axaml index 86745d136..0126a7aca 100644 --- a/src/Filee.App/Views/PresetEditorView.axaml +++ b/src/Filee.App/Views/PresetEditorView.axaml @@ -685,49 +685,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -793,6 +750,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Filee.Core/Formats/FormatFields.cs b/src/Filee.Core/Formats/FormatFields.cs index d83fccfec..320c70e5a 100644 --- a/src/Filee.Core/Formats/FormatFields.cs +++ b/src/Filee.Core/Formats/FormatFields.cs @@ -84,7 +84,7 @@ .. Enum.GetValues().Select(category => category.ToString().ToLow "h265", "h264", "ac3", "caf", "mp2", "dss", "wv", "tta", "w64", "eac3", "ape", "tak", "dsf", "dff", "dts", "tar", "tgz", "tbz2", "txz", "tar7z", "tlz", "tzst", "gz", "bz2", "xz", "lz", "lzma", "zst", "jar", "zxp", "nupkg", "apks", "aab", "msix", "mcpack", "mcaddon", "mcworld", "mctemplate", "mrpack", "cab", "gerber", - "cpio", "deb", "rpm", "dwg", "ttf", "otf", "woff", "woff2", "ass", "ssa", "ttml", "scc", "glb", "gltf", + "cpio", "deb", "rpm", "dwg", "ttf", "otf", "woff", "woff2", "ass", "ssa", "ttml", "scc", "sup", "glb", "gltf", "stl", "obj", "3mf", "ply", "fbx", "3ds", "gcode", "geojson", "kml", "kmz", "gpx", "shp", "fit", "osm", "xm", "it", "ani", "vtf", "blp", "gma", "vpk", "bsp", "mdl", "smd", "cue" ]), (FormatGrade.Legacy, @@ -124,7 +124,7 @@ .. Enum.GetValues().Select(category => category.ToString().ToLow // Broadcast and editing masters, broadcast audio and captions, fansub and delivery subtitles, CCTV and // raw streams. ([ - "dv", "mxf", "cavs", "dav", "nov", "h265", "h264", "ac3", "mp2", "eac3", "dts", "ass", "ssa", "ttml", "scc" + "dv", "mxf", "cavs", "dav", "nov", "h265", "h264", "ac3", "mp2", "eac3", "dts", "ass", "ssa", "ttml", "scc", "sup" ], ["video-pro"]), // Lossless archiving and recorders. (["dss", "wv", "tta", "w64", "ape", "tak", "dsf", "dff"], ["audio-pro"]), diff --git a/src/Filee.Core/Formats/FormatRegistry.cs b/src/Filee.Core/Formats/FormatRegistry.cs index f08ba3ddf..b874dbc3d 100644 --- a/src/Filee.Core/Formats/FormatRegistry.cs +++ b/src/Filee.Core/Formats/FormatRegistry.cs @@ -438,6 +438,8 @@ public static class FormatRegistry new("ttml", "TTML", FormatCategory.Subtitle, ["ttml", "dfxp"]), new("sub", "MicroDVD", FormatCategory.Subtitle, ["sub"]), new("scc", "SCC", FormatCategory.Subtitle, ["scc"], Writable: false), + // Blu-ray picture subtitles (PGS, #1872): read by Filee, text recognized with Tesseract or Apple Vision. + new("sup", "Blu-ray subtitles (SUP)", FormatCategory.Subtitle, ["sup"], Writable: false), // 3D models new("glb", "GLB", FormatCategory.Model3D, ["glb"]), diff --git a/src/Filee.Core/Gallery/SharedPresetVersions.cs b/src/Filee.Core/Gallery/SharedPresetVersions.cs index 65a67bfaa..d37e68cbb 100644 --- a/src/Filee.Core/Gallery/SharedPresetVersions.cs +++ b/src/Filee.Core/Gallery/SharedPresetVersions.cs @@ -64,6 +64,7 @@ internal static class SharedPresetVersions ["wbk"] = "2.6.0", ["3ds"] = "2.6.0", ["ppsm"] = "2.6.0", + ["sup"] = "2.6.0", }; /// Extensions added after to a format it already knew (a new format's come with it). diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs index 1e6f14d28..27772f7ef 100644 --- a/src/Filee.Core/Settings/AppSettings.cs +++ b/src/Filee.Core/Settings/AppSettings.cs @@ -186,7 +186,7 @@ public static bool IsFlipKeyAllowed(string key, IEnumerable gest public sealed class AppSettings { /// Current schema version. Increase when the format changes and add a migration. - public const int CurrentSchemaVersion = 111; + public const int CurrentSchemaVersion = 112; public int SchemaVersion { get; set; } = CurrentSchemaVersion; diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs index dcc64eb5b..a9ebdb49e 100644 --- a/src/Filee.Core/Settings/UserDataStore.cs +++ b/src/Filee.Core/Settings/UserDataStore.cs @@ -1263,6 +1263,9 @@ public static bool ApplyToLibrary(int from, List presets, List CreateAll(EngineEnvironment env, ILogger new PandocConverter(), new GhostscriptConverter(), new VisionConverter(), // before Tesseract: a Mac's OCR step (Tesseract reads the languages Vision doesn't) - new TesseractConverter(), + new TesseractConverter(loggers?.CreateLogger()), new CalibreConverter(), new WeasyPrintConverter(), new LibreOfficeConverter(env, loggers?.CreateLogger()), diff --git a/src/Filee.Engines/Ocr/SubtitleOcr.cs b/src/Filee.Engines/Ocr/SubtitleOcr.cs new file mode 100644 index 000000000..31deb32ce --- /dev/null +++ b/src/Filee.Engines/Ocr/SubtitleOcr.cs @@ -0,0 +1,348 @@ +// Blu-ray picture subtitles (.sup) → SRT or plain text via OCR (Tesseract or Apple Vision). + +using System.Runtime.InteropServices; +using System.Text; +using System.Text.RegularExpressions; +using Filee.Core.Conversion; +using Filee.Core.Formats; +using Filee.Engines.Pdf; +using Filee.Engines.Subtitles; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using SkiaSharp; + +namespace Filee.Engines.Ocr; + +/// Converts PGS picture subtitles to text subtitles by preparing each bitmap and running an OCR backend. +internal static partial class SubtitleOcr +{ + /// White border added around each subtitle bitmap before OCR so edge glyphs are not clipped. + internal const int Padding = 16; + + /// Bitmaps shorter than this (in pixels) are doubled before OCR so small subtitle glyphs read accurately. + internal const int SmallHeightThreshold = 100; + + /// Images grouped per Tesseract invocation to avoid process startup overhead per caption. + private const int BatchSize = 20; + + /// + /// Converts a .sup file into (srt or txt) using + /// to read the prepared PNGs (relative names in the scratch folder). + /// + public static async Task> ConvertSupAsync( + ConversionStep step, + Func, Action, CancellationToken, Task>> recognize, + IProgress? progress, + CancellationToken cancellationToken, + ILogger? logger = null) + { + var log = logger ?? NullLogger.Instance; + var scratch = Path.Combine(step.WorkDirectory, "sup-" + Guid.NewGuid().ToString("N")[..8]); + Directory.CreateDirectory(scratch); + + string? output = null; + var imageNames = new List(); + var captionSlices = new List<(TimeSpan Start, TimeSpan End, int StartIndex, int Count)>(); + + // Stream captions one at a time so each caption's RGBA buffers are written to PNG and dropped immediately. + using (var stream = File.OpenRead(step.InputPath)) + { + var totalBytes = stream.CanSeek ? stream.Length : 0; + foreach (var caption in PgsReader.Read(stream, cancellationToken)) + { + cancellationToken.ThrowIfCancellationRequested(); + output ??= step.Output.Allocate(FormatRegistry.Get(step.To).PrimaryExtension); + if (output is null) + return []; + + var ordered = caption.Objects.OrderBy(o => o.Y).ThenBy(o => o.X).ToList(); + var startIndex = imageNames.Count; + foreach (var obj in ordered) + { + var name = $"c{imageNames.Count:D6}.png"; + WritePreparedPng(obj, Path.Combine(scratch, name)); + imageNames.Add(name); + } + captionSlices.Add((caption.Start, caption.End, startIndex, ordered.Count)); + if (totalBytes > 0) + progress?.Report(0.05 * stream.Position / totalBytes); + } + } + progress?.Report(0.05); + + if (output is null || imageNames.Count == 0) + throw new ConversionRefusedException("error.sup_no_captions"); + + var recognized = await recognize(scratch, imageNames, done => + progress?.Report(0.05 + 0.9 * done / imageNames.Count), cancellationToken); + + var document = new SubtitleDocument(); + var dropped = 0; + foreach (var (start, end, startIndex, count) in captionSlices) + { + var parts = new List(count); + for (var i = 0; i < count; i++) + { + var cleaned = CleanText(recognized[startIndex + i]); + if (cleaned.Length > 0) + parts.Add(cleaned); + } + if (parts.Count == 0) + { + dropped++; + continue; + } + document.Add(start, end, string.Join('\n', parts)); + } + + if (dropped > 0) + log.LogInformation("Dropped {Dropped} empty PGS caption(s) after OCR of {File}", dropped, Path.GetFileName(step.InputPath)); + + document.Finish(); + if (document.Cues.Count == 0) + throw new ConversionRefusedException("error.sup_no_captions"); + + var data = SubtitleWriter.Write(document, step.To); + WriteAtomically(output, data, cancellationToken); + progress?.Report(1); + return [output]; + } + + /// + /// Converts a PGS bitmap into dark text on a white canvas, padded by px on every side and + /// doubled in size when shorter than px. + /// + internal static SKBitmap PrepareBitmap(PgsBitmap bitmap) + { + var paddedWidth = bitmap.Width + Padding * 2; + var paddedHeight = bitmap.Height + Padding * 2; + var rgba = new byte[paddedWidth * paddedHeight * 4]; + rgba.AsSpan().Fill(255); // opaque white background and padding + + var src = bitmap.Rgba; + for (var y = 0; y < bitmap.Height; y++) + { + var srcRow = y * bitmap.Width * 4; + var dstRow = (y + Padding) * paddedWidth * 4 + Padding * 4; + for (var x = 0; x < bitmap.Width; x++) + { + var s = srcRow + x * 4; + var r = src[s]; + var g = src[s + 1]; + var b = src[s + 2]; + var a = src[s + 3]; + var luma = (299 * r + 587 * g + 114 * b + 500) / 1000; + var v = (byte)Math.Clamp(255 - luma * a / 255, 0, 255); + var d = dstRow + x * 4; + rgba[d] = v; + rgba[d + 1] = v; + rgba[d + 2] = v; + rgba[d + 3] = 255; + } + } + + var padded = new SKBitmap(new SKImageInfo(paddedWidth, paddedHeight, SKColorType.Rgba8888, SKAlphaType.Opaque)); + Marshal.Copy(rgba, 0, padded.GetPixels(), rgba.Length); + + if (bitmap.Height >= SmallHeightThreshold) + return padded; + + using (padded) + { + var target = new SKImageInfo(paddedWidth * 2, paddedHeight * 2, SKColorType.Rgba8888, SKAlphaType.Opaque); + return padded.Resize(target, new SKSamplingOptions(SKCubicResampler.CatmullRom)) + ?? throw new InvalidOperationException("Failed to upscale subtitle bitmap for OCR."); + } + } + + /// Prepares for OCR and encodes it as PNG at . + internal static void WritePreparedPng(PgsBitmap bitmap, string path) + { + using var prepared = PrepareBitmap(bitmap); + using var file = File.Create(path); + prepared.Encode(file, SKEncodedImageFormat.Png, 100); + } + + /// + /// Runs Tesseract in parallel batches via list files (tesseract batch.txt stdout … --psm 6), falling back to + /// one image per call when a batch's form-feed page count does not match. + /// + internal static async Task> RecognizeWithTesseractAsync( + string executable, + string scratch, + string languages, + IReadOnlyList imageNames, + Action onDone, + CancellationToken cancellationToken) + { + var results = new string[imageNames.Count]; + var batches = new List<(int Offset, List Names)>(); + for (var i = 0; i < imageNames.Count; i += BatchSize) + { + var count = Math.Min(BatchSize, imageNames.Count - i); + batches.Add((i, [.. imageNames.Skip(i).Take(count)])); + } + + using var gate = new SemaphoreSlim(TesseractConverter.Runs); + var tasks = new List(batches.Count); + var done = 0; + try + { + for (var b = 0; b < batches.Count; b++) + { + await gate.WaitAsync(cancellationToken); + if (tasks.Any(t => t.IsFaulted)) + { + gate.Release(); + break; + } + var batchIndex = b; + var (offset, names) = batches[b]; + tasks.Add(Task.Run(async () => + { + try + { + var texts = await RunBatchAsync(executable, scratch, languages, batchIndex, names, cancellationToken); + for (var i = 0; i < names.Count; i++) + { + results[offset + i] = texts[i]; + TryDelete(Path.Combine(scratch, names[i])); + } + onDone(Interlocked.Add(ref done, names.Count)); + } + finally + { + gate.Release(); + } + }, cancellationToken)); + } + } + finally + { + await Task.WhenAll(tasks).ContinueWith(_ => { }, TaskScheduler.Default); + } + await Task.WhenAll(tasks); + return results; + } + + private static async Task RunBatchAsync( + string executable, + string scratch, + string languages, + int batchIndex, + IReadOnlyList names, + CancellationToken cancellationToken) + { + if (names.Count == 1) + return [await RunSingleAsync(executable, scratch, languages, names[0], cancellationToken)]; + + var listName = $"batch_{batchIndex}.txt"; + var listPath = Path.Combine(scratch, listName); + await File.WriteAllTextAsync(listPath, string.Join('\n', names) + "\n", new UTF8Encoding(false), cancellationToken); + try + { + var result = await TesseractConverter.RunTesseractAsync(executable, scratch, + [listName, "stdout", "--tessdata-dir", "tessdata", "-l", languages, "--psm", "6"], cancellationToken); + if (result.ExitCode == 0 && TrySplitPages(result.StandardOutput, names.Count) is { } pages) + return pages; + } + finally + { + TryDelete(listPath); + } + + // Batch output didn't split cleanly into the expected page count: fall back to one image per call. + var fallback = new string[names.Count]; + for (var i = 0; i < names.Count; i++) + { + cancellationToken.ThrowIfCancellationRequested(); + fallback[i] = await RunSingleAsync(executable, scratch, languages, names[i], cancellationToken); + } + return fallback; + } + + private static async Task RunSingleAsync( + string executable, + string scratch, + string languages, + string imageName, + CancellationToken cancellationToken) + { + var result = await TesseractConverter.RunTesseractAsync(executable, scratch, + [imageName, "stdout", "--tessdata-dir", "tessdata", "-l", languages, "--psm", "6"], cancellationToken); + if (result.ExitCode != 0) + throw new InvalidOperationException($"Tesseract failed (exit {result.ExitCode}). {result.StandardError.Trim()}"); + return result.StandardOutput; + } + + /// Splits form-feed separated Tesseract batch output into exactly pages, or null. + internal static string[]? TrySplitPages(string output, int expected) + { + var parts = output.Split('\f'); + // Tesseract appends a trailing form feed after the final page in list-file mode. + if (parts.Length == expected + 1 && string.IsNullOrWhiteSpace(parts[^1])) + return parts[..expected]; + return parts.Length == expected ? parts : null; + } + + /// Normalizes OCR output: trims lines, drops empty ones, collapses spaces and removes CJK inter-character spaces. + internal static string CleanText(string raw) + { + if (string.IsNullOrWhiteSpace(raw)) + return ""; + var lines = raw.Replace("\r\n", "\n").Replace('\r', '\n').Replace('\f', '\n').Split('\n'); + var cleaned = new List(lines.Length); + foreach (var line in lines) + { + var collapsed = MultipleSpaces().Replace(line.Trim(), " "); + if (collapsed.Length == 0) + continue; + cleaned.Add(RemoveCjkSpaces(collapsed)); + } + return string.Join('\n', cleaned); + } + + /// Removes single spaces between adjacent Chinese / Japanese characters (issue #691); Korean keeps spaces. + internal static string RemoveCjkSpaces(string line) + { + if (!line.Contains(' ', StringComparison.Ordinal)) + return line; + var sb = new StringBuilder(line.Length); + for (var i = 0; i < line.Length; i++) + { + var ch = line[i]; + if (ch == ' ' && sb.Length > 0 && i + 1 < line.Length + && PdfDocumentReader.IsCjk(sb[^1]) && PdfDocumentReader.IsCjk(line[i + 1])) + continue; + sb.Append(ch); + } + return sb.ToString(); + } + + private static void WriteAtomically(string output, byte[] data, CancellationToken cancellationToken) + { + var directory = Path.GetDirectoryName(Path.GetFullPath(output))!; + var temp = Path.Combine(directory, $".{Path.GetFileName(output)}.{Guid.NewGuid():N}.tmp"); + try + { + File.WriteAllBytes(temp, data); + cancellationToken.ThrowIfCancellationRequested(); + File.Move(temp, output, overwrite: true); + } + finally + { + TryDelete(temp); + } + } + + private static void TryDelete(string path) + { + if (!File.Exists(path)) + return; + try { File.Delete(path); } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { } + } + + [GeneratedRegex(@"[ \t]{2,}")] + private static partial Regex MultipleSpaces(); +} diff --git a/src/Filee.Engines/Ocr/TesseractConverter.cs b/src/Filee.Engines/Ocr/TesseractConverter.cs index 21604a95b..d74728992 100644 --- a/src/Filee.Engines/Ocr/TesseractConverter.cs +++ b/src/Filee.Engines/Ocr/TesseractConverter.cs @@ -16,6 +16,7 @@ using Filee.Engines.Infrastructure; using Filee.Engines.Pdf; using ImageMagick; +using Microsoft.Extensions.Logging; using PdfSharp.Drawing; using PdfSharp.Pdf; using PdfSharp.Pdf.IO; @@ -29,8 +30,8 @@ namespace Filee.Engines.Ocr; -/// Scans and pictures → searchable PDF through Tesseract. -public sealed class TesseractConverter : IConverter +/// Scans and pictures → searchable PDF, and Blu-ray picture subtitles (.sup) → SRT / TXT, through Tesseract. +public sealed class TesseractConverter(ILogger? logger = null) : IConverter { private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(10); @@ -67,7 +68,13 @@ public sealed class TesseractConverter : IConverter public int MaxParallelism => 1; public IReadOnlyList Edges { get; } = - [.. ImageSources.Select(f => new ConversionEdge(f, "pdf", Ocr: true)), new("pdf", "pdf", Ocr: true)]; + [ + .. ImageSources.Select(f => new ConversionEdge(f, "pdf", Ocr: true)), + new("pdf", "pdf", Ocr: true), + // Blu-ray picture subtitles (.sup) always need OCR, so these are ordinary edges (not gated by PdfOptions.Ocr). + new("sup", "srt"), + new("sup", "txt", DirectOnly: true), + ]; public EngineStatus GetStatus() { @@ -85,12 +92,20 @@ public async Task> ConvertAsync(ConversionStep step, IProg { var tesseract = _executable ?? Locate() ?? throw new InvalidOperationException("Tesseract is not installed."); var languages = OcrLanguages.Parse(step.Preset.Pdf.OcrLanguage); + if (step.From == "sup") + { + var dataFiles = await LanguageDataAsync(languages, OcrLanguages.EnsureAsync, cancellationToken); + var joinedCodes = OcrLanguages.Join(languages.Select(l => l.Code)); + return await SubtitleOcr.ConvertSupAsync(step, (supScratch, names, onDone, ct) => + { + CopyTessdata(supScratch, dataFiles); + return SubtitleOcr.RecognizeWithTesseractAsync(tesseract, supScratch, joinedCodes, names, onDone, ct); + }, progress, cancellationToken, logger); + } + var data = await LanguageDataAsync(languages, OcrLanguages.EnsureAsync, cancellationToken); var scratch = Path.Combine(step.WorkDirectory, "ocr-" + Guid.NewGuid().ToString("N")[..8]); - var tessdata = Path.Combine(scratch, "tessdata"); - Directory.CreateDirectory(tessdata); - foreach (var file in data) - File.Copy(file, Path.Combine(tessdata, Path.GetFileName(file))); + var tessdata = CopyTessdata(scratch, data); CopyPdfFont(tessdata, PdfFontFolders(tesseract, System.Environment.GetEnvironmentVariable("TESSDATA_PREFIX"))); var ocr = new Run(tesseract, scratch, OcrLanguages.Join(languages.Select(l => l.Code))); progress?.Report(0.05); @@ -507,6 +522,21 @@ internal static void PutTextOnPicture(string textPdf, string picture, double wid document.Save(output); } + /// Copies the pinned language files into {scratch}/tessdata and returns that folder. + private static string CopyTessdata(string scratch, IReadOnlyList dataFiles) + { + var tessdata = Path.Combine(scratch, "tessdata"); + Directory.CreateDirectory(tessdata); + foreach (var file in dataFiles) + File.Copy(file, Path.Combine(tessdata, Path.GetFileName(file))); + return tessdata; + } + + /// Runs Tesseract inside with Filee's shared timeout and environment. + internal static Task RunTesseractAsync(string executable, string folder, IEnumerable args, + CancellationToken cancellationToken) => + ProcessRunner.RunAsync(executable, args, Timeout, cancellationToken, workingDirectory: folder, environment: Environment); + /// /// One Tesseract reading (joined as its -l takes them), working in /// (the job's scratch folder, with their data in its tessdata). Tesseract only ever @@ -527,7 +557,7 @@ public async Task ToPdfAsync(string input, string outputBase, int? dpi, Cancella args.AddRange(["-c", "textonly_pdf=1"]); if (dpi is { } value) args.AddRange(["--dpi", value.ToString(System.Globalization.CultureInfo.InvariantCulture)]); - var result = await ProcessRunner.RunAsync(Executable, args, Timeout, cancellationToken, workingDirectory: Folder, environment: Environment); + var result = await RunTesseractAsync(Executable, Folder, args, cancellationToken); if (result.ExitCode != 0 || !File.Exists(Path.Combine(Folder, outputBase + ".pdf"))) throw new InvalidOperationException($"Tesseract failed (exit {result.ExitCode}). {result.StandardError.Trim()}"); } diff --git a/src/Filee.Engines/Ocr/VisionConverter.cs b/src/Filee.Engines/Ocr/VisionConverter.cs index 1a8c5ca17..95c4f5298 100644 --- a/src/Filee.Engines/Ocr/VisionConverter.cs +++ b/src/Filee.Engines/Ocr/VisionConverter.cs @@ -44,7 +44,12 @@ internal VisionConverter(ITextRecognizer? recognizer, IConverter tesseract) public int MaxParallelism => 1; public IReadOnlyList Edges { get; } = - [.. TesseractConverter.ImageSources.Select(f => new ConversionEdge(f, "pdf", Ocr: true)), new("pdf", "pdf", Ocr: true)]; + [ + .. TesseractConverter.ImageSources.Select(f => new ConversionEdge(f, "pdf", Ocr: true)), + new("pdf", "pdf", Ocr: true), + new("sup", "srt"), + new("sup", "txt", DirectOnly: true), + ]; public EngineStatus GetStatus() { @@ -75,6 +80,10 @@ public async Task> ConvertAsync(ConversionStep step, IProg string.Join(", ", chosen.Where(l => VisionLanguages.For(l.Code, recognizer.Languages) is null).Select(l => l.NativeName))); } + if (step.From == "sup") + return await SubtitleOcr.ConvertSupAsync(step, (supScratch, names, onDone, ct) => + RecognizePicturesAsync(recognizer, supScratch, names, languages, onDone, ct), progress, cancellationToken); + var scratch = Path.Combine(step.WorkDirectory, "vision-" + Guid.NewGuid().ToString("N")[..8]); Directory.CreateDirectory(scratch); progress?.Report(0.05); @@ -111,6 +120,53 @@ await Task.Run(() => return [output]; } + private static async Task> RecognizePicturesAsync( + ITextRecognizer recognizer, + string scratch, + IReadOnlyList names, + IReadOnlyList languages, + Action onDone, + CancellationToken cancellationToken) + { + var results = new string[names.Count]; + using var gate = new SemaphoreSlim(Runs); + var tasks = new List(names.Count); + var done = 0; + try + { + for (var i = 0; i < names.Count; i++) + { + await gate.WaitAsync(cancellationToken); + if (tasks.Any(t => t.IsFaulted)) + { + gate.Release(); + break; + } + var index = i; + var path = Path.Combine(scratch, names[index]); + tasks.Add(Task.Run(() => + { + try + { + var lines = Recognize(recognizer, path, languages, cancellationToken); + results[index] = string.Join('\n', lines.Select(l => string.Join(' ', l.Words.Select(w => w.Text)))); + onDone(Interlocked.Increment(ref done)); + } + finally + { + gate.Release(); + } + }, cancellationToken)); + } + } + finally + { + await Task.WhenAll(tasks).ContinueWith(_ => { }, TaskScheduler.Default); + } + await Task.WhenAll(tasks); + return results; + } + /// /// Reads one picture. When Vision fails on a combination of languages it reads again without the last one (usually /// the English that VisionLanguages adds), down to the first language, the main one, alone. Each try hands Vision its diff --git a/src/Filee.Engines/Pdf/PdfDocumentReader.cs b/src/Filee.Engines/Pdf/PdfDocumentReader.cs index 6f84d5607..a28dc70dd 100644 --- a/src/Filee.Engines/Pdf/PdfDocumentReader.cs +++ b/src/Filee.Engines/Pdf/PdfDocumentReader.cs @@ -1223,7 +1223,7 @@ private static bool BracketsPair(string text) } /// Chinese and Japanese text has no spaces between words (Korean does). - private static bool IsCjk(char ch) => ch is >= '぀' and <= 'ヿ' or >= '㐀' and <= '鿿' or >= '豈' and <= '﫿' or >= '＀' and <= '⦆' or >= ' ' and <= '〿'; + internal static bool IsCjk(char ch) => ch is >= '぀' and <= 'ヿ' or >= '㐀' and <= '鿿' or >= '豈' and <= '﫿' or >= '＀' and <= '⦆' or >= ' ' and <= '〿'; // ───────────────────────── Helpers ───────────────────────── diff --git a/src/Filee.Engines/Subtitles/PgsReader.cs b/src/Filee.Engines/Subtitles/PgsReader.cs new file mode 100644 index 000000000..f47dabbd4 --- /dev/null +++ b/src/Filee.Engines/Subtitles/PgsReader.cs @@ -0,0 +1,444 @@ +// Blu-ray Presentation Graphic Stream (PGS, .sup) reader: streams display sets, BT.709 palettes and RLE bitmaps into timed captions. + +using System.Buffers.Binary; +using Filee.Core.Conversion; + +namespace Filee.Engines.Subtitles; + +/// One decoded picture object positioned on the video frame. +internal sealed record PgsBitmap(int X, int Y, int Width, int Height, byte[] Rgba); + +/// One timed subtitle display containing one or more bitmap objects. +internal sealed record PgsCaption(TimeSpan Start, TimeSpan End, IReadOnlyList Objects); + +/// Streams Blu-ray PGS (.sup) picture subtitle segments into timed RGBA captions. +internal static class PgsReader +{ + private const byte SegmentPds = 0x14; + private const byte SegmentOds = 0x15; + private const byte SegmentPcs = 0x16; + private const byte SegmentWds = 0x17; + private const byte SegmentEnd = 0x80; + + private const byte StateEpochStart = 0x80; + private const byte PaletteUpdateOnlyFlag = 0x80; + private const byte CroppedFlag = 0x40; + private const byte SequenceFirst = 0x80; + private const byte SequenceLast = 0x40; + + /// Duration given to a final caption that is never cleared before end of file. + internal static readonly TimeSpan DefaultLastDuration = TimeSpan.FromSeconds(5); + + /// Largest single PGS bitmap accepted (4096 × 4096 pixels) to reject corrupt headers. + internal const long MaxObjectPixels = 4096L * 4096; + + /// Cap on assembled RLE payload per object (16 MB). + internal const int MaxObjectDataBytes = 16 * 1024 * 1024; + + /// Cap on RGBA bytes decoded for a single caption so live memory stays bounded. + internal const long MaxCaptionBytes = 64L * 1024 * 1024; + + /// Cap on total captions yielded from one file to bound hostile or malformed streams. + internal const int MaxCaptions = 100_000; + + /// + /// Streams captions from a .sup stream, yielding each caption as soon as the next display set ends or + /// replaces it so callers can process and discard its RGBA bitmaps immediately. + /// + /// The stream does not start with PGS magic or yields no captions. + public static IEnumerable Read(Stream stream, CancellationToken cancellationToken = default) + { + var header = new byte[13]; + if (!ReadExact(stream, header) || header[0] != (byte)'P' || header[1] != (byte)'G') + throw new ConversionRefusedException("error.sup_no_captions"); + + var payloadBuffer = new byte[ushort.MaxValue]; + var palettes = new Dictionary(); + var objects = new Dictionary(); + var pendingObjects = new Dictionary(); + + ParsedPcs? currentPcs = null; + ActiveCaption? active = null; + var yielded = 0; + + while (yielded < MaxCaptions) + { + cancellationToken.ThrowIfCancellationRequested(); + + var pts = BinaryPrimitives.ReadUInt32BigEndian(header.AsSpan(2, 4)); + var type = header[10]; + var size = BinaryPrimitives.ReadUInt16BigEndian(header.AsSpan(11, 2)); + if (size > 0 && !ReadExact(stream, payloadBuffer.AsSpan(0, size))) + break; // truncated trailing segment + + var payload = payloadBuffer.AsSpan(0, size); + + switch (type) + { + case SegmentPcs: + currentPcs = ParsePcs(payload, pts); + if (currentPcs is { State: StateEpochStart }) + { + palettes.Clear(); + objects.Clear(); + pendingObjects.Clear(); + } + break; + + case SegmentPds: + ParsePds(payload, palettes); + break; + + case SegmentOds: + ParseOds(payload, pendingObjects, objects); + break; + + case SegmentWds: + // Window definitions are not needed for OCR; objects carry their own frame coordinates. + break; + + case SegmentEnd: + if (currentPcs is not null) + { + var finished = ApplyDisplaySet(currentPcs, palettes, objects, ref active); + currentPcs = null; + if (finished is not null) + { + yielded++; + yield return finished; + if (yielded >= MaxCaptions) + yield break; + } + } + break; + } + + if (!ReadExact(stream, header) || header[0] != (byte)'P' || header[1] != (byte)'G') + break; + } + + if (active is not null && yielded < MaxCaptions) + { + yielded++; + yield return new PgsCaption(active.Start, active.Start + DefaultLastDuration, active.Bitmaps); + } + + if (yielded == 0) + throw new ConversionRefusedException("error.sup_no_captions"); + } + + /// Converts 90 kHz PGS presentation timestamps to a . + internal static TimeSpan PtsToTimeSpan(uint pts) => + TimeSpan.FromTicks((long)pts * 1000 / 9); + + /// Converts limited-range BT.709 YCbCr (Y 16–235, Cb/Cr 16–240) to clamped sRGB bytes. + internal static (byte R, byte G, byte B) YCbCrToRgb(byte y, byte cb, byte cr) + { + var yd = 1.1643835616438356 * (y - 16); + var cbd = cb - 128; + var crd = cr - 128; + var r = ClampByte(yd + 1.7927410714285714 * crd); + var g = ClampByte(yd - 0.21324861427372963 * cbd - 0.532909328559444 * crd); + var b = ClampByte(yd + 2.1124017857142854 * cbd); + return (r, g, b); + } + + /// Decodes PGS run-length encoded palette indices into a × buffer. + internal static byte[] DecodeRle(ReadOnlySpan rle, int width, int height) + { + var pixels = new byte[width * height]; + var x = 0; + var y = 0; + var i = 0; + while (i < rle.Length && y < height) + { + var b = rle[i++]; + if (b != 0) + { + if (x < width) + pixels[y * width + x] = b; + x++; + continue; + } + if (i >= rle.Length) + break; + + var flag = rle[i++]; + if (flag == 0) + { + x = 0; + y++; + continue; + } + + int count; + byte color; + switch (flag & 0xC0) + { + case 0x00: + count = flag & 0x3F; + color = 0; + break; + case 0x40: + if (i >= rle.Length) + return pixels; + count = ((flag & 0x3F) << 8) | rle[i++]; + color = 0; + break; + case 0x80: + if (i >= rle.Length) + return pixels; + count = flag & 0x3F; + color = rle[i++]; + break; + default: + if (i + 1 >= rle.Length) + return pixels; + count = ((flag & 0x3F) << 8) | rle[i++]; + color = rle[i++]; + break; + } + + if (x < width && count > 0) + { + var writable = Math.Min(count, width - x); + if (color != 0) + pixels.AsSpan(y * width + x, writable).Fill(color); + x += writable; + } + } + return pixels; + } + + private static bool ReadExact(Stream stream, Span buffer) + { + var total = 0; + while (total < buffer.Length) + { + var read = stream.Read(buffer[total..]); + if (read <= 0) + return false; + total += read; + } + return true; + } + + private static ParsedPcs? ParsePcs(ReadOnlySpan payload, uint pts) + { + if (payload.Length < 11) + return null; + var state = payload[7]; + var paletteUpdateOnly = (payload[8] & PaletteUpdateOnlyFlag) != 0; + var paletteId = payload[9]; + var objectCount = payload[10]; + var objects = new List(objectCount); + + var pos = 11; + for (var i = 0; i < objectCount; i++) + { + if (pos + 8 > payload.Length) + break; + var objectId = BinaryPrimitives.ReadUInt16BigEndian(payload.Slice(pos, 2)); + var cropped = (payload[pos + 3] & CroppedFlag) != 0; + var x = BinaryPrimitives.ReadUInt16BigEndian(payload.Slice(pos + 4, 2)); + var y = BinaryPrimitives.ReadUInt16BigEndian(payload.Slice(pos + 6, 2)); + pos += 8; + + int cropX = 0, cropY = 0, cropW = 0, cropH = 0; + if (cropped) + { + if (pos + 8 > payload.Length) + break; + cropX = BinaryPrimitives.ReadUInt16BigEndian(payload.Slice(pos, 2)); + cropY = BinaryPrimitives.ReadUInt16BigEndian(payload.Slice(pos + 2, 2)); + cropW = BinaryPrimitives.ReadUInt16BigEndian(payload.Slice(pos + 4, 2)); + cropH = BinaryPrimitives.ReadUInt16BigEndian(payload.Slice(pos + 6, 2)); + pos += 8; + } + objects.Add(new CompositionObject(objectId, x, y, cropped, cropX, cropY, cropW, cropH)); + } + + return new ParsedPcs(pts, state, paletteUpdateOnly, paletteId, objects); + } + + private static void ParsePds(ReadOnlySpan payload, Dictionary palettes) + { + if (payload.Length < 2) + return; + var paletteId = payload[0]; + var rgba = new byte[256 * 4]; + for (var pos = 2; pos + 5 <= payload.Length; pos += 5) + { + var entry = payload[pos]; + var (r, g, b) = YCbCrToRgb(payload[pos + 1], payload[pos + 3], payload[pos + 2]); + var alpha = payload[pos + 4]; + var idx = entry * 4; + rgba[idx] = r; + rgba[idx + 1] = g; + rgba[idx + 2] = b; + rgba[idx + 3] = alpha; + } + palettes[paletteId] = rgba; + } + + private static void ParseOds(ReadOnlySpan payload, Dictionary pending, Dictionary objects) + { + if (payload.Length < 4) + return; + var objectId = BinaryPrimitives.ReadUInt16BigEndian(payload.Slice(0, 2)); + var sequence = payload[3]; + var isFirst = (sequence & SequenceFirst) != 0; + var isLast = (sequence & SequenceLast) != 0; + + PendingObject? state; + ReadOnlySpan fragment; + if (isFirst) + { + if (payload.Length < 11) + return; + var width = BinaryPrimitives.ReadUInt16BigEndian(payload.Slice(7, 2)); + var height = BinaryPrimitives.ReadUInt16BigEndian(payload.Slice(9, 2)); + if (width == 0 || height == 0 || (long)width * height > MaxObjectPixels) + { + pending.Remove(objectId); + return; + } + state = new PendingObject(width, height, new MemoryStream()); + pending[objectId] = state; + fragment = payload[11..]; + } + else + { + if (!pending.TryGetValue(objectId, out state)) + return; + fragment = payload[4..]; + } + + if (state.Data.Length + fragment.Length > MaxObjectDataBytes) + { + pending.Remove(objectId); + return; + } + state.Data.Write(fragment); + + if (isLast) + { + pending.Remove(objectId); + var indices = DecodeRle(state.Data.GetBuffer().AsSpan(0, (int)state.Data.Length), state.Width, state.Height); + objects[objectId] = new DecodedObject(state.Width, state.Height, indices); + } + } + + private static PgsCaption? ApplyDisplaySet( + ParsedPcs pcs, + Dictionary palettes, + Dictionary objects, + ref ActiveCaption? active) + { + var pts = PtsToTimeSpan(pcs.Pts); + + // Palette-only updates animate fades or highlights on the current caption without splitting it. + if (pcs.PaletteUpdateOnly) + { + if (active is not null && palettes.TryGetValue(pcs.PaletteId, out var updatedPalette)) + { + var updated = RenderObjects(active.Specs, updatedPalette, objects); + if (TotalAlpha(updated) > TotalAlpha(active.Bitmaps)) + active = active with { Bitmaps = updated }; + } + return null; + } + + if (pcs.Objects.Count == 0) + return Flush(ref active, pts); + + var finished = Flush(ref active, pts); + + if (palettes.TryGetValue(pcs.PaletteId, out var palette)) + { + var rendered = RenderObjects(pcs.Objects, palette, objects); + if (rendered.Count > 0) + active = new ActiveCaption(pts, pcs.Objects, rendered); + } + + return finished; + } + + private static PgsCaption? Flush(ref ActiveCaption? active, TimeSpan end) + { + if (active is null) + return null; + var completed = end > active.Start ? new PgsCaption(active.Start, end, active.Bitmaps) : null; + active = null; + return completed; + } + + private static List RenderObjects( + IReadOnlyList specs, + byte[] palette, + Dictionary objects) + { + var rendered = new List(specs.Count); + long captionBytes = 0; + foreach (var spec in specs) + { + if (!objects.TryGetValue(spec.ObjectId, out var obj)) + continue; + + int srcX = 0, srcY = 0, width = obj.Width, height = obj.Height; + if (spec.Cropped) + { + srcX = Math.Clamp(spec.CropX, 0, obj.Width); + srcY = Math.Clamp(spec.CropY, 0, obj.Height); + width = Math.Clamp(spec.CropWidth, 0, obj.Width - srcX); + height = Math.Clamp(spec.CropHeight, 0, obj.Height - srcY); + } + if (width <= 0 || height <= 0) + continue; + + var byteCount = (long)width * height * 4; + if (captionBytes + byteCount > MaxCaptionBytes) + break; + + var rgba = new byte[byteCount]; + for (var row = 0; row < height; row++) + { + var srcRow = (srcY + row) * obj.Width + srcX; + var dstRow = row * width * 4; + for (var col = 0; col < width; col++) + { + var p = obj.Indices[srcRow + col] * 4; + var d = dstRow + col * 4; + rgba[d] = palette[p]; + rgba[d + 1] = palette[p + 1]; + rgba[d + 2] = palette[p + 2]; + rgba[d + 3] = palette[p + 3]; + } + } + + captionBytes += byteCount; + rendered.Add(new PgsBitmap(spec.X, spec.Y, width, height, rgba)); + } + return rendered; + } + + private static long TotalAlpha(IReadOnlyList bitmaps) + { + long sum = 0; + foreach (var bitmap in bitmaps) + { + var rgba = bitmap.Rgba; + for (var i = 3; i < rgba.Length; i += 4) + sum += rgba[i]; + } + return sum; + } + + private static byte ClampByte(double value) => (byte)Math.Clamp((int)Math.Round(value), 0, 255); + + private sealed record CompositionObject(ushort ObjectId, int X, int Y, bool Cropped, int CropX, int CropY, int CropWidth, int CropHeight); + private sealed record ParsedPcs(uint Pts, byte State, bool PaletteUpdateOnly, byte PaletteId, IReadOnlyList Objects); + private sealed record PendingObject(int Width, int Height, MemoryStream Data); + private sealed record DecodedObject(int Width, int Height, byte[] Indices); + private sealed record ActiveCaption(TimeSpan Start, IReadOnlyList Specs, IReadOnlyList Bitmaps); +} diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs index b49173cd0..40b9ac428 100644 --- a/tests/Filee.App.Tests/RenderTests.cs +++ b/tests/Filee.App.Tests/RenderTests.cs @@ -1610,8 +1610,29 @@ public void Preset_editor_shows_and_saves_text_recognition(string language) vm = new PresetEditorViewModel(preset, loc); vm.Target = vm.Targets.Single(t => t.Value == "png"); Assert.False(vm.ShowOcr); + Assert.False(vm.ShowOcrLanguage); + Assert.False(vm.ShowOcrSection); Assert.True(vm.Apply()); Assert.False(preset.Pdf.Ocr); + + // Subtitle targets (#1872): show OCR language picker without the PDF OCR switch, and save the language. + var subPreset = new Filee.Core.Presets.Preset { Name = "SRT", TargetFormat = "srt" }; + var subVm = new PresetEditorViewModel(subPreset, loc); + Assert.False(subVm.ShowOcr); + Assert.True(subVm.ShowSubtitleOcrLanguage); + Assert.True(subVm.ShowOcrLanguage); + Assert.True(subVm.ShowOcrSection); + subVm.OcrLanguage = subVm.OcrLanguageChoices.Single(l => l.Value == "jpn"); + Assert.True(subVm.Apply()); + Assert.False(subPreset.Pdf.Ocr); + Assert.Equal("jpn", subPreset.Pdf.OcrLanguage); + + subVm = new PresetEditorViewModel(subPreset, loc); + subVm.Target = subVm.Targets.Single(t => t.Value == "ass"); + Assert.False(subVm.ShowOcr); + Assert.True(subVm.ShowSubtitleOcrLanguage); + Assert.True(subVm.ShowOcrLanguage); + Assert.Equal("jpn", subVm.OcrLanguage.Value); } [AvaloniaTheory] diff --git a/tests/Filee.Core.Tests/FormatFieldsTests.cs b/tests/Filee.Core.Tests/FormatFieldsTests.cs index 2a5cab731..dd4634a4f 100644 --- a/tests/Filee.Core.Tests/FormatFieldsTests.cs +++ b/tests/Filee.Core.Tests/FormatFieldsTests.cs @@ -34,7 +34,7 @@ private static string[] Hidden(IReadOnlySet turnedOff) => "mod", "mp2", "mpc", "mrpack", "msix", "mxf", "nex", "nov", "nupkg", "obj", "oeb", "org", "osm", "otf", "pal", "pam", "pcd", "pcx", "pdb", "pdn", "pfm", "phy", "plist", "plt", "ply", "pml", "ppm", "prc", "ps", "psb", "psd", "psw", "qoi", "ras", "raw", "rb", "rm", "rpm", "rst", "s3m", "scc", "sda", "sdc", "sdw", "sgi", "shp", "smd", "snb", "spx", - "ssa", "stl", "sub", "swf", "tak", "tar", "tar7z", "tbz2", "tcr", "tex", "textile", "tgz", "tlz", "toml", + "ssa", "stl", "sub", "sup", "swf", "tak", "tar", "tar7z", "tbz2", "tcr", "tex", "textile", "tgz", "tlz", "toml", "tta", "ttf", "ttml", "txtz", "txz", "typ", "tz", "tzst", "usm", "vob", "voc", "vpk", "vtf", "w64", "wbmp", "wmf", "woff", "woff2", "wpd", "wtv", "wv", "xbm", "xcf", "xlt", "xm", "xpm", "xz", "yaml", "z", "zst", "zxp" ]; @@ -55,7 +55,7 @@ private static string[] Hidden(IReadOnlySet turnedOff) => ] }, { "writing", ["adoc", "cgm", "dbk", "htmlz", "mediawiki", "org", "rst", "tex", "textile", "txtz", "typ"] }, { "video-pro", [ - "ac3", "ass", "cavs", "dav", "dts", "dv", "eac3", "h264", "h265", "mp2", "mxf", "nov", "scc", "ssa", "ttml" + "ac3", "ass", "cavs", "dav", "dts", "dv", "eac3", "h264", "h265", "mp2", "mxf", "nov", "scc", "ssa", "sup", "ttml" ] }, { "audio-pro", ["ape", "dff", "dsf", "dss", "tak", "tta", "w64", "wv"] }, { "legacy", [ @@ -82,7 +82,7 @@ private static string[] Hidden(IReadOnlySet turnedOff) => ] }, { "writing", ["adoc", "cgm", "chm", "dbk", "htmlz", "mediawiki", "org", "rst", "tex", "textile", "txtz", "typ"] }, { "video-pro", [ - "ac3", "ass", "cavs", "dav", "dts", "dv", "eac3", "h264", "h265", "mp2", "mxf", "nov", "scc", "ssa", "ttml" + "ac3", "ass", "cavs", "dav", "dts", "dv", "eac3", "h264", "h265", "mp2", "mxf", "nov", "scc", "ssa", "sup", "ttml" ] }, { "audio-pro", ["ape", "caf", "dff", "dsf", "dss", "it", "mpc", "s3m", "tak", "tta", "w64", "wv", "xm"] }, { "legacy", [ @@ -145,7 +145,7 @@ public void Grade_counts_match_the_published_table() { [FormatGrade.Everyday] = 19, [FormatGrade.General] = 101, - [FormatGrade.Specialist] = 146, + [FormatGrade.Specialist] = 147, [FormatGrade.Legacy] = 52, }, counts); diff --git a/tests/Filee.Core.Tests/OcrRouteTests.cs b/tests/Filee.Core.Tests/OcrRouteTests.cs index 5834fbb99..7cd1c179b 100644 --- a/tests/Filee.Core.Tests/OcrRouteTests.cs +++ b/tests/Filee.Core.Tests/OcrRouteTests.cs @@ -136,6 +136,34 @@ public async Task Source_bookmarks_keep_original_names_after_ocr(bool normalizeP Assert.StartsWith(JobQueue.DefaultWorkRoot + Path.DirectorySeparatorChar, input.PdfPath)); } + [Fact] + public void Blu_ray_sup_routes_to_srt_and_chains_through_subtitle_engine_without_pdf_ocr_flag() + { + var planner = new RoutePlanner([ + new FakeConverter("tesseract", [.. OcrEdges, new("sup", "srt"), new("sup", "txt", DirectOnly: true)]), + new FakeConverter("subtitle", + new ConversionEdge("srt", "ass"), + new ConversionEdge("srt", "vtt"), + new ConversionEdge("srt", "ttml"), + new ConversionEdge("srt", "smi"), + new ConversionEdge("srt", "lrc"), + new ConversionEdge("srt", "sub"), + new ConversionEdge("srt", "txt", DirectOnly: true)), + new FakeConverter("docx", new ConversionEdge("txt", "docx")), + ]); + + Assert.Equal("tesseract:sup→srt", Steps(planner.Plan("sup", "srt"))); + Assert.Equal("tesseract:sup→srt, subtitle:srt→ass", Steps(planner.Plan("sup", "ass"))); + Assert.Equal("tesseract:sup→srt, subtitle:srt→vtt", Steps(planner.Plan("sup", "vtt"))); + Assert.Equal("tesseract:sup→srt, subtitle:srt→ttml", Steps(planner.Plan("sup", "ttml"))); + Assert.Equal("tesseract:sup→srt, subtitle:srt→smi", Steps(planner.Plan("sup", "smi"))); + Assert.Equal("tesseract:sup→srt, subtitle:srt→lrc", Steps(planner.Plan("sup", "lrc"))); + Assert.Equal("tesseract:sup→srt, subtitle:srt→sub", Steps(planner.Plan("sup", "sub"))); + Assert.Equal("tesseract:sup→txt", Steps(planner.Plan("sup", "txt"))); + // DirectOnly on sup → txt prevents chaining subtitles into documents. + Assert.Null(planner.Plan("sup", "docx")); + } + [Fact] public void A_version_39_library_gets_searchable_pdf_after_compress_pdf() { diff --git a/tests/Filee.Core.Tests/SupFormatTests.cs b/tests/Filee.Core.Tests/SupFormatTests.cs new file mode 100644 index 000000000..920f3de79 --- /dev/null +++ b/tests/Filee.Core.Tests/SupFormatTests.cs @@ -0,0 +1,51 @@ +// Blu-ray picture subtitles (.sup, #1872): read-only specialist subtitle format on the subtitles donut, learned by +// existing libraries without taking custom claims. + +using Filee.Core.Formats; +using Filee.Core.Presets; +using Filee.Core.Profiles; +using Filee.Core.Settings; + +namespace Filee.Core.Tests; + +public class SupFormatTests +{ + [Theory] + [InlineData("movie.sup")] + [InlineData("MOVIE.SUP")] + public void Blu_ray_subtitles_use_the_subtitles_donut(string file) + { + Assert.Same(FormatRegistry.Get("sup"), FormatRegistry.Detect(file)); + Assert.Equal("subtitles", ProfileSelector.Select(BuiltInData.CreateProfiles(), [file])?.Id); + } + + [Fact] + public void It_is_read_only_and_classed_as_ass_and_scc_are() + { + var sup = FormatRegistry.Get("sup"); + Assert.Equal(FormatCategory.Subtitle, sup.Category); + Assert.False(sup.Writable); + Assert.Equal(FormatGrade.Specialist, FormatFields.GradeOf(sup)); + Assert.Equal(["video-pro"], FormatFields.Of(sup).Select(f => f.Id)); + } + + [Fact] + public void Version_111_libraries_learn_sup_without_taking_custom_claims() + { + var presets = BuiltInData.CreatePresets(); + var profiles = BuiltInData.CreateProfiles(); + var subtitles = profiles.Single(p => p.Id == "subtitles"); + subtitles.Extensions.Remove("sup"); + + Assert.True(SettingsMigrations.ApplyToLibrary(111, presets, profiles)); + Assert.Contains("sup", subtitles.Extensions); + Assert.False(SettingsMigrations.ApplyToLibrary(111, presets, profiles)); + Assert.False(SettingsMigrations.ApplyToLibrary(112, presets, profiles)); + + subtitles.Extensions.Remove("sup"); + profiles.Insert(0, new ToolbarProfile { Id = "my-subs", Extensions = ["SUP"] }); + Assert.False(SettingsMigrations.ApplyToLibrary(111, presets, profiles)); + Assert.DoesNotContain("sup", subtitles.Extensions); // the user's own donut has it + Assert.Equal("my-subs", ProfileSelector.Select(profiles, ["movie.sup"])?.Id); + } +} diff --git a/tests/Filee.Engines.Tests/PgsTests.cs b/tests/Filee.Engines.Tests/PgsTests.cs new file mode 100644 index 000000000..3a8690e0f --- /dev/null +++ b/tests/Filee.Engines.Tests/PgsTests.cs @@ -0,0 +1,583 @@ +// Blu-ray PGS (.sup) reader, OCR preparation, Vision stand-in pipeline and real Tesseract end-to-end tests (#1872). + +using System.Buffers.Binary; +using Filee.Core.Conversion; +using Filee.Core.Presets; +using Filee.Engines.Infrastructure; +using Filee.Engines.Ocr; +using Filee.Engines.Subtitles; +using ImageMagick; +using ImageMagick.Drawing; + +namespace Filee.Engines.Tests; + +/// Builds synthetic Blu-ray PGS (.sup) streams in memory for unit and OCR tests. +internal sealed class PgsBuilder +{ + private readonly MemoryStream _stream = new(); + private ushort _compositionNumber; + + public PgsBuilder AddDisplaySet( + TimeSpan pts, + byte state, + byte paletteId, + IReadOnlyList<(byte Id, byte Y, byte Cr, byte Cb, byte A)>? palette, + IReadOnlyList<(ushort ObjectId, int Width, int Height, byte[] Indices, int MaxFragmentBytes)>? objects, + IReadOnlyList<(ushort ObjectId, int X, int Y, (int X, int Y, int W, int H)? Crop)> compositionObjects, + bool paletteUpdateOnly = false) + { + var ptsTicks = (uint)Math.Round(pts.TotalSeconds * 90_000); + WritePcs(ptsTicks, state, paletteUpdateOnly, paletteId, compositionObjects); + WriteWds(ptsTicks, compositionObjects.Count > 0 ? 1 : 0); + if (palette is not null) + WritePds(ptsTicks, paletteId, palette); + if (objects is not null) + { + foreach (var obj in objects) + WriteOds(ptsTicks, obj.ObjectId, obj.Width, obj.Height, obj.Indices, obj.MaxFragmentBytes); + } + WriteSegment(ptsTicks, 0x80, []); + return this; + } + + public PgsBuilder Clear(TimeSpan pts) => + AddDisplaySet(pts, state: 0x00, paletteId: 0, palette: null, objects: null, compositionObjects: []); + + public PgsBuilder AddRawSegment(uint pts, byte type, ReadOnlySpan payload) + { + WriteSegment(pts, type, payload); + return this; + } + + public byte[] ToArray() => _stream.ToArray(); + + /// Renders white text with a black outline on a transparent canvas into a 3-entry palette bitmap. + public static (int Width, int Height, byte[] Indices) RenderTextBitmap(string text, int width = 480, int height = 80, double pointSize = 36) + { + var font = EngineEnvironment.FirstExisting( + @"C:\Windows\Fonts\arial.ttf", + "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", + "/System/Library/Fonts/Supplemental/Arial.ttf"); + using var image = new MagickImage(MagickColors.Transparent, (uint)width, (uint)height); + var draw = new Drawables() + .FontPointSize(pointSize) + .StrokeColor(MagickColors.Black) + .StrokeWidth(2) + .FillColor(MagickColors.White); + if (font is not null) + draw.Font(font); + draw.Text(20, height - 22, text).Draw(image); + + var rgba = image.GetPixels().ToByteArray(PixelMapping.RGBA)!; + var indices = new byte[width * height]; + for (var i = 0; i < indices.Length; i++) + { + var r = rgba[i * 4]; + var g = rgba[i * 4 + 1]; + var b = rgba[i * 4 + 2]; + var a = rgba[i * 4 + 3]; + if (a < 64) + indices[i] = 0; // transparent + else + indices[i] = (r + g + b) / 3 >= 128 ? (byte)1 : (byte)2; // 1 = white fill, 2 = black outline + } + return (width, height, indices); + } + + public static IReadOnlyList<(byte Id, byte Y, byte Cr, byte Cb, byte A)> DefaultPalette => + [ + (0, 16, 128, 128, 0), // transparent + (1, 235, 128, 128, 255), // opaque white + (2, 16, 128, 128, 255), // opaque black outline + ]; + + /// Encodes palette indices using every PGS RLE code form (single, short/long zero, short/long colour, EOL). + public static byte[] EncodeRle(ReadOnlySpan indices, int width, int height) + { + using var ms = new MemoryStream(); + for (var y = 0; y < height; y++) + { + var row = indices.Slice(y * width, width); + var x = 0; + while (x < width) + { + var color = row[x]; + var run = 1; + while (x + run < width && row[x + run] == color && run < 16383) + run++; + + if (color == 0) + { + if (run < 64) + { + ms.WriteByte(0x00); + ms.WriteByte((byte)run); + } + else + { + ms.WriteByte(0x00); + ms.WriteByte((byte)(0x40 | (run >> 8))); + ms.WriteByte((byte)(run & 0xFF)); + } + } + else if (run == 1) + { + ms.WriteByte(color); + } + else if (run < 64) + { + ms.WriteByte(0x00); + ms.WriteByte((byte)(0x80 | run)); + ms.WriteByte(color); + } + else + { + ms.WriteByte(0x00); + ms.WriteByte((byte)(0xC0 | (run >> 8))); + ms.WriteByte((byte)(run & 0xFF)); + ms.WriteByte(color); + } + x += run; + } + ms.WriteByte(0x00); + ms.WriteByte(0x00); // EOL + } + return ms.ToArray(); + } + + private void WritePcs( + uint pts, + byte state, + bool paletteUpdateOnly, + byte paletteId, + IReadOnlyList<(ushort ObjectId, int X, int Y, (int X, int Y, int W, int H)? Crop)> objs) + { + using var ms = new MemoryStream(); + WriteU16(ms, 1920); + WriteU16(ms, 1080); + ms.WriteByte(0x10); // 23.976 fps + WriteU16(ms, _compositionNumber++); + ms.WriteByte(state); + ms.WriteByte(paletteUpdateOnly ? (byte)0x80 : (byte)0x00); + ms.WriteByte(paletteId); + ms.WriteByte((byte)objs.Count); + foreach (var (id, x, y, crop) in objs) + { + WriteU16(ms, id); + ms.WriteByte(0); // window id + ms.WriteByte(crop.HasValue ? (byte)0x40 : (byte)0x00); + WriteU16(ms, (ushort)x); + WriteU16(ms, (ushort)y); + if (crop is { } c) + { + WriteU16(ms, (ushort)c.X); + WriteU16(ms, (ushort)c.Y); + WriteU16(ms, (ushort)c.W); + WriteU16(ms, (ushort)c.H); + } + } + WriteSegment(pts, 0x16, ms.ToArray()); + } + + private void WriteWds(uint pts, int count) + { + using var ms = new MemoryStream(); + ms.WriteByte((byte)count); + if (count > 0) + { + ms.WriteByte(0); + WriteU16(ms, 0); + WriteU16(ms, 0); + WriteU16(ms, 1920); + WriteU16(ms, 1080); + } + WriteSegment(pts, 0x17, ms.ToArray()); + } + + private void WritePds(uint pts, byte paletteId, IReadOnlyList<(byte Id, byte Y, byte Cr, byte Cb, byte A)> entries) + { + using var ms = new MemoryStream(); + ms.WriteByte(paletteId); + ms.WriteByte(0); + foreach (var (id, y, cr, cb, a) in entries) + { + ms.WriteByte(id); + ms.WriteByte(y); + ms.WriteByte(cr); + ms.WriteByte(cb); + ms.WriteByte(a); + } + WriteSegment(pts, 0x14, ms.ToArray()); + } + + private void WriteOds(uint pts, ushort objectId, int width, int height, byte[] indices, int maxFragmentBytes) + { + var rle = EncodeRle(indices, width, height); + var chunkSize = maxFragmentBytes > 0 ? maxFragmentBytes : rle.Length; + var offset = 0; + var first = true; + do + { + var take = Math.Min(chunkSize, rle.Length - offset); + var last = offset + take >= rle.Length; + using var ms = new MemoryStream(); + WriteU16(ms, objectId); + ms.WriteByte(0); // version + byte seq = 0; + if (first) seq |= 0x80; + if (last) seq |= 0x40; + ms.WriteByte(seq); + if (first) + { + var dataLen = rle.Length + 4; + ms.WriteByte((byte)(dataLen >> 16)); + ms.WriteByte((byte)(dataLen >> 8)); + ms.WriteByte((byte)dataLen); + WriteU16(ms, (ushort)width); + WriteU16(ms, (ushort)height); + } + ms.Write(rle, offset, take); + WriteSegment(pts, 0x15, ms.ToArray()); + offset += take; + first = false; + } + while (offset < rle.Length); + } + + private void WriteSegment(uint pts, byte type, ReadOnlySpan payload) + { + Span header = stackalloc byte[13]; + header[0] = (byte)'P'; + header[1] = (byte)'G'; + BinaryPrimitives.WriteUInt32BigEndian(header[2..6], pts); + BinaryPrimitives.WriteUInt32BigEndian(header[6..10], 0); + header[10] = type; + BinaryPrimitives.WriteUInt16BigEndian(header[11..13], (ushort)payload.Length); + _stream.Write(header); + _stream.Write(payload); + } + + private static void WriteU16(Stream s, ushort value) + { + s.WriteByte((byte)(value >> 8)); + s.WriteByte((byte)value); + } +} + +public class PgsTests(EngineFixture fx) : IClassFixture +{ + private static readonly bool Installed = TesseractConverter.Locate() is not null && !new VisionConverter().GetStatus().IsAvailable; + + private const string Skip = "Tesseract is not installed (pwsh build/fetch-engines.ps1 -Only 7zip,tesseract), or Apple Vision reads instead"; + + private static byte[] Solid(int w, int h, byte color) + { + var data = new byte[w * h]; + data.AsSpan().Fill(color); + return data; + } + + private static List ReadAll(byte[] data, CancellationToken cancellationToken) + { + using var stream = new MemoryStream(data, writable: false); + return [.. PgsReader.Read(stream, cancellationToken)]; + } + + [Fact] + public void Reader_streams_first_caption_before_reading_rest_of_stream() + { + var sup = new PgsBuilder() + .AddDisplaySet(TimeSpan.FromSeconds(1), 0x80, 0, PgsBuilder.DefaultPalette, + [(1, 4, 2, Solid(4, 2, 1), 0)], [(1, 100, 900, null)]) + .Clear(TimeSpan.FromSeconds(2)) + .AddDisplaySet(TimeSpan.FromSeconds(3), 0x80, 0, PgsBuilder.DefaultPalette, + [(2, 4, 2, Solid(4, 2, 1), 0)], [(2, 100, 900, null)]) + .Clear(TimeSpan.FromSeconds(4)) + .AddDisplaySet(TimeSpan.FromSeconds(5), 0x80, 0, PgsBuilder.DefaultPalette, + [(3, 4, 2, Solid(4, 2, 1), 0)], [(3, 100, 900, null)]) + .Clear(TimeSpan.FromSeconds(6)) + .ToArray(); + + using var stream = new MemoryStream(sup, writable: false); + using var enumerator = PgsReader.Read(stream, TestContext.Current.CancellationToken).GetEnumerator(); + + Assert.True(enumerator.MoveNext()); + Assert.Equal(TimeSpan.FromSeconds(1), enumerator.Current.Start); + Assert.Equal(TimeSpan.FromSeconds(2), enumerator.Current.End); + Assert.True(stream.Position < stream.Length, $"Expected streaming read, but stream reached {stream.Position}/{stream.Length}."); + + Assert.True(enumerator.MoveNext()); + Assert.Equal(TimeSpan.FromSeconds(3), enumerator.Current.Start); + Assert.True(stream.Position < stream.Length); + + Assert.True(enumerator.MoveNext()); + Assert.Equal(TimeSpan.FromSeconds(5), enumerator.Current.Start); + Assert.False(enumerator.MoveNext()); + } + + [Fact] + public void Timings_handle_clear_direct_replacement_palette_update_and_open_end() + { + var sup = new PgsBuilder() + // Caption 1: 1.0s → 2.5s (cleared) + .AddDisplaySet(TimeSpan.FromSeconds(1), 0x80, 0, PgsBuilder.DefaultPalette, + [(1, 4, 2, Solid(4, 2, 1), 0)], [(1, 100, 900, null)]) + // Palette-only update during caption 1 (fade-in/out): must NOT split into a second caption. + .AddDisplaySet(TimeSpan.FromSeconds(1.5), 0x00, 0, [(0, 16, 128, 128, 0), (1, 235, 128, 128, 128)], + null, [], paletteUpdateOnly: true) + .Clear(TimeSpan.FromSeconds(2.5)) + // Caption 2: 4.0s → 6.0s (replaced directly by caption 3 without a clear) + .AddDisplaySet(TimeSpan.FromSeconds(4), 0x80, 0, PgsBuilder.DefaultPalette, + [(2, 4, 2, Solid(4, 2, 1), 0)], [(2, 100, 900, null)]) + // Caption 3: 6.0s → open end (+5s = 11.0s), reuses object 2 within the same epoch + .AddDisplaySet(TimeSpan.FromSeconds(6), 0x00, 0, null, + null, [(2, 100, 850, null)]) + .ToArray(); + + var captions = ReadAll(sup, TestContext.Current.CancellationToken); + + Assert.Equal(3, captions.Count); + Assert.Equal(TimeSpan.FromSeconds(1), captions[0].Start); + Assert.Equal(TimeSpan.FromSeconds(2.5), captions[0].End); + // Stronger-alpha render from initial display set was kept over dimmed fade palette update. + Assert.Equal(255, captions[0].Objects[0].Rgba[3]); + + Assert.Equal(TimeSpan.FromSeconds(4), captions[1].Start); + Assert.Equal(TimeSpan.FromSeconds(6), captions[1].End); + + Assert.Equal(TimeSpan.FromSeconds(6), captions[2].Start); + Assert.Equal(TimeSpan.FromSeconds(11), captions[2].End); + } + + [Fact] + public void Rle_round_trips_every_code_form_and_pads_short_rows() + { + const int width = 300; + const int height = 3; + var expected = new byte[width * height]; + // Row 0: single pixel (1), short zero run (10), short colour run (20 of 2), long zero run (100), long colour run (169 of 3) + expected[0] = 1; + expected.AsSpan(11, 20).Fill(2); + expected.AsSpan(131, 169).Fill(3); + // Row 1: full long zero run (300) + // Row 2: short row encoded manually (only 5 pixels then EOL; rest must stay 0) + expected.AsSpan(2 * width, 5).Fill(4); + + var rle = PgsBuilder.EncodeRle(expected, width, height); + var decoded = PgsReader.DecodeRle(rle, width, height); + Assert.Equal(expected, decoded); + + // Explicitly verify a short row terminated early by EOL is padded with 0. + byte[] shortRowRle = [0x04, 0x04, 0x00, 0x00, 0x05, 0x00, 0x00]; + var padded = PgsReader.DecodeRle(shortRowRle, 6, 2); + Assert.Equal([4, 4, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0], padded); + } + + [Fact] + public void Object_split_across_multiple_ods_fragments_and_cropped_decodes_cleanly() + { + const int width = 20; + const int height = 10; + var indices = new byte[width * height]; + for (var y = 0; y < height; y++) + for (var x = 0; x < width; x++) + indices[y * width + x] = (byte)(x >= 4 && x < 14 && y >= 2 && y < 7 ? 1 : 2); + + // MaxFragmentBytes = 8 splits the RLE across multiple ODS segments (first, middle, last). + var sup = new PgsBuilder() + .AddDisplaySet(TimeSpan.FromSeconds(1), 0x80, 0, PgsBuilder.DefaultPalette, + [(7, width, height, indices, 8)], + [(7, 50, 100, (4, 2, 10, 5))]) + .Clear(TimeSpan.FromSeconds(2)) + .ToArray(); + + var caption = Assert.Single(ReadAll(sup, TestContext.Current.CancellationToken)); + var bmp = Assert.Single(caption.Objects); + Assert.Equal(10, bmp.Width); + Assert.Equal(5, bmp.Height); + // Every pixel inside the cropped rect was palette index 1 (opaque white). + for (var i = 0; i < bmp.Rgba.Length; i += 4) + Assert.Equal([255, 255, 255, 255], bmp.Rgba[i..(i + 4)]); + } + + [Fact] + public void Palette_converts_bt709_white_and_black_and_keeps_alpha() + { + Assert.Equal((255, 255, 255), PgsReader.YCbCrToRgb(235, 128, 128)); + Assert.Equal((0, 0, 0), PgsReader.YCbCrToRgb(16, 128, 128)); + + var sup = new PgsBuilder() + .AddDisplaySet(TimeSpan.FromSeconds(1), 0x80, 0, + [(0, 16, 128, 128, 0), (1, 235, 128, 128, 200), (2, 16, 128, 128, 120)], + [(1, 3, 1, [0, 1, 2], 0)], + [(1, 0, 0, null)]) + .Clear(TimeSpan.FromSeconds(2)) + .ToArray(); + + var bmp = Assert.Single(Assert.Single(ReadAll(sup, TestContext.Current.CancellationToken)).Objects); + Assert.Equal([0, 0, 0, 0, 255, 255, 255, 200, 0, 0, 0, 120], bmp.Rgba); + } + + [Fact] + public void Malformed_inputs_are_refused_or_stopped_without_hanging() + { + var ct = TestContext.Current.CancellationToken; + // Not starting with "PG" + var ex = Assert.Throws(() => ReadAll("not a pgs file at all"u8.ToArray(), ct)); + Assert.Equal("error.sup_no_captions", ex.ErrorKey); + + // Truncated segment right after magic + ex = Assert.Throws(() => ReadAll([(byte)'P', (byte)'G', 0, 0, 0, 1, 0, 0, 0, 0, 0x16, 0x00, 0xFF], ct)); + Assert.Equal("error.sup_no_captions", ex.ErrorKey); + + // RLE run past row width must never throw or overwrite the next row + byte[] overflowRle = [0x00, 0x80 | 50, 0x01, 0x00, 0x00, 0x02, 0x00, 0x00]; + var decoded = PgsReader.DecodeRle(overflowRle, 4, 2); + Assert.Equal([1, 1, 1, 1, 2, 0, 0, 0], decoded); + + // Absurd ODS dimensions (6000 × 6000 > MaxObjectPixels) are skipped cleanly -> no captions -> refused + byte[] hugeOds = [0x00, 0x01, 0x00, 0xC0, 0x00, 0x00, 0x06, 0x17, 0x70, 0x17, 0x70, 0x00, 0x00]; + var badSup = new PgsBuilder() + .AddDisplaySet(TimeSpan.FromSeconds(1), 0x80, 0, PgsBuilder.DefaultPalette, null, [(1, 0, 0, null)]) + .AddRawSegment(90_000, 0x15, hugeOds) + .AddRawSegment(90_000, 0x80, []) + .ToArray(); + ex = Assert.Throws(() => ReadAll(badSup, ct)); + Assert.Equal("error.sup_no_captions", ex.ErrorKey); + } + + [Fact] + public void Ocr_preparation_inverts_white_on_transparent_pads_and_scales_small_bitmaps() + { + // Small bitmap (8 × 8, height < 100): 4×4 white block at (0..3, 0..3), black outline at (4,0), transparent at (5,0) + var rgba = new byte[8 * 8 * 4]; + for (var y = 0; y < 4; y++) + for (var x = 0; x < 4; x++) + { + var p = (y * 8 + x) * 4; + rgba[p] = 255; rgba[p + 1] = 255; rgba[p + 2] = 255; rgba[p + 3] = 255; // white glyph → black (0) + } + rgba[4 * 4 + 3] = 255; // black outline → white (255) + rgba[5 * 4] = 255; rgba[5 * 4 + 1] = 255; rgba[5 * 4 + 2] = 255; // transparent → white (255) + + using var small = SubtitleOcr.PrepareBitmap(new PgsBitmap(0, 0, 8, 8, rgba)); + Assert.Equal((8 + SubtitleOcr.Padding * 2) * 2, small.Width); + Assert.Equal((8 + SubtitleOcr.Padding * 2) * 2, small.Height); + // Corner padding is pure white; interior of the scaled white glyph is dark. + Assert.Equal(255, small.GetPixel(0, 0).Red); + Assert.True(small.GetPixel((SubtitleOcr.Padding + 2) * 2, (SubtitleOcr.Padding + 2) * 2).Red < 40); + Assert.Equal(255, small.GetPixel((SubtitleOcr.Padding + 5) * 2, SubtitleOcr.Padding * 2).Red); + + // Tall bitmap (10 × 120, height >= 100): padded only, NOT doubled. + var tallRgba = new byte[10 * 120 * 4]; + tallRgba[0] = 255; tallRgba[1] = 255; tallRgba[2] = 255; tallRgba[3] = 255; + using var tall = SubtitleOcr.PrepareBitmap(new PgsBitmap(0, 0, 10, 120, tallRgba)); + Assert.Equal(10 + SubtitleOcr.Padding * 2, tall.Width); + Assert.Equal(120 + SubtitleOcr.Padding * 2, tall.Height); + Assert.Equal(0, tall.GetPixel(SubtitleOcr.Padding, SubtitleOcr.Padding).Red); + Assert.Equal(255, tall.GetPixel(SubtitleOcr.Padding + 1, SubtitleOcr.Padding).Red); + } + + [Fact] + public void Text_cleanup_handles_cjk_korean_and_form_feed_splitting() + { + Assert.Equal("你好世界", SubtitleOcr.CleanText(" 你 好 世 界 \r\n\r\n")); + Assert.Equal("안녕하세요 세상", SubtitleOcr.CleanText("안녕하세요 세상")); + Assert.Equal("Hello world\nSecond line", SubtitleOcr.CleanText(" Hello world \n\n Second line \f")); + + var withTrailing = SubtitleOcr.TrySplitPages("one\n\ftwo\n\f", 2); + Assert.NotNull(withTrailing); + Assert.Equal(["one\n", "two\n"], withTrailing); + var withoutTrailing = SubtitleOcr.TrySplitPages("one\ftwo", 2); + Assert.NotNull(withoutTrailing); + Assert.Equal(["one", "two"], withoutTrailing); + Assert.Null(SubtitleOcr.TrySplitPages("only one", 2)); + } + + [Fact] + public async Task Two_objects_in_one_display_set_come_out_top_to_bottom_through_vision_pipeline() + { + var folder = fx.NewFolder(); + var supPath = Path.Combine(folder, "two-lines.sup"); + // Put the lower object FIRST in the PCS with distinct widths (10 vs 20) to verify Y-then-X ordering deterministically. + var sup = new PgsBuilder() + .AddDisplaySet(TimeSpan.FromSeconds(1), 0x80, 0, PgsBuilder.DefaultPalette, + [(1, 10, 10, Solid(10, 10, 1), 0), (2, 20, 10, Solid(20, 10, 1), 0)], + [(2, 100, 950, null), (1, 100, 880, null)]) + .Clear(TimeSpan.FromSeconds(3)) + .ToArray(); + await File.WriteAllBytesAsync(supPath, sup, TestContext.Current.CancellationToken); + + var fakeVision = new WidthRecognizer(); + var catalog = new ConverterCatalog([new VisionConverter(fakeVision, new VisionFakes.Tesseract(false)), new SubtitleConverter()]); + + var job = await fx.ConvertAsync([supPath], new Preset { TargetFormat = "srt" }, catalog); + + Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}"))); + var cues = SubtitleReader.Read("srt", await File.ReadAllBytesAsync(job.Outputs.Single(), TestContext.Current.CancellationToken)).Cues; + var cue = Assert.Single(cues); + Assert.Equal(TimeSpan.FromSeconds(1), cue.Start); + Assert.Equal(TimeSpan.FromSeconds(3), cue.End); + Assert.Equal("Top line\nBottom line", cue.Text); + } + + [Fact] + public async Task Real_tesseract_converts_two_caption_sup_to_srt_ass_and_txt() + { + Assert.SkipUnless(Installed, Skip); + var folder = fx.NewFolder(); + var supPath = Path.Combine(folder, "sample.sup"); + var first = PgsBuilder.RenderTextBitmap("Hello world"); + var second = PgsBuilder.RenderTextBitmap("Second line"); + var sup = new PgsBuilder() + .AddDisplaySet(TimeSpan.FromSeconds(1), 0x80, 0, PgsBuilder.DefaultPalette, + [(1, first.Width, first.Height, first.Indices, 0)], [(1, 200, 900, null)]) + .Clear(TimeSpan.FromSeconds(3)) + .AddDisplaySet(TimeSpan.FromSeconds(4), 0x80, 0, PgsBuilder.DefaultPalette, + [(2, second.Width, second.Height, second.Indices, 0)], [(2, 200, 900, null)]) + .Clear(TimeSpan.FromSeconds(6)) + .ToArray(); + await File.WriteAllBytesAsync(supPath, sup, TestContext.Current.CancellationToken); + + // .sup → .srt + var srtJob = await fx.ConvertAsync([supPath], new Preset { TargetFormat = "srt" }); + Assert.True(srtJob.State == JobState.Completed, string.Join("; ", srtJob.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}"))); + var cues = SubtitleReader.Read("srt", await File.ReadAllBytesAsync(srtJob.Outputs.Single(), TestContext.Current.CancellationToken)).Cues; + Assert.Equal(2, cues.Count); + Assert.Contains("hello world", cues[0].Text, StringComparison.OrdinalIgnoreCase); + Assert.Equal(TimeSpan.FromSeconds(1), cues[0].Start); + Assert.Equal(TimeSpan.FromSeconds(3), cues[0].End); + Assert.Contains("second line", cues[1].Text, StringComparison.OrdinalIgnoreCase); + Assert.Equal(TimeSpan.FromSeconds(4), cues[1].Start); + Assert.Equal(TimeSpan.FromSeconds(6), cues[1].End); + + // .sup → .ass via route planner (tesseract:sup→srt, subtitle:srt→ass) + var assJob = await fx.ConvertAsync([supPath], new Preset { TargetFormat = "ass" }); + Assert.True(assJob.State == JobState.Completed, string.Join("; ", assJob.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}"))); + var assText = await File.ReadAllTextAsync(assJob.Outputs.Single(), TestContext.Current.CancellationToken); + Assert.Contains("[Events]", assText); + Assert.Contains("hello world", assText, StringComparison.OrdinalIgnoreCase); + Assert.Contains("second line", assText, StringComparison.OrdinalIgnoreCase); + + // .sup → .txt direct + var txtJob = await fx.ConvertAsync([supPath], new Preset { TargetFormat = "txt" }); + Assert.True(txtJob.State == JobState.Completed, string.Join("; ", txtJob.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}"))); + var txt = await File.ReadAllTextAsync(txtJob.Outputs.Single(), TestContext.Current.CancellationToken); + Assert.Contains("hello world", txt, StringComparison.OrdinalIgnoreCase); + Assert.Contains("second line", txt, StringComparison.OrdinalIgnoreCase); + } + + private sealed class WidthRecognizer : ITextRecognizer + { + public bool IsAvailable => true; + public IReadOnlyCollection Languages => ["en-US"]; + + public IReadOnlyList Recognize(string picture, IReadOnlyList languages, CancellationToken cancellationToken) + { + using var info = new MagickImage(); + info.Ping(picture); + // Top object (width 10) becomes (10 + 32) * 2 = 84 px wide; bottom (width 20) becomes (20 + 32) * 2 = 104 px wide. + return [OcrLine.Estimate(info.Width == 84 ? "Top line" : "Bottom line", 0.1, 0.5, 0.8, 0.1)]; + } + } +}