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>
This commit is contained in:
1 parent
a1da1c8106
commit
80ca3970ec
7 files changed
+442
-195
No files matched your search
+34
-167
@@ -20,21 +20,11 @@ final class Document: NSDocument {
|
|||||||
// written back into the original file (Tags + cover attachment) by
|
// written back into the original file (Tags + cover attachment) by
|
||||||
// MP42MkvTagWriter on save.
|
// MP42MkvTagWriter on save.
|
||||||
private(set) var isMatroska = false
|
private(set) var isMatroska = false
|
||||||
private var mkvWriter: MP42MkvTagWriter?
|
// The pairing/staleness baseline (importer track snapshot, chapter rows,
|
||||||
private var mkvRemuxer: MP42MkvRemuxer?
|
// file size/mtime) and the branching write-back (in-place tag writer vs
|
||||||
// Tracks exactly as the importer produced them (file order, chapter
|
// stream-copy remuxer) live in MatroskaSaver — shared with QueueItem so a
|
||||||
// pseudo-track filtered): the baseline MP42MkvRemuxer pairs TrackEntry
|
// queued Matroska file saves exactly like the window does.
|
||||||
// elements against, so a deleted track is detected by object identity.
|
private(set) var mkvSaver: MatroskaSaver?
|
||||||
private var mkvSourceTracks: [MP42Track] = []
|
|
||||||
// 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?
|
|
||||||
|
|
||||||
override init() {
|
override init() {
|
||||||
self.cancelled = false
|
self.cancelled = false
|
||||||
@@ -115,54 +105,19 @@ final class Document: NSDocument {
|
|||||||
// applying the MP4 conversion heuristic, so the model matches the file
|
// applying the MP4 conversion heuristic, so the model matches the file
|
||||||
// (MP42MkvTagWriter diffs track fields against it on save).
|
// (MP42MkvTagWriter diffs track fields against it on save).
|
||||||
let importer = try MP42FileImporter(url: url, tagsOnly: true)
|
let importer = try MP42FileImporter(url: url, tagsOnly: true)
|
||||||
let file = MP42File()
|
let file = MatroskaSaver.buildModel(from: importer)
|
||||||
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 = file
|
||||||
|
// (file.undo was not wired during buildModel's addTrack calls, so
|
||||||
|
// those did not open undo groups.)
|
||||||
mp4.undo = undoManager
|
mp4.undo = undoManager
|
||||||
isMatroska = true
|
isMatroska = true
|
||||||
// Order-sensitive snapshot for the remuxer's TrackEntry pairing; the
|
let saver = MatroskaSaver(sourceURL: url, importer: importer, model: file)
|
||||||
// chapter pseudo-track has no TrackEntry and must not shift positions.
|
// The save sheet listens on the model's progress handler (see
|
||||||
mkvSourceTracks = importer.tracks.filter { $0.isMember(of: MP42ChapterTrack.self) == false }
|
// DocumentWindowController.startProgressReporting); forward through it.
|
||||||
mkvChaptersSnapshot = Self.matroskaChapterRows(mp4.chapters)
|
saver.progressHandler = { [weak self] progress in
|
||||||
snapshotMatroskaFile(at: url)
|
self?.mp4.progressHandler?(progress)
|
||||||
}
|
}
|
||||||
|
mkvSaver = saver
|
||||||
// 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
|
// MARK: Save
|
||||||
@@ -239,8 +194,7 @@ final class Document: NSDocument {
|
|||||||
|
|
||||||
func cancelSave() {
|
func cancelSave() {
|
||||||
cancelled = true
|
cancelled = true
|
||||||
mkvWriter?.cancel()
|
mkvSaver?.cancel()
|
||||||
mkvRemuxer?.cancel()
|
|
||||||
mp4.cancel()
|
mp4.cancel()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -270,8 +224,6 @@ final class Document: NSDocument {
|
|||||||
allowSleep()
|
allowSleep()
|
||||||
optimize = false
|
optimize = false
|
||||||
options = [:]
|
options = [:]
|
||||||
mkvWriter = nil
|
|
||||||
mkvRemuxer = nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if isMatroska {
|
if isMatroska {
|
||||||
@@ -310,112 +262,14 @@ final class Document: NSDocument {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private func writeMatroska(to url: URL, for saveOperation: NSDocument.SaveOperationType) throws {
|
private func writeMatroska(to url: URL, for saveOperation: NSDocument.SaveOperationType) throws {
|
||||||
guard MP42FileImporter.isMatroskaFileType(url.pathExtension) else {
|
guard let saver = mkvSaver 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, or the
|
|
||||||
// model carries a track the importer never produced (an imported
|
|
||||||
// subtitle). Tracks are paired by object identity, so a reordered
|
|
||||||
// (impossible: reorder is gated on MKV docs) or merely renamed track
|
|
||||||
// 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 || $0.language != $1.language }
|
|
||||||
default: chaptersChanged = true
|
|
||||||
}
|
|
||||||
|
|
||||||
// `optimize` (Save and Optimize) forces the structural branch: the
|
|
||||||
// Matroska equivalent of reordering atoms is rebuilding the whole file
|
|
||||||
// — blocks stream-copied verbatim, Tracks/Tags rewritten, SeekHead and
|
|
||||||
// Cues regenerated — i.e. exactly the Save-As pass, done in place
|
|
||||||
// through the remuxer's temp file + atomic rename.
|
|
||||||
if tracksChanged || chaptersChanged || optimize || 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
|
|
||||||
}
|
|
||||||
|
|
||||||
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 static func matroskaChapterRows(_ track: MP42ChapterTrack?)
|
|
||||||
-> [(timestamp: UInt64, title: String, language: String)]? {
|
|
||||||
guard let track else { return nil }
|
|
||||||
// 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],
|
|
||||||
replacementChapters: MP42ChapterTrack?) throws {
|
|
||||||
guard let sourceURL = fileURL else {
|
|
||||||
throw NSError(domain: NSCocoaErrorDomain, code: NSFileWriteUnknownError,
|
throw NSError(domain: NSCocoaErrorDomain, code: NSFileWriteUnknownError,
|
||||||
userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("The Matroska source file is unknown.", comment: "Document MKV remux missing source error.")])
|
userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("The Matroska source file is unknown.", comment: "Document MKV remux missing source error.")])
|
||||||
}
|
}
|
||||||
let remuxer = MP42MkvRemuxer(sourceURL: sourceURL)
|
// `optimize` (Save and Optimize) forces the structural rebuild, as
|
||||||
remuxer.expectedFileSize = mkvFileSize
|
// does Save-As; the saver branches in-place tag writer vs stream-copy
|
||||||
remuxer.expectedModificationDate = mkvFileModificationDate
|
// remuxer (see MatroskaSaver.save).
|
||||||
remuxer.progressHandler = { [weak self] progress in
|
try saver.save(model: mp4, to: url, forceStructural: optimize || saveOperation != .saveOperation)
|
||||||
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
|
|
||||||
// order — otherwise the appended track would look "added" again on
|
|
||||||
// the next save and the TrackEntry count would mispair.
|
|
||||||
let addedTracks = currentTracks.filter { track in
|
|
||||||
mkvSourceTracks.contains(where: { $0 === track }) == false
|
|
||||||
}
|
|
||||||
mkvSourceTracks = mkvSourceTracks.filter { track in
|
|
||||||
currentTracks.contains(where: { $0 === track })
|
|
||||||
} + addedTracks
|
|
||||||
snapshotMatroskaFile(at: url)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Save panel
|
// MARK: Save panel
|
||||||
@@ -445,6 +299,19 @@ final class Document: NSDocument {
|
|||||||
guard let windowForSheet = windowForSheet else { return }
|
guard let windowForSheet = windowForSheet else { return }
|
||||||
|
|
||||||
let queue = QueueController.shared
|
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 {
|
if mp4.hasFileRepresentation {
|
||||||
let item = QueueItem(mp4: mp4)
|
let item = QueueItem(mp4: mp4)
|
||||||
queue.add(item, applyPreset: true)
|
queue.add(item, applyPreset: true)
|
||||||
|
|||||||
@@ -802,8 +802,9 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Reordering must never touch a Matroska document: the remuxer pairs
|
// Reordering must never touch a Matroska document: the remuxer pairs
|
||||||
// TrackEntry elements against mkvSourceTracks by identity, and a
|
// TrackEntry elements against the saver's importer-order snapshot by
|
||||||
// reordered model would mispair them (same rule as delete(tracks:)).
|
// identity, and a reordered model would mispair them (same rule as
|
||||||
|
// delete(tracks:)).
|
||||||
if tracks.isEmpty == false, doc.isMatroska == false {
|
if tracks.isEmpty == false, doc.isMatroska == false {
|
||||||
if Prefs.organizeAlternateGroups {
|
if Prefs.organizeAlternateGroups {
|
||||||
mp4.organizeAlternateGroups()
|
mp4.organizeAlternateGroups()
|
||||||
|
|||||||
@@ -0,0 +1,229 @@
|
|||||||
|
//
|
||||||
|
// MatroskaSaver.swift
|
||||||
|
// Subler
|
||||||
|
//
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
import MP42Foundation
|
||||||
|
|
||||||
|
/// Owns the on-disk baseline of a tags-only Matroska source file and writes
|
||||||
|
/// model changes back into it with the window's save semantics: in-place
|
||||||
|
/// metadata/track-field retagging via MP42MkvTagWriter, or a stream-copy
|
||||||
|
/// rebuild via MP42MkvRemuxer when the edit is structural (deleted/added
|
||||||
|
/// tracks, chapter changes), when a full rebuild is forced (optimize,
|
||||||
|
/// Save-As-style different destination), never producing an MP4.
|
||||||
|
///
|
||||||
|
/// Shared by Document (window saves) and QueueItem (queue retags MKVs in
|
||||||
|
/// place instead of converting them) so the pairing/staleness bookkeeping
|
||||||
|
/// cannot drift between the two save paths.
|
||||||
|
final class MatroskaSaver {
|
||||||
|
|
||||||
|
private var sourceURL: URL
|
||||||
|
// 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 sourceTracks: [MP42Track]
|
||||||
|
// 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 model-vs-snapshot against the model on save: because the
|
||||||
|
// importer itself drops some atoms (duplicate zero timestamps), those
|
||||||
|
// silently-dropped atoms must not look like edits.
|
||||||
|
private var chaptersSnapshot: [(timestamp: UInt64, title: String, language: String)]?
|
||||||
|
// 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 (and the
|
||||||
|
// queue certainly doesn't).
|
||||||
|
private var fileSize: UInt64 = 0
|
||||||
|
private var fileModificationDate: Date?
|
||||||
|
|
||||||
|
private var activeWriter: MP42MkvTagWriter?
|
||||||
|
private var activeRemuxer: MP42MkvRemuxer?
|
||||||
|
|
||||||
|
// Called on the writing thread; hosts forward it to their progress UI
|
||||||
|
// (the window's save sheet listens on the model's progress handler, the
|
||||||
|
// queue on its delegate).
|
||||||
|
var progressHandler: ((Double) -> Void)?
|
||||||
|
|
||||||
|
/// Builds the tags-only display model for a Matroska importer: metadata
|
||||||
|
/// merged in, every importer track added (chapter pseudo-track included)
|
||||||
|
/// with 1-based display trackIds like MKV players number tracks.
|
||||||
|
///
|
||||||
|
/// The returned file's undo manager is deliberately not wired yet — the
|
||||||
|
/// caller wires it after this returns so these addTrack: calls do not
|
||||||
|
/// open undo groups.
|
||||||
|
static func buildModel(from importer: MP42FileImporter) -> MP42File {
|
||||||
|
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.
|
||||||
|
displayTrackId += 1
|
||||||
|
track.trackId = displayTrackId
|
||||||
|
}
|
||||||
|
return file
|
||||||
|
}
|
||||||
|
|
||||||
|
/// - parameter model: the tags-only model built by `buildModel(from:)`
|
||||||
|
/// from this same `importer` (track identity is the pairing baseline).
|
||||||
|
init(sourceURL: URL, importer: MP42FileImporter, model: MP42File) {
|
||||||
|
self.sourceURL = sourceURL
|
||||||
|
// Order-sensitive snapshot for the remuxer's TrackEntry pairing; the
|
||||||
|
// chapter pseudo-track has no TrackEntry and must not shift positions.
|
||||||
|
self.sourceTracks = importer.tracks.filter { $0.isMember(of: MP42ChapterTrack.self) == false }
|
||||||
|
self.chaptersSnapshot = Self.chapterRows(model.chapters)
|
||||||
|
snapshotSourceFile()
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Save
|
||||||
|
|
||||||
|
/// Writes the model back with the window's save branching.
|
||||||
|
///
|
||||||
|
/// - parameter forceStructural: forces the remuxer rebuild even without
|
||||||
|
/// detected model changes — what the window passes for optimize and
|
||||||
|
/// Save-As, and what the queue passes when the destination differs
|
||||||
|
/// from the source (a renamed output or a queue destination folder).
|
||||||
|
func save(model: MP42File, to url: URL, forceStructural: Bool) 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 = model.tracks.filter { $0.isMember(of: MP42ChapterTrack.self) == false }
|
||||||
|
// Structural change == some importer-created track is gone, or the
|
||||||
|
// model carries a track the importer never produced (an imported
|
||||||
|
// subtitle). Tracks are paired by object identity, so a reordered
|
||||||
|
// (impossible: reorder is gated on MKV docs) or merely renamed track
|
||||||
|
// still compares equal.
|
||||||
|
let tracksChanged = currentTracks.count != sourceTracks.count ||
|
||||||
|
currentTracks.contains { track in sourceTracks.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.chapterRows(model.chapters)
|
||||||
|
let chaptersChanged: Bool
|
||||||
|
switch (modelChapterRows, chaptersSnapshot) {
|
||||||
|
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 || $0.language != $1.language }
|
||||||
|
default: chaptersChanged = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// A forced rebuild is the Matroska equivalent of reordering atoms:
|
||||||
|
// rebuilding the whole file — blocks stream-copied verbatim,
|
||||||
|
// Tracks/Tags rewritten, SeekHead and Cues regenerated — i.e.
|
||||||
|
// exactly the Save-As pass, done in place through the remuxer's
|
||||||
|
// temp file + atomic rename when the destination is the source.
|
||||||
|
if tracksChanged || chaptersChanged || forceStructural {
|
||||||
|
// 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 remux(model: model, to: url, currentTracks: currentTracks,
|
||||||
|
replacementChapters: chaptersChanged ? (model.chapters ?? MP42ChapterTrack()) : nil)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
let writer = MP42MkvTagWriter(url: url)
|
||||||
|
writer.expectedFileSize = fileSize
|
||||||
|
writer.expectedModificationDate = fileModificationDate
|
||||||
|
writer.progressHandler = { [weak self] progress in
|
||||||
|
self?.progressHandler?(progress)
|
||||||
|
}
|
||||||
|
activeWriter = writer
|
||||||
|
defer { activeWriter = nil }
|
||||||
|
// Track edits (name/language/enabled/subtitle forced) ride along; the
|
||||||
|
// chapter pseudo-track is skipped by the writer.
|
||||||
|
try writer.write(model.metadata, tracks: model.tracks)
|
||||||
|
// The file we just wrote is the new baseline for the staleness check.
|
||||||
|
snapshotSourceFile()
|
||||||
|
}
|
||||||
|
|
||||||
|
func cancel() {
|
||||||
|
activeWriter?.cancel()
|
||||||
|
activeRemuxer?.cancel()
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Remux
|
||||||
|
|
||||||
|
// 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 remux(model: MP42File, to url: URL, currentTracks: [MP42Track],
|
||||||
|
replacementChapters: MP42ChapterTrack?) throws {
|
||||||
|
let remuxer = MP42MkvRemuxer(sourceURL: sourceURL)
|
||||||
|
remuxer.expectedFileSize = fileSize
|
||||||
|
remuxer.expectedModificationDate = fileModificationDate
|
||||||
|
remuxer.progressHandler = { [weak self] progress in
|
||||||
|
self?.progressHandler?(progress)
|
||||||
|
}
|
||||||
|
// nil keeps the source Chapters element verbatim.
|
||||||
|
remuxer.replacementChapters = replacementChapters
|
||||||
|
activeRemuxer = remuxer
|
||||||
|
defer { activeRemuxer = nil }
|
||||||
|
try remuxer.remux(to: url, metadata: model.metadata,
|
||||||
|
sourceTracks: sourceTracks, currentTracks: currentTracks)
|
||||||
|
// 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").
|
||||||
|
chaptersSnapshot = Self.chapterRows(model.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
|
||||||
|
// order — otherwise the appended track would look "added" again on
|
||||||
|
// the next save and the TrackEntry count would mispair.
|
||||||
|
let addedTracks = currentTracks.filter { track in
|
||||||
|
sourceTracks.contains(where: { $0 === track }) == false
|
||||||
|
}
|
||||||
|
sourceTracks = sourceTracks.filter { track in
|
||||||
|
currentTracks.contains(where: { $0 === track })
|
||||||
|
} + addedTracks
|
||||||
|
// A Save-As-style different destination becomes the new source: the
|
||||||
|
// next save reads/pairs against the file we just wrote.
|
||||||
|
if url != sourceURL {
|
||||||
|
sourceURL = url
|
||||||
|
}
|
||||||
|
snapshotSourceFile()
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Baseline helpers
|
||||||
|
|
||||||
|
private func snapshotSourceFile() {
|
||||||
|
let attributes = try? FileManager.default.attributesOfItem(atPath: sourceURL.path)
|
||||||
|
fileSize = (attributes?[.size] as? NSNumber)?.uint64Value ?? 0
|
||||||
|
fileModificationDate = attributes?[.modificationDate] as? Date
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func chapterRows(_ track: MP42ChapterTrack?)
|
||||||
|
-> [(timestamp: UInt64, title: String, language: String)]? {
|
||||||
|
guard let track else { return nil }
|
||||||
|
// 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) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -106,6 +106,14 @@ class QueueSubtitlesAction : NSObject, QueueActionProtocol {
|
|||||||
|
|
||||||
for importer in subtitlesImporters {
|
for importer in subtitlesImporters {
|
||||||
for track in importer.tracks {
|
for track in importer.tracks {
|
||||||
|
// Honor addTrack:'s conversion-settings invariant (see
|
||||||
|
// Document.readMatroska / importSubtitleTracksForMatroska):
|
||||||
|
// the MP4 path converts text subs to tx3g at mux time; a
|
||||||
|
// Matroska remux ignores the settings and re-parses the text
|
||||||
|
// from track.URL as S_TEXT/UTF8 instead.
|
||||||
|
if trackNeedConversion(track.format), let subtitleTrack = track as? MP42SubtitleTrack {
|
||||||
|
subtitleTrack.conversionSettings = MP42ConversionSettings.subtitlesConversion()
|
||||||
|
}
|
||||||
item.mp4File?.addTrack(track)
|
item.mp4File?.addTrack(track)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -339,6 +347,12 @@ class QueueOrganizeGroupsAction : NSObject, QueueActionProtocol {
|
|||||||
override init() {}
|
override init() {}
|
||||||
|
|
||||||
func runAction(_ item: QueueItem) -> Bool {
|
func runAction(_ item: QueueItem) -> Bool {
|
||||||
|
// Organize/infer must never touch a Matroska item: same rule as the
|
||||||
|
// window's didSelect/import paths — the tags-only model is the tag
|
||||||
|
// writer's positional diff baseline against the file's TrackEntry
|
||||||
|
// list — and language/characteristic inference has no Matroska
|
||||||
|
// equivalent to write into anyway.
|
||||||
|
guard item.isMatroska == false else { return true }
|
||||||
item.mp4File?.organizeAlternateGroups()
|
item.mp4File?.organizeAlternateGroups()
|
||||||
item.mp4File?.inferTracksLanguages()
|
item.mp4File?.inferTracksLanguages()
|
||||||
item.mp4File?.inferMediaCharacteristics()
|
item.mp4File?.inferMediaCharacteristics()
|
||||||
@@ -361,6 +375,9 @@ class QueueFixFallbacksAction : NSObject, QueueActionProtocol {
|
|||||||
override init() {}
|
override init() {}
|
||||||
|
|
||||||
func runAction(_ item: QueueItem) -> Bool {
|
func runAction(_ item: QueueItem) -> Bool {
|
||||||
|
// Fallback tracks are an MP4 track-reference concept; a Matroska
|
||||||
|
// retag has nothing to link.
|
||||||
|
guard item.isMatroska == false else { return true }
|
||||||
item.mp4File?.setAutoFallback()
|
item.mp4File?.setAutoFallback()
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@@ -540,6 +557,10 @@ class QueueColorSpaceAction : NSObject, QueueActionProtocol {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func runAction(_ item: QueueItem) -> Bool {
|
func runAction(_ item: QueueItem) -> Bool {
|
||||||
|
// Color atoms are not among the four track fields a Matroska retag
|
||||||
|
// writes (name/language/enabled/forced) — the window keeps the video
|
||||||
|
// tab read-only on MKV docs for the same reason.
|
||||||
|
guard item.isMatroska == false else { return true }
|
||||||
if let tracks = item.mp4File?.tracks(withMediaType: kMP42MediaType_Video) as? [MP42VideoTrack] {
|
if let tracks = item.mp4File?.tracks(withMediaType: kMP42MediaType_Video) as? [MP42VideoTrack] {
|
||||||
for track in tracks {
|
for track in tracks {
|
||||||
if track.format == kMP42VideoCodecType_H264 ||
|
if track.format == kMP42VideoCodecType_H264 ||
|
||||||
@@ -581,6 +602,12 @@ class QueueOptimizeAction: NSObject, QueueActionProtocol {
|
|||||||
override init() {}
|
override init() {}
|
||||||
|
|
||||||
func runAction(_ item: QueueItem) -> Bool {
|
func runAction(_ item: QueueItem) -> Bool {
|
||||||
|
// On a Matroska item "optimize" is the forced full rebuild that the
|
||||||
|
// write pass already performed (QueueItem.process sees this action
|
||||||
|
// and forces the MatroskaSaver remux branch — the container-
|
||||||
|
// equivalent of atom reordering); MP4Optimize would have nothing to
|
||||||
|
// reorderBy on a tags-only model.
|
||||||
|
if item.isMatroska { return true }
|
||||||
return item.mp4File?.optimize() ?? false
|
return item.mp4File?.optimize() ?? false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -236,7 +236,7 @@ final class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDel
|
|||||||
updateUI(indexes: IndexSet(integer: queue.index(of: item)))
|
updateUI(indexes: IndexSet(integer: queue.index(of: item)))
|
||||||
|
|
||||||
DispatchQueue.global().async {
|
DispatchQueue.global().async {
|
||||||
if originalStatus != .completed {
|
if originalStatus != .completed, item.isMatroska == false {
|
||||||
do {
|
do {
|
||||||
try item.prepare()
|
try item.prepare()
|
||||||
} catch {
|
} catch {
|
||||||
@@ -251,6 +251,13 @@ final class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDel
|
|||||||
var doc: Document?
|
var doc: Document?
|
||||||
if originalStatus == .completed {
|
if originalStatus == .completed {
|
||||||
try doc = Document(contentsOf: item.destURL, ofType: "")
|
try doc = Document(contentsOf: item.destURL, ofType: "")
|
||||||
|
} else if item.isMatroska {
|
||||||
|
// Open the source file instead of the item's model:
|
||||||
|
// only the document's own MKV read sets up a complete
|
||||||
|
// tags-only Matroska document (Document.readMatroska
|
||||||
|
// builds the pairing/staleness baseline the save
|
||||||
|
// writes back through).
|
||||||
|
try doc = Document(contentsOf: item.fileURL, ofType: "")
|
||||||
} else if let mp4 = item.mp4File {
|
} else if let mp4 = item.mp4File {
|
||||||
doc = Document(mp4: mp4)
|
doc = Document(mp4: mp4)
|
||||||
}
|
}
|
||||||
@@ -277,6 +284,18 @@ final class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDel
|
|||||||
//MARK: Items creation
|
//MARK: Items creation
|
||||||
|
|
||||||
private func destination(for url: URL) -> URL {
|
private func destination(for url: URL) -> URL {
|
||||||
|
// Matroska files are retagged in their own container by the queue
|
||||||
|
// (matching the window's save), so the extension must survive: the
|
||||||
|
// file itself when no destination folder is set (in-place retag), or
|
||||||
|
// the same name in the folder (a stream-copy remux writes it there,
|
||||||
|
// the queue equivalent of Save-As).
|
||||||
|
if MP42FileImporter.isMatroskaFileType(url.pathExtension) {
|
||||||
|
if let destination = prefs.destination {
|
||||||
|
return destination.appendingPathComponent(url.lastPathComponent)
|
||||||
|
}
|
||||||
|
return url
|
||||||
|
}
|
||||||
|
|
||||||
let value = try? url.resourceValues(forKeys: [URLResourceKey.typeIdentifierKey])
|
let value = try? url.resourceValues(forKeys: [URLResourceKey.typeIdentifierKey])
|
||||||
|
|
||||||
var isMpeg4 = false
|
var isMpeg4 = false
|
||||||
|
|||||||
+116
-23
@@ -41,6 +41,26 @@ import MP42Foundation
|
|||||||
var mp4File: MP42File?
|
var mp4File: MP42File?
|
||||||
var localizedWorkingDescription: String?
|
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?
|
weak var delegate: Queue?
|
||||||
|
|
||||||
private var statusInternal: Status
|
private var statusInternal: Status
|
||||||
@@ -107,6 +127,21 @@ import MP42Foundation
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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
|
// MARK: Public properties
|
||||||
|
|
||||||
@objc dynamic var status: Status {
|
@objc dynamic var status: Status {
|
||||||
@@ -253,28 +288,19 @@ import MP42Foundation
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
if mp4File == nil {
|
if mp4File == nil {
|
||||||
let value = try? fileURL.resourceValues(forKeys: [URLResourceKey.typeIdentifierKey])
|
if isMatroska {
|
||||||
|
// Match the window's MKV open (Document.readMatroska): the
|
||||||
if let type = value?.typeIdentifier, type == "com.apple.m4a-audio" || type == "com.apple.m4v-video" || type == "public.mpeg-4" {
|
// tags-only model gets retagged into the original file at
|
||||||
mp4File = try MP42File(url: fileURL)
|
// write time instead of being converted to MP4. The saver
|
||||||
} else {
|
// snapshots the pairing/staleness baseline from this import;
|
||||||
let mp4 = MP42File()
|
// a handoff item carries its model (and attached saver) and
|
||||||
let importer = try MP42FileImporter(url: fileURL)
|
// never gets here.
|
||||||
let activeTracks = importer.tracks.filter { isTrackMuxable($0.format) || trackNeedConversion($0.format) }
|
let importer = try MP42FileImporter(url: fileURL, tagsOnly: true)
|
||||||
|
let mp4 = MatroskaSaver.buildModel(from: importer)
|
||||||
mp4.metadata.merge(importer.metadata, overwrite: true)
|
matroskaSaver = MatroskaSaver(sourceURL: fileURL, importer: importer, model: mp4)
|
||||||
|
|
||||||
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
|
mp4File = mp4
|
||||||
|
} else {
|
||||||
|
try importForConversion()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -285,6 +311,32 @@ import MP42Foundation
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 {
|
func process() throws {
|
||||||
|
|
||||||
guard let filePathURL = (fileURL as NSURL?)?.filePathURL else { return }
|
guard let filePathURL = (fileURL as NSURL?)?.filePathURL else { return }
|
||||||
@@ -296,6 +348,7 @@ import MP42Foundation
|
|||||||
defer {
|
defer {
|
||||||
mp4File?.progressHandler = nil
|
mp4File?.progressHandler = nil
|
||||||
mp4File = nil
|
mp4File = nil
|
||||||
|
matroskaSaver = nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// The file has been added directly to the queue
|
// The file has been added directly to the queue
|
||||||
@@ -310,6 +363,9 @@ import MP42Foundation
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
mp4.progressHandler = { [weak self] in self?.delegate?.updateProgress($0) }
|
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
|
// Check if there is enough space on the destination disk
|
||||||
if filePathURL != destURL {
|
if filePathURL != destURL {
|
||||||
@@ -320,7 +376,24 @@ import MP42Foundation
|
|||||||
}
|
}
|
||||||
|
|
||||||
if cancelled == false {
|
if cancelled == false {
|
||||||
if filePathURL == destURL && mp4.hasFileRepresentation {
|
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
|
// We have an existing mp4 file, update it
|
||||||
try mp4.update(options: attributes)
|
try mp4.update(options: attributes)
|
||||||
} else {
|
} else {
|
||||||
@@ -345,6 +418,7 @@ import MP42Foundation
|
|||||||
func cancel() {
|
func cancel() {
|
||||||
queue.sync {
|
queue.sync {
|
||||||
self.cancelled = true
|
self.cancelled = true
|
||||||
|
matroskaSaver?.cancel()
|
||||||
mp4File?.cancel()
|
mp4File?.cancel()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -378,7 +452,12 @@ import MP42Foundation
|
|||||||
aCoder.encode(5, forKey: "SBQueueItemTagEncodeVersion")
|
aCoder.encode(5, forKey: "SBQueueItemTagEncodeVersion")
|
||||||
|
|
||||||
aCoder.encode(uniqueID, forKey: "SBQueueItemID")
|
aCoder.encode(uniqueID, forKey: "SBQueueItemID")
|
||||||
aCoder.encode(mp4File, forKey: "SBQueueItemMp4File")
|
// 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 SB_SANDBOX
|
||||||
|
|
||||||
@@ -468,6 +547,20 @@ import MP42Foundation
|
|||||||
QueueSetOutputFilenameAction.classForCoder(), QueueClearExistingMetadataAction.classForCoder(),
|
QueueSetOutputFilenameAction.classForCoder(), QueueClearExistingMetadataAction.classForCoder(),
|
||||||
QueueOptimizeAction.classForCoder(), QueueSendToiTunesAction.classForCoder(),
|
QueueOptimizeAction.classForCoder(), QueueSendToiTunesAction.classForCoder(),
|
||||||
QueueChangeAudioLanguageAction.classForCoder(), QueueChangeSubtitleLanguageAction.classForCoder()], forKey: "SBQueueItemActions") as? [QueueActionProtocol] ?? []
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -476,8 +476,19 @@ class SBSendToQueueScriptCommand: NSScriptCommand, ScriptCommandDocumentTargetin
|
|||||||
options[MP4264BitData] = Prefs.mp464bitOffset
|
options[MP4264BitData] = Prefs.mp464bitOffset
|
||||||
options[MP4264BitTime] = Prefs.mp464bitTimes
|
options[MP4264BitTime] = Prefs.mp464bitTimes
|
||||||
|
|
||||||
// Create queue item and add to queue
|
// Create queue item and add to queue. A Matroska document keeps its
|
||||||
let item = QueueItem(mp4: sublerDoc.mp4, destURL: destinationURL, attributes: options, optimize: Prefs.mp4SaveAsOptimize)
|
// own file as the item's source and hands over the Matroska baseline
|
||||||
|
// (pairing is by object identity): the item then writes back into
|
||||||
|
// the container — the destination must stay mkv/mka/mks, checked at
|
||||||
|
// save time — instead of muxing QuickTime atoms over a tags-only
|
||||||
|
// model.
|
||||||
|
let item: QueueItem
|
||||||
|
if sublerDoc.isMatroska, let sourceURL = sublerDoc.fileURL, let saver = sublerDoc.mkvSaver {
|
||||||
|
item = QueueItem(mp4: sublerDoc.mp4, fileURL: sourceURL, destURL: destinationURL, attributes: options, optimize: Prefs.mp4SaveAsOptimize)
|
||||||
|
item.attachMatroskaSaver(saver)
|
||||||
|
} else {
|
||||||
|
item = QueueItem(mp4: sublerDoc.mp4, destURL: destinationURL, attributes: options, optimize: Prefs.mp4SaveAsOptimize)
|
||||||
|
}
|
||||||
|
|
||||||
// Add the queue item
|
// Add the queue item
|
||||||
QueueController.shared.add(item)
|
QueueController.shared.add(item)
|
||||||
|
|||||||
Reference in new issue
Block a user