Open and edit Matroska files in place, including track removal

.mkv/.mka/.mks now open directly into a tags-only document instead of
forcing the convert-import sheet:

- Metadata, cover art, and the four per-track fields Matroska stores
  (name, language, enabled, subtitle forced) save back into the same
  file via MP42MkvTagWriter; MP4-only properties stay read-only.
- Real tracks can be deleted and Save-As is enabled; both go through
  MP42MkvRemuxer's stream-copy rebuild (Document keeps an importer-order
  track snapshot and pairs TrackEntry elements by object identity).
  Destinations must stay .mkv/.mka/.mks.
- Info.plist: the Matroska document type becomes Editor so NSDocument
  offers .mkv Save-As instead of defaulting to the MP4 type.
- Delete on MKV docs skips organizeAlternateGroups/
  inferMediaCharacteristics because they reorder the model, which the
  TrackEntry pairing depends on; chapter rows stay undeletable.

Bumps MP42Foundation for the Matroska tagging/remux support.

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
Scott GarrettandClaude Code committed 2026-11-25 19:48:34 -05:00
1 parent 0c3d7de364
commit eb386a52c3
14 files changed
+540 -32

No files matched your search

+170 -11
View File
@@ -15,6 +15,20 @@ final class Document: NSDocument {
private(set) var mp4: MP42File
private var unsupportedMp4Brand: Bool
// Matroska documents open in tags-only mode: the model is an in-memory
// MP42File whose tracks are demuxed for display and whose metadata is
// 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] = []
private var mkvFileSize: UInt64 = 0
private var mkvFileModificationDate: Date?
override init() {
self.cancelled = false
self.options = [:]
@@ -60,6 +74,11 @@ final class Document: NSDocument {
override public var isEntireFileLoaded: Bool { get { return false } }
override func read(from url: URL, ofType typeName: String) throws {
if MP42FileImporter.isMatroskaFileType(url.pathExtension) {
try readMatroska(from: url)
return
}
do {
mp4 = try MP42File(url: url)
mp4.undo = undoManager
@@ -69,8 +88,12 @@ final class Document: NSDocument {
}
override func revert(toContentsOf url: URL, ofType typeName: String) throws {
mp4 = try MP42File(url: url)
mp4.undo = undoManager
if isMatroska || MP42FileImporter.isMatroskaFileType(url.pathExtension) {
try readMatroska(from: url)
} else {
mp4 = try MP42File(url: url)
mp4.undo = undoManager
}
if let docController = windowControllers.first as? DocumentWindowController {
docController.reloadData()
@@ -80,6 +103,60 @@ final class Document: NSDocument {
updateChangeCount(.changeCleared)
}
private func readMatroska(from url: URL) throws {
// tagsOnly: the importer mirrors the file's own track flags instead of
// 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
}
mp4 = file
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 }
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
}
// MARK: Save
override nonisolated class var autosavesInPlace: Bool { return false }
@@ -125,6 +202,12 @@ final class Document: NSDocument {
if let error = error {
completionHandler(error);
} else if self.isMatroska {
// The file was retagged in place; the tracks in the model are
// still the ones on disk, so only the undo stack needs reset.
self.undoManager?.removeAllActions()
docController?.reloadData()
completionHandler(error)
} else {
do {
let reloadedFile = try MP42File(url: url)
@@ -148,6 +231,8 @@ final class Document: NSDocument {
func cancelSave() {
cancelled = true
mkvWriter?.cancel()
mkvRemuxer?.cancel()
mp4.cancel()
}
@@ -173,6 +258,20 @@ final class Document: NSDocument {
unblockUserInteraction()
preventSleep()
defer {
allowSleep()
optimize = false
options = [:]
mkvWriter = nil
mkvRemuxer = nil
}
if isMatroska {
try writeMatroska(to: url, for: saveOperation)
cancelled = false
return
}
if Prefs.organizeAlternateGroups {
mp4.organizeAlternateGroups()
if Prefs.inferMediaCharacteristics {
@@ -181,19 +280,14 @@ final class Document: NSDocument {
}
}
defer {
allowSleep()
optimize = false
options = [:]
}
switch saveOperation {
case .saveOperation:
try mp4.update(options: options)
case .saveAsOperation:
try mp4.write(to: url, options: options)
default:
fatalError("Unsupported save operation")
throw NSError(domain: NSCocoaErrorDomain, code: NSFileWriteUnknownError,
userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("The save operation is not supported.", comment: "Document unsupported save operation error.")])
}
if optimize && cancelled == false {
@@ -207,6 +301,67 @@ final class Document: NSDocument {
cancelled = false
}
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. 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 ||
currentTracks.contains { track in mkvSourceTracks.contains(where: { $0 === track }) == false }
if tracksRemoved || saveOperation != .saveOperation {
try remuxMatroska(to: url, currentTracks: currentTracks)
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 func remuxMatroska(to url: URL, currentTracks: [MP42Track]) throws {
guard let sourceURL = fileURL 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)
}
mkvRemuxer = remuxer
try remuxer.remux(to: url, metadata: mp4.metadata,
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.
mkvSourceTracks = mkvSourceTracks.filter { track in
currentTracks.contains(where: { $0 === track })
}
snapshotMatroskaFile(at: url)
}
// MARK: Save panel
private var accessoryViewController: SaveOptions?
@@ -267,8 +422,12 @@ final class Document: NSDocument {
return true
case #selector(save(_:)) where isDocumentEdited == true:
return true
case #selector(saveAs(_:)),
#selector(sendToQueue(_:)):
case #selector(saveAs(_:)):
// MKV Save-As runs through MP42MkvRemuxer (stream copy, same
// container — the destination must stay .mkv/.mka/.mks, checked
// in writeMatroska).
return true
case #selector(sendToQueue(_:)):
return true
case #selector(saveAndOptimize(_:)) where isDocumentEdited == false && mp4.hasFileRepresentation == true:
return true