Files
SublerMKV/Classes/QueueItem.swift
T
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

594 lines
23 KiB
Swift

//
// QueueItem.swift
// Subler
//
// Created by Damiano Galassi on 28/01/2019.
//
import Cocoa
import MP42Foundation
@objc(SBQueueItem) final class QueueItem: NSObject, NSSecureCoding {
@objc enum Status: Int {
case ready
case editing
case working
case completed
case failed
case cancelled
}
private var destURLInternal: URL
#if SB_SANDBOX
private let destURLInternalBookmark: Data?
#endif
@objc dynamic let fileURL: URL
#if SB_SANDBOX
private let fileURLBookmark: Data?
#endif
@objc dynamic var destURL: URL {
get {
return queue.sync { destURLInternal }
}
set (value) {
queue.sync { destURLInternal = value }
}
}
var mp4File: MP42File?
var localizedWorkingDescription: String?
// Matroska items mirror the window's save: a tags-only model whose
// metadata is written back into the original file (never muxed to MP4).
// The pairing baseline (which importer tracks back which TrackEntry
// elements, chapter rows, file size/mtime) lives in the saver; it's
// transient — a resumed queue re-imports the file instead.
private var matroskaSaver: MatroskaSaver?
/// An item is Matroska iff its source file is one: always true for both
/// entry paths (a queue file chosen by extension, a document's source),
/// and derived (never archived) so prepare() and process() can't disagree.
var isMatroska: Bool {
return MP42FileImporter.isMatroskaFileType(fileURL.pathExtension)
}
/// A document being sent to the queue hands its Matroska baseline to the
/// item: the pairing is by object identity, so it travels with the exact
/// model the document was editing.
func attachMatroskaSaver(_ saver: MatroskaSaver) {
matroskaSaver = saver
}
weak var delegate: Queue?
private var statusInternal: Status
@objc private let uniqueID: String
private var attributes: [String : Any]
private var actionsInternal: [QueueActionProtocol]
private var cancelled: Bool
private let queue: DispatchQueue
private init(fileURL: URL, destURL: URL) {
statusInternal = .ready
uniqueID = UUID().uuidString
actionsInternal = []
attributes = [:]
cancelled = false
self.fileURL = fileURL
self.destURLInternal = destURL
#if SB_SANDBOX
fileURLBookmark = nil
destURLInternalBookmark = nil
#endif
queue = DispatchQueue(label: "org.subler.itemQueue")
}
convenience init(fileURL: URL, destination: URL) {
self.init(fileURL: fileURL, destURL: destination)
var url = fileURL
url.removeCachedResourceValue(forKey: URLResourceKey.fileSizeKey)
let value = try? url.resourceValues(forKeys: [URLResourceKey.fileSizeKey])
if let fileSize = value?.fileSize, fileSize > 3800000000 {
attributes[MP4264BitData] = true
}
if Prefs.chaptersPreviewTrack {
attributes[MP42GenerateChaptersPreviewTrack] = true
attributes[MP42ChaptersPreviewPosition] = Prefs.chaptersPreviewPosition
}
if Prefs.forceHvc1 {
attributes[MP42ForceHvc1] = true
}
}
convenience init(mp4: MP42File) {
self.init(fileURL: mp4.url!, destURL: mp4.url!)
mp4File = mp4
if Prefs.chaptersPreviewTrack {
attributes[MP42GenerateChaptersPreviewTrack] = true
attributes[MP42ChaptersPreviewPosition] = Prefs.chaptersPreviewPosition
}
}
convenience init(mp4: MP42File, destURL: URL, attributes: [String : Any] = [:], optimize: Bool = false) {
self.init(fileURL: destURL, destURL: destURL)
self.mp4File = mp4
self.attributes = attributes
if optimize {
addAction(QueueOptimizeAction())
}
}
/// Document handoff (send to queue / AppleScript) that must keep the
/// original file as the source: unlike init(mp4:destURL:...) the
/// destination may differ from the source — a Matroska item writes back
/// into the source in place, or stream-copy remuxes to a different
/// destination (plus the baseline from attachMatroskaSaver).
convenience init(mp4: MP42File, fileURL: URL, destURL: URL, attributes: [String : Any] = [:], optimize: Bool = false) {
self.init(fileURL: fileURL, destURL: destURL)
self.mp4File = mp4
self.attributes = attributes
if optimize {
addAction(QueueOptimizeAction())
}
}
// MARK: Public properties
@objc dynamic var status: Status {
get {
return queue.sync { statusInternal }
}
set (newStatus) {
queue.sync { statusInternal = newStatus }
}
}
// MARK: Actions
@objc dynamic var actions: [QueueActionProtocol] {
get {
return queue.sync { actionsInternal }
}
}
func addAction(_ action: QueueActionProtocol) {
willChangeValue(for: \.actions)
queue.sync { actionsInternal.append(action) }
didChangeValue(for: \.actions)
}
func removeAction(at index: Int) {
willChangeValue(for: \.actions)
_ = queue.sync { actionsInternal.remove(at: index) }
didChangeValue(for: \.actions)
}
// MARK: Item processing
enum ProcessError: Error {
case fileExists
case fileNotFound
case outOfDiskSpace
case optimizationFailure
}
private func checkDiskSpace(at url: URL) -> Int {
var directoryURL = url
directoryURL.removeCachedResourceValue(forKey: .volumeAvailableCapacityKey)
let value = try? directoryURL.resourceValues(forKeys: [.volumeAvailableCapacityKey])
if let availableCapacity = value?.volumeAvailableCapacity {
return availableCapacity
} else {
return 0
}
}
private func configureAudio(track: MP42AudioTrack, mp4: MP42File) {
var conversionNeeded = false
let bitrate = Prefs.audioBitrate
let drc = Prefs.audioDRC
let mixdown = MP42AudioMixdown(Prefs.audioMixdown)
// AC-3 track, we might need to do the aac + ac3 trick.
if track.format == kMP42AudioCodecType_AC3 ||
track.format == kMP42AudioCodecType_EnhancedAC3 {
if Prefs.audioConvertAC3 {
if Prefs.audioKeepAC3 && track.fallbackTrack == nil {
let copy = track.copy() as! MP42AudioTrack
let settings = MP42AudioConversionSettings(format: kMP42AudioCodecType_MPEG4AAC, bitRate: bitrate, mixDown: mixdown, drc: drc)
copy.conversionSettings = settings
track.fallbackTrack = copy
track.isEnabled = false
mp4.addTrack(copy)
} else {
conversionNeeded = true
}
}
}
// DTS -> convert only if specified in the prefs.
else if track.format == kMP42AudioCodecType_DTS {
if Prefs.audioConvertDts {
switch Prefs.audioDtsOptions {
case 1: // Convert to AC-3
let copy = track.copy() as! MP42AudioTrack
let settings = MP42AudioConversionSettings(format: kMP42AudioCodecType_MPEG4AAC, bitRate: bitrate, mixDown: mixdown, drc: drc)
copy.conversionSettings = settings
track.fallbackTrack = copy
track.isEnabled = false
// Wouldn't it be better to use pref settings too instead of 640/Multichannel and the drc from the prefs?
track.conversionSettings = MP42AudioConversionSettings(format: kMP42AudioCodecType_AC3, bitRate: 640, mixDown: kMP42AudioMixdown_None, drc: drc)
mp4.addTrack(copy)
case 2: // Keep DTS
let copy = track.copy() as! MP42AudioTrack
let settings = MP42AudioConversionSettings(format: kMP42AudioCodecType_MPEG4AAC, bitRate: bitrate, mixDown: mixdown, drc: drc)
copy.conversionSettings = settings
track.fallbackTrack = copy
track.isEnabled = false
mp4.addTrack(copy)
default:
conversionNeeded = true
}
}
}
// If an audio track needs to be converted, apply the mixdown from the preferences.
if trackNeedConversion(track.format) || conversionNeeded {
let settings = MP42AudioConversionSettings(format: kMP42AudioCodecType_MPEG4AAC, bitRate: bitrate, mixDown: mixdown, drc: drc)
track.conversionSettings = settings
}
}
private func configureSubtitles(track: MP42SubtitleTrack, mp4: MP42File) {
// VobSub -> only if specified in the prefs.
if track.format == kMP42SubtitleCodecType_VobSub && Prefs.subtitleConvertBitmap {
let settings = MP42ConversionSettings.subtitlesConversion()
track.conversionSettings = settings
} else if trackNeedConversion(track.format) {
let settings = MP42ConversionSettings.subtitlesConversion()
track.conversionSettings = settings
}
}
func prepare() throws {
defer {
localizedWorkingDescription = nil
delegate?.updateProgress(0)
}
if FileManager.default.fileExists(atPath: fileURL.path) == false {
throw ProcessError.fileNotFound
}
#if SB_SANDBOX
let fileToken = MP42SecurityAccessToken(object: fileURL as NSURL)
#endif
if mp4File == nil {
if isMatroska {
// Match the window's MKV open (Document.readMatroska): the
// tags-only model gets retagged into the original file at
// write time instead of being converted to MP4. The saver
// snapshots the pairing/staleness baseline from this import;
// a handoff item carries its model (and attached saver) and
// never gets here.
let importer = try MP42FileImporter(url: fileURL, tagsOnly: true)
let mp4 = MatroskaSaver.buildModel(from: importer)
matroskaSaver = MatroskaSaver(sourceURL: fileURL, importer: importer, model: mp4)
mp4File = mp4
} else {
try importForConversion()
}
}
for action in actions.filter({ $0.type == .pre }) {
localizedWorkingDescription = action.localizedDescription
delegate?.updateProgress(0)
_ = action.runAction(self)
}
}
private func importForConversion() throws {
let value = try? fileURL.resourceValues(forKeys: [URLResourceKey.typeIdentifierKey])
if let type = value?.typeIdentifier, type == "com.apple.m4a-audio" || type == "com.apple.m4v-video" || type == "public.mpeg-4" {
mp4File = try MP42File(url: fileURL)
} else {
let mp4 = MP42File()
let importer = try MP42FileImporter(url: fileURL)
let activeTracks = importer.tracks.filter { isTrackMuxable($0.format) || trackNeedConversion($0.format) }
mp4.metadata.merge(importer.metadata, overwrite: true)
for track in activeTracks {
if let track = track as? MP42AudioTrack {
configureAudio(track: track, mp4: mp4)
} else if let track = track as? MP42SubtitleTrack {
configureSubtitles(track: track, mp4: mp4)
}
mp4.addTrack(track)
}
mp4File = mp4
}
}
func process() throws {
guard let filePathURL = (fileURL as NSURL?)?.filePathURL else { return }
#if SB_SANDBOX
let destToken = MP42SecurityAccessToken(object: destURL as NSURL)
#endif
defer {
mp4File?.progressHandler = nil
mp4File = nil
matroskaSaver = nil
}
// The file has been added directly to the queue
if mp4File == nil {
try prepare()
}
guard let mp4 = mp4File else { return }
#if SB_SANDBOX
let mp4Token = MP42SecurityAccessToken(object: mp4)
#endif
mp4.progressHandler = { [weak self] in self?.delegate?.updateProgress($0) }
matroskaSaver?.progressHandler = { [weak self] progress in
self?.delegate?.updateProgress(progress)
}
// Check if there is enough space on the destination disk
if filePathURL != destURL {
let availableCapacity = checkDiskSpace(at: destURL.deletingLastPathComponent())
if mp4.dataSize > availableCapacity {
throw ProcessError.outOfDiskSpace
}
}
if cancelled == false {
if isMatroska {
// Match the window's Matroska save: write metadata and the
// four per-track fields back into the container instead of
// muxing an MP4. Added subtitle tracks (QueueSubtitlesAction)
// and edited chapters ride the stream-copy remuxer, as do a
// renamed/moved destination (set-output-filename action,
// queue destination folder) and optimize — the queue's
// equivalent of the window's save-and-optimize full rebuild.
// The branching is exactly Document.writeMatroska's, down to
// in-place temp file + atomic rename.
guard let saver = matroskaSaver else {
throw NSError(domain: NSCocoaErrorDomain, code: NSFileWriteUnknownError,
userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("The Matroska source file is unknown.", comment: "Document MKV remux missing source error.")])
}
let optimizeRequested = actions.contains { $0 is QueueOptimizeAction }
try saver.save(model: mp4, to: destURL,
forceStructural: optimizeRequested || destURL != fileURL)
} else if filePathURL == destURL && mp4.hasFileRepresentation {
// We have an existing mp4 file, update it
try mp4.update(options: attributes)
} else {
// Write the new file to disk
try mp4.write(to: destURL, options: attributes)
}
}
if cancelled == false {
for action in actions.filter( { $0.type == .post }) {
localizedWorkingDescription = action.localizedDescription
delegate?.updateProgress(0)
let result = action.runAction(self)
if result == false, let _ = action as? QueueOptimizeAction {
throw ProcessError.optimizationFailure
}
}
localizedWorkingDescription = nil
}
}
func cancel() {
queue.sync {
self.cancelled = true
matroskaSaver?.cancel()
mp4File?.cancel()
}
}
// MARK: AppleScript
@objc func name() -> String {
return destURL.lastPathComponent
}
@objc func sourcePath() -> String {
return fileURL.path
}
@objc func destinationPath() -> String {
return destURL.path
}
override var objectSpecifier: NSScriptObjectSpecifier? {
get {
let appDescription = NSApp.classDescription
return NSUniqueIDSpecifier(containerClassDescription: appDescription as! NSScriptClassDescription, containerSpecifier: nil, key: "items", uniqueID: uniqueID)
}
}
// MARK: Secure coding
static var supportsSecureCoding: Bool { return true }
func encode(with aCoder: NSCoder) {
aCoder.encode(5, forKey: "SBQueueItemTagEncodeVersion")
aCoder.encode(uniqueID, forKey: "SBQueueItemID")
// A tags-only Matroska model comes back by re-importing the file —
// its TrackEntry pairing is object identity and cannot be archived,
// and a restored MP4 write branch could never save it anyway.
if isMatroska == false {
aCoder.encode(mp4File, forKey: "SBQueueItemMp4File")
}
#if SB_SANDBOX
if let bookmark = fileURLBookmark {
aCoder.encode(bookmark, forKey: "SBQueueItemFileURLBookmark")
} else {
do {
let bookmark = try fileURL.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil)
aCoder.encode(bookmark, forKey: "SBQueueItemFileURLBookmark")
} catch {
print(error)
}
}
if let bookmark = destURLInternalBookmark {
aCoder.encode(bookmark, forKey: "SBQueueItemDestURLBookmark")
} else if let bookmark = try? MP42SecurityAccessToken.bookmark(from: destURLInternal) {
aCoder.encode(bookmark, forKey: "SBQueueItemDestURLBookmark")
}
#endif
aCoder.encode(fileURL, forKey: "SBQueueItemFileURL")
aCoder.encode(destURL, forKey: "SBQueueItemDestURL")
aCoder.encode(attributes, forKey: "SBQueueItemAttributes")
aCoder.encode(actionsInternal, forKey: "SBQueueItemActions")
aCoder.encode(statusInternal.rawValue, forKey: "SBQueueItemStatus")
}
required init?(coder aDecoder: NSCoder) {
cancelled = false
queue = DispatchQueue(label: "org.subler.itemQueue")
statusInternal = QueueItem.Status(rawValue: Int(aDecoder.decodeInt32(forKey: "SBQueueItemStatus"))) ?? .failed
mp4File = aDecoder.decodeObject(of: [MP42File.classForCoder()], forKey: "SBQueueItemMp4File") as? MP42File
uniqueID = aDecoder.decodeObject(of: [NSString.classForCoder()], forKey: "SBQueueItemID") as? String ?? UUID().uuidString
attributes = aDecoder.decodeObject(of: [NSDictionary.classForCoder(), NSString.classForCoder(), NSNumber.classForCoder()], forKey: "SBQueueItemAttributes") as? [String : Any] ?? [:]
#if SB_SANDBOX
if var bookmark = aDecoder.decodeObject(of: [NSData.classForCoder()], forKey: "SBQueueItemFileURLBookmark") as? Data {
do {
var isStale: ObjCBool = false
fileURL = try MP42SecurityAccessToken.url(fromBookmark: bookmark, bookmarkDataIsStale: &isStale)
if isStale.boolValue == true {
bookmark = try MP42SecurityAccessToken.bookmark(from: fileURL)
}
} catch {
return nil
}
fileURLBookmark = bookmark
} else {
return nil
}
if var bookmark = aDecoder.decodeObject(of: [NSData.classForCoder()], forKey: "SBQueueItemDestURLBookmark") as? Data {
do {
var isStale: ObjCBool = false
destURLInternal = try MP42SecurityAccessToken.url(fromBookmark: bookmark, bookmarkDataIsStale: &isStale)
if isStale.boolValue == true {
bookmark = try MP42SecurityAccessToken.bookmark(from: destURLInternal)
}
} catch {
return nil
}
destURLInternalBookmark = bookmark
} else {
return nil
}
#else
if let fileURL = aDecoder.decodeObject(of: [NSURL.classForCoder()], forKey: "SBQueueItemFileURL") as? URL,
let destURLInternal = aDecoder.decodeObject(of: [NSURL.classForCoder()], forKey: "SBQueueItemDestURL") as? URL {
self.fileURL = fileURL
self.destURLInternal = destURLInternal
} else {
return nil
}
#endif
actionsInternal = aDecoder.decodeObject(of: [NSArray.classForCoder(), QueueSetAction.classForCoder(),
QueueMetadataAction.classForCoder(), QueueSubtitlesAction.classForCoder(),
QueueSetLanguageAction.classForCoder(), QueueFixFallbacksAction.classForCoder(),
QueueClearTrackNameAction.classForCoder(), QueuePrettifyAudioTrackNameAction.classForCoder(),
QueueRenameChaptersAction.classForCoder(),
QueueOrganizeGroupsAction.classForCoder(), QueueColorSpaceAction.classForCoder(),
QueueSetOutputFilenameAction.classForCoder(), QueueClearExistingMetadataAction.classForCoder(),
QueueOptimizeAction.classForCoder(), QueueSendToiTunesAction.classForCoder(),
QueueChangeAudioLanguageAction.classForCoder(), QueueChangeSubtitleLanguageAction.classForCoder()], forKey: "SBQueueItemActions") as? [QueueActionProtocol] ?? []
// Matroska items always rebuild their tags-only model on resume
// (prepare() re-imports — pre-actions re-run against it, so the
// filename action re-derives the name too): the identity pairing
// cannot survive archiving. Older archives may also carry the
// retired convert-to-mp4 destination — point it back at the source
// for the in-place retag.
// (stored-property access only: super.init hasn't run yet)
if MP42FileImporter.isMatroskaFileType(fileURL.pathExtension) {
mp4File = nil
if MP42FileImporter.isMatroskaFileType(destURLInternal.pathExtension) == false {
destURLInternal = fileURL
}
}
}
}
extension QueueItem.ProcessError: LocalizedError {
var errorDescription: String? {
switch self {
case .fileNotFound:
return NSLocalizedString("File not found.", comment: "QueueItem Error")
case .fileExists:
return NSLocalizedString("A file already exists at the destination.", comment: "QueueItem Error")
case .outOfDiskSpace:
return NSLocalizedString("Not enough disk space.", comment: "QueueItem Error")
case .optimizationFailure:
return NSLocalizedString("The file couldn't be optimized.", comment: "QueueItem Error")
}
}
var recoverySuggestion: String? {
switch self {
case .fileNotFound:
return NSLocalizedString("The source file couldn't be found.", comment: "My error")
case .fileExists:
return NSLocalizedString("Try to use another name for the destination file.", comment: "QueueItem Error")
case .outOfDiskSpace:
return NSLocalizedString("Please free some space on the destination disk.", comment: "QueueItem Error")
case .optimizationFailure:
return NSLocalizedString("An error occurred while optimizing the file.", comment: "QueueItem Error")
}
}
}