Offer VobSub conversion for PGS subtitle tracks
The subtitle import sheet gains a VobSub action for PGS-format tracks (default following the bitmap-subtitle conversion preference), which muxes them as real subp tracks via the framework's new MP42PgsToVobSubConverter instead of only offering OCR'd tx3g text. Localized for all six shipping languages. Also names any flagged subtitle track "SDH" (the recognized community tokens now share one name) and documents the MKV conversion-path naming and the PGS-to-VobSub machinery in CLAUDE.md. Bumps the MP42Foundation submodule for the converter and the filename/TrackName SDH recognizer. Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
1 parent
5d6c0cd84c
commit
dd956fa783
9 files changed
+29
-4
No files matched your search
@@ -37,7 +37,7 @@ Two layers with a strict boundary:
|
|||||||
- **Document flow**: `Document.swift` (NSDocument subclass) owns the opened file; `read(from:)` produces an `MP42File`. `DocumentWindowController` hosts the per-document window (tracks table, property view tabs). Export goes through `Document.save(to:...)` / `SaveOptions` and runs asynchronously; `sendToQueue` hands the document to the queue instead.
|
- **Document flow**: `Document.swift` (NSDocument subclass) owns the opened file; `read(from:)` produces an `MP42File`. `DocumentWindowController` hosts the per-document window (tracks table, property view tabs). Export goes through `Document.save(to:...)` / `SaveOptions` and runs asynchronously; `sendToQueue` hands the document to the queue instead.
|
||||||
- **MKV tags-only mode**: `.mkv/.mka/.mks` open directly (`DocumentController.openDocument` in `AppDelegate.swift` passes them through instead of forcing the convert-import sheet). `Document.isMatroska` then drives everything: the model is an in-memory `MP42File` filled from `MP42FileImporter` in **tagsOnly mode** (`initWithURL:tagsOnly:` — mirrors the file's own `TrackFlagEnabled` instead of the MP4 "first-of-type enabled" heuristic, so untouched tracks don't look edited), Save branches in `Document.writeMatroska`: plain edits rewrite metadata + per-track fields in place via `MP42MkvTagWriter` (never touching clusters), while **deleted/added tracks or Save-As** trigger a stream-copy rebuild via `MP42MkvRemuxer` (temp file + atomic rename even in place; `hasFileRepresentation == false` still keeps `sendToQueue` on its conversion branch; destination must stay mkv/mka/mks). The remuxer pairs `TrackEntry` elements against `Document.mkvSourceTracks` — an importer-order snapshot taken in `readMatroska` — with keep/drop decided by **object identity**, so the deletion check is immune to model index shifts; after a successful remux the snapshot is re-filtered in the same order **plus the added tracks appended** (matching the order the remuxer writes their TrackEntry elements last in the output). Subtitle tracks can be **added** to MKV docs (`.srt`/`.ssa`/`.ass` only): `DocumentWindowController.selectFile`/`showImportSheet` route MKV docs to `importSubtitleTracksForMatroska` (direct `MP42FileImporter` per file, no track-selection sheet; the accepted-extension list `matroskaSubtitleExtensions` must stay in sync with the remuxer's gate), and the `didSelect`/AppleScript `importFilesDirectly` path skips `organizeAlternateGroups`/`inferMediaCharacteristics` for MKV for the same pairing-protection reason. The AppleScript `save as` command (ScriptCommand.swift) must route Matroska docs through `Document.save(...)` — the raw `mp4.write(to:)` path would mux QuickTime atoms over an MKV document. Reordering must never happen on MKV docs (it would break the pairing): drag stays blocked and `DocumentWindowController.delete(tracks:)` skips `organizeAlternateGroups`/`inferMediaCharacteristics` for MKV. Save-As is enabled for MKV, and so is **File ▸ Optimize** (`saveAndOptimize`): on Matroska documents optimize means `writeMatroska`'s forced structural branch — a full remuxer rebuild of the file from the existing tracks (the container-equivalent of QuickTime atom-ordering), not `MP42File optimize`. Its validation precondition is `fileURL != nil` on MKV, because tags-only models answer `hasFileRepresentation == false` (their tracks are never muxed) and would otherwise keep the menu disabled forever. NSDocument Duplicate needs no MKV gate because **no nib wires `duplicateDocument:`** — that menu item doesn't exist for any container. Track **reorder and MP4-only properties stay gated** (`PropertyView.isReadOnly` disables the tabs; metadata tabs stay editable; adding stays restricted to the subtitle files and chapter txt/csv described here), but real tracks **and the chapter pseudo-track** can be **deleted** (deleting the chapter track empties the model, so the save remuxes and removes the `Chapters` element — same as emptying the Chapters tab), and the four fields Matroska actually stores per track are editable and saved — name, language, enabled, subtitle forced. UI split: `TracksViewController.isReadOnly` gates drag/reorder while `isFieldEditable(_:)` re-enables the name/language/enabled cells on real (non-chapter) rows; `PropertyView.allowsTrackEditing` lets `VideoViewController` re-enable just the subtitle forced popup (Never/All only — the per-sample "Any samples" option has no Matroska equivalent).Chapters are **editable** on MKV docs (`didSelect` exempts `ChapterViewController` from the read-only blanket alongside `MovieViewController`) and chapter-less docs can **gain chapters** via `.txt` import (OGG/mp4chaps format → `addChapters`, which replaces the model's chapter track since `MP42File addTrack:` replaces previous chapter tracks) or update an existing track via `.csv` (`updateChapters`) — routed from `selectFile`'s MKV branch, drag-drop, and the AppleScript `importFilesDirectly` path (it mirrors the panel's extension dispatch, so `.txt`/`.csv` go to the chapter commands — `addChapters` bootstraps the chapter track on either container — and everything else to `FileImportController`); or one chapter at a time via the Actions toolbar's **Insert a chapter** (`DocumentWindowController.insertChapter`, works on both containers, creates the chapter track when absent and timestamps the new chapter 1s past the latest start clamped to the track duration, so it never ties with — and clamp-cascades — existing chapters) or in bulk via **Insert a chapter every** (`addChaptersEvery`); both do the tags-only trackId/`updateChangeCount` bookkeeping when they create the track, and both work on either containerLine truncated
|
- **MKV tags-only mode**: `.mkv/.mka/.mks` open directly (`DocumentController.openDocument` in `AppDelegate.swift` passes them through instead of forcing the convert-import sheet). `Document.isMatroska` then drives everything: the model is an in-memory `MP42File` filled from `MP42FileImporter` in **tagsOnly mode** (`initWithURL:tagsOnly:` — mirrors the file's own `TrackFlagEnabled` instead of the MP4 "first-of-type enabled" heuristic, so untouched tracks don't look edited), Save branches in `Document.writeMatroska`: plain edits rewrite metadata + per-track fields in place via `MP42MkvTagWriter` (never touching clusters), while **deleted/added tracks or Save-As** trigger a stream-copy rebuild via `MP42MkvRemuxer` (temp file + atomic rename even in place; `hasFileRepresentation == false` still keeps `sendToQueue` on its conversion branch; destination must stay mkv/mka/mks). The remuxer pairs `TrackEntry` elements against `Document.mkvSourceTracks` — an importer-order snapshot taken in `readMatroska` — with keep/drop decided by **object identity**, so the deletion check is immune to model index shifts; after a successful remux the snapshot is re-filtered in the same order **plus the added tracks appended** (matching the order the remuxer writes their TrackEntry elements last in the output). Subtitle tracks can be **added** to MKV docs (`.srt`/`.ssa`/`.ass` only): `DocumentWindowController.selectFile`/`showImportSheet` route MKV docs to `importSubtitleTracksForMatroska` (direct `MP42FileImporter` per file, no track-selection sheet; the accepted-extension list `matroskaSubtitleExtensions` must stay in sync with the remuxer's gate), and the `didSelect`/AppleScript `importFilesDirectly` path skips `organizeAlternateGroups`/`inferMediaCharacteristics` for MKV for the same pairing-protection reason. The AppleScript `save as` command (ScriptCommand.swift) must route Matroska docs through `Document.save(...)` — the raw `mp4.write(to:)` path would mux QuickTime atoms over an MKV document. Reordering must never happen on MKV docs (it would break the pairing): drag stays blocked and `DocumentWindowController.delete(tracks:)` skips `organizeAlternateGroups`/`inferMediaCharacteristics` for MKV. Save-As is enabled for MKV, and so is **File ▸ Optimize** (`saveAndOptimize`): on Matroska documents optimize means `writeMatroska`'s forced structural branch — a full remuxer rebuild of the file from the existing tracks (the container-equivalent of QuickTime atom-ordering), not `MP42File optimize`. Its validation precondition is `fileURL != nil` on MKV, because tags-only models answer `hasFileRepresentation == false` (their tracks are never muxed) and would otherwise keep the menu disabled forever. NSDocument Duplicate needs no MKV gate because **no nib wires `duplicateDocument:`** — that menu item doesn't exist for any container. Track **reorder and MP4-only properties stay gated** (`PropertyView.isReadOnly` disables the tabs; metadata tabs stay editable; adding stays restricted to the subtitle files and chapter txt/csv described here), but real tracks **and the chapter pseudo-track** can be **deleted** (deleting the chapter track empties the model, so the save remuxes and removes the `Chapters` element — same as emptying the Chapters tab), and the four fields Matroska actually stores per track are editable and saved — name, language, enabled, subtitle forced. UI split: `TracksViewController.isReadOnly` gates drag/reorder while `isFieldEditable(_:)` re-enables the name/language/enabled cells on real (non-chapter) rows; `PropertyView.allowsTrackEditing` lets `VideoViewController` re-enable just the subtitle forced popup (Never/All only — the per-sample "Any samples" option has no Matroska equivalent).Chapters are **editable** on MKV docs (`didSelect` exempts `ChapterViewController` from the read-only blanket alongside `MovieViewController`) and chapter-less docs can **gain chapters** via `.txt` import (OGG/mp4chaps format → `addChapters`, which replaces the model's chapter track since `MP42File addTrack:` replaces previous chapter tracks) or update an existing track via `.csv` (`updateChapters`) — routed from `selectFile`'s MKV branch, drag-drop, and the AppleScript `importFilesDirectly` path (it mirrors the panel's extension dispatch, so `.txt`/`.csv` go to the chapter commands — `addChapters` bootstraps the chapter track on either container — and everything else to `FileImportController`); or one chapter at a time via the Actions toolbar's **Insert a chapter** (`DocumentWindowController.insertChapter`, works on both containers, creates the chapter track when absent and timestamps the new chapter 1s past the latest start clamped to the track duration, so it never ties with — and clamp-cascades — existing chapters) or in bulk via **Insert a chapter every** (`addChaptersEvery`); both do the tags-only trackId/`updateChangeCount` bookkeeping when they create the track, and both work on either containerLine truncated
|
||||||
- **Queue engine**: `QueueController` (window UI) → `Queue` (serial `DispatchQueue` worker, persists `[QueueItem]` to disk via `NSKeyedArchiver`, holds IOKit sleep assertions while working) → `QueueItem` (imports a source file into an `MP42File`, then muxes to the destination) → `QueueAction` objects (`QueueActionProtocol`, `.pre`/`.post` types) apply individual transformations (set metadata, force subtitles, language fixes, etc.) to a queue item. Watch for `Queue.Working/Completed/Failed/Cancelled` notifications driving UI updates.
|
- **Queue engine**: `QueueController` (window UI) → `Queue` (serial `DispatchQueue` worker, persists `[QueueItem]` to disk via `NSKeyedArchiver`, holds IOKit sleep assertions while working) → `QueueItem` (imports a source file into an `MP42File`, then muxes to the destination) → `QueueAction` objects (`QueueActionProtocol`, `.pre`/`.post` types) apply individual transformations (set metadata, force subtitles, language fixes, etc.) to a queue item. Watch for `Queue.Working/Completed/Failed/Cancelled` notifications driving UI updates.
|
||||||
- **Import**: `FileImportController` wraps `MP42FileImporter` to let users pick which source tracks to import; `isTrackMuxable` / `trackNeedConversion` (in `Utilities.swift`) gate which tracks pass through vs. get converted. BLU-RAY PGS `.sup` files flow through this same machinery automatically (the open panel and drag-drop key off `MP42FileImporter.supportedFileFormats()/supportedContentTypes()`): they're produced by `MP42VobSubImporter`, which converts them to VobSub first — see the submodule section. They stay out of Matroska documents: `matroskaSubtitleExtensions` deliberately does not list `sup` (the remuxer only writes S_TEXT/UTF8 additions). All three subtitle importers (`MP42SrtImporter`/`MP42SSAImporter`/`MP42VobSubImporter`) take language from the filename via `getFilenameLanguage`, which scans separator-split tokens **right-to-left** (mkvmerge-style: 3-char tokens try ISO 639-2/T then the library's B codes `fre`/`ger`/`dut`/`chi`; the dash is deliberately not a separator, so `pt-BR` survives as one extended tag instead of its region half being misread as ISO 639-1 `br`=Breton); `und` when nothing decodes lets SRT/SSA fall back to `guessStringLanguage` and the sup path keep the converter's idx default. Community type tokens in the name (`sdh`/`hearing_impaired`/`deaf`, `cc`/`closed caption`, `forced`, `commentary`, `lyrics`) make `getFilenameSubtitlesTrackName` name the track after the type alone (e.g. `SDH` — MP4 has no SDH flag, the name is the convention players show; the language deliberately stays out of the name since it rides its own element); the existing `MP42File organizeMediaCharacteristicsForMediaType:` name-keyword pass then turns those names into the real QuickTime tags (`public.subtitles.forced-only`, `public.accessibility.transcribes-spoken-dialog`, …), and MKV-added subtitle tracks carry the name via the remuxer's `Name` element.
|
- **Import**: `FileImportController` wraps `MP42FileImporter` to let users pick which source tracks to import; `isTrackMuxable` / `trackNeedConversion` (in `Utilities.swift`) gate which tracks pass through vs. get converted. BLU-RAY PGS `.sup` files flow through this same machinery automatically (the open panel and drag-drop key off `MP42FileImporter.supportedFileFormats()/supportedContentTypes()`): they're produced by `MP42VobSubImporter`, which converts them to VobSub first — see the submodule section. They stay out of Matroska documents: `matroskaSubtitleExtensions` deliberately does not list `sup` (the remuxer only writes S_TEXT/UTF8 additions). All three subtitle importers (`MP42SrtImporter`/`MP42SSAImporter`/`MP42VobSubImporter`) take language from the filename via `getFilenameLanguage`, which scans separator-split tokens **right-to-left** (mkvmerge-style: 3-char tokens try ISO 639-2/T then the library's B codes `fre`/`ger`/`dut`/`chi`; the dash is deliberately not a separator, so `pt-BR` survives as one extended tag instead of its region half being misread as ISO 639-1 `br`=Breton); `und` when nothing decodes lets SRT/SSA fall back to `guessStringLanguage` and the sup path keep the converter's idx default. Community type tokens in the name (`sdh`/`hearing_impaired`/`impaired`/`deaf`, `cc`/`closed caption`, `commentary`/`commentaries`, `forced`, `lyrics`/`lyric`) make `getFilenameSubtitlesTrackName` name **any** flagged track `SDH` — one recognizable name serves users better than one name per type, and MP4 has no flag anyway, the name is the convention players show (the `SDH` name then picks up `transcribes-spoken-dialog`/`describes-music-and-sound` through `MP42File organizeMediaCharacteristicsForMediaType:`; the old per-type name→tag choreography like `forced-only` no longer fires from filenames — deliberate). The language deliberately stays out of the name since it rides its own element. MKV container tracks run through the same recognizer on the **conversion path** (`getSubtitleTypeTokenFromString` applied to the `TrackEntry Name` in `MP42MkvImporter`; a track without a TrackName inherits the token from the MKV's own filename — the decision keys on the TrackName element's presence, never the model name, because every track starts life with a default localized "<type> Track" name); tagsOnly mode is exempt — that model is the tag writer's diff baseline. MKV-added subtitle tracks carry the name via the remuxer's `Name` element.
|
||||||
- **Metadata**: `Classes/MetadataImporters/` holds a `MetadataImporter` protocol with concrete importers (TheMovieDB, TheTVDB, iTunesStore, AppleTV, SquaredTVArt, chapter DBs). Note: the chapter-DB search (`DocumentWindowController.searchChapters`, which stays in the always-valid branch of `validateUserInterfaceItem`) is currently **orphaned** — no menu item, XIB connection or code path invokes it. Search results (`MetadataResult`/`MetadataResultMap`) are applied onto `MP42Metadata` via `MetadataSearchController`. API tokens are stored/refreshed through `Token.swift`.
|
- **Metadata**: `Classes/MetadataImporters/` holds a `MetadataImporter` protocol with concrete importers (TheMovieDB, TheTVDB, iTunesStore, AppleTV, SquaredTVArt, chapter DBs). Note: the chapter-DB search (`DocumentWindowController.searchChapters`, which stays in the always-valid branch of `validateUserInterfaceItem`) is currently **orphaned** — no menu item, XIB connection or code path invokes it. Search results (`MetadataResult`/`MetadataResultMap`) are applied onto `MP42Metadata` via `MetadataSearchController`. API tokens are stored/refreshed through `Token.swift`.
|
||||||
- **Presets**: `Preset` / `QueuePreset` / `MetadataPreset` + `PresetManager` — user-defined rule sets that auto-apply actions and metadata to queue items.
|
- **Presets**: `Preset` / `QueuePreset` / `MetadataPreset` + `PresetManager` — user-defined rule sets that auto-apply actions and metadata to queue items.
|
||||||
- **Preferences**: `Prefs.swift` is the single source of truth for settings — nested enums of `@Stored` / `@StoredEnum` property-wrapped `UserDefaults` keys (defaults are auto-registered at startup). Add new settings here, not ad-hoc `UserDefaults` calls.
|
- **Preferences**: `Prefs.swift` is the single source of truth for settings — nested enums of `@Stored` / `@StoredEnum` property-wrapped `UserDefaults` keys (defaults are auto-registered at startup). Add new settings here, not ad-hoc `UserDefaults` calls.
|
||||||
@@ -52,6 +52,8 @@ The app never parses MP4/atom data directly — codec, container, and subtitle-c
|
|||||||
|
|
||||||
PGS `.sup` subtitle import: `MP42VobSubImporter` claims both `idx` and `sup`. A `.sup` is converted up-front to a private temp `.idx/.sub` pair via `MP42SupConverter` (the `@objc` façade over the sup2vob Swift sources vendored in `MP42/Sup2Vob/` from https://git.technomancer.com/Scott-Files/sup2vob — upstream logic is kept identical so upstream fixes re-merge cleanly; upstream's CLI-only globals and `main.swift` are the framework's only adaptations), then the existing VobSub machinery handles everything: the track comes out as `kMP42SubtitleCodecType_VobSub` (muxable straight into MP4 as `subp` via `MP4AddSubpicTrack`, or tx3g-convertible via `MP42BitmapSubConverter`), the frame size rides the idx `size:` line into `track.width/height`, language comes from the source filename (`getFilenameLanguage`, since PGS carries none — the generated idx `id:` is just "en"), and `track.URL` stays the user's `.sup`. The temp pair is deleted in the importer's `dealloc` — safe because tracks hold the importer strongly through export. The ObjC→Swift hop uses the existing `MP42-Shared-Swift.h` shim (generated header), new Swift files must join both targets' Sources phases like `SampleDescription.swift`.
|
PGS `.sup` subtitle import: `MP42VobSubImporter` claims both `idx` and `sup`. A `.sup` is converted up-front to a private temp `.idx/.sub` pair via `MP42SupConverter` (the `@objc` façade over the sup2vob Swift sources vendored in `MP42/Sup2Vob/` from https://git.technomancer.com/Scott-Files/sup2vob — upstream logic is kept identical so upstream fixes re-merge cleanly; upstream's CLI-only globals and `main.swift` are the framework's only adaptations), then the existing VobSub machinery handles everything: the track comes out as `kMP42SubtitleCodecType_VobSub` (muxable straight into MP4 as `subp` via `MP4AddSubpicTrack`, or tx3g-convertible via `MP42BitmapSubConverter`), the frame size rides the idx `size:` line into `track.width/height`, language comes from the source filename (`getFilenameLanguage`, since PGS carries none — the generated idx `id:` is just "en"), and `track.URL` stays the user's `.sup`. The temp pair is deleted in the importer's `dealloc` — safe because tracks hold the importer strongly through export. The ObjC→Swift hop uses the existing `MP42-Shared-Swift.h` shim (generated header), new Swift files must join both targets' Sources phases like `SampleDescription.swift`.
|
||||||
|
|
||||||
|
PGS-from-MKV → VobSub: a PGS track inside an MKV imports as a **real subp track**, not just OCR'd tx3g text. `FileImportController`'s subtitle action sheet gains a `VobSub` entry (tag 2, default follows `Prefs.subtitleConvertBitmap` like VobSub sources) for PGS-format tracks; selecting it sets `MP42ConversionSettings.subtitlesVobSubConversion`, and the muxer's bitmap-converter branch recognizes PGS-source + VobSub-target and uses `MP42PgsToVobSubConverter` instead of `MP42BitmapSubConverter`. That converter runs the whole sup2vob conversion synchronously in `initWithTrack:error:` (sup2vob derives one global DVD palette/geometry for the track, and the muxer needs `magicCookie` + `frameWidth/Height` before creating the subpic track); the live muxing stream is discarded and `copyEncodedSample` replays prepass-collected samples, ending on exactly one EOF-flagged buffer. **Matroska traps found empirically here:** mkvmerge stores each PGS segment with its 13-byte "PG" envelope removed (blocks are `type` + 2-byte-be `len` + payload repeated, blank frames are real blank presentations, everything zlib-compressed) — a plain concatenation of demuxed blocks is NOT a `.sup`; phase 1 must walk each block's stripped segments and rebuild `PG + pts:4(90kHz from the block's ns timestamp ×9/100000) + 4 zero bytes + type + len` (mkvextract reconstructs exactly this — the rebuilt stream is byte-identical to it; blocks that already carry envelopes pass through verbatim for other muxers). The rebuilt temp `.sup` is fed to a second `MP42VobSubImporter` (the same machinery as `.sup` drag-import) whose demux supplies the subpic samples/palette. The converter header isn't exported (matches `MP42BitmapSubConverter`'s non-Public Headers-phase convention), and it can't be exercised from outside the framework via `copyNextSample`/`MP42FileImporter+Private` — those are `objc_direct`/internal, so harnesses must stay in public API (see the `@selector`-on-direct-method constraint noted in the converter source).
|
||||||
|
|
||||||
Matroska tagging in the submodule: `MP42Ebml` provides EBML vint/ID primitives and a Segment top-level scanner (element extents + Void slack); `MP42MatroskaTagMapping` holds the read/write tag maps shared with `MP42MkvImporter` (reader and writer can't drift — a metadata key with no SimpleTag name in the map is **silently dropped** on save, so any new editable metadata key needs a map entry); `MP42MkvTagWriter.writeMetadata:tracks:` rewrites the `Tags` element, cover-art `AttachedFile`, and per-track `TrackEntry` fields (name/language/enabled/forced) in place (mkvpropedit-style: reuse the old extent + Void padding when the payload fits, otherwise rebuild the file tail with recomputed SeekHead/Cues positions through a temp file + atomic replace; size+mtime staleness guard refuses writes on files changed since open; foreign tag groups, unknown TrackEntry children, and non-cover attachments are preserved verbatim; each TrackEntry is diffed against the model's **effective** values so an untouched save is byte-for-byte a no-op). `MP42MkvTagWriter+Internal.h` (framework-internal, not in the umbrella) shares its kid/file model types and payload builders with `MP42MkvRemuxer`, the stream-copy track-removal/subtitle-addition engine: it rebuilds the whole file, copying every block verbatim except blocks whose unmarked-vint track number (`MP42Ebml.blockTrackNumberAt:`, ≤255) belongs to a removed track — kept tracks keep their original TrackNumbers, so **gaps after a removal are intentional** and no block header is ever rewritten; clusters are scanned header-only (BlockGroup track decided from a ≤64KB peek at its `Block` child), emptied clusters skipped, the trailing unknown-size cluster materialized; SeekHead is written with 8-wide placeholder positions pwrite-patched at the end, and Cues are regenerated at EOF (per-track `CueTrackPositions` incl. `CueRelativePosition`) only when the source had them; `Info` copies verbatim except that an existing `Duration` is recomputed: the pass tracks the greatest written block start+1ms (`_writtenMaxBlockEnd`) and pwrite-patches an 8-byte double slot at the Info write site (never +BlockDuration — added blocks must measure exactly like source blocks or remux idempotence breaks); files without a source Duration keep having none; values are TimecodeScale units. Dangling `DefaultTrackUID`/`ChapterTrackUID` refs are preserved. Chapters: the source `Chapters` element copies verbatim unless `replacementChapters` is set — non-nil rebuilds `EditionEntry{ChapterAtom{...}}` from the model track (sorted ascending, ties clamped to previous+1ms, "Chapter N" fallback titles), and a track with `chapterCount == 0` removes the element and its SeekHead entry. Chapter writing lives in the remuxer only because `Chapters` sits before the Clusters — any size change shifts every following byte, which the tag writer's tail-only in-place machinery can't absorb. It refuses multiple Segments, stray unknown-size elements, count mismatches between TrackEntry and the passed-in `sourceTracks`, and zero-remaining-track remuxes (the drop-all guard fires before additions, so drop-all-plus-add stays refused). Added tracks = `currentTracks` members absent from `sourceTracks` (identity); each must be an `MP42SubtitleTrack` whose `URL.pathExtension` is srt/ssa/ass (kept in sync with `DocumentWindowController.matroskaSubtitleExtensions`) — the model never holds subtitle text, so lines are **re-parsed from `track.URL` at save time** (SRT via `LoadSRTFromURL` + serializer drain; SSA/ASS via `MP42SSAParser`, styling stripped) and written as `S_TEXT/UTF8`. Each added track gets an appended `TrackEntry` (TrackNumber = max of all entries + 1 ≤ 0x3FFF, CodecID `S_TEXT/UTF8`, ISO `0x22B59C` + IETF `0x22B59D` language). Blocks are `BlockGroup{Block(unmarked-vint TrackNumber + int16 BE relative TC + UTF-8), BlockDuration}` — the `BlockGroup` wrapper is **mandatory**: a bare `Block` as a direct Cluster child is silently ignored by libebml readers even though ffmpeg tolerates it. Each line rides in the last existing Cluster whose Timecode ≤ its start time (negative relTCs are legal); lines whose relTC would exceed ±32767 go into **synthesized Clusters** emitted right after that cluster, original clusters are never rewritten or split.
|
Matroska tagging in the submodule: `MP42Ebml` provides EBML vint/ID primitives and a Segment top-level scanner (element extents + Void slack); `MP42MatroskaTagMapping` holds the read/write tag maps shared with `MP42MkvImporter` (reader and writer can't drift — a metadata key with no SimpleTag name in the map is **silently dropped** on save, so any new editable metadata key needs a map entry); `MP42MkvTagWriter.writeMetadata:tracks:` rewrites the `Tags` element, cover-art `AttachedFile`, and per-track `TrackEntry` fields (name/language/enabled/forced) in place (mkvpropedit-style: reuse the old extent + Void padding when the payload fits, otherwise rebuild the file tail with recomputed SeekHead/Cues positions through a temp file + atomic replace; size+mtime staleness guard refuses writes on files changed since open; foreign tag groups, unknown TrackEntry children, and non-cover attachments are preserved verbatim; each TrackEntry is diffed against the model's **effective** values so an untouched save is byte-for-byte a no-op). `MP42MkvTagWriter+Internal.h` (framework-internal, not in the umbrella) shares its kid/file model types and payload builders with `MP42MkvRemuxer`, the stream-copy track-removal/subtitle-addition engine: it rebuilds the whole file, copying every block verbatim except blocks whose unmarked-vint track number (`MP42Ebml.blockTrackNumberAt:`, ≤255) belongs to a removed track — kept tracks keep their original TrackNumbers, so **gaps after a removal are intentional** and no block header is ever rewritten; clusters are scanned header-only (BlockGroup track decided from a ≤64KB peek at its `Block` child), emptied clusters skipped, the trailing unknown-size cluster materialized; SeekHead is written with 8-wide placeholder positions pwrite-patched at the end, and Cues are regenerated at EOF (per-track `CueTrackPositions` incl. `CueRelativePosition`) only when the source had them; `Info` copies verbatim except that an existing `Duration` is recomputed: the pass tracks the greatest written block start+1ms (`_writtenMaxBlockEnd`) and pwrite-patches an 8-byte double slot at the Info write site (never +BlockDuration — added blocks must measure exactly like source blocks or remux idempotence breaks); files without a source Duration keep having none; values are TimecodeScale units. Dangling `DefaultTrackUID`/`ChapterTrackUID` refs are preserved. Chapters: the source `Chapters` element copies verbatim unless `replacementChapters` is set — non-nil rebuilds `EditionEntry{ChapterAtom{...}}` from the model track (sorted ascending, ties clamped to previous+1ms, "Chapter N" fallback titles), and a track with `chapterCount == 0` removes the element and its SeekHead entry. Chapter writing lives in the remuxer only because `Chapters` sits before the Clusters — any size change shifts every following byte, which the tag writer's tail-only in-place machinery can't absorb. It refuses multiple Segments, stray unknown-size elements, count mismatches between TrackEntry and the passed-in `sourceTracks`, and zero-remaining-track remuxes (the drop-all guard fires before additions, so drop-all-plus-add stays refused). Added tracks = `currentTracks` members absent from `sourceTracks` (identity); each must be an `MP42SubtitleTrack` whose `URL.pathExtension` is srt/ssa/ass (kept in sync with `DocumentWindowController.matroskaSubtitleExtensions`) — the model never holds subtitle text, so lines are **re-parsed from `track.URL` at save time** (SRT via `LoadSRTFromURL` + serializer drain; SSA/ASS via `MP42SSAParser`, styling stripped) and written as `S_TEXT/UTF8`. Each added track gets an appended `TrackEntry` (TrackNumber = max of all entries + 1 ≤ 0x3FFF, CodecID `S_TEXT/UTF8`, ISO `0x22B59C` + IETF `0x22B59D` language). Blocks are `BlockGroup{Block(unmarked-vint TrackNumber + int16 BE relative TC + UTF-8), BlockDuration}` — the `BlockGroup` wrapper is **mandatory**: a bare `Block` as a direct Cluster child is silently ignored by libebml readers even though ffmpeg tolerates it. Each line rides in the last existing Cluster whose Timecode ≤ its start time (negative relTCs are legal); lines whose relTC would exceed ±32767 go into **synthesized Clusters** emitted right after that cluster, original clusters are never rewritten or split.
|
||||||
|
|
||||||
Movie-tab fields that have no Matroska-spec tag (Rating, ContentRating, MediaKind, HDVideo, Cast, TVNetwork, TVEpisodeID) round-trip through community-style SimpleTag names `RATING`/`CONTENTRATING`/`MEDIAKIND`/`HD`/`CAST`/`NETWORK`/`EPISODEID`. Array-typed model values (Cast, Director, Producer, Screenwriters) are written joined with `", "` and re-split by the importer. The importer only synthesizes a TVEpisodeID from season/episode on the **conversion** path — in tagsOnly mode a synthesized value would leak into the file as a tag the user never set.
|
Movie-tab fields that have no Matroska-spec tag (Rating, ContentRating, MediaKind, HDVideo, Cast, TVNetwork, TVEpisodeID) round-trip through community-style SimpleTag names `RATING`/`CONTENTRATING`/`MEDIAKIND`/`HD`/`CAST`/`NETWORK`/`EPISODEID`. Array-typed model values (Cast, Director, Producer, Screenwriters) are written joined with `", "` and re-split by the importer. The importer only synthesizes a TVEpisodeID from season/episode on the **conversion** path — in tagsOnly mode a synthesized value would leak into the file as a tag the user never set.
|
||||||
|
|||||||
@@ -55,7 +55,16 @@ final class FileImportController: ViewController, NSTableViewDataSource, NSTable
|
|||||||
tag: 0,
|
tag: 0,
|
||||||
enabled: needsConversion == false)
|
enabled: needsConversion == false)
|
||||||
actions.append(action)
|
actions.append(action)
|
||||||
|
|
||||||
|
// PGS can be kept as bitmap subtitles: the muxer converts the
|
||||||
|
// stream to VobSub (sup2vob) and writes a real MP4 subp track.
|
||||||
|
if track.format == kMP42SubtitleCodecType_PGS {
|
||||||
|
let bitmapAction = Action(title: NSLocalizedString("VobSub", comment: "File Import action menu item."),
|
||||||
|
tag: 2,
|
||||||
|
enabled: true)
|
||||||
|
actions.append(bitmapAction)
|
||||||
|
}
|
||||||
|
|
||||||
if (needsConversion || track.format == kMP42SubtitleCodecType_VobSub) {
|
if (needsConversion || track.format == kMP42SubtitleCodecType_VobSub) {
|
||||||
let conversionAction = Action(title: NSLocalizedString("Tx3g", comment: "File Import action menu item."),
|
let conversionAction = Action(title: NSLocalizedString("Tx3g", comment: "File Import action menu item."),
|
||||||
tag: 1,
|
tag: 1,
|
||||||
@@ -157,6 +166,11 @@ final class FileImportController: ViewController, NSTableViewDataSource, NSTable
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// PGS: keep it bitmap — VobSub by default, tx3g only if the
|
||||||
|
// user's bitmap-subtitles-to-tx3g preference says so
|
||||||
|
else if track.format == kMP42SubtitleCodecType_PGS {
|
||||||
|
self.selectedActionTag = Prefs.subtitleConvertBitmap ? 1 : 2
|
||||||
|
}
|
||||||
// Vobsub
|
// Vobsub
|
||||||
else if track.format == kMP42SubtitleCodecType_VobSub && Prefs.subtitleConvertBitmap {
|
else if track.format == kMP42SubtitleCodecType_VobSub && Prefs.subtitleConvertBitmap {
|
||||||
self.selectedActionTag = 1
|
self.selectedActionTag = 1
|
||||||
@@ -371,7 +385,10 @@ final class FileImportController: ViewController, NSTableViewDataSource, NSTable
|
|||||||
|
|
||||||
case let track as MP42SubtitleTrack:
|
case let track as MP42SubtitleTrack:
|
||||||
|
|
||||||
if trackSettings.selectedActionTag > 0 {
|
if trackSettings.selectedActionTag == 2 {
|
||||||
|
// PGS → VobSub: mux as a bitmap subp track (sup2vob)
|
||||||
|
track.conversionSettings = MP42ConversionSettings.subtitlesVobSubConversion()
|
||||||
|
} else if trackSettings.selectedActionTag > 0 {
|
||||||
track.conversionSettings = MP42ConversionSettings.subtitlesConversion()
|
track.conversionSettings = MP42ConversionSettings.subtitlesConversion()
|
||||||
}
|
}
|
||||||
selectedTracks.append(trackSettings.track)
|
selectedTracks.append(trackSettings.track)
|
||||||
|
|||||||
+1
-1
Submodule MP42Foundation updated: e02f60b5f6...57772086a5.
@@ -615,6 +615,7 @@ Toolbar */
|
|||||||
|
|
||||||
/* File Import action menu item. */
|
/* File Import action menu item. */
|
||||||
"Tx3g" = "Tx3g";
|
"Tx3g" = "Tx3g";
|
||||||
|
"VobSub" = "VobSub";
|
||||||
|
|
||||||
/* color profile */
|
/* color profile */
|
||||||
"Undefined (2-2-2)" = "No definido (2-2-2)";
|
"Undefined (2-2-2)" = "No definido (2-2-2)";
|
||||||
|
|||||||
@@ -559,6 +559,7 @@ Toolbar */
|
|||||||
|
|
||||||
/* File Import action menu item. */
|
/* File Import action menu item. */
|
||||||
"Tx3g" = "Tx3g";
|
"Tx3g" = "Tx3g";
|
||||||
|
"VobSub" = "VobSub";
|
||||||
|
|
||||||
/* No comment provided by engineer. */
|
/* No comment provided by engineer. */
|
||||||
"Unknown" = "Inconnu";
|
"Unknown" = "Inconnu";
|
||||||
|
|||||||
@@ -594,6 +594,7 @@ Toolbar */
|
|||||||
|
|
||||||
/* File Import action menu item. */
|
/* File Import action menu item. */
|
||||||
"Tx3g" = "Tx3g";
|
"Tx3g" = "Tx3g";
|
||||||
|
"VobSub" = "VobSub";
|
||||||
|
|
||||||
/* color profile */
|
/* color profile */
|
||||||
"Undefined (2-2-2)" = "Non definito (2-2-2)";
|
"Undefined (2-2-2)" = "Non definito (2-2-2)";
|
||||||
|
|||||||
@@ -615,6 +615,7 @@ Toolbar */
|
|||||||
|
|
||||||
/* File Import action menu item. */
|
/* File Import action menu item. */
|
||||||
"Tx3g" = "Tx3g";
|
"Tx3g" = "Tx3g";
|
||||||
|
"VobSub" = "VobSub";
|
||||||
|
|
||||||
/* color profile */
|
/* color profile */
|
||||||
"Undefined (2-2-2)" = "Indefinido (2-2-2)";
|
"Undefined (2-2-2)" = "Indefinido (2-2-2)";
|
||||||
|
|||||||
@@ -535,6 +535,7 @@ Toolbar */
|
|||||||
|
|
||||||
/* File Import action menu item. */
|
/* File Import action menu item. */
|
||||||
"Tx3g" = "Tx3g";
|
"Tx3g" = "Tx3g";
|
||||||
|
"VobSub" = "VobSub";
|
||||||
|
|
||||||
/* No comment provided by engineer. */
|
/* No comment provided by engineer. */
|
||||||
"Unknown" = "未知";
|
"Unknown" = "未知";
|
||||||
|
|||||||
@@ -538,6 +538,7 @@
|
|||||||
|
|
||||||
/* File Import action menu item. */
|
/* File Import action menu item. */
|
||||||
"Tx3g" = "Tx3g";
|
"Tx3g" = "Tx3g";
|
||||||
|
"VobSub" = "VobSub";
|
||||||
|
|
||||||
/* No comment provided by engineer. */
|
/* No comment provided by engineer. */
|
||||||
"Unknown" = "未知";
|
"Unknown" = "未知";
|
||||||
|
|||||||
Reference in new issue
Block a user