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:
Scott GarrettandClaude Code committed 2026-11-26 12:54:58 -05:00
1 parent 330236735d
commit 8520d729c6
4 files changed
+89 -24

No files matched your search

+40 -3
View File
@@ -26,6 +26,12 @@ final class Document: NSDocument {
// 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).
// 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 mkvFileModificationDate: Date?
@@ -146,6 +152,7 @@ final class Document: NSDocument {
// 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)
}
@@ -315,9 +322,27 @@ final class Document: NSDocument {
// 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 }
default: chaptersChanged = true
}
if tracksChanged || saveOperation != .saveOperation {
try remuxMatroska(to: url, currentTracks: currentTracks)
if tracksChanged || chaptersChanged || 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
}
@@ -341,7 +366,13 @@ final class Document: NSDocument {
// 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 {
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 {
throw NSError(domain: NSCocoaErrorDomain, code: NSFileWriteUnknownError,
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
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
+44 -18
View File
@@ -236,11 +236,13 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
detailsItem.viewController.view.addSubview(trackViewController.view)
// Tags-only mode: tracks are displayed but cannot be modified, except
// for the fields MP42MkvTagWriter writes back (see allowsTrackEditing).
// Set after the view is loaded so it wins over controls that the view
// controllers enable during their own updates.
// for the fields MP42MkvTagWriter writes back (see allowsTrackEditing)
// and the chapters tab (ChapterViewController edits ride the remuxer's
// 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
if doc.isMatroska, !(trackViewController is MovieViewController) {
if doc.isMatroska, !(trackViewController is MovieViewController),
!(trackViewController is ChapterViewController) {
trackViewController.allowsTrackEditing = true
trackViewController.isReadOnly = true
} else {
@@ -506,7 +508,14 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
private func addChapters(fileURL: URL) {
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.selectTracks([track])
}
@@ -517,6 +526,7 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
if let track = mp4.chapters {
chapterViewController?.track = track
tracksViewController.selectTracks([track])
if doc.isMatroska { doc.updateChangeCount(.changeDone) }
}
}
catch {
@@ -571,20 +581,30 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
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.
// A Matroska document can gain subtitle text tracks (the
// stream-copy remuxer writes them as S_TEXT/UTF8) and chapters
// (.txt creates/replaces the chapter track, .csv updates an
// existing one — same dispatch the MP4 branch uses below).
let chapterExtensions = ["txt", "csv"]
if #available(macOS 11, *) {
panel.allowedContentTypes = DocumentWindowController.matroskaSubtitleExtensions.compactMap {
panel.allowedContentTypes = (DocumentWindowController.matroskaSubtitleExtensions + chapterExtensions).compactMap {
UTType(filenameExtension: $0)
}
} else {
panel.allowedFileTypes = DocumentWindowController.matroskaSubtitleExtensions
panel.allowedFileTypes = DocumentWindowController.matroskaSubtitleExtensions + chapterExtensions
}
panel.beginSheetModal(for: windowForSheet) { (response) in
if response == NSApplication.ModalResponse.OK {
self.showImportSheet(fileURLs: panel.urls)
guard response == NSApplication.ModalResponse.OK else { return }
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
@@ -752,13 +772,19 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
let items = pasteboard.readObjects(forClasses: [NSURL.classForCoder()], options: [:]) as? [URL]
else { return false }
// Metadata drops are fine in tags-only mode; chapter and track
// imports modify tracks, which Matroska documents cannot do.
if doc.isMatroska == false {
let chapters = items.filter { $0.pathExtension.lowercased() == "txt" }
if let url = chapters.first {
// Metadata drops are fine in tags-only mode. Chapters ride the
// remuxer on Matroska documents, so txt/csv drops route there too;
// everything else that would add a track goes through the import
// panel (which routes Matroska docs to the subtitle-only path).
if doc.isMatroska {
if let url = items.first(where: { $0.pathExtension.lowercased() == "txt" }) {
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" }