Retag queued Matroska files in place instead of converting to MP4

The queue now mirrors the document window for .mkv/.mka/.mks sources.
The window's whole save branching (importer-order track snapshot, chapter
row snapshot, staleness guard, tag-writer-vs-remuxer choice) moved out of
Document into a shared MatroskaSaver used by both Document and QueueItem
so the two paths cannot drift. Queue items import tags-only, keep the
Matroska extension (in place, or stream-copy into a destination folder),
MP4-only actions no-op on them, and send-to-queue hands the item the
document's model plus its identity pairing baseline via attachMatroskaSaver.

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
Scott GarrettandClaude Code committed 2026-11-29 20:33:47 -05:00
1 parent a1da1c8106
commit 80ca3970ec
7 files changed
+442 -195

No files matched your search

+34 -167
View File
@@ -20,21 +20,11 @@ final class Document: NSDocument {
// written back into the original file (Tags + cover attachment) by
// MP42MkvTagWriter on save.
private(set) var isMatroska = false
private var mkvWriter: MP42MkvTagWriter?
private var mkvRemuxer: MP42MkvRemuxer?
// Tracks exactly as the importer produced them (file order, chapter
// pseudo-track filtered): the baseline MP42MkvRemuxer pairs TrackEntry
// elements against, so a deleted track is detected by object identity.
private var mkvSourceTracks: [MP42Track] = []
// Chapter rows as the file's baseline holds them (model milliseconds,
// plus the track-level chapter language the remuxer stamps as
// ChapterLanguage). 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 an edit.
private var mkvChaptersSnapshot: [(timestamp: UInt64, title: String, language: String)]?
private var mkvFileSize: UInt64 = 0
private var mkvFileModificationDate: Date?
// The pairing/staleness baseline (importer track snapshot, chapter rows,
// file size/mtime) and the branching write-back (in-place tag writer vs
// stream-copy remuxer) live in MatroskaSaver — shared with QueueItem so a
// queued Matroska file saves exactly like the window does.
private(set) var mkvSaver: MatroskaSaver?
override init() {
self.cancelled = false
@@ -115,54 +105,19 @@ final class Document: NSDocument {
// applying the MP4 conversion heuristic, so the model matches the file
// (MP42MkvTagWriter diffs track fields against it on save).
let importer = try MP42FileImporter(url: url, tagsOnly: true)
let file = MP42File()
file.metadata.merge(importer.metadata, overwrite: true)
var displayTrackId: MP42TrackId = 0
for track in importer.tracks {
// -[MP42File addTrack:] asserts that tracks whose codec cannot be
// muxed into MP4 as-is (mp3, vorbis, srt, pgs, …) carry conversion
// settings. Tags-only documents never mux these tracks, but
// satisfy the invariant with the same defaults the convert-import
// flow uses (see FileImportController.addTracks).
if trackNeedConversion(track.format), track.isMember(of: MP42ChapterTrack.self) == false {
switch track {
case let audioTrack as MP42AudioTrack:
audioTrack.conversionSettings = MP42AudioConversionSettings.audioConversion(withBitRate: Prefs.audioBitrate,
mixDown: MP42AudioMixdown(Prefs.audioMixdown),
drc: Prefs.audioDRC)
case let subtitleTrack as MP42SubtitleTrack:
subtitleTrack.conversionSettings = MP42ConversionSettings.subtitlesConversion()
default:
break
}
}
file.addTrack(track)
// addTrack: zeroes trackId (pending-mux bookkeeping, the real
// IDs come from the muxer) and tags-only documents are never
// muxed, so assign display IDs 1-based like MKV players number
// tracks. The chapter track is numbered too, matching how the
// muxer would eventually number it.
// (file.undo is not wired yet at this point, so this does not
// open an undo group.)
displayTrackId += 1
track.trackId = displayTrackId
}
let file = MatroskaSaver.buildModel(from: importer)
mp4 = file
// (file.undo was not wired during buildModel's addTrack calls, so
// those did not open undo groups.)
mp4.undo = undoManager
isMatroska = true
// Order-sensitive snapshot for the remuxer's TrackEntry pairing; the
// chapter pseudo-track has no TrackEntry and must not shift positions.
mkvSourceTracks = importer.tracks.filter { $0.isMember(of: MP42ChapterTrack.self) == false }
mkvChaptersSnapshot = Self.matroskaChapterRows(mp4.chapters)
snapshotMatroskaFile(at: url)
}
// The tag writer refuses to overwrite a file that changed on disk since
// we read it; NSDocument doesn't perform that check for us here.
private func snapshotMatroskaFile(at url: URL) {
let attributes = try? FileManager.default.attributesOfItem(atPath: url.path)
mkvFileSize = (attributes?[.size] as? NSNumber)?.uint64Value ?? 0
mkvFileModificationDate = attributes?[.modificationDate] as? Date
let saver = MatroskaSaver(sourceURL: url, importer: importer, model: file)
// The save sheet listens on the model's progress handler (see
// DocumentWindowController.startProgressReporting); forward through it.
saver.progressHandler = { [weak self] progress in
self?.mp4.progressHandler?(progress)
}
mkvSaver = saver
}
// MARK: Save
@@ -239,8 +194,7 @@ final class Document: NSDocument {
func cancelSave() {
cancelled = true
mkvWriter?.cancel()
mkvRemuxer?.cancel()
mkvSaver?.cancel()
mp4.cancel()
}
@@ -270,8 +224,6 @@ final class Document: NSDocument {
allowSleep()
optimize = false
options = [:]
mkvWriter = nil
mkvRemuxer = nil
}
if isMatroska {
@@ -310,112 +262,14 @@ final class Document: NSDocument {
}
private func writeMatroska(to url: URL, for saveOperation: NSDocument.SaveOperationType) throws {
guard MP42FileImporter.isMatroskaFileType(url.pathExtension) else {
throw NSError(domain: NSCocoaErrorDomain, code: NSFileWriteUnknownError,
userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("Matroska documents can only be saved as a .mkv, .mka or .mks file.", comment: "Document MKV save destination type error.")])
}
let currentTracks = mp4.tracks.filter { $0.isMember(of: MP42ChapterTrack.self) == false }
// 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 }
// 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 || $0.language != $1.language }
default: chaptersChanged = true
}
// `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).
try remuxMatroska(to: url, currentTracks: currentTracks,
replacementChapters: chaptersChanged ? (mp4.chapters ?? MP42ChapterTrack()) : nil)
return
}
let writer = MP42MkvTagWriter(url: url)
writer.expectedFileSize = mkvFileSize
writer.expectedModificationDate = mkvFileModificationDate
// The save sheet listens on the model's progress handler (see
// DocumentWindowController.startProgressReporting); forward through it.
writer.progressHandler = { [weak self] progress in
self?.mp4.progressHandler?(progress)
}
mkvWriter = writer
// Track edits (name/language/enabled/subtitle forced) ride along; the
// chapter pseudo-track is skipped by the writer.
try writer.write(mp4.metadata, tracks: mp4.tracks)
mkvWriter = nil
// The file we just wrote is the new baseline for the staleness check.
snapshotMatroskaFile(at: url)
}
// Stream-copy rebuild: blocks are copied verbatim except those of removed
// tracks, and metadata/cover/track-field edits ride in the same pass.
// Writes a temp file and renames atomically; see MP42MkvRemuxer.h.
private static func matroskaChapterRows(_ track: MP42ChapterTrack?)
-> [(timestamp: UInt64, title: String, language: String)]? {
guard let track else { return nil }
// The language is track-level; repeated per row so the zip comparison
// above covers language-only edits.
let language = track.language
return track.chapters.map { ($0.timestamp, $0.title, language) }
}
private func remuxMatroska(to url: URL, currentTracks: [MP42Track],
replacementChapters: MP42ChapterTrack?) throws {
guard let sourceURL = fileURL else {
guard let saver = mkvSaver else {
throw NSError(domain: NSCocoaErrorDomain, code: NSFileWriteUnknownError,
userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("The Matroska source file is unknown.", comment: "Document MKV remux missing source error.")])
}
let remuxer = MP42MkvRemuxer(sourceURL: sourceURL)
remuxer.expectedFileSize = mkvFileSize
remuxer.expectedModificationDate = mkvFileModificationDate
remuxer.progressHandler = { [weak self] progress in
self?.mp4.progressHandler?(progress)
}
// nil keeps the source Chapters element verbatim.
remuxer.replacementChapters = replacementChapters
mkvRemuxer = remuxer
try remuxer.remux(to: url, metadata: mp4.metadata,
sourceTracks: mkvSourceTracks, currentTracks: currentTracks)
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
// 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)
// `optimize` (Save and Optimize) forces the structural rebuild, as
// does Save-As; the saver branches in-place tag writer vs stream-copy
// remuxer (see MatroskaSaver.save).
try saver.save(model: mp4, to: url, forceStructural: optimize || saveOperation != .saveOperation)
}
// MARK: Save panel
@@ -445,6 +299,19 @@ final class Document: NSDocument {
guard let windowForSheet = windowForSheet else { return }
let queue = QueueController.shared
// Matroska document: match the window's save semantics — the queue
// item writes metadata back into the original file instead of muxing
// a converted copy, so the destination is the file itself (no save
// panel) and the item inherits the document's Matroska baseline: the
// TrackEntry↔track pairing is by object identity and cannot be
// rebuilt from the model.
if isMatroska, let fileURL = fileURL, let saver = mkvSaver {
let item = QueueItem(mp4: mp4, fileURL: fileURL, destURL: fileURL)
item.attachMatroskaSaver(saver)
queue.add(item)
close()
return
}
if mp4.hasFileRepresentation {
let item = QueueItem(mp4: mp4)
queue.add(item, applyPreset: true)