diff --git a/CHANGES.md b/CHANGES.md index f27a839..ecfa627 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -8,7 +8,7 @@ original Subler checkout. from the GitHub Subler project. - **Since then**: 18 commits in the app repository and 15 in the **MP42Foundation** submodule (2026-11-25 → 2026-11-28). -- **Fork identity**: version `1.9.5mkv2` (upstream base + `mkv` + a fork +- **Fork identity**: version `1.9.5mkv3` (upstream base + `mkv` + a fork change counter), builds as `SublerMKV.app` (`org.galad.SublerMKV`); development moved from GitHub to Gitea (`git.technomancer.com:Scott-Files/`). @@ -103,6 +103,11 @@ inside the app bundle so they never drift from the app's own code. adapted, so upstream fixes re-merge cleanly. Result: a real VobSub track (muxable into MP4 as `subp`, or tx3g-convertible), language taken from the filename, track URL kept on the user's `.sup`. +- **Queue loads `.sup` sidecars**: the queue's "Load external subtitles" scan + now picks up adjacent `.sup` files on MP4 items — the same importer and the + same drop-on-window default (`Prefs.subtitleConvertBitmap` decides tx3g vs + `subp`). Matroska queue items skip them, matching the remuxer's srt/ssa/ass + addition gate. - **PGS inside MKV → VobSub**: the import sheet offers a VobSub conversion action for PGS-format tracks. Requires rebuilding the `.sup` stream from mkvmerge's stripped-envelope, zlib-compressed blocks (reconstructing the diff --git a/CLAUDE.md b/CLAUDE.md index 9c9998e..fb46e10 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -36,7 +36,7 @@ Two layers with a strict boundary: - **Document flow**: `Document.swift` (NSDocument subclass) owns the opened file; `read(from:)` produces an `MP42File`. `DocumentWindowController` hosts the per-document window (tracks table, property view tabs). Export goes through `Document.save(to:...)` / `SaveOptions` and runs asynchronously; `sendToQueue` hands the document to the queue instead. - **MKV tags-only mode**: `.mkv/.mka/.mks` open directly (`DocumentController.openDocument` in `AppDelegate.swift` passes them through instead of forcing the convert-import sheet). `Document.isMatroska` then drives everything: the model is an in-memory `MP42File` filled from `MP42FileImporter` in **tagsOnly mode** (`initWithURL:tagsOnly:` — mirrors the file's own `TrackFlagEnabled` instead of the MP4 "first-of-type enabled" heuristic, so untouched tracks don't look edited), The save branching lives in **`MatroskaSaver`** (`Classes/MatroskaSaver.swift`, shared by `Document.writeMatroska` and `QueueItem` so a queued MKV saves exactly like the window): plain edits rewrite metadata + per-track fields in place via `MP42MkvTagWriter` (never touching clusters), while **deleted/added tracks, chapter edits, a forced rebuild (optimize/Save-As) or a destination different from the source** trigger the stream-copy rebuild via `MP42MkvRemuxer` (temp file + atomic rename even in place; destination must stay mkv/mka/mks — validated in `MatroskaSaver.save`). `MatroskaSaver.buildModel(from:)` is the shared tags-only model builder (conversion settings for un-muxable codecs to satisfy `addTrack:`, 1-based display trackIds; the caller wires `undo` afterwards so read opens no undo groups). MKV documents' `sendToQueue` skips the save panel and queues an in-place retag item carrying the document's model *and* its `MatroskaSaver` (`attachMatroskaSaver:` — the pairing is object identity and cannot be rebuilt from a bare model); the AppleScript send-to-queue does the same but keeps the script's destination URL (validated Matroska at save time). The remuxer pairs `TrackEntry` elements against the `MatroskaSaver`'s importer-order snapshot (built in `readMatroska`) with keep/drop decided by **object identity**, so the deletion check is immune to model index shifts; after a successful remux the snapshot is re-filtered in the same order **plus the added tracks appended** (matching the order the remuxer writes their TrackEntry elements last in the output). Subtitle tracks can be **added** to MKV docs (`.srt`/`.ssa`/`.ass` only): `DocumentWindowController.selectFile`/`showImportSheet` route MKV docs to `importSubtitleTracksForMatroska` (direct `MP42FileImporter` per file, no track-selection sheet; the accepted-extension list `matroskaSubtitleExtensions` must stay in sync with the remuxer's gate), and the `didSelect`/AppleScript `importFilesDirectly` path skips `organizeAlternateGroups`/`inferMediaCharacteristics` for MKV for the same pairing-protection reason. The AppleScript `save as` command (ScriptCommand.swift) must route Matroska docs through `Document.save(...)` — the raw `mp4.write(to:)` path would mux QuickTime atoms over an MKV document. Reordering must never happen on MKV docs (it would break the pairing): drag stays blocked and `DocumentWindowController.delete(tracks:)` skips `organizeAlternateGroups`/`inferMediaCharacteristics` for MKV. Save-As is enabled for MKV, and so is **File ▸ Optimize** (`saveAndOptimize`): on Matroska documents optimize means `writeMatroska`'s forced structural branch — a full remuxer rebuild of the file from the existing tracks (the container-equivalent of QuickTime atom-ordering), not `MP42File optimize`. Its validation precondition is `fileURL != nil` on MKV, because tags-only models answer `hasFileRepresentation == false` (their tracks are never muxed) and would otherwise keep the menu disabled forever. NSDocument Duplicate needs no MKV gate because **no nib wires `duplicateDocument:`** — that menu item doesn't exist for any container. Track **reorder and MP4-only properties stay gated** (`PropertyView.isReadOnly` disables the tabs; metadata tabs stay editable; adding stays restricted to the subtitle files and chapter txt/csv described here), but real tracks **and the chapter pseudo-track** can be **deleted** (deleting the chapter track empties the model, so the save remuxes and removes the `Chapters` element — same as emptying the Chapters tab), and the four fields Matroska actually stores per track are editable and saved — name, language, enabled, subtitle forced. UI split: `TracksViewController.isReadOnly` gates drag/reorder while `isFieldEditable(_:)` re-enables the name/language/enabled cells on real (non-chapter) rows; `PropertyView.allowsTrackEditing` lets `VideoViewController` re-enable just the subtitle forced popup (Never/All only — the per-sample "Any samples" option has no Matroska equivalent).Chapters are **editable** on MKV docs (`didSelect` exempts `ChapterViewController` from the read-only blanket alongside `MovieViewController`) and chapter-less docs can **gain chapters** via `.txt` import (OGG/mp4chaps format → `addChapters`, which replaces the model's chapter track since `MP42File addTrack:` replaces previous chapter tracks) or update an existing track via `.csv` (`updateChapters`) — routed from `selectFile`'s MKV branch, drag-drop, and the AppleScript `importFilesDirectly` path (it mirrors the panel's extension dispatch, so `.txt`/`.csv` go to the chapter commands — `addChapters` bootstraps the chapter track on either container — and everything else to `FileImportController`); or one chapter at a time via the Actions toolbar's **Insert a chapter** (`DocumentWindowController.insertChapter`, works on both containers, creates the chapter track when absent and timestamps the new chapter 1s past the latest start clamped to the track duration, so it never ties with — and clamp-cascades — existing chapters) or in bulk via **Insert a chapter every** (`addChaptersEvery`); both do the tags-only trackId/`updateChangeCount` bookkeeping when they create the track, and both work on either container. Chapter changes ride the **remuxer**, not the tag writer: `MatroskaSaver`'s chapter-row snapshot (model rows at read/save time, compared model-vs-model so the baseline tracks exactly what a rewrite would emit) drives `chaptersChanged` into the structural condition, and its remux branch passes `mp4.chapters` (or an empty `MP42ChapterTrack` when the model has none, to delete the element) as the remuxer's `replacementChapters`; nil means verbatim copy. -- **Queue engine**: `QueueController` (window UI) → `Queue` (serial `DispatchQueue` worker, persists `[QueueItem]` to disk via `NSKeyedArchiver` at `Application Support/SublerMKV/queue.sbmkvqueue` — the fork's storage folder, shared by presets/tessdata/logs; `saveToDisk` creates the folder, as the swallowed write error would otherwise mean silent non-persistence — holds IOKit sleep assertions while working) → `QueueItem` (imports a source file into an `MP42File`, then muxes to the destination) → `QueueAction` objects (`QueueActionProtocol`, `.pre`/`.post` types) apply individual transformations (set metadata, force subtitles, language fixes, etc.) to a queue item. Watch for `Queue.Working/Completed/Failed/Cancelled` notifications driving UI updates. **Matroska items match the window's save instead of converting**: `QueueItem.isMatroska` (derived from the source file's extension, never archived) makes `prepare()` do the tags-only import (`MatroskaSaver.buildModel`) and `process()` write back through the same `MatroskaSaver` — `QueueController.destination(for:)` keeps the mkv/mka/mks extension for it (the file itself, or the same name inside a queue destination folder → stream-copy remux there, the Save-As equivalent). On MKV items the queue's Optimize forces the remux rebuild (`QueueOptimizeAction` itself no-ops — `MP4Optimize` has nothing to reorder on a tags-only model), `QueueOrganizeGroupsAction`/`QueueFixFallbacksAction`/`QueueColorSpaceAction` no-op (MP4-only concepts; organize churn would corrupt the tag writer's positional TrackEntry diff), while `QueueSubtitlesAction`'s adjacent `.srt/.ass/.ssa` finds ride the remuxer as added tracks (it sets conversion settings to satisfy `addTrack:` like the window's MKV import path). Queue restores never carry the tags-only model (identity pairing can't be archived; the item re-imports and pre-actions re-run), and decoding normalizes legacy items' retired convert-to-mp4 destinations back to the source; editing an MKV item opens the source file as a real MKV document rather than wrapping the item's model. +- **Queue engine**: `QueueController` (window UI) → `Queue` (serial `DispatchQueue` worker, persists `[QueueItem]` to disk via `NSKeyedArchiver` at `Application Support/SublerMKV/queue.sbmkvqueue` — the fork's storage folder, shared by presets/tessdata/logs; `saveToDisk` creates the folder, as the swallowed write error would otherwise mean silent non-persistence — holds IOKit sleep assertions while working) → `QueueItem` (imports a source file into an `MP42File`, then muxes to the destination) → `QueueAction` objects (`QueueActionProtocol`, `.pre`/`.post` types) apply individual transformations (set metadata, force subtitles, language fixes, etc.) to a queue item. Watch for `Queue.Working/Completed/Failed/Cancelled` notifications driving UI updates. **Matroska items match the window's save instead of converting**: `QueueItem.isMatroska` (derived from the source file's extension, never archived) makes `prepare()` do the tags-only import (`MatroskaSaver.buildModel`) and `process()` write back through the same `MatroskaSaver` — `QueueController.destination(for:)` keeps the mkv/mka/mks extension for it (the file itself, or the same name inside a queue destination folder → stream-copy remux there, the Save-As equivalent). On MKV items the queue's Optimize forces the remux rebuild (`QueueOptimizeAction` itself no-ops — `MP4Optimize` has nothing to reorder on a tags-only model), `QueueOrganizeGroupsAction`/`QueueFixFallbacksAction`/`QueueColorSpaceAction` no-op (MP4-only concepts; organize churn would corrupt the tag writer's positional TrackEntry diff), while `QueueSubtitlesAction`'s adjacent `.srt/.ass/.ssa` finds ride the remuxer as added tracks (it sets conversion settings to satisfy `addTrack:` like the window's MKV import path). The scan also picks up adjacent `.sup` files on **non-Matroska** items (`.sup` stays skipped on MKV items, matching the remuxer's srt/ssa/ass-only addition gate): `MP42VobSubImporter` turns it into a VobSub track just like dragging the file onto the window, and the action mirrors that path's default — tx3g conversion settings only when `Prefs.subtitleConvertBitmap` says so, otherwise mux as a subp bitmap track. Queue restores never carry the tags-only model (identity pairing can't be archived; the item re-imports and pre-actions re-run), and decoding normalizes legacy items' retired convert-to-mp4 destinations back to the source; editing an MKV item opens the source file as a real MKV document rather than wrapping the item's model. - **Import**: `FileImportController` wraps `MP42FileImporter` to let users pick which source tracks to import; `isTrackMuxable` / `trackNeedConversion` (in `Utilities.swift`) gate which tracks pass through vs. get converted. BLU-RAY PGS `.sup` files flow through this same machinery automatically (the open panel and drag-drop key off `MP42FileImporter.supportedFileFormats()/supportedContentTypes()`): they're produced by `MP42VobSubImporter`, which converts them to VobSub first — see the submodule section. They stay out of Matroska documents: `matroskaSubtitleExtensions` deliberately does not list `sup` (the remuxer only writes S_TEXT/UTF8 additions). All three subtitle importers (`MP42SrtImporter`/`MP42SSAImporter`/`MP42VobSubImporter`) take language from the filename via `getFilenameLanguage`, which scans separator-split tokens **right-to-left** (mkvmerge-style: 3-char tokens try ISO 639-2/T then the library's B codes `fre`/`ger`/`dut`/`chi`; the dash is deliberately not a separator, so `pt-BR` survives as one extended tag instead of its region half being misread as ISO 639-1 `br`=Breton); `und` when nothing decodes lets SRT/SSA fall back to `guessStringLanguage` and the sup path keep the converter's idx default. Community type tokens in the name (`sdh`/`hearing_impaired`/`impaired`/`deaf`, `cc`/`closed caption`, `commentary`/`commentaries`, `forced`, `lyrics`/`lyric`) make `getFilenameSubtitlesTrackName` name **any** flagged track `SDH` — one recognizable name serves users better than one name per type, and MP4 has no flag anyway, the name is the convention players show (the `SDH` name then picks up `transcribes-spoken-dialog`/`describes-music-and-sound` through `MP42File organizeMediaCharacteristicsForMediaType:`; the old per-type name→tag choreography like `forced-only` no longer fires from filenames — deliberate). The language deliberately stays out of the name since it rides its own element. MKV container tracks run through the same recognizer on the **conversion path** (`getSubtitleTypeTokenFromString` applied to the `TrackEntry Name` in `MP42MkvImporter`; a track without a TrackName inherits the token from the MKV's own filename — the decision keys on the TrackName element's presence, never the model name, because every track starts life with a default localized " Track" name); tagsOnly mode is exempt — that model is the tag writer's diff baseline. MKV-added subtitle tracks carry the name via the remuxer's `Name` element. - **Metadata**: `Classes/MetadataImporters/` holds a `MetadataImporter` protocol with concrete importers (TheMovieDB, TheTVDB, iTunesStore, AppleTV, SquaredTVArt, chapter DBs). Note: the chapter-DB search (`DocumentWindowController.searchChapters`, which stays in the always-valid branch of `validateUserInterfaceItem`) is currently **orphaned** — no menu item, XIB connection or code path invokes it. Search results (`MetadataResult`/`MetadataResultMap`) are applied onto `MP42Metadata` via `MetadataSearchController`. API credentials are **compiled-in constants** in the service classes (TMDb `TheMovieDBService.key`, TVDB `TheTVDBService.apiKey`, SquaredTVArt's URL key), so they need no user setup and don't live in prefs; only the short-lived TVDB bearer-token session is cached in `UserDefaults` (`SBTheTVBDv4Token`, ~4 h validity) and re-fetched automatically on expiry. (`Token.swift` is unrelated — it's the filename-template tokenizer.) - **Presets**: `Preset` / `QueuePreset` / `MetadataPreset` + `PresetManager` — user-defined rule sets that auto-apply actions and metadata to queue items. diff --git a/Classes/QueueAction.swift b/Classes/QueueAction.swift index d393bb8..44e21cb 100644 --- a/Classes/QueueAction.swift +++ b/Classes/QueueAction.swift @@ -71,7 +71,7 @@ class QueueSetOutputFilenameAction: NSObject, QueueActionProtocol { static var supportsSecureCoding: Bool { return true } } -/// An action that search in the item source directory for additionals srt subtitles. +/// An action that search in the item source directory for additionals srt/ass/ssa and sup subtitles. class QueueSubtitlesAction : NSObject, QueueActionProtocol { var type: QueueActionType { return .pre } @@ -80,13 +80,19 @@ class QueueSubtitlesAction : NSObject, QueueActionProtocol { override init() {} - private func loadExternalSubtitles(url: URL) -> [MP42FileImporter] { + private func loadExternalSubtitles(url: URL, allowBitmap: Bool) -> [MP42FileImporter] { let movieFilename = url.deletingPathExtension().lastPathComponent var importers: [MP42FileImporter] = [] if let contents = try? FileManager.default.contentsOfDirectory(at: url.deletingLastPathComponent(), includingPropertiesForKeys: nil, options: [.skipsSubdirectoryDescendants, .skipsHiddenFiles, .skipsPackageDescendants]) { for url in contents { let ext = url.pathExtension.lowercased() - if ext == "srt" || ext == "ass" || ext == "ssa" { + // A .sup is claimed by MP42VobSubImporter (sup2vob → VobSub + // track), exactly like dragging the file onto the window. + // Matroska items must skip it: the remuxer only adds + // S_TEXT/UTF8 tracks, so it stays out of the window's + // matroskaSubtitleExtensions list too. + let isBitmap = (ext == "sup" && allowBitmap) + if ext == "srt" || ext == "ass" || ext == "ssa" || isBitmap { let subtitleFilename = url.deletingPathExtension().lastPathComponent if movieFilename.count <= subtitleFilename.count && subtitleFilename.hasPrefix(movieFilename) { @@ -102,7 +108,7 @@ class QueueSubtitlesAction : NSObject, QueueActionProtocol { } func runAction(_ item: QueueItem) -> Bool { - let subtitlesImporters = loadExternalSubtitles(url: item.fileURL) + let subtitlesImporters = loadExternalSubtitles(url: item.fileURL, allowBitmap: item.isMatroska == false) for importer in subtitlesImporters { for track in importer.tracks { @@ -111,7 +117,13 @@ class QueueSubtitlesAction : NSObject, QueueActionProtocol { // 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 { + // A .sup surfaces as a VobSub track, which needs no + // conversion; mimic the drop-on-window default (same rule as + // QueueItem.configureSubtitles): tx3g only when the user's + // bitmap-subtitles preference asks for it, else mux the + // bitmap track as-is (subp). + let convertBitmapToTx3g = track.format == kMP42SubtitleCodecType_VobSub && Prefs.subtitleConvertBitmap + if (trackNeedConversion(track.format) || convertBitmapToTx3g), let subtitleTrack = track as? MP42SubtitleTrack { subtitleTrack.conversionSettings = MP42ConversionSettings.subtitlesConversion() } item.mp4File?.addTrack(track) diff --git a/Subler.xcodeproj/project.pbxproj b/Subler.xcodeproj/project.pbxproj index 8f5c3a9..4f2f8a4 100644 --- a/Subler.xcodeproj/project.pbxproj +++ b/Subler.xcodeproj/project.pbxproj @@ -1560,7 +1560,7 @@ "CODE_SIGN_IDENTITY[sdk=macosx*]" = "-"; CODE_SIGN_STYLE = Automatic; COPY_PHASE_STRIP = NO; - CURRENT_PROJECT_VERSION = 1.9.5mkv2; + CURRENT_PROJECT_VERSION = 1.9.5mkv3; DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = dwarf; DEVELOPMENT_TEAM = ""; @@ -1582,7 +1582,7 @@ "@executable_path/../Frameworks", ); MACOSX_DEPLOYMENT_TARGET = "$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)"; - MARKETING_VERSION = 1.9.5mkv2; + MARKETING_VERSION = 1.9.5mkv3; OTHER_CFLAGS = ""; OTHER_LDFLAGS = "-Wl,-rpath,@loader_path/../Frameworks"; OTHER_SWIFT_FLAGS = ""; @@ -1609,7 +1609,7 @@ CODE_SIGN_IDENTITY = "Mac Developer"; "CODE_SIGN_IDENTITY[sdk=macosx*]" = "-"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 1.9.5mkv2; + CURRENT_PROJECT_VERSION = 1.9.5mkv3; DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEVELOPMENT_TEAM = ""; @@ -1630,7 +1630,7 @@ "@executable_path/../Frameworks", ); MACOSX_DEPLOYMENT_TARGET = "$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)"; - MARKETING_VERSION = 1.9.5mkv2; + MARKETING_VERSION = 1.9.5mkv3; OTHER_CFLAGS = ""; OTHER_LDFLAGS = "-Wl,-rpath,@loader_path/../Frameworks"; OTHER_SWIFT_FLAGS = "";