From 330236735d3876000d5e1f37f59b48e2c3f8acaa Mon Sep 17 00:00:00 2001 From: Scott Garrett Date: Thu, 26 Nov 2026 11:53:50 -0500 Subject: [PATCH] Add subtitle tracks to open Matroska documents MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MKV docs can now import .srt/.ssa/.ass subtitle files, written as S_TEXT/UTF8 by MP42MkvRemuxer (submodule bump). Video/audio adds and other subtitle formats stay refused by both sides. - DocumentWindowController: split selectFile: validation so MKV docs get an Import panel restricted to matroskaSubtitleExtensions (kept in sync with the remuxer's gate); showImportSheet routes MKV docs to importSubtitleTracksForMatroska, which imports each file with a plain MP42FileImporter (no track-selection sheet), attaches the conversion-settings defaults addTrack: asserts on, and assigns the next display trackId. Drag-drop already funnels through showImportSheet. didSelect skips organizeAlternateGroups/inferMediaCharacteristics on MKV docs — same TrackEntry-pairing protection as delete. - Document: the tagsChanged check already caught additions; the post-remux snapshot now appends the added tracks behind the kept ones, matching the TrackEntry order in the written file, so a later tags-only save pairs correctly instead of double-appending. - ScriptCommand: the AppleScript "save as" command called mp4.write(to:) directly, which muxed a QuickTime MP4 over a Matroska document. Route isMatroska documents through Document.save(saveAsOperation) so writeMatroska picks the tag-writer/remux path and enforces the mkv destination. Verified with the /tmp/subler-mkv-test harness (matrix PASS=276: add srt/ass, add+drop mix, no-cues source, bad-file and drop-all refusals, idempotent re-save, post-add tag edit) and against the live app (scripted import + save on a fixture copy; output checked with mkvmerge/mkvextract/ffmpeg and reopened cleanly). Co-Authored-By: Claude Code --- CLAUDE.md | 4 +- Classes/Document.swift | 22 +++++-- Classes/DocumentWindowController.swift | 90 ++++++++++++++++++++++++-- Classes/ScriptCommand.swift | 25 ++++++- MP42Foundation | 2 +- 5 files changed, 125 insertions(+), 18 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index b22ea93..2660872 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 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. 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 **add/reorder and MP4-only properties stay gated** (`PropertyView.isReadOnly` disables the tabs; metadata tabs stay editable), 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 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). - **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`. @@ -50,7 +50,7 @@ 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. -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 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. +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. 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. diff --git a/Classes/Document.swift b/Classes/Document.swift index 997ef50..85ef18e 100644 --- a/Classes/Document.swift +++ b/Classes/Document.swift @@ -308,13 +308,15 @@ final class Document: NSDocument { } let currentTracks = mp4.tracks.filter { $0.isMember(of: MP42ChapterTrack.self) == false } - // Structural change == some importer-created track is gone. Tracks are - // paired by object identity, so a reordered (impossible: reorder is - // gated on MKV docs) or merely renamed track still compares equal. - let tracksRemoved = currentTracks.count != mkvSourceTracks.count || + // Structural change == some importer-created track is gone, or the + // model carries a track the importer never produced (an imported + // subtitle). Tracks are paired by object identity, so a reordered + // (impossible: reorder is gated on MKV docs) or merely renamed track + // still compares equal. + let tracksChanged = currentTracks.count != mkvSourceTracks.count || currentTracks.contains { track in mkvSourceTracks.contains(where: { $0 === track }) == false } - if tracksRemoved || saveOperation != .saveOperation { + if tracksChanged || saveOperation != .saveOperation { try remuxMatroska(to: url, currentTracks: currentTracks) return } @@ -355,10 +357,16 @@ final class Document: NSDocument { sourceTracks: mkvSourceTracks, currentTracks: currentTracks) mkvRemuxer = nil // The output keeps the surviving TrackEntry elements in source file - // order, so re-snapshot the pairing baseline in that same order. + // order and appends one TrackEntry per added subtitle track last + // (MP42MkvRemuxer), so re-snapshot the pairing baseline in that same + // order — otherwise the appended track would look "added" again on + // the next save and the TrackEntry count would mispair. + let addedTracks = currentTracks.filter { track in + mkvSourceTracks.contains(where: { $0 === track }) == false + } mkvSourceTracks = mkvSourceTracks.filter { track in currentTracks.contains(where: { $0 === track }) - } + } + addedTracks snapshotMatroskaFile(at: url) } diff --git a/Classes/DocumentWindowController.swift b/Classes/DocumentWindowController.swift index 01bd4d4..4dbddb0 100644 --- a/Classes/DocumentWindowController.swift +++ b/Classes/DocumentWindowController.swift @@ -282,9 +282,13 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac #selector(sendToQueue(_:)): return true - // Track/chapter modifications: unavailable in Matroska tags-only mode. - case #selector(selectFile(_:)), - #selector(searchChapters(_:)), + // Matroska documents may import subtitle text files (written as + // S_TEXT/UTF8 by the stream-copy remuxer on save). + case #selector(selectFile(_:)): + return true + + // Chapter/track bulk modifications: unavailable in Matroska tags-only mode. + case #selector(searchChapters(_:)), #selector(addChaptersEvery(_:)), #selector(iTunesFriendlyTrackGroups(_:)), #selector(clearTrackNames(_:)), @@ -566,6 +570,26 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac panel.canChooseFiles = true panel.canChooseDirectories = false + if doc.isMatroska { + // A Matroska document can only gain subtitle text tracks (the + // stream-copy remuxer writes them as S_TEXT/UTF8); chapter files + // (.txt/.csv) stay unavailable because chapter writing is not + // implemented for Matroska. + if #available(macOS 11, *) { + panel.allowedContentTypes = DocumentWindowController.matroskaSubtitleExtensions.compactMap { + UTType(filenameExtension: $0) + } + } else { + panel.allowedFileTypes = DocumentWindowController.matroskaSubtitleExtensions + } + panel.beginSheetModal(for: windowForSheet) { (response) in + if response == NSApplication.ModalResponse.OK { + self.showImportSheet(fileURLs: panel.urls) + } + } + return + } + if #available(macOS 11, *) { panel.allowedContentTypes = MP42FileImporter.supportedContentTypes() + [.text, .commaSeparatedText] } else { @@ -588,8 +612,15 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac } } + /// Subtitle text files a Matroska document can gain — must stay in sync + /// with the extension gate in MP42MkvRemuxer's added-track validation. + static let matroskaSubtitleExtensions = ["srt", "ssa", "ass"] + func showImportSheet(fileURLs: [URL]) { - guard doc.isMatroska == false else { return } + if doc.isMatroska { + importSubtitleTracksForMatroska(fileURLs: fileURLs) + return + } do { let controller = try FileImportController(fileURLs: fileURLs, delegate: self) @@ -610,6 +641,52 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac } } + // A Matroska document gains subtitle tracks by re-parsing the source text + // file at save time (MP42MkvRemuxer writes S_TEXT/UTF8 BlockGroups), so + // the model only needs the track object with its URL — no FileImportController + // sheet, and crucially none of didSelect's organizeAlternateGroups/ + // inferMediaCharacteristics churn, which would shift model indices and + // break the remuxer's TrackEntry↔sourceTracks identity pairing. + func importSubtitleTracksForMatroska(fileURLs: [URL]) { + let allowed = DocumentWindowController.matroskaSubtitleExtensions + let subtitleURLs = fileURLs.filter { allowed.contains($0.pathExtension.lowercased()) } + guard subtitleURLs.isEmpty == false else { return } + + var addedTracks: [MP42Track] = [] + var nextDisplayId: MP42TrackId = (mp4.tracks.map { $0.trackId }.max() ?? 0) + 1 + for url in subtitleURLs { + do { + let importer = try MP42FileImporter(url: url) + for track in importer.tracks { + guard track.isMember(of: MP42ChapterTrack.self) == false else { continue } + // Same addTrack: invariant the tags-only read establishes + // (see Document.readMatroska) — codecs MP4 cannot carry + // as-is must carry conversion settings. + if trackNeedConversion(track.format) { + (track as? MP42SubtitleTrack)?.conversionSettings = MP42ConversionSettings.subtitlesConversion() + } + mp4.addTrack(track) + // addTrack: zeroes trackId; keep the table numbering dense. + track.trackId = nextDisplayId + nextDisplayId += 1 + addedTracks.append(track) + } + } + catch { + if let windowForSheet = doc.windowForSheet { + presentError(error, modalFor: windowForSheet, delegate: nil, didPresent: nil, contextInfo: nil) + } else { + presentError(error) + } + } + } + + guard addedTracks.isEmpty == false else { return } + doc.updateChangeCount(.changeDone) + tracksViewController.reloadData() + tracksViewController.selectTracks(addedTracks) + } + @objc func importFilesDirectly(_ fileURLs: [URL]) { do { let controller = try FileImportController(fileURLs: fileURLs, delegate: self) @@ -631,7 +708,10 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac mp4.addTrack(track) } - if tracks.isEmpty == false { + // Reordering must never touch a Matroska document: the remuxer pairs + // TrackEntry elements against mkvSourceTracks by identity, and a + // reordered model would mispair them (same rule as delete(tracks:)). + if tracks.isEmpty == false, doc.isMatroska == false { if Prefs.organizeAlternateGroups { mp4.organizeAlternateGroups() if Prefs.inferMediaCharacteristics { diff --git a/Classes/ScriptCommand.swift b/Classes/ScriptCommand.swift index 879eaf2..03d3d17 100644 --- a/Classes/ScriptCommand.swift +++ b/Classes/ScriptCommand.swift @@ -342,15 +342,34 @@ class SBSaveAsScriptCommand: NSScriptCommand, ScriptCommandDocumentTargeting { logger.write(toLog: "No document available for save as operation") return nil } - + // Use the helper method to extract the destination path guard let path = extractFilePath() else { return nil } - + let destinationURL = URL(fileURLWithPath: path) let fileName = destinationURL.lastPathComponent - + + // mp4.write(to:) below muxes QuickTime atoms and would happily write + // an MP4 over a Matroska document, so route those through NSDocument + // instead: that picks the tag-writer/remux path in writeMatroska, + // enforces the mkv/mka/mks destination, does the fileURL/change-count + // bookkeeping, and reports progress itself via Document.save. + if sublerDoc.isMatroska { + // "Matroska video" is the CFBundleTypeName covering mkv/mka/mks + // (NSDocument.documentType is unavailable from Swift; writeSafely + // only re-checks the destination extension itself). + sublerDoc.save(to: destinationURL, ofType: "Matroska video", for: .saveAsOperation) { error in + if let error = error { + logger.write(toLog: "Failed to save document: \(error.localizedDescription)") + } else { + logger.write(toLog: "Script save of \(fileName) completed") + } + } + return path + } + // Build options dictionary with 64-bit settings from UI preferences var options: [String: Any] = [:] options[MP4264BitData] = Prefs.mp464bitOffset diff --git a/MP42Foundation b/MP42Foundation index 1040f47..8ba3f25 160000 --- a/MP42Foundation +++ b/MP42Foundation @@ -1 +1 @@ -Subproject commit 1040f4754233cf590c420e2ee010ec65c5b3ad24 +Subproject commit 8ba3f25a2c7a7026d29985164f909bfa0e3959f2