Files
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

369 lines
13 KiB
Swift

//
// Document.swift
// Subler
//
// Created by Damiano Galassi on 10/02/2018.
//
import Cocoa
import IOKit.pwr_mgt
import MP42Foundation
@objc(SBDocument)
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
// 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
self.options = [:]
self.optimize = false
self.unsupportedMp4Brand = false
self.mp4 = MP42File()
super.init()
self.mp4.undo = undoManager
}
init(mp4: MP42File) {
self.cancelled = false
self.options = [:]
self.optimize = false
self.unsupportedMp4Brand = false
self.mp4 = mp4
super.init()
if let url = mp4.url {
fileURL = url
} else {
updateChangeCount(.changeDone)
}
self.mp4.undo = undoManager
}
override func makeWindowControllers() {
let documentWindowController = DocumentWindowController()
addWindowController(documentWindowController)
documentWindowController.showWindow(self)
if let url = fileURL, unsupportedMp4Brand {
// We can't edit this file, so ask the user if it wants to import it
documentWindowController.showImportSheet(fileURLs: [url])
fileURL = nil
}
}
// MARK: Read
override class func canConcurrentlyReadDocuments(ofType typeName: String) -> Bool { return true }
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
} catch {
unsupportedMp4Brand = true
}
}
override func revert(toContentsOf url: URL, ofType typeName: String) throws {
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()
undoManager?.removeAllActions()
}
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 = 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
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
override nonisolated class var autosavesInPlace: Bool { return false }
private var optimize: Bool
private var options: [String : Any]
private var cancelled: Bool
private func saveOptions(for saveOperation: NSDocument.SaveOperationType) -> [String : Any] {
var options = [String : Any]()
if Prefs.chaptersPreviewTrack {
options[MP42GenerateChaptersPreviewTrack] = true
options[MP42ChaptersPreviewPosition] = Prefs.chaptersPreviewPosition
}
if Prefs.forceHvc1 {
options[MP42ForceHvc1] = true
}
if let accessoryViewController = accessoryViewController,
saveOperation == .saveAsOperation || saveOperation == .saveToOperation {
options[MP4264BitData] = accessoryViewController._64bit_data.state == .on ? true : false
options[MP4264BitTime] = accessoryViewController._64bit_time.state == .on ? true : false
optimize = accessoryViewController.optimize.state == .on ? true : false
}
return options
}
@IBAction func saveAndOptimize(_ sender: Any) {
optimize = true
save(self)
}
override func canAsynchronouslyWrite(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType) -> Bool { return true }
override func save(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType, completionHandler: @escaping (Error?) -> Void) {
let docController = windowControllers.first as? DocumentWindowController
let modifiedCompletionhandler = { (error: Error?) -> Void in
docController?.endProgressReporting()
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)
self.mp4 = reloadedFile
self.mp4.undo = self.undoManager
self.undoManager?.removeAllActions()
docController?.reloadData()
completionHandler(error)
} catch {
completionHandler(error)
}
}
}
options = saveOptions(for: saveOperation)
releaseSavePanel()
docController?.startProgressReporting()
super.save(to: url, ofType: typeName, for: saveOperation, completionHandler: modifiedCompletionhandler)
}
func cancelSave() {
cancelled = true
mkvSaver?.cancel()
mp4.cancel()
}
private var sleepAssertion: IOPMAssertionID = IOPMAssertionID(0)
private var sleepAssertionSuccess: IOReturn = kIOReturnInvalid
private func preventSleep() {
sleepAssertionSuccess = IOPMAssertionCreateWithName(kIOPMAssertPreventUserIdleSystemSleep as CFString,
IOPMAssertionLevel(kIOPMAssertionLevelOn),
"Subler Save Operation" as CFString,
&sleepAssertion)
}
private func allowSleep() {
if sleepAssertionSuccess == kIOReturnSuccess {
IOPMAssertionRelease(sleepAssertion)
sleepAssertionSuccess = kIOReturnInvalid
sleepAssertion = IOPMAssertionID(0)
}
}
override func writeSafely(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType) throws {
unblockUserInteraction()
preventSleep()
defer {
allowSleep()
optimize = false
options = [:]
}
if isMatroska {
try writeMatroska(to: url, for: saveOperation)
cancelled = false
return
}
if Prefs.organizeAlternateGroups {
mp4.organizeAlternateGroups()
if Prefs.inferMediaCharacteristics {
mp4.inferTracksLanguages()
mp4.inferMediaCharacteristics()
}
}
switch saveOperation {
case .saveOperation:
try mp4.update(options: options)
case .saveAsOperation:
try mp4.write(to: url, options: options)
default:
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 {
DispatchQueue.main.async {
let docController = self.windowControllers.first as? DocumentWindowController
docController?.setProgress(title: NSLocalizedString("Optimizing…", comment: "Document Optimize sheet."))
}
mp4.optimize()
}
cancelled = false
}
private func writeMatroska(to url: URL, for saveOperation: NSDocument.SaveOperationType) throws {
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.")])
}
// `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
private var accessoryViewController: SaveOptions?
override var shouldRunSavePanelWithAccessoryView: Bool { return false }
override var savePanelShowsFileFormatsControl: Bool { return false }
override func prepareSavePanel(_ savePanel: NSSavePanel) -> Bool {
self.accessoryViewController = SaveOptions(doc: self, savePanel: savePanel)
savePanel.isExtensionHidden = false
savePanel.accessoryView = accessoryViewController?.view
return true
}
private func releaseSavePanel() {
accessoryViewController?.saveUserDefaults()
accessoryViewController = nil
}
// MARK: Queue
@IBAction func sendToQueue(_ sender: Any) {
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)
close()
}
else {
let panel = NSSavePanel()
panel.prompt = NSLocalizedString("Send To Queue", comment: "")
let handler = { (response: NSApplication.ModalResponse) in
if response == NSApplication.ModalResponse.OK, let url = panel.url {
let options = self.saveOptions(for: .saveAsOperation)
let item = QueueItem(mp4: self.mp4, destURL: url, attributes: options, optimize: self.optimize)
queue.add(item)
self.releaseSavePanel()
self.close()
}
}
if prepareSavePanel(panel) {
panel.beginSheetModal(for: windowForSheet, completionHandler: handler)
}
}
}
// MARK: User interface validation
override func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool {
switch item.action {
case #selector(revertToSaved(_:)) where isDocumentEdited == true:
return true
case #selector(save(_:)) where isDocumentEdited == true:
return true
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
// On a Matroska document optimize = full remuxer rebuild (see
// writeMatroska), the container-equivalent of the atom-order optimize.
// Tags-only models report hasFileRepresentation == false (their tracks
// are never muxed), so the on-disk precondition there is just the
// remux source: fileURL.
case #selector(saveAndOptimize(_:)) where isDocumentEdited == false
&& (isMatroska ? fileURL != nil : mp4.hasFileRepresentation == true):
return true
default:
return false
}
}
}