Files
SublerMKV/Classes/MatroskaSaver.swift
Scott GarrettandClaude Code 80ca3970ec 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>
2026-11-29 20:33:47 -05:00

230 lines
12 KiB
Swift

//
// MatroskaSaver.swift
// Subler
//
import Foundation
import MP42Foundation
/// Owns the on-disk baseline of a tags-only Matroska source file and writes
/// model changes back into it with the window's save semantics: in-place
/// metadata/track-field retagging via MP42MkvTagWriter, or a stream-copy
/// rebuild via MP42MkvRemuxer when the edit is structural (deleted/added
/// tracks, chapter changes), when a full rebuild is forced (optimize,
/// Save-As-style different destination), never producing an MP4.
///
/// Shared by Document (window saves) and QueueItem (queue retags MKVs in
/// place instead of converting them) so the pairing/staleness bookkeeping
/// cannot drift between the two save paths.
final class MatroskaSaver {
private var sourceURL: URL
// 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 sourceTracks: [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 model-vs-snapshot against the model on save: because the
// importer itself drops some atoms (duplicate zero timestamps), those
// silently-dropped atoms must not look like edits.
private var chaptersSnapshot: [(timestamp: UInt64, title: String, language: String)]?
// 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 (and the
// queue certainly doesn't).
private var fileSize: UInt64 = 0
private var fileModificationDate: Date?
private var activeWriter: MP42MkvTagWriter?
private var activeRemuxer: MP42MkvRemuxer?
// Called on the writing thread; hosts forward it to their progress UI
// (the window's save sheet listens on the model's progress handler, the
// queue on its delegate).
var progressHandler: ((Double) -> Void)?
/// Builds the tags-only display model for a Matroska importer: metadata
/// merged in, every importer track added (chapter pseudo-track included)
/// with 1-based display trackIds like MKV players number tracks.
///
/// The returned file's undo manager is deliberately not wired yet — the
/// caller wires it after this returns so these addTrack: calls do not
/// open undo groups.
static func buildModel(from importer: MP42FileImporter) -> MP42File {
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.
displayTrackId += 1
track.trackId = displayTrackId
}
return file
}
/// - parameter model: the tags-only model built by `buildModel(from:)`
/// from this same `importer` (track identity is the pairing baseline).
init(sourceURL: URL, importer: MP42FileImporter, model: MP42File) {
self.sourceURL = sourceURL
// Order-sensitive snapshot for the remuxer's TrackEntry pairing; the
// chapter pseudo-track has no TrackEntry and must not shift positions.
self.sourceTracks = importer.tracks.filter { $0.isMember(of: MP42ChapterTrack.self) == false }
self.chaptersSnapshot = Self.chapterRows(model.chapters)
snapshotSourceFile()
}
// MARK: Save
/// Writes the model back with the window's save branching.
///
/// - parameter forceStructural: forces the remuxer rebuild even without
/// detected model changes — what the window passes for optimize and
/// Save-As, and what the queue passes when the destination differs
/// from the source (a renamed output or a queue destination folder).
func save(model: MP42File, to url: URL, forceStructural: Bool) 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 = model.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 != sourceTracks.count ||
currentTracks.contains { track in sourceTracks.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.chapterRows(model.chapters)
let chaptersChanged: Bool
switch (modelChapterRows, chaptersSnapshot) {
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
}
// A forced rebuild is the Matroska equivalent of reordering atoms:
// 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 when the destination is the source.
if tracksChanged || chaptersChanged || forceStructural {
// 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 remux(model: model, to: url, currentTracks: currentTracks,
replacementChapters: chaptersChanged ? (model.chapters ?? MP42ChapterTrack()) : nil)
return
}
let writer = MP42MkvTagWriter(url: url)
writer.expectedFileSize = fileSize
writer.expectedModificationDate = fileModificationDate
writer.progressHandler = { [weak self] progress in
self?.progressHandler?(progress)
}
activeWriter = writer
defer { activeWriter = nil }
// Track edits (name/language/enabled/subtitle forced) ride along; the
// chapter pseudo-track is skipped by the writer.
try writer.write(model.metadata, tracks: model.tracks)
// The file we just wrote is the new baseline for the staleness check.
snapshotSourceFile()
}
func cancel() {
activeWriter?.cancel()
activeRemuxer?.cancel()
}
// MARK: Remux
// 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 func remux(model: MP42File, to url: URL, currentTracks: [MP42Track],
replacementChapters: MP42ChapterTrack?) throws {
let remuxer = MP42MkvRemuxer(sourceURL: sourceURL)
remuxer.expectedFileSize = fileSize
remuxer.expectedModificationDate = fileModificationDate
remuxer.progressHandler = { [weak self] progress in
self?.progressHandler?(progress)
}
// nil keeps the source Chapters element verbatim.
remuxer.replacementChapters = replacementChapters
activeRemuxer = remuxer
defer { activeRemuxer = nil }
try remuxer.remux(to: url, metadata: model.metadata,
sourceTracks: sourceTracks, currentTracks: currentTracks)
// 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").
chaptersSnapshot = Self.chapterRows(model.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
sourceTracks.contains(where: { $0 === track }) == false
}
sourceTracks = sourceTracks.filter { track in
currentTracks.contains(where: { $0 === track })
} + addedTracks
// A Save-As-style different destination becomes the new source: the
// next save reads/pairs against the file we just wrote.
if url != sourceURL {
sourceURL = url
}
snapshotSourceFile()
}
// MARK: Baseline helpers
private func snapshotSourceFile() {
let attributes = try? FileManager.default.attributesOfItem(atPath: sourceURL.path)
fileSize = (attributes?[.size] as? NSNumber)?.uint64Value ?? 0
fileModificationDate = attributes?[.modificationDate] as? Date
}
private static func chapterRows(_ 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) }
}
}