diff --git a/CLAUDE.md b/CLAUDE.md index 0a29eca..99c7a9c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -35,10 +35,10 @@ 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 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. +- **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 container. Chapter changes ride the **remuxer**, not the tag writer: `Document.mkvChaptersSnapshot` (model rows at read/save time, compared model-vs-model so the baseline tracks exactly what a rewrite would emit) 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`. +- **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. - **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. - **AppleScript**: `Subler.sdef` defines the scripting dictionary; `ScriptCommand.swift` / `QueueScriptCommand.swift` implement the commands (e.g., "send to queue"). @@ -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 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: …"). +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. The importer's chapter normalization (force first start to 0, drop non-first zero-start atoms) is an **MP4 conversion-path** quirk only — **tagsOnly mode mirrors the file's atoms verbatim**, offset first starts and duplicate zero starts included (mkvmerge writes both shapes). That asymmetry matters because the tagsOnly model is the baseline a Chapters rewrite rebuilds from: dropping or shifting atoms at read time would silently corrupt them on the first edit, so instead the remuxer's strictly-ascending clamp shifts tied starts by +1 ms at write time and nothing is lost. 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 diff --git a/Classes/Document.swift b/Classes/Document.swift index 876e8cd..cf3e816 100644 --- a/Classes/Document.swift +++ b/Classes/Document.swift @@ -339,7 +339,12 @@ final class Document: NSDocument { default: chaptersChanged = true } - if tracksChanged || chaptersChanged || saveOperation != .saveOperation { + // `optimize` (Save and Optimize) forces the structural branch: the + // Matroska equivalent of reordering atoms is rebuilding the whole file + // — blocks stream-copied verbatim, Tracks/Tags rewritten, SeekHead and + // Cues regenerated — i.e. exactly the Save-As pass, done in place + // through the remuxer's temp file + atomic rename. + if tracksChanged || chaptersChanged || optimize || saveOperation != .saveOperation { // An absent model track means "no chapters" — pass an empty // track so the remuxer removes the element rather than copying // the old one verbatim (nil replacement = verbatim). @@ -480,7 +485,13 @@ final class Document: NSDocument { return true case #selector(sendToQueue(_:)): return true - case #selector(saveAndOptimize(_:)) where isDocumentEdited == false && mp4.hasFileRepresentation == true: + // On a Matroska document optimize = full remuxer rebuild (see + // writeMatroska), the container-equivalent of the atom-order optimize. + // Tags-only models report hasFileRepresentation == false (their tracks + // are never muxed), so the on-disk precondition there is just the + // remux source: fileURL. + case #selector(saveAndOptimize(_:)) where isDocumentEdited == false + && (isMatroska ? fileURL != nil : mp4.hasFileRepresentation == true): return true default: return false diff --git a/Classes/DocumentWindowController.swift b/Classes/DocumentWindowController.swift index 6d167fd..ca75d9d 100644 --- a/Classes/DocumentWindowController.swift +++ b/Classes/DocumentWindowController.swift @@ -280,7 +280,8 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac #selector(searchMetadata(_:)), #selector(sendToQueue(_:)), #selector(insertChapter(_:)), - #selector(addChaptersEvery(_:)): + #selector(addChaptersEvery(_:)), + #selector(searchChapters(_:)): return true // Matroska documents may import subtitle text files (written as @@ -288,12 +289,11 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac case #selector(selectFile(_:)): return true - // Track bulk modifications (and the chapter-DB search, whose apply - // path lacks the tags-only bookkeeping): unavailable in Matroska - // tags-only mode. The Insert-a-chapter actions are NOT on this list — - // chapter changes ride the stream-copy remuxer, so they work on MKV. - case #selector(searchChapters(_:)), - #selector(iTunesFriendlyTrackGroups(_:)), + // Track bulk modifications: unavailable in Matroska tags-only mode. + // Chapter actions (searchChapters, the Insert-a-chapter commands) are + // NOT on this list — chapter changes ride the stream-copy remuxer, + // so they work on MKV too. + case #selector(iTunesFriendlyTrackGroups(_:)), #selector(clearTrackNames(_:)), #selector(prettifyAudioTrackNames(_:)), #selector(fixAudioFallbacks(_:)): @@ -552,7 +552,13 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac chapterTrack.addChapter(chapter) } - mp4.addTrack(chapterTrack) + mp4.addTrack(chapterTrack) // addTrack: replaces any previous chapter track + if doc.isMatroska { + // Tags-only bookkeeping, same as addChapters/insertChapter: + // addTrack: zeroes trackId, and nothing else marks the document. + chapterTrack.trackId = (mp4.tracks.map { $0.trackId }.max() ?? 0) + 1 + doc.updateChangeCount(.changeDone) + } tracksViewController.reloadData() tracksViewController.selectTracks([chapterTrack]) } @@ -761,8 +767,22 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac } @objc func importFilesDirectly(_ fileURLs: [URL]) { + // Mirror the open panel's extension routing (selectFile): chapter + // text files go to the chapter commands — addChapters bootstraps the + // chapter track on both containers — everything else to the regular + // track importer. + var mediaURLs: [URL] = [] + for url in fileURLs { + switch url.pathExtension.lowercased() { + case "txt": addChapters(fileURL: url) + case "csv": updateChapters(fileURL: url) + default: mediaURLs.append(url) + } + } + guard mediaURLs.isEmpty == false else { return } + do { - let controller = try FileImportController(fileURLs: fileURLs, delegate: self) + let controller = try FileImportController(fileURLs: mediaURLs, delegate: self) // Call addTracks directly - the Settings initialization logic runs when the controller is created controller.addTracks(self) diff --git a/MP42Foundation b/MP42Foundation index 10dcee3..e8231de 160000 --- a/MP42Foundation +++ b/MP42Foundation @@ -1 +1 @@ -Subproject commit 10dcee30a6ea41203a31abfe6007e3cd81f92797 +Subproject commit e8231dea5990f1644463d6fde102aa7e6b43dc25