Make chapter tracks deletable, insertable, and language-editable

Delete: the phase-1 gate against deleting the chapter pseudo-track on
Matroska documents is obsolete now that chapter changes ride the
stream-copy remuxer — a removed pseudo-track simply makes the model
report "no chapters", which removes the Chapters element on save (the
same path emptying the Chapters tab already took). The toolbar Delete
button's validation is corrected too; it still rejected chapter-only
selections after deleteSelection was opened up.

Insert: the Actions toolbar gets a single "Insert a chapter" item, and
"Insert a chapter every" (previously MP4-only) is enabled on Matroska.
Both create the chapter track when the document has none, doing the
tags-only bookkeeping the model needs (dense display trackId,
updateChangeCount). A single insert lands 1s after the latest start,
clamped to the track duration, so it can never tie with a stored
chapter — ties get clamped +1ms on write and would silently shift the
user's own chapter times.

Language: the chapter row's language popup stays editable on MKV
documents (the value rides the remuxer's chapter rebuild, not the tag
writer, since the pseudo-track has no TrackEntry), and the Matroska
chapters snapshot carries it so a language-only edit triggers the
remux. Pairs with the submodule's ChapterLanguage round trip.

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
Scott GarrettandClaude Code committed 2026-11-26 18:17:37 -05:00
1 parent 8520d729c6
commit f457b4e89c
13 files changed
+124 -30

No files matched your search

+2 -2
View File
@@ -35,7 +35,7 @@ Two layers with a strict boundary:
### 1. App layer (`Classes/`, Swift)
- **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; Duplicate/save-and-optimize stay disabled. 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 (non-chapter) tracks can be **deleted** (`TracksViewController.deleteSelection` filters chapter rows on MKV; the menu item validates the same rule), 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 and drag-drop. Chapter changes ride the **remuxer**, not the tag writer: `Document.mkvChaptersSnapshot` (model rows at read/save time; compared model-vs-model because the importer silently drops some atoms — duplicate zero timestamps — so file-vs-model would report phantom edits) drives `chaptersChanged` into the structural condition, and `remuxMatroska` passes `mp4.chapters` (or an empty `MP42ChapterTrack` when the model has none, to delete the element) as the remuxer's `replacementChapters`; nil means verbatim copy.
- **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; Duplicate/save-and-optimize stay disabled. 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 and drag-drop; 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 container. Chapter changes ride the **remuxer**, not the tag writer: `Document.mkvChaptersSnapshot` (model rows at read/save time; compared model-vs-model because the importer silently drops some atoms — duplicate zero timestamps — so file-vs-model would report phantom edits) drives `chaptersChanged` into the structural condition, and `remuxMatroska` passes `mp4.chapters` (or an empty `MP42ChapterTrack` when the model has none, to delete the element) as the remuxer's `replacementChapters`; nil means verbatim copy.
- **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.
- **Metadata**: `Classes/MetadataImporters/` holds a `MetadataImporter` protocol with concrete importers (TheMovieDB, TheTVDB, iTunesStore, AppleTV, SquaredTVArt, chapter DBs). Search results (`MetadataResult`/`MetadataResultMap`) are applied onto `MP42Metadata` via `MetadataSearchController`. API tokens are stored/refreshed through `Token.swift`.
@@ -56,7 +56,7 @@ Movie-tab fields that have no Matroska-spec tag (Rating, ContentRating, MediaKin
The Matroska track-field element ids are a trap: the ids that actually work in the wild (libebml/mkvtoolnix/ffmpeg and every reader) are `0x22B59C` = ISO-639-2/B `Language`, `0x22B59D` = BCP-47 `LanguageIETF`, `0xB9` = `TrackFlagEnabled`. The EBML spec's later `0x447A` carries the same ISO value but mkvtoolnix never writes it — `MatroskaParser.c` reads it defensively, the writer normalizes it to `0x22B59C`. Modern mkvtoolnix files may carry **only** `0x22B59D` (mkvmerge derives the ISO code from the IETF tag), so `Language` can be absent; the importer/writer prefer `LanguageIETF` when present and fall back to the ISO element. Match TrackEntry↔model by file order (chapter pseudo-track filtered); a count mismatch refuses the write.
Chapter elements are their own trap set (all verified empirically against mkvmerge-written files): `ChapterAtom` is `0xB6` — **not** `0xB0`, which is PixelWidth in TrackEntry scope (`MatroskaParser.c` has always parsed 0xB6 correctly; don't "fix" it). Chapter timecodes are absolute **nanoseconds**, not TimecodeScale units like nearly every other Matroska time — libmatroska writes and mkvtoolnix/ffmpeg both read them as ns regardless of segment scale, so the importer's plain `/1e6` to ms and the remuxer's plain `×1e6` back are right. `ChapterUID` (`0x73C4`) is mandatory in practice: ffmpeg **silently skips** atoms without it (mkvtoolnix still lists them, which makes the loss easy to miss); `EditionUID` likewise. The writer derives both deterministically from the chapter content so re-saving unchanged input reproduces the file. Note the reader asymmetry: `MP42MkvImporter` forces the first chapter to 0 and skips non-first zero-timestamp chapters, so atoms it dropped are permanently lost once an edit rewrites the Chapters element.
Chapter elements are their own trap set (all verified empirically against mkvmerge-written files): `ChapterAtom` is `0xB6` — **not** `0xB0`, which is PixelWidth in TrackEntry scope (`MatroskaParser.c` has always parsed 0xB6 correctly; don't "fix" it). Chapter timecodes are absolute **nanoseconds**, not TimecodeScale units like nearly every other Matroska time — libmatroska writes and mkvtoolnix/ffmpeg both read them as ns regardless of segment scale, so the importer's plain `/1e6` to ms and the remuxer's plain `×1e6` back are right. `ChapterUID` (`0x73C4`) is mandatory in practice: ffmpeg **silently skips** atoms without it (mkvtoolnix still lists them, which makes the loss easy to miss); `EditionUID` likewise. The writer derives both deterministically from the chapter content so re-saving unchanged input reproduces the file. Note the reader asymmetry: `MP42MkvImporter` forces the first chapter to 0 and skips non-first zero-timestamp chapters, so atoms it dropped are permanently lost once an edit rewrites the Chapters element. Chapter language round-trips at **track level**: the importer adopts the first `ChapterDisplay/ChapterLanguage` (0x437C) it finds as the model track's `language`, and the remuxer stamps that track language into every atom — omitted when nil/absent or when it maps to ISO `eng` (the spec default; keeps rewrites byte-identical to language-less files). `MP42Languages ISO_639_2CodeForExtendedTag:` answers unknown tags with `"und"`, so a garbage language explicitly writes `und` rather than silently defaulting — extended tags are locale-identifier style (`"en"`, `"it"`), not English names. The chapter-row language popup stays enabled on MKV (`TracksViewController.isLanguageEditable`) because the value rides the remuxer's chapter rebuild, not the tag writer (no TrackEntry), and the `mkvChaptersSnapshot` rows carry the language so a language-only edit flips `chaptersChanged`. Note: `ffprobe -show_chapters` does NOT surface ChapterLanguage in its chapter tags — assert it with `mkvinfo` ("Chapter language: …").
## Cross-cutting concerns