Edit and add chapters in Matroska documents
The chapters tab leaves read-only jail on MKV docs: didSelect exempts ChapterViewController from the tags-only blanket, and chapter-less docs can gain chapters through the same txt/csv dispatch MP4 documents use (selectFile's MKV branch and drag-drop now allow .txt/.csv alongside the subtitle extensions; addChapters/updateChapters assign the display trackId and flag the document dirty on MKV). Chapter edits ride the remuxer, never the tag writer: Chapters sits before the Clusters, so any size change shifts every following byte. Document.mkvChaptersSnapshot holds the baseline rows and drives a chaptersChanged check against the model (model-vs-model, because the reader itself drops duplicate zero-timestamp atoms and those must not look like user edits); when changed, remuxMatroska passes mp4.chapters (or an empty track to delete every chapter) as the remuxer's replacementChapters, then refreshes the snapshot so an untouched save goes back to the byte-stable tag-writer path. Verified live: add a chapter row in the UI, File>Save — the file gains the atom (ties clamped to 1ms), mkvmerge/ffmpeg both read it, a forced no-op re-save is byte-identical, and reopening shows all rows. Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
1 parent
330236735d
commit
8520d729c6
4 files changed
+89
-24
No files matched your search
@@ -35,7 +35,7 @@ Two layers with a strict boundary:
|
|||||||
### 1. App layer (`Classes/`, Swift)
|
### 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.
|
- **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 described above), 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 remain read-only (Chapters-element writing deferred).
|
- **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.
|
||||||
- **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.
|
- **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). Search results (`MetadataResult`/`MetadataResultMap`) are applied onto `MP42Metadata` via `MetadataSearchController`. API tokens are stored/refreshed through `Token.swift`.
|
||||||
@@ -50,12 +50,14 @@ Referenced by the main project; `MP42Foundation.framework` is linked and copied
|
|||||||
|
|
||||||
The app never parses MP4/atom data directly — codec, container, and subtitle-conversion work belongs in the submodule, not in `Classes/`. `Classes/MP42FileAdditions.swift` extends framework types with app-level conveniences.
|
The app never parses MP4/atom data directly — codec, container, and subtitle-conversion work belongs in the submodule, not in `Classes/`. `Classes/MP42FileAdditions.swift` extends framework types with app-level conveniences.
|
||||||
|
|
||||||
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`/`Duration` copy verbatim (may overstate a dropped track) and dangling `DefaultTrackUID`/`ChapterTrackUID` refs are preserved. 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.
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
## Cross-cutting concerns
|
## Cross-cutting concerns
|
||||||
|
|
||||||
- **Sandbox vs non-sandbox builds**: `#if SB_SANDBOX` guards App Store code paths (security-scoped bookmarks via `MP42SecurityAccessToken`); the default build is the non-sandboxed Sparkle-updatable variant (`Subler.entitlements` exist for the sandboxed config).
|
- **Sandbox vs non-sandbox builds**: `#if SB_SANDBOX` guards App Store code paths (security-scoped bookmarks via `MP42SecurityAccessToken`); the default build is the non-sandboxed Sparkle-updatable variant (`Subler.entitlements` exist for the sandboxed config).
|
||||||
|
|||||||
+40
-3
@@ -26,6 +26,12 @@ final class Document: NSDocument {
|
|||||||
// pseudo-track filtered): the baseline MP42MkvRemuxer pairs TrackEntry
|
// pseudo-track filtered): the baseline MP42MkvRemuxer pairs TrackEntry
|
||||||
// elements against, so a deleted track is detected by object identity.
|
// elements against, so a deleted track is detected by object identity.
|
||||||
private var mkvSourceTracks: [MP42Track] = []
|
private var mkvSourceTracks: [MP42Track] = []
|
||||||
|
// Chapter rows as the file's baseline holds them (model milliseconds).
|
||||||
|
// nil when the last read/written file had no chapters. Compared against
|
||||||
|
// the model on save: model-vs-snapshot (not model-vs-file) because the
|
||||||
|
// importer itself drops some atoms (duplicate zero timestamps), and
|
||||||
|
// those silently-dropped atoms must not look like a user edit.
|
||||||
|
private var mkvChaptersSnapshot: [(timestamp: UInt64, title: String)]?
|
||||||
private var mkvFileSize: UInt64 = 0
|
private var mkvFileSize: UInt64 = 0
|
||||||
private var mkvFileModificationDate: Date?
|
private var mkvFileModificationDate: Date?
|
||||||
|
|
||||||
@@ -146,6 +152,7 @@ final class Document: NSDocument {
|
|||||||
// Order-sensitive snapshot for the remuxer's TrackEntry pairing; the
|
// Order-sensitive snapshot for the remuxer's TrackEntry pairing; the
|
||||||
// chapter pseudo-track has no TrackEntry and must not shift positions.
|
// chapter pseudo-track has no TrackEntry and must not shift positions.
|
||||||
mkvSourceTracks = importer.tracks.filter { $0.isMember(of: MP42ChapterTrack.self) == false }
|
mkvSourceTracks = importer.tracks.filter { $0.isMember(of: MP42ChapterTrack.self) == false }
|
||||||
|
mkvChaptersSnapshot = Self.matroskaChapterRows(mp4.chapters)
|
||||||
snapshotMatroskaFile(at: url)
|
snapshotMatroskaFile(at: url)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -315,9 +322,27 @@ final class Document: NSDocument {
|
|||||||
// still compares equal.
|
// still compares equal.
|
||||||
let tracksChanged = currentTracks.count != mkvSourceTracks.count ||
|
let tracksChanged = currentTracks.count != mkvSourceTracks.count ||
|
||||||
currentTracks.contains { track in mkvSourceTracks.contains(where: { $0 === track }) == false }
|
currentTracks.contains { track in mkvSourceTracks.contains(where: { $0 === track }) == false }
|
||||||
|
// Chapters ride the remuxer too: the Chapters element sits before the
|
||||||
|
// Clusters, so any size change shifts every following byte (the tag
|
||||||
|
// writer's in-place machinery is tail-only). An added-but-empty
|
||||||
|
// chapter track means "delete every chapter" — the remuxer removes
|
||||||
|
// the element.
|
||||||
|
let modelChapterRows = Self.matroskaChapterRows(mp4.chapters)
|
||||||
|
let chaptersChanged: Bool
|
||||||
|
switch (modelChapterRows, mkvChaptersSnapshot) {
|
||||||
|
case (nil, nil): chaptersChanged = false
|
||||||
|
case let (model?, snapshot?):
|
||||||
|
chaptersChanged = model.count != snapshot.count ||
|
||||||
|
zip(model, snapshot).contains { $0.timestamp != $1.timestamp || $0.title != $1.title }
|
||||||
|
default: chaptersChanged = true
|
||||||
|
}
|
||||||
|
|
||||||
if tracksChanged || saveOperation != .saveOperation {
|
if tracksChanged || chaptersChanged || saveOperation != .saveOperation {
|
||||||
try remuxMatroska(to: url, currentTracks: currentTracks)
|
// 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).
|
||||||
|
try remuxMatroska(to: url, currentTracks: currentTracks,
|
||||||
|
replacementChapters: chaptersChanged ? (mp4.chapters ?? MP42ChapterTrack()) : nil)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -341,7 +366,13 @@ final class Document: NSDocument {
|
|||||||
// Stream-copy rebuild: blocks are copied verbatim except those of removed
|
// Stream-copy rebuild: blocks are copied verbatim except those of removed
|
||||||
// tracks, and metadata/cover/track-field edits ride in the same pass.
|
// tracks, and metadata/cover/track-field edits ride in the same pass.
|
||||||
// Writes a temp file and renames atomically; see MP42MkvRemuxer.h.
|
// Writes a temp file and renames atomically; see MP42MkvRemuxer.h.
|
||||||
private func remuxMatroska(to url: URL, currentTracks: [MP42Track]) throws {
|
private static func matroskaChapterRows(_ track: MP42ChapterTrack?) -> [(timestamp: UInt64, title: String)]? {
|
||||||
|
guard let track else { return nil }
|
||||||
|
return track.chapters.map { ($0.timestamp, $0.title) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private func remuxMatroska(to url: URL, currentTracks: [MP42Track],
|
||||||
|
replacementChapters: MP42ChapterTrack?) throws {
|
||||||
guard let sourceURL = fileURL else {
|
guard let sourceURL = fileURL else {
|
||||||
throw NSError(domain: NSCocoaErrorDomain, code: NSFileWriteUnknownError,
|
throw NSError(domain: NSCocoaErrorDomain, code: NSFileWriteUnknownError,
|
||||||
userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("The Matroska source file is unknown.", comment: "Document MKV remux missing source error.")])
|
userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("The Matroska source file is unknown.", comment: "Document MKV remux missing source error.")])
|
||||||
@@ -352,10 +383,16 @@ final class Document: NSDocument {
|
|||||||
remuxer.progressHandler = { [weak self] progress in
|
remuxer.progressHandler = { [weak self] progress in
|
||||||
self?.mp4.progressHandler?(progress)
|
self?.mp4.progressHandler?(progress)
|
||||||
}
|
}
|
||||||
|
// nil keeps the source Chapters element verbatim.
|
||||||
|
remuxer.replacementChapters = replacementChapters
|
||||||
mkvRemuxer = remuxer
|
mkvRemuxer = remuxer
|
||||||
try remuxer.remux(to: url, metadata: mp4.metadata,
|
try remuxer.remux(to: url, metadata: mp4.metadata,
|
||||||
sourceTracks: mkvSourceTracks, currentTracks: currentTracks)
|
sourceTracks: mkvSourceTracks, currentTracks: currentTracks)
|
||||||
mkvRemuxer = nil
|
mkvRemuxer = nil
|
||||||
|
// The written file's chapters are exactly what the model holds now
|
||||||
|
// (modulo the writer's own sort/clamp, which the model then absorbs
|
||||||
|
// on the next read — an untouched save must not look "changed").
|
||||||
|
mkvChaptersSnapshot = Self.matroskaChapterRows(mp4.chapters)
|
||||||
// The output keeps the surviving TrackEntry elements in source file
|
// The output keeps the surviving TrackEntry elements in source file
|
||||||
// order and appends one TrackEntry per added subtitle track last
|
// order and appends one TrackEntry per added subtitle track last
|
||||||
// (MP42MkvRemuxer), so re-snapshot the pairing baseline in that same
|
// (MP42MkvRemuxer), so re-snapshot the pairing baseline in that same
|
||||||
|
|||||||
@@ -236,11 +236,13 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
|
|||||||
detailsItem.viewController.view.addSubview(trackViewController.view)
|
detailsItem.viewController.view.addSubview(trackViewController.view)
|
||||||
|
|
||||||
// Tags-only mode: tracks are displayed but cannot be modified, except
|
// Tags-only mode: tracks are displayed but cannot be modified, except
|
||||||
// for the fields MP42MkvTagWriter writes back (see allowsTrackEditing).
|
// for the fields MP42MkvTagWriter writes back (see allowsTrackEditing)
|
||||||
// Set after the view is loaded so it wins over controls that the view
|
// and the chapters tab (ChapterViewController edits ride the remuxer's
|
||||||
// controllers enable during their own updates.
|
// replacementChapters). Set after the view is loaded so it wins over
|
||||||
|
// controls that the view controllers enable during their own updates.
|
||||||
trackViewController.isMatroskaDocument = doc.isMatroska
|
trackViewController.isMatroskaDocument = doc.isMatroska
|
||||||
if doc.isMatroska, !(trackViewController is MovieViewController) {
|
if doc.isMatroska, !(trackViewController is MovieViewController),
|
||||||
|
!(trackViewController is ChapterViewController) {
|
||||||
trackViewController.allowsTrackEditing = true
|
trackViewController.allowsTrackEditing = true
|
||||||
trackViewController.isReadOnly = true
|
trackViewController.isReadOnly = true
|
||||||
} else {
|
} else {
|
||||||
@@ -506,7 +508,14 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
|
|||||||
|
|
||||||
private func addChapters(fileURL: URL) {
|
private func addChapters(fileURL: URL) {
|
||||||
let track = MP42ChapterTrack(fromFile: fileURL)
|
let track = MP42ChapterTrack(fromFile: fileURL)
|
||||||
mp4.addTrack(track)
|
mp4.addTrack(track) // replaces any previous chapter track
|
||||||
|
if doc.isMatroska {
|
||||||
|
// addTrack: zeroes trackId; keep the table numbering dense, and
|
||||||
|
// flag the document dirty (the tags-only model has no muxing to
|
||||||
|
// mark it, same as importSubtitleTracksForMatroska).
|
||||||
|
track.trackId = (mp4.tracks.map { $0.trackId }.max() ?? 0) + 1
|
||||||
|
doc.updateChangeCount(.changeDone)
|
||||||
|
}
|
||||||
tracksViewController.reloadData()
|
tracksViewController.reloadData()
|
||||||
tracksViewController.selectTracks([track])
|
tracksViewController.selectTracks([track])
|
||||||
}
|
}
|
||||||
@@ -517,6 +526,7 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
|
|||||||
if let track = mp4.chapters {
|
if let track = mp4.chapters {
|
||||||
chapterViewController?.track = track
|
chapterViewController?.track = track
|
||||||
tracksViewController.selectTracks([track])
|
tracksViewController.selectTracks([track])
|
||||||
|
if doc.isMatroska { doc.updateChangeCount(.changeDone) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch {
|
catch {
|
||||||
@@ -571,20 +581,30 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
|
|||||||
panel.canChooseDirectories = false
|
panel.canChooseDirectories = false
|
||||||
|
|
||||||
if doc.isMatroska {
|
if doc.isMatroska {
|
||||||
// A Matroska document can only gain subtitle text tracks (the
|
// A Matroska document can gain subtitle text tracks (the
|
||||||
// stream-copy remuxer writes them as S_TEXT/UTF8); chapter files
|
// stream-copy remuxer writes them as S_TEXT/UTF8) and chapters
|
||||||
// (.txt/.csv) stay unavailable because chapter writing is not
|
// (.txt creates/replaces the chapter track, .csv updates an
|
||||||
// implemented for Matroska.
|
// existing one — same dispatch the MP4 branch uses below).
|
||||||
|
let chapterExtensions = ["txt", "csv"]
|
||||||
if #available(macOS 11, *) {
|
if #available(macOS 11, *) {
|
||||||
panel.allowedContentTypes = DocumentWindowController.matroskaSubtitleExtensions.compactMap {
|
panel.allowedContentTypes = (DocumentWindowController.matroskaSubtitleExtensions + chapterExtensions).compactMap {
|
||||||
UTType(filenameExtension: $0)
|
UTType(filenameExtension: $0)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
panel.allowedFileTypes = DocumentWindowController.matroskaSubtitleExtensions
|
panel.allowedFileTypes = DocumentWindowController.matroskaSubtitleExtensions + chapterExtensions
|
||||||
}
|
}
|
||||||
panel.beginSheetModal(for: windowForSheet) { (response) in
|
panel.beginSheetModal(for: windowForSheet) { (response) in
|
||||||
if response == NSApplication.ModalResponse.OK {
|
guard response == NSApplication.ModalResponse.OK else { return }
|
||||||
self.showImportSheet(fileURLs: panel.urls)
|
var subtitleURLs: [URL] = []
|
||||||
|
for url in panel.urls {
|
||||||
|
switch url.pathExtension.lowercased() {
|
||||||
|
case "txt": self.addChapters(fileURL: url)
|
||||||
|
case "csv": self.updateChapters(fileURL: url)
|
||||||
|
default: subtitleURLs.append(url)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if subtitleURLs.isEmpty == false {
|
||||||
|
self.showImportSheet(fileURLs: subtitleURLs)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
@@ -752,13 +772,19 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
|
|||||||
let items = pasteboard.readObjects(forClasses: [NSURL.classForCoder()], options: [:]) as? [URL]
|
let items = pasteboard.readObjects(forClasses: [NSURL.classForCoder()], options: [:]) as? [URL]
|
||||||
else { return false }
|
else { return false }
|
||||||
|
|
||||||
// Metadata drops are fine in tags-only mode; chapter and track
|
// Metadata drops are fine in tags-only mode. Chapters ride the
|
||||||
// imports modify tracks, which Matroska documents cannot do.
|
// remuxer on Matroska documents, so txt/csv drops route there too;
|
||||||
if doc.isMatroska == false {
|
// everything else that would add a track goes through the import
|
||||||
let chapters = items.filter { $0.pathExtension.lowercased() == "txt" }
|
// panel (which routes Matroska docs to the subtitle-only path).
|
||||||
if let url = chapters.first {
|
if doc.isMatroska {
|
||||||
|
if let url = items.first(where: { $0.pathExtension.lowercased() == "txt" }) {
|
||||||
addChapters(fileURL: url)
|
addChapters(fileURL: url)
|
||||||
}
|
}
|
||||||
|
if let url = items.first(where: { $0.pathExtension.lowercased() == "csv" }) {
|
||||||
|
updateChapters(fileURL: url)
|
||||||
|
}
|
||||||
|
} else if let url = items.first(where: { $0.pathExtension.lowercased() == "txt" }) {
|
||||||
|
addChapters(fileURL: url)
|
||||||
}
|
}
|
||||||
|
|
||||||
let metadata = items.filter { let ext = $0.pathExtension.lowercased(); return ext == "xml" || ext == "nfo" }
|
let metadata = items.filter { let ext = $0.pathExtension.lowercased(); return ext == "xml" || ext == "nfo" }
|
||||||
|
|||||||
+1
-1
Submodule MP42Foundation updated: 8ba3f25a2c...0cf79eca1c.
Reference in new issue
Block a user