Add subtitle tracks to open Matroska documents
MKV docs can now import .srt/.ssa/.ass subtitle files, written as S_TEXT/UTF8 by MP42MkvRemuxer (submodule bump). Video/audio adds and other subtitle formats stay refused by both sides. - DocumentWindowController: split selectFile: validation so MKV docs get an Import panel restricted to matroskaSubtitleExtensions (kept in sync with the remuxer's gate); showImportSheet routes MKV docs to importSubtitleTracksForMatroska, which imports each file with a plain MP42FileImporter (no track-selection sheet), attaches the conversion-settings defaults addTrack: asserts on, and assigns the next display trackId. Drag-drop already funnels through showImportSheet. didSelect skips organizeAlternateGroups/inferMediaCharacteristics on MKV docs — same TrackEntry-pairing protection as delete. - Document: the tagsChanged check already caught additions; the post-remux snapshot now appends the added tracks behind the kept ones, matching the TrackEntry order in the written file, so a later tags-only save pairs correctly instead of double-appending. - ScriptCommand: the AppleScript "save as" command called mp4.write(to:) directly, which muxed a QuickTime MP4 over a Matroska document. Route isMatroska documents through Document.save(saveAsOperation) so writeMatroska picks the tag-writer/remux path and enforces the mkv destination. Verified with the /tmp/subler-mkv-test harness (matrix PASS=276: add srt/ass, add+drop mix, no-cues source, bad-file and drop-all refusals, idempotent re-save, post-add tag edit) and against the live app (scripted import + save on a fixture copy; output checked with mkvmerge/mkvextract/ffmpeg and reopened cleanly). Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
1 parent
eb386a52c3
commit
330236735d
5 files changed
+125
-18
No files matched your search
+15
-7
@@ -308,13 +308,15 @@ final class Document: NSDocument {
|
||||
}
|
||||
|
||||
let currentTracks = mp4.tracks.filter { $0.isMember(of: MP42ChapterTrack.self) == false }
|
||||
// Structural change == some importer-created track is gone. Tracks are
|
||||
// paired by object identity, so a reordered (impossible: reorder is
|
||||
// gated on MKV docs) or merely renamed track still compares equal.
|
||||
let tracksRemoved = currentTracks.count != mkvSourceTracks.count ||
|
||||
// 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 }
|
||||
|
||||
if tracksRemoved || saveOperation != .saveOperation {
|
||||
if tracksChanged || saveOperation != .saveOperation {
|
||||
try remuxMatroska(to: url, currentTracks: currentTracks)
|
||||
return
|
||||
}
|
||||
@@ -355,10 +357,16 @@ final class Document: NSDocument {
|
||||
sourceTracks: mkvSourceTracks, currentTracks: currentTracks)
|
||||
mkvRemuxer = nil
|
||||
// The output keeps the surviving TrackEntry elements in source file
|
||||
// order, so re-snapshot the pairing baseline in that same order.
|
||||
// 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)
|
||||
}
|
||||
|
||||
|
||||
@@ -282,9 +282,13 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
|
||||
#selector(sendToQueue(_:)):
|
||||
return true
|
||||
|
||||
// Track/chapter modifications: unavailable in Matroska tags-only mode.
|
||||
case #selector(selectFile(_:)),
|
||||
#selector(searchChapters(_:)),
|
||||
// Matroska documents may import subtitle text files (written as
|
||||
// S_TEXT/UTF8 by the stream-copy remuxer on save).
|
||||
case #selector(selectFile(_:)):
|
||||
return true
|
||||
|
||||
// Chapter/track bulk modifications: unavailable in Matroska tags-only mode.
|
||||
case #selector(searchChapters(_:)),
|
||||
#selector(addChaptersEvery(_:)),
|
||||
#selector(iTunesFriendlyTrackGroups(_:)),
|
||||
#selector(clearTrackNames(_:)),
|
||||
@@ -566,6 +570,26 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
|
||||
panel.canChooseFiles = true
|
||||
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.
|
||||
if #available(macOS 11, *) {
|
||||
panel.allowedContentTypes = DocumentWindowController.matroskaSubtitleExtensions.compactMap {
|
||||
UTType(filenameExtension: $0)
|
||||
}
|
||||
} else {
|
||||
panel.allowedFileTypes = DocumentWindowController.matroskaSubtitleExtensions
|
||||
}
|
||||
panel.beginSheetModal(for: windowForSheet) { (response) in
|
||||
if response == NSApplication.ModalResponse.OK {
|
||||
self.showImportSheet(fileURLs: panel.urls)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if #available(macOS 11, *) {
|
||||
panel.allowedContentTypes = MP42FileImporter.supportedContentTypes() + [.text, .commaSeparatedText]
|
||||
} else {
|
||||
@@ -588,8 +612,15 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
|
||||
}
|
||||
}
|
||||
|
||||
/// Subtitle text files a Matroska document can gain — must stay in sync
|
||||
/// with the extension gate in MP42MkvRemuxer's added-track validation.
|
||||
static let matroskaSubtitleExtensions = ["srt", "ssa", "ass"]
|
||||
|
||||
func showImportSheet(fileURLs: [URL]) {
|
||||
guard doc.isMatroska == false else { return }
|
||||
if doc.isMatroska {
|
||||
importSubtitleTracksForMatroska(fileURLs: fileURLs)
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
let controller = try FileImportController(fileURLs: fileURLs, delegate: self)
|
||||
@@ -610,6 +641,52 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
|
||||
}
|
||||
}
|
||||
|
||||
// A Matroska document gains subtitle tracks by re-parsing the source text
|
||||
// file at save time (MP42MkvRemuxer writes S_TEXT/UTF8 BlockGroups), so
|
||||
// the model only needs the track object with its URL — no FileImportController
|
||||
// sheet, and crucially none of didSelect's organizeAlternateGroups/
|
||||
// inferMediaCharacteristics churn, which would shift model indices and
|
||||
// break the remuxer's TrackEntry↔sourceTracks identity pairing.
|
||||
func importSubtitleTracksForMatroska(fileURLs: [URL]) {
|
||||
let allowed = DocumentWindowController.matroskaSubtitleExtensions
|
||||
let subtitleURLs = fileURLs.filter { allowed.contains($0.pathExtension.lowercased()) }
|
||||
guard subtitleURLs.isEmpty == false else { return }
|
||||
|
||||
var addedTracks: [MP42Track] = []
|
||||
var nextDisplayId: MP42TrackId = (mp4.tracks.map { $0.trackId }.max() ?? 0) + 1
|
||||
for url in subtitleURLs {
|
||||
do {
|
||||
let importer = try MP42FileImporter(url: url)
|
||||
for track in importer.tracks {
|
||||
guard track.isMember(of: MP42ChapterTrack.self) == false else { continue }
|
||||
// Same addTrack: invariant the tags-only read establishes
|
||||
// (see Document.readMatroska) — codecs MP4 cannot carry
|
||||
// as-is must carry conversion settings.
|
||||
if trackNeedConversion(track.format) {
|
||||
(track as? MP42SubtitleTrack)?.conversionSettings = MP42ConversionSettings.subtitlesConversion()
|
||||
}
|
||||
mp4.addTrack(track)
|
||||
// addTrack: zeroes trackId; keep the table numbering dense.
|
||||
track.trackId = nextDisplayId
|
||||
nextDisplayId += 1
|
||||
addedTracks.append(track)
|
||||
}
|
||||
}
|
||||
catch {
|
||||
if let windowForSheet = doc.windowForSheet {
|
||||
presentError(error, modalFor: windowForSheet, delegate: nil, didPresent: nil, contextInfo: nil)
|
||||
} else {
|
||||
presentError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
guard addedTracks.isEmpty == false else { return }
|
||||
doc.updateChangeCount(.changeDone)
|
||||
tracksViewController.reloadData()
|
||||
tracksViewController.selectTracks(addedTracks)
|
||||
}
|
||||
|
||||
@objc func importFilesDirectly(_ fileURLs: [URL]) {
|
||||
do {
|
||||
let controller = try FileImportController(fileURLs: fileURLs, delegate: self)
|
||||
@@ -631,7 +708,10 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
|
||||
mp4.addTrack(track)
|
||||
}
|
||||
|
||||
if tracks.isEmpty == false {
|
||||
// Reordering must never touch a Matroska document: the remuxer pairs
|
||||
// TrackEntry elements against mkvSourceTracks by identity, and a
|
||||
// reordered model would mispair them (same rule as delete(tracks:)).
|
||||
if tracks.isEmpty == false, doc.isMatroska == false {
|
||||
if Prefs.organizeAlternateGroups {
|
||||
mp4.organizeAlternateGroups()
|
||||
if Prefs.inferMediaCharacteristics {
|
||||
|
||||
@@ -342,15 +342,34 @@ class SBSaveAsScriptCommand: NSScriptCommand, ScriptCommandDocumentTargeting {
|
||||
logger.write(toLog: "No document available for save as operation")
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
// Use the helper method to extract the destination path
|
||||
guard let path = extractFilePath() else {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
let destinationURL = URL(fileURLWithPath: path)
|
||||
let fileName = destinationURL.lastPathComponent
|
||||
|
||||
|
||||
// mp4.write(to:) below muxes QuickTime atoms and would happily write
|
||||
// an MP4 over a Matroska document, so route those through NSDocument
|
||||
// instead: that picks the tag-writer/remux path in writeMatroska,
|
||||
// enforces the mkv/mka/mks destination, does the fileURL/change-count
|
||||
// bookkeeping, and reports progress itself via Document.save.
|
||||
if sublerDoc.isMatroska {
|
||||
// "Matroska video" is the CFBundleTypeName covering mkv/mka/mks
|
||||
// (NSDocument.documentType is unavailable from Swift; writeSafely
|
||||
// only re-checks the destination extension itself).
|
||||
sublerDoc.save(to: destinationURL, ofType: "Matroska video", for: .saveAsOperation) { error in
|
||||
if let error = error {
|
||||
logger.write(toLog: "Failed to save document: \(error.localizedDescription)")
|
||||
} else {
|
||||
logger.write(toLog: "Script save of \(fileName) completed")
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
// Build options dictionary with 64-bit settings from UI preferences
|
||||
var options: [String: Any] = [:]
|
||||
options[MP4264BitData] = Prefs.mp464bitOffset
|
||||
|
||||
Reference in new issue
Block a user