Make chapter tracks deletable, insertable, and language-editable

Delete: the phase-1 gate against deleting the chapter pseudo-track on
Matroska documents is obsolete now that chapter changes ride the
stream-copy remuxer — a removed pseudo-track simply makes the model
report "no chapters", which removes the Chapters element on save (the
same path emptying the Chapters tab already took). The toolbar Delete
button's validation is corrected too; it still rejected chapter-only
selections after deleteSelection was opened up.

Insert: the Actions toolbar gets a single "Insert a chapter" item, and
"Insert a chapter every" (previously MP4-only) is enabled on Matroska.
Both create the chapter track when the document has none, doing the
tags-only bookkeeping the model needs (dense display trackId,
updateChangeCount). A single insert lands 1s after the latest start,
clamped to the track duration, so it can never tie with a stored
chapter — ties get clamped +1ms on write and would silently shift the
user's own chapter times.

Language: the chapter row's language popup stays editable on MKV
documents (the value rides the remuxer's chapter rebuild, not the tag
writer, since the pseudo-track has no TrackEntry), and the Matroska
chapters snapshot carries it so a language-only edit triggers the
remux. Pairs with the submodule's ChapterLanguage round trip.

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
Scott GarrettandClaude Code committed 2026-11-26 18:17:37 -05:00
1 parent 8520d729c6
commit f457b4e89c
13 files changed
+124 -30

No files matched your search

+15 -9
View File
@@ -26,12 +26,13 @@ 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)]?
// 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?
@@ -333,7 +334,8 @@ final class Document: NSDocument {
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 }
zip(model, snapshot).contains { $0.timestamp != $1.timestamp
|| $0.title != $1.title || $0.language != $1.language }
default: chaptersChanged = true
}
@@ -366,9 +368,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 static func matroskaChapterRows(_ track: MP42ChapterTrack?) -> [(timestamp: UInt64, title: String)]? {
private static func matroskaChapterRows(_ track: MP42ChapterTrack?)
-> [(timestamp: UInt64, title: String, language: String)]? {
guard let track else { return nil }
return track.chapters.map { ($0.timestamp, $0.title) }
// 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],
+5
View File
@@ -58,11 +58,16 @@ class DocumentToolbarDelegate: NSObject, NSToolbarDelegate {
submenu.addItem(menuItem)
}
let insertChapter = NSMenuItem()
insertChapter.title = NSLocalizedString("Insert a chapter", comment: "Toolbar")
insertChapter.action = #selector(DocumentWindowController.insertChapter(_:))
let chapters = NSMenuItem()
chapters.title = NSLocalizedString("Insert a chapter every", comment: "Toolbar")
chapters.submenu = submenu
let menu = NSMenu()
menu.addItem(insertChapter)
menu.addItem(chapters)
menu.addItem(NSMenuItem.separator())
menu.addItem(withTitle: NSLocalizedString("Organize alternate groups", comment: "Toolbar"),
+68 -15
View File
@@ -254,12 +254,9 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
}
func delete(tracks: [MP42Track]) {
var tracks = tracks
if doc.isMatroska {
// Only real tracks are deletable on tags-only documents; the save
// path stream-copy-remuxes their blocks away (MP42MkvRemuxer).
tracks = tracks.filter { $0.isMember(of: MP42ChapterTrack.self) == false }
}
// On MKV docs the save path stream-copy-remuxes removed real tracks'
// blocks away (MP42MkvRemuxer); a removed chapter pseudo-track makes
// the model report "no chapters", which deletes the Chapters element.
if tracks.isEmpty == false {
mp4.removeTracks(tracks)
@@ -281,7 +278,9 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
case #selector(selectMetadataFile(_:)),
#selector(searchMetadata(_:)),
#selector(sendToQueue(_:)):
#selector(sendToQueue(_:)),
#selector(insertChapter(_:)),
#selector(addChaptersEvery(_:)):
return true
// Matroska documents may import subtitle text files (written as
@@ -289,9 +288,11 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
case #selector(selectFile(_:)):
return true
// Chapter/track bulk modifications: unavailable in Matroska tags-only mode.
// Track bulk modifications (and the chapter-DB search, whose apply
// path lacks the tags-only bookkeeping): unavailable in Matroska
// tags-only mode. The Insert-a-chapter actions are NOT on this list —
// chapter changes ride the stream-copy remuxer, so they work on MKV.
case #selector(searchChapters(_:)),
#selector(addChaptersEvery(_:)),
#selector(iTunesFriendlyTrackGroups(_:)),
#selector(clearTrackNames(_:)),
#selector(prettifyAudioTrackNames(_:)),
@@ -313,11 +314,9 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
case #selector(DocumentWindowController.deleteTrack(_:)):
// MKV documents allow deleting real tracks (stream-copy remux on
// save); a chapter-row-only or empty selection stays invalid.
let hasDeletable = tracksViewController.selectedTracks.contains {
doc.isMatroska == false || $0.isMember(of: MP42ChapterTrack.self) == false
}
return hasDeletable && NSApp.isActive
// save) and the chapter pseudo-track (the Chapters element is
// removed on save), so any non-empty selection is deletable.
return tracksViewController.selectedTracks.isEmpty == false && NSApp.isActive
default:
return false
@@ -375,8 +374,58 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
delete(tracks: tracksViewController.selectedTracks)
}
// Single-chapter insert that also bootstraps the chapter track, so it
// works on documents without any chapters yet (both containers: on MKV
// the new rows ride the remuxer on save, like the Chapters tab's edits).
@IBAction func insertChapter(_ sender: Any) {
let track: MP42ChapterTrack
if let existing = mp4.chapters {
track = existing
} else {
track = MP42ChapterTrack()
mp4.addTrack(track) // addTrack: replaces any previous chapter track
if doc.isMatroska {
// addTrack: zeroes trackId; keep the table numbering dense.
track.trackId = (mp4.tracks.map { $0.trackId }.max() ?? 0) + 1
}
}
// A brand-new track gets its first chapter at 0; inserting into an
// existing track places the chapter 1s after the latest start, so it
// never ties with a stored chapter (ties get clamped +1ms on write,
// which would silently shift the user's own chapter times). The user
// retimes/renames the row either way.
var newTimestamp: UInt64 = 0
if let last = track.chapters.max(by: { $0.timestamp < $1.timestamp }) {
newTimestamp = last.timestamp + 1000
if track.duration > last.timestamp + 1, newTimestamp >= track.duration {
newTimestamp = track.duration - 1
}
}
let index = track.addChapter("Chapter", timestamp: newTimestamp)
if doc.isMatroska {
// The tags-only model has no muxing step to mark the document.
doc.updateChangeCount(.changeDone)
}
tracksViewController.reloadData()
tracksViewController.selectTracks([track])
chapterViewController?.selectChapter(at: Int(index))
}
@IBAction func addChaptersEvery(_ sender: NSMenuItem) {
let track: MP42ChapterTrack = mp4.chapters ?? { let track = MP42ChapterTrack(); self.mp4.addTrack(track); return track }()
// Creates the chapter track when the document has none (same
// bookkeeping as insertChapter: addTrack: zeroes trackId and the
// tags-only model has no muxing step to mark the document dirty).
let existing = mp4.chapters
let track: MP42ChapterTrack = existing ?? MP42ChapterTrack()
if existing == nil {
mp4.addTrack(track) // addTrack: replaces any previous chapter track
if doc.isMatroska {
track.trackId = (mp4.tracks.map { $0.trackId }.max() ?? 0) + 1
}
}
let minutes = sender.tag * 60 * 1000
if minutes > 0 {
@@ -388,6 +437,10 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
track.addChapter("Chapter 1", timestamp: 0)
}
if doc.isMatroska {
doc.updateChangeCount(.changeDone)
}
tracksViewController.reloadData()
tracksViewController.selectTracks([track])
}
@@ -129,6 +129,18 @@ final class ChapterViewController : PropertyView, NSTableViewDataSource, NSTable
deleteSelection(in: tableView)
}
// Selects and scrolls to a row (used after the window controller appends
// a chapter from the Actions menu, when the tab may not have shown this
// track's table yet).
func selectChapter(at index: Int) {
guard isViewLoaded, index >= 0, index < track.chapters.count else { return }
tableView.reloadData()
tableView.scrollRowToVisible(index)
let indexSet = IndexSet(integer: index)
tableView.selectRowIndexes(indexSet, byExtendingSelection: false)
view.window?.makeFirstResponder(tableView)
}
@IBAction func addChapter(_ sender: Any) {
let index = track.addChapter("Chapter", timestamp: 0)
let indexSet = IndexSet(integer: Int(index))
+15 -3
View File
@@ -46,6 +46,14 @@ final class TracksViewController: NSViewController, NSTableViewDataSource, NSTab
return document.isMatroska == false || track.isMember(of: MP42ChapterTrack.self) == false
}
// The chapter pseudo-track has no TrackEntry for the tag writer, but it
// carries the language the remuxer stamps into every ChapterDisplay on
// save, so its language popup is editable on Matroska documents too.
private func isLanguageEditable(_ track: MP42Track?) -> Bool {
guard let track = track else { return false }
return isFieldEditable(track) || track.isMember(of: MP42ChapterTrack.self)
}
private static let languagesMenu: NSMenu = {
let menu = NSMenu()
menu.autoenablesItems = false
@@ -125,8 +133,12 @@ final class TracksViewController: NSViewController, NSTableViewDataSource, NSTab
func deleteSelection(in tableview: NSTableView) {
// On MKV documents real tracks are deletable too (the remuxer drops
// their blocks on save); the chapter pseudo-track still is not.
let deletable = document.isMatroska ? selectedTracks.filter { isFieldEditable($0) } : selectedTracks
// their blocks on save) and so is the chapter pseudo-track: with it
// gone the model reports "no chapters", so the save remuxes and the
// Chapters element is deleted (same as emptying the Chapters tab).
let deletable = document.isMatroska
? selectedTracks.filter { isFieldEditable($0) || $0.isMember(of: MP42ChapterTrack.self) }
: selectedTracks
guard deletable.isEmpty == false else { return }
delegate?.delete(tracks: deletable)
}
@@ -236,7 +248,7 @@ final class TracksViewController: NSViewController, NSTableViewDataSource, NSTab
}
cell?.textField?.stringValue = MP42Languages.defaultManager.localizedLang(forExtendedTag: track.language)
cell?.popUpButton?.isEnabled = isFieldEditable(track)
cell?.popUpButton?.isEnabled = isLanguageEditable(track)
return cell
case trackInfoColumn?: