Compare commits
No files matched your search
+1
-1
@@ -1,3 +1,3 @@
|
||||
[submodule "MP42Foundation"]
|
||||
path = MP42Foundation
|
||||
url = https://github.com/SublerApp/MP42Foundation.git
|
||||
url = https://git.technomancer.com/Scott-Files/MP42Foundation.git
|
||||
@@ -23,12 +23,6 @@
|
||||
<action selector="orderFrontStandardAboutPanel:" target="-2" id="142"/>
|
||||
</connections>
|
||||
</menuItem>
|
||||
<menuItem title="Check for Updates…" id="529">
|
||||
<modifierMask key="keyEquivalentModifierMask"/>
|
||||
<connections>
|
||||
<action selector="checkForUpdates:" target="530" id="531"/>
|
||||
</connections>
|
||||
</menuItem>
|
||||
<menuItem title="Donate…" id="ojS-sZ-qGM">
|
||||
<modifierMask key="keyEquivalentModifierMask"/>
|
||||
<connections>
|
||||
@@ -500,6 +494,5 @@ CA
|
||||
<outlet property="sendToExternalApp" destination="597" id="Kz4-8d-I4D"/>
|
||||
</connections>
|
||||
</customObject>
|
||||
<customObject id="530" customClass="SPUStandardUpdaterController"/>
|
||||
</objects>
|
||||
</document>
|
||||
+245
@@ -0,0 +1,245 @@
|
||||
# CHANGES — SublerMKV fork
|
||||
|
||||
Executive summary of everything this fork adds or changes relative to the
|
||||
original Subler checkout.
|
||||
|
||||
- **Baseline**: upstream commit `0c3d7de` (2026-10-20, "Fix wobbling preference
|
||||
panels switch animation caused by macOS 27.2") — the last commit inherited
|
||||
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.5mkv1` (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/`).
|
||||
|
||||
## Executive summary
|
||||
|
||||
Two headline capabilities, plus the packaging to support them:
|
||||
|
||||
1. **Matroska files can now be opened and edited in place.** Subler previously
|
||||
forced `.mkv`/`.mka`/`.mks` through a convert-to-MP4 import. The fork opens
|
||||
them directly as documents: metadata, cover art, track fields, chapters,
|
||||
subtitle-track additions, and track deletions all save back *as Matroska*,
|
||||
without a lossy transcode and without ever writing QuickTime atoms over an
|
||||
MKV.
|
||||
2. **A complete BLU-RAY PGS subtitle pipeline.** Raw `.sup` PGS files import
|
||||
natively; PGS tracks inside MKVs convert to VobSub (`subp`) at the stream's
|
||||
**own resolution** (e.g. 1920x1080, not the old forced 720x480 DVD frame);
|
||||
and subtitle filenames are recognized for language and type flags (SDH,
|
||||
forced, commentary, …) the way mkvmerge does it.
|
||||
|
||||
Supporting work: direct metadata lookups from IDs embedded in filenames, the
|
||||
project + submodules re-hosted on Gitea, the Sparkle auto-updater removed, and
|
||||
two command-line helpers (`extractsubs`, `sup2vob`) now built and shipped
|
||||
inside the app bundle so they never drift from the app's own code.
|
||||
|
||||
## 1. Matroska in-place editing
|
||||
|
||||
*App: `eb386a5`, `3302367`, `8520d72`, `f457b4e`, `06ecb0a` — Framework: `1040f47`, `8ba3f25`, `0cf79ec`, `10dcee3`, `e8231de`*
|
||||
|
||||
- **Direct open**: `.mkv/.mka/.mks` open into a tags-only `MP42File` model
|
||||
instead of the convert-import sheet. MP4-only properties stay read-only;
|
||||
the four fields Matroska actually stores per track — **name, language,
|
||||
enabled, subtitle-forced** — are editable, along with all metadata and
|
||||
cover art.
|
||||
- **Two save engines** (in MP42Foundation), chosen automatically:
|
||||
- `MP42MkvTagWriter` — mkvpropedit-style **in-place** rewrite of the `Tags`
|
||||
element, cover-art attachment, and per-track fields. Reuses the old extent
|
||||
+ Void padding when the payload fits; otherwise rebuilds the file tail
|
||||
with recomputed SeekHead/Cues positions (temp file + atomic replace).
|
||||
Untouched tracks diff to **byte-for-byte no-ops**; foreign tag groups,
|
||||
unknown TrackEntry children, and non-cover attachments are preserved
|
||||
verbatim; a size+mtime staleness guard refuses writes on changed files.
|
||||
- `MP42MkvRemuxer` — stream-copy **rebuild** used when the structure must
|
||||
change: deleted tracks, added subtitle tracks, chapter edits, Save-As, or
|
||||
File ▸ Optimize. Every block is copied bit-for-bit (blocks of removed
|
||||
tracks dropped by unmarked-vint track number), clusters are header-only
|
||||
scanned, SeekHead positions are patched at the end, Cues are regenerated
|
||||
only when the source had them, and `Info/Duration` is recomputed from
|
||||
written block extents.
|
||||
- **Track management**: real tracks can be deleted (pairing TrackEntry ↔ model
|
||||
by object identity, immune to index shifts); `.srt`/`.ssa`/`.ass` subtitle
|
||||
tracks can be **added** (re-parsed from source at save time, written as
|
||||
`S_TEXT/UTF8` with proper `BlockGroup` framing and synthesized clusters
|
||||
when timestamps demand it). Reordering stays blocked on MKV to protect the
|
||||
pairing; destinations must remain mkv/mka/mks.
|
||||
- **Chapters are first-class**: editable rows, `.txt` (mp4chaps) import to
|
||||
bootstrap chapters on a chapter-less file, `.csv` update, single-chapter
|
||||
insertion (timestamped 1 s past the latest start, clamped), bulk "insert
|
||||
every N", deletion of the whole chapter track (removes the `Chapters`
|
||||
element). Chapter changes ride the remuxer (detected via a model snapshot),
|
||||
and chapter **language round-trips** at track level. TagsOnly mode mirrors
|
||||
the file's chapter atoms verbatim — no MP4-path normalization — so an
|
||||
untouched save never shifts or drops atoms.
|
||||
- **AppleScript**: `save as` routes Matroska documents through the proper
|
||||
Matroska save path (the raw MP4 writer would corrupt them); direct file
|
||||
import mirrors the panel's extension dispatch; PGS/MKV naming conventions
|
||||
respected without MP4-only model reshuffling.
|
||||
- **Queue parity**: batched MKVs are retagged **in place** instead of being
|
||||
converted to MP4. The window's whole save branching moved into a shared
|
||||
`MatroskaSaver` (baseline snapshots + tag-writer-vs-remuxer choice) used
|
||||
by both `Document` and `QueueItem`: queue items import tags-only, keep the
|
||||
mkv/mka/mks extension (in place, or stream-copy into a destination folder),
|
||||
and remux only when an edit demands it (found `.srt/.ass/.ssa` additions,
|
||||
renamed chapters, optimize, renamed output). MP4-only queue actions
|
||||
(organize groups, fix fallbacks, color space, atom optimize) no-op on MKV;
|
||||
send-to-queue from a window hands the item the document's model *and*
|
||||
pairing baseline; editing a queued MKV opens a real MKV document.
|
||||
- **Spec traps handled** (all verified against mkvtoolnix-written files):
|
||||
correct `Language`/`LanguageIETF`/`TrackFlagEnabled` element ids,
|
||||
`ChapterAtom = 0xB6`, chapter timecodes in absolute nanoseconds, mandatory
|
||||
`ChapterUID`/`EditionUID` derived deterministically from content, and
|
||||
community-style SimpleTags (`RATING`, `CONTENTRATING`, `MEDIAKIND`, `HD`,
|
||||
`CAST`, `NETWORK`, `EPISODEID`) so Movie-tab fields with no Matroska-spec
|
||||
tag still round-trip.
|
||||
|
||||
## 2. Subtitle pipeline
|
||||
|
||||
*App: `5d6c0cd`, `dd956fa`, `87e0c82`, `401584a` — Framework: `e02f60b`, `5777208`, `837aa1c`, `30dd96f`, `e7c7b80`, `e428558`*
|
||||
|
||||
- **BLU-RAY PGS `.sup` import**: `MP42VobSubImporter` claims `.sup` directly,
|
||||
converting via **sup2vob** — the upstream Swift sources vendored into
|
||||
MP42Foundation (`MP42/Sup2Vob/`) with only the CLI globals and facade
|
||||
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`.
|
||||
- **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
|
||||
13-byte `PG` segment framing byte-identically to mkvextract) before the
|
||||
same sup2vob machinery runs.
|
||||
- **Full source resolution**: the conversion always runs sup2vob's `--full`
|
||||
passthrough — frames keep the PGS's own PCS canvas (typically 1920x1080)
|
||||
instead of being downscaled to the 720x480/576 DVD frame the old code
|
||||
forced. Verified end-to-end: framework output is **byte-identical** to
|
||||
`sup2vob --full`, and ffprobe reports `dvd_subtitle 1920x1080` on muxed
|
||||
output from both the `.sup` and the MKV path.
|
||||
- **VobSub frame sizes honored**: `.sub`/`.idx` additions now mux at the
|
||||
frame size declared in the idx rather than a default.
|
||||
- **Filename intelligence** (mkvmerge-style, right-to-left token scan):
|
||||
ISO 639-2/B and B-code language tags (`pt-BR` extended tags survive), and
|
||||
community type tokens (`sdh`, `cc`, `commentary`, `forced`, `lyrics`,
|
||||
deaf/hearing-impaired variants) — any flagged track is named **SDH**, the
|
||||
one recognizable convention players show, which then picks up media
|
||||
characteristics automatically. MKV track names run through the same
|
||||
recognizer on the conversion path (track name, falling back to the MKV's
|
||||
own filename).
|
||||
- **Bug fix**: SSA files without a `[V4+ Styles]` section no longer fail to
|
||||
parse.
|
||||
|
||||
## 3. Metadata
|
||||
|
||||
*App: `f20ad7e`*
|
||||
|
||||
- **Direct metadata lookup from filename IDs**: names like
|
||||
`Movie (2024) {tmdb-1015812}` or embedded IMDb/TVDB IDs are parsed
|
||||
(ParseFilename now handles parenthesized years and brace-wrapped service
|
||||
IDs, IMDb IDs widened to 7–9 digits) and emitted as `id:<kind>:<value>`.
|
||||
The search sheet, the queue metadata action, and the AppleScript
|
||||
fetch-metadata command try the direct TMDb lookup first and fall back to
|
||||
title search when the ID is unknown or unsupported.
|
||||
|
||||
## 4. Fork infrastructure and distribution
|
||||
|
||||
*App: `0f8d251`, `628ccfe`, `20438f3`, `475737a`, `e96773f` — Framework: `79c251c`, `7ff1ed4`, `a287ea6`*
|
||||
|
||||
- **Gitea migration**: project, README clone URLs, and the `contrib`
|
||||
submodule all moved from GitHub to Gitea (SSH for development, public
|
||||
HTTPS URLs in the README/submodule config).
|
||||
- **Sparkle removed**: the auto-updater integration (framework, updater menu
|
||||
item, feed URL/public key, SPM package reference) is gone — this fork
|
||||
updates itself however its users choose.
|
||||
- **Fork version scheme `<upstream>.mkv<N>`** distinguishes fork builds from
|
||||
upstream without touching the forked-from version: the trailing counter in
|
||||
`MARKETING_VERSION`/`CURRENT_PROJECT_VERSION` (currently `1.9.5mkv1`)
|
||||
increments with each batch of fork changes, and restarts at 1 whenever
|
||||
upstream's base version moves.
|
||||
- **Build output renamed `SublerMKV.app`**: target renamed and `PRODUCT_NAME`
|
||||
set to `SublerMKV`; the interpolated bundle id becomes
|
||||
`org.galad.SublerMKV`, so fork builds are fully independent of an installed
|
||||
upstream `Subler.app` — own preferences (API tokens re-entered once), own
|
||||
queue defaults, and its own LaunchServices registration instead of two
|
||||
same-idded apps competing to open files.
|
||||
- **Own storage folder**: all App Support data moved from
|
||||
`Application Support/Subler/` to `Application Support/SublerMKV/` — the
|
||||
queue (renamed `queue.sbmkvqueue`), presets, downloaded OCR tessdata, and
|
||||
the debug log — so both apps can run without sharing any file.
|
||||
`Queue.saveToDisk` also gained the missing parent-directory creation the
|
||||
old (always-existing) folder had masked; without it the atomic write error
|
||||
is swallowed and the queue silently never persists.
|
||||
- **Spec trap found**: the Swift **module name** feeds every class's
|
||||
ObjC-runtime registration (`Subler.LanguageTransformer`), and XIB binding
|
||||
value-transformers reference that exact name — renaming the product alone
|
||||
made the queue-options nib throw `Cannot find value transformer` mid-load
|
||||
(dead popups, frozen checkboxes). `PRODUCT_MODULE_NAME = Subler` pins the
|
||||
module whatever the product is called; no XIB edits.
|
||||
- **Xcode 27.2 project migration** for both the app and the framework.
|
||||
|
||||
## 5. Command-line tools shipped in the app bundle
|
||||
|
||||
*App: `c08d607`, `5111294`, `56d843c` — Framework: `72e879e`*
|
||||
|
||||
- **`extractsubs`** bundles into `Contents/Resources/`: extracts subtitle
|
||||
tracks from mkv/mp4 files via ffmpeg stream copy, named
|
||||
`<input>.<track>[.<type>].<lang>.<ext>` — exactly the shape Subler's
|
||||
filename recognizer probes, so results drag straight back into the app —
|
||||
and runs `sup2vob --full` on extracted PGS. Defaults to English tracks
|
||||
(`--all` for everything); up-front dependency checks with clear messages;
|
||||
single-invocation extraction with per-track retry; a mkvmerge/mkvextract
|
||||
rescue path for `S_TEXT/WEBVTT` tracks ffmpeg cannot read.
|
||||
- **`sup2vob` slim CLI** (`MP42Foundation/sup2vob/`): only `main.swift` + a
|
||||
Makefile — it compiles the framework's own `MP42/Sup2Vob/` sources, so CLI
|
||||
and app conversion code can never drift, and the CLI doubles as the
|
||||
byte-identity oracle for the framework converter.
|
||||
- **Built into the app**: the Subler build runs that Makefile (incremental)
|
||||
and installs the binary at `Contents/MacOS/sup2vob`, so building Subler
|
||||
refreshes the CLI, and the bundled `extractsubs` finds it as a bundle
|
||||
sibling — the shipped pair needs no install beyond ffmpeg/ffprobe.
|
||||
|
||||
## Appendix — commit index
|
||||
|
||||
### SublerMKV (app), since `0c3d7de`
|
||||
|
||||
| Commit | Subject |
|
||||
|---|---|
|
||||
| `eb386a5` | Open and edit Matroska files in place, including track removal |
|
||||
| `3302367` | Add subtitle tracks to open Matroska documents |
|
||||
| `8520d72` | Edit and add chapters in Matroska documents |
|
||||
| `f457b4e` | Make chapter tracks deletable, insertable, and language-editable |
|
||||
| `06ecb0a` | Route AppleScript chapter imports and make File > Optimize work on MKV |
|
||||
| `401584a` | Mux added VobSub tracks at the frame size declared in the idx |
|
||||
| `f20ad7e` | Search metadata directly from IDs embedded in file names |
|
||||
| `0f8d251` | Point the project at Gitea and document the fork |
|
||||
| `628ccfe` | Use the gitea SSH login in clone URLs |
|
||||
| `20438f3` | Pull the contrib dependency from Gitea too |
|
||||
| `475737a` | Drop the Sparkle updater and stamp the fork version 1.9.5mkv |
|
||||
| `e96773f` | Point the submodule and README at the public HTTPS URLs |
|
||||
| `5d6c0cd` | Add PGS .sup subtitle import and filename flag recognition |
|
||||
| `dd956fa` | Offer VobSub conversion for PGS subtitle tracks |
|
||||
| `87e0c82` | Document the sup2vob full-frame passthrough for PGS conversions |
|
||||
| `c08d607` | Ship the extractsubs subtitle-extraction helper with the app |
|
||||
| `56d843c` | Document the slim sup2vob CLI in the submodule |
|
||||
| `5111294` | Build sup2vob into the app bundle so it ships and stays fresh |
|
||||
|
||||
### MP42Foundation (submodule), same period
|
||||
|
||||
| Commit | Subject |
|
||||
|---|---|
|
||||
| `1040f47` | Add Matroska tagging and track-removal support |
|
||||
| `e428558` | Fix SSA header parsing for files without a [V4+ Styles] section |
|
||||
| `8ba3f25` | Write added subtitle tracks during Matroska remux |
|
||||
| `0cf79ec` | Rebuild Matroska chapters on remux and recompute Info Duration |
|
||||
| `10dcee3` | Round trip the chapter language between model and Matroska |
|
||||
| `e8231de` | Mirror the file's chapter atoms verbatim in tagsOnly mode |
|
||||
| `e7c7b80` | Mux VobSub subpic tracks at the frame size declared by the idx |
|
||||
| `79c251c` | Move the contrib submodule to Gitea |
|
||||
| `a287ea6` | Adopt Xcode 27.2 project migration |
|
||||
| `7ff1ed4` | Serve the contrib submodule URL over HTTPS |
|
||||
| `30dd96f` | Recognize subtitle language and type tokens in filenames |
|
||||
| `e02f60b` | Import BLU-RAY PGS .sup files via vendored sup2vob |
|
||||
| `5777208` | Convert Matroska PGS tracks to VobSub and name flagged tracks SDH |
|
||||
| `837aa1c` | Keep the PGS source resolution through the sup2vob conversion |
|
||||
| `72e879e` | Add a slim sup2vob CLI built from the vendored Sup2Vob sources |
|
||||
|
||||
*(The submodule's pre-fork history was re-hosted on Gitea, so its commits are
|
||||
listed by date range rather than as a range from the base checkout.)*
|
||||
@@ -0,0 +1,69 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Project Overview
|
||||
|
||||
Subler is a macOS AppKit application for muxing and tagging MP4/M4V/M4A files: it demuxes video/audio/subtitle/chapter tracks from mov, mp4, mkv, and raw formats, muxes them into QuickTime-compatible MP4 files (including Apple-compatible tx3g subtitle tracks), and edits metadata with lookups against TMDb, TVDB, and the iTunes Store.
|
||||
|
||||
- App layer (`Classes/`) is pure Swift 5; the app has no storyboards — UI is XIB-based AppKit (`MainMenu.xib` plus per-controller `.xib`/`.strings`).
|
||||
- All container-level demux/mux/encode work lives in the **MP42Foundation** git submodule (Objective-C/Objective-C++), built as a framework.
|
||||
- Single app target (named `SublerMKV`, builds `SublerMKV.app` via `PRODUCT_NAME`; legacy productName "MP4Sub"; bundle id `org.galad.SublerMKV`, so fork builds keep their own prefs/LaunchServices registration apart from an installed upstream `org.galad.Subler`). `PRODUCT_MODULE_NAME = Subler` deliberately **pins the Swift module to the original name**: XIB binding value-transformers reference Swift classes module-qualified (`Subler.LanguageTransformer`), and Swift registers runtime names by module — letting the module follow the product made the QueueOptions nib throw `Cannot find value transformer with name "Subler.LanguageTransformer"` mid-binding-load (queue-settings checkboxes/popups dead, frozen at design-time state), so any product rename must keep this setting fixed), deployment target `$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)` (upstream was 10.13). No external package dependencies: the fork removed the Sparkle auto-update integration (updater menu item, `SPUStandardUpdaterController` in MainMenu.xib, `SUFeedURL`/`SUPublicEDKey` in Info.plist, the SPM package reference in the pbxproj).
|
||||
|
||||
## Build
|
||||
|
||||
The MP42Foundation submodule must be initialized or the app will not compile:
|
||||
|
||||
```
|
||||
git submodule update --init --recursive
|
||||
```
|
||||
|
||||
Build with Xcode (Subler scheme) or CLI:
|
||||
|
||||
```
|
||||
xcodebuild -project Subler.xcodeproj -scheme Subler -configuration Debug build
|
||||
```
|
||||
|
||||
No deployment-target override is needed: the projects moved from upstream's 10.13 to `$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)` (recent toolchains refuse 10.13).
|
||||
|
||||
There is **no test target and no CI** — changes are verified by building and running the app manually. Of the `Utilities/` tools, MP4Dump (legacy ObjC debugging) is not part of the app build, but `ParseFilename/` **is** — it's copied into the app bundle and executed at runtime by `MetadataHelper.parseFilename` via `Process`. `extractsubs` is also copied into the bundle (Resources phase → `Contents/Resources/extractsubs`, exec bit preserved by the copy) but **nothing in the app invokes it** — it's a user-facing CLI helper shipped with the app: it extracts subtitle tracks from mkv/mp4 files via ffmpeg stream copy (named `<input>.<track>[.<type>].<lang>.<ext>` — the shape `getFilenameLanguage`/`getFilenameSubtitlesTrackName` probe, so results drag straight back in) and runs `sup2vob --full` on extracted PGS `.sup` files. It needs ffprobe/ffmpeg on PATH; sup2vob comes from PATH **or from the bundle next to the script** (`Contents/MacOS/sup2vob`, built by the app — see the submodule section), so the bundled pair needs no install. mkvtoolnix and python3 are only needed for its `S_TEXT/WEBVTT` rescue path, and it skips extraction with a clear message rather than failing per-track mid-pipeline.
|
||||
|
||||
## Architecture
|
||||
|
||||
Two layers with a strict boundary:
|
||||
|
||||
### 1. App layer (`Classes/`, Swift)
|
||||
|
||||
- **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 `impLine truncated
|
||||
- **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.
|
||||
- **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 "<type> 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.
|
||||
- **Preferences**: `Prefs.swift` is the single source of truth for settings — nested enums of `@Stored` / `@StoredEnum` property-wrapped `UserDefaults` keys (defaults are auto-registered at startup). Add new settings here, not ad-hoc `UserDefaults` calls.
|
||||
- **AppleScript**: `Subler.sdef` defines the scripting dictionary; `ScriptCommand.swift` / `QueueScriptCommand.swift` implement the commands (e.g., "send to queue").
|
||||
- **Logging**: `Logger.shared` is the app-wide log sink; `ActivityWindowController` renders the log UI.
|
||||
|
||||
### 2. MP42Foundation (git submodule, own `MP42Foundation.xcodeproj`)
|
||||
|
||||
Referenced by the main project; `MP42Foundation.framework` is linked and copied into the app bundle. Imported throughout the app as `import MP42Foundation`. Key types: `MP42File` (in-memory MP4 model + muxing/writing), `MP42FileImporter` (demuxing mov/mp4/mkv/subtitle sources, FFmpeg-based), track classes (`MP42VideoTrack`, `MP42AudioTrack`, `MP42SubtitleTrack`, `MP42ChapterTrack`), `MP42Metadata` / `MP42MetadataItem`, `MP42AudioMixdown` / `MP42AudioConversionSettings`, `MP42Languages`.
|
||||
|
||||
The app never parses MP4/atom data directly — codec, container, and subtitle-conversion work belongs in the submodule, not in `Classes/`. `Classes/MP42FileAdditions.swift` extends framework types with app-level conveniences.
|
||||
|
||||
PGS `.sup` subtitle import: `MP42VobSubImporter` claims both `idx` and `sup`. A `.sup` is converted up-front to a private temp `.idx/.sub` pair via `MP42SupConverter` (the `@objc` façade over the sup2vob Swift sources vendored in `MP42/Sup2Vob/` from https://git.technomancer.com/Scott-Files/sup2vob — upstream logic is kept identical so upstream fixes re-merge cleanly; upstream's CLI-only globals and `main.swift` are the framework's only adaptations), then the existing VobSub machinery handles everything: the track comes out as `kMP42SubtitleCodecType_VobSub` (muxable straight into MP4 as `subp` via `MP4AddSubpicTrack`, or tx3g-convertible via `MP42BitmapSubConverter`), the frame size rides the idx `size:` line into `track.width/height`, language comes from the source filename (`getFilenameLanguage`, since PGS carries none — the generated idx `id:` is just "en"), and `track.URL` stays the user's `.sup`. The façade always runs upstream's `--full` mode (`fullFramePassthrough = true`, set in the adaptation layer `MP42SupConverter.swift`): frames keep the geometry the PGS itself defines — the idx size line is the **PCS canvas** (e.g. 1920x1080) and nothing is downscaled to the 720x480/576 DVD frame, which now only survives as fallback for a stream with no usable canvas (the framework's output is byte-identical to `sup2vob --full`). The temp pair is deleted in the importer's `dealloc` — safe because tracks hold the importer strongly through export. The ObjC→Swift hop uses the existing `MP42-Shared-Swift.h` shim (generated header), new Swift files must join both targets' Sources phases like `SampleDescription.swift`. The **same vendored sources** also build the CLI: `MP42Foundation/sup2vob/` holds only upstream's `main.swift` (adapted once: the two CLI globals `debugFrames`/`fullFramePassthrough` belong to the vendored `Convert.swift`, so main.swift drops its re-declaration) plus a `Makefile` compiling against `../MP42/Sup2Vob/` — one upstream merge updates app and CLI together, nothing can drift, and the CLI's `--full` output doubles as the byte-identical oracle for the framework converter. The Subler app build **invokes this same Makefile** (the "Build sup2vob CLI" run-script phase, `make -C MP42Foundation/sup2vob` — incremental, a no-op when unchanged) and installs the product into `Subler.app/Contents/MacOS/sup2vob`, so building Subler refreshes the CLI; a terminal `sup2vob` can just be a symlink to that bundle binary. The phase is why the Subler target sets `ENABLE_USER_SCRIPT_SANDBOXING = NO` (build-script file access within the source tree only — unrelated to the app's runtime security); the CLI itself also stays buildable standalone (`make && sudo make install`).
|
||||
|
||||
PGS-from-MKV → VobSub: a PGS track inside an MKV imports as a **real subp track**, not just OCR'd tx3g text. `FileImportController`'s subtitle action sheet gains a `VobSub` entry (tag 2, default follows `Prefs.subtitleConvertBitmap` like VobSub sources) for PGS-format tracks; selecting it sets `MP42ConversionSettings.subtitlesVobSubConversion`, and the muxer's bitmap-converter branch recognizes PGS-source + VobSub-target and uses `MP42PgsToVobSubConverter` instead of `MP42BitmapSubConverter`. That converter runs the whole sup2vob conversion synchronously in `initWithTrack:error:` (sup2vob derives one global palette/geometry for the track — the PGS canvas size — and the muxer needs `magicCookie` + `frameWidth/Height` before creating the subpic track); the live muxing stream is discarded and `copyEncodedSample` replays prepass-collected samples, ending on exactly one EOF-flagged buffer. **Matroska traps found empirically here:** mkvmerge stores each PGS segment with its 13-byte "PG" envelope removed (blocks are `type` + 2-byte-be `len` + payload repeated, blank frames are real blank presentations, everything zlib-compressed) — a plain concatenation of demuxed blocks is NOT a `.sup`; phase 1 must walk each block's stripped segments and rebuild `PG + pts:4(90kHz from the block's ns timestamp ×9/100000) + 4 zero bytes + type + len` (mkvextract reconstructs exactly this — the rebuilt stream is byte-identical to it; blocks that already carry envelopes pass through verbatim for other muxers). The rebuilt temp `.sup` is fed to a second `MP42VobSubImporter` (the same machinery as `.sup` drag-import) whose demux supplies the subpic samples/palette. The converter header isn't exported (matches `MP42BitmapSubConverter`'s non-Public Headers-phase convention), and it can't be exercised from outside the framework via `copyNextSample`/`MP42FileImporter+Private` — those are `objc_direct`/internal, so harnesses must stay in public API (see the `@selector`-on-direct-method constraint noted in the converter source).
|
||||
|
||||
Matroska tagging in the submodule: `MP42Ebml` provides EBML vint/ID primitives and a Segment top-level scanner (element extents + Void slack); `MP42MatroskaTagMapping` holds the read/write tag maps shared with `MP42MkvImporter` (reader and writer can't drift — a metadata key with no SimpleTag name in the map is **silently dropped** on save, so any new editable metadata key needs a map entry); `MP42MkvTagWriter.writeMetadata:tracks:` rewrites the `Tags` element, cover-art `AttachedFile`, and per-track `TrackEntry` fields (name/language/enabled/forced) in place (mkvpropedit-style: reuse the old extent + Void padding when the payload fits, otherwise rebuild the file tail with recomputed SeekHead/Cues positions through a temp file + atomic replace; size+mtime staleness guard refuses writes on files changed since open; foreign tag groups, unknown TrackEntry children, and non-cover attachments are preserved verbatim; each TrackEntry is diffed against the model's **effective** values so an untouched save is byte-for-byte a no-op). `MP42MkvTagWriter+Internal.h` (framework-internal, not in the umbrella) shares its kid/file model types and payload builders with `MP42MkvRemuxer`, the stream-copy track-removal/subtitle-addition engine: it rebuilds the whole file, copying every block verbatim except blocks whose unmarked-vint track number (`MP42Ebml.blockTrackNumberAt:`, ≤255) belongs to a removed track — kept tracks keep their original TrackNumbers, so **gaps after a removal are intentional** and no block header is ever rewritten; clusters are scanned header-only (BlockGroup track decided from a ≤64KB peek at its `Block` child), emptied clusters skipped, the trailing unknown-size cluster materialized; SeekHead is written with 8-wide placeholder positions pwrite-patched at the end, and Cues are regenerated at EOF (per-track `CueTrackPositions` incl. `CueRelativePosition`) only when the source had them; `Info` copies verbatim except that an existing `Duration` is recomputed: the pass tracks the greatest written block start+1ms (`_writtenMaxBlockEnd`) and pwrite-patches an 8-byte double slot at the Info write site (never +BlockDuration — added blocks must measure exactly like source blocks or remux idempotence breaks); files without a source Duration keep having none; values are TimecodeScale units. Dangling `DefaultTrackUID`/`ChapterTrackUID` refs are preserved. Chapters: the source `Chapters` element copies verbatim unless `replacementChapters` is set — non-nil rebuilds `EditionEntry{ChapterAtom{...}}` from the model track (sorted ascending, ties clamped to previous+1ms, "Chapter N" fallback titles), and a track with `chapterCount == 0` removes the element and its SeekHead entry. Chapter writing lives in the remuxer only because `Chapters` sits before the Clusters — any size change shifts every following byte, which the tag writer's tail-only in-place machinery can't absorb. It refuses multiple Segments, stray unknown-size elements, count mismatches between TrackEntry and the passed-in `sourceTracks`, and zero-remaining-track remuxes (the drop-all guard fires before additions, so drop-all-plus-add stays refused). Added tracks = `currentTracks` members absent from `sourceTracks` (identity); each must be an `MP42SubtitleTrack` whose `URL.pathExtension` is srt/ssa/ass (kept in sync with `DocumentWindowController.matroskaSubtitleExtensions`) — the model never holds subtitle text, so lines are **re-parsed from `track.URL` at save time** (SRT via `LoadSRTFromURL` + serializer drain; SSA/ASS via `MP42SSAParser`, styling stripped) and written as `S_TEXT/UTF8`. Each added track gets an appended `TrackEntry` (TrackNumber = max of all entries + 1 ≤ 0x3FFF, CodecID `S_TEXT/UTF8`, ISO `0x22B59C` + IETF `0x22B59D` language). Blocks are `BlockGroup{Block(unmarked-vint TrackNumber + int16 BE relative TC + UTF-8), BlockDuration}` — the `BlockGroup` wrapper is **mandatory**: a bare `Block` as a direct Cluster child is silently ignored by libebml readers even though ffmpeg tolerates it. Each line rides in the last existing Cluster whose Timecode ≤ its start time (negative relTCs are legal); lines whose relTC would exceed ±32767 go into **synthesized Clusters** emitted right after that cluster, original clusters are never rewritten or split.
|
||||
|
||||
Movie-tab fields that have no Matroska-spec tag (Rating, ContentRating, MediaKind, HDVideo, Cast, TVNetwork, TVEpisodeID) round-trip through community-style SimpleTag names `RATING`/`CONTENTRATING`/`MEDIAKIND`/`HD`/`CAST`/`NETWORK`/`EPISODEID`. Array-typed model values (Cast, Director, Producer, Screenwriters) are written joined with `", "` and re-split by the importer. The importer only synthesizes a TVEpisodeID from season/episode on the **conversion** path — in tagsOnly mode a synthesized value would leak into the file as a tag the user never set.
|
||||
|
||||
The Matroska track-field element ids are a trap: the ids that actually work in the wild (libebml/mkvtoolnix/ffmpeg and every reader) are `0x22B59C` = ISO-639-2/B `Language`, `0x22B59D` = BCP-47 `LanguageIETF`, `0xB9` = `TrackFlagEnabled`. The EBML spec's later `0x447A` carries the same ISO value but mkvtoolnix never writes it — `MatroskaParser.c` reads it defensively, the writer normalizes it to `0x22B59C`. Modern mkvtoolnix files may carry **only** `0x22B59D` (mkvmerge derives the ISO code from the IETF tag), so `Language` can be absent; the importer/writer prefer `LanguageIETF` when present and fall back to the ISO element. Match TrackEntry↔model by file order (chapter pseudo-track filtered); a count mismatch refuses the write.
|
||||
|
||||
Chapter elements are their own trap set (all verified empirically against mkvmerge-written files): `ChapterAtom` is `0xB6` — **not** `0xB0`, which is PixelWidth in TrackEntry scope (`MatroskaParser.c` has always parsed 0xB6 correctly; don't "fix" it). Chapter timecodes are absolute **nanoseconds**, not TimecodeScale units like nearly every other Matroska time — libmatroska writes and mkvtoolnix/ffmpeg both read them as ns regardless of segment scale, so the importer's plain `/1e6` to ms and the remuxer's plain `×1e6` back are right. `ChapterUID` (`0x73C4`) is mandatory in practice: ffmpeg **silently skips** atoms without it (mkvtoolnix still lists them, which makes the loss easy to miss); `EditionUID` likewise. The writer derives both deterministically from the chapter content so re-saving unchanged input reproduces the file. The importer's chapter normalization (force first start to 0, drop non-first zero-start atoms) is an **MP4 conversion-path** quirk only — **tagsOnly mode mirrors the file's atoms verbatim**, offset first starts and duplicate zero starts included (mkvmerge writes both shapes). That asymmetry matters because the tagsOnly model is the baseline a Chapters rewrite rebuilds from: dropping or shifting atoms at read time would silently corrupt them on the first edit, so instead the remuxer's strictly-ascending clamp shifts tied starts by +1 ms at write time and nothing is lost. Chapter language round-trips at **track level**: the importer adopts the first `ChapterDisplay/ChapterLanguage` (0x437C) it finds as the model track's `language`, and the remuxer stamps that track language into every atom — omitted when nil/absent or when it maps to ISO `eng` (the spec default; keeps rewrites byte-identical to language-less files). `MP42Languages ISO_639_2CodeForExtendedTag:` answers unknown tags with `"und"`, so a garbage language explicitly writes `und` rather than silently defaulting — extended tags are locale-identifier style (`"en"`, `"it"`), not English names. The chapter-row language popup stays enabled on MKV (`TracksViewController.isLanguageEditable`) because the value rides the remuxer's chapter rebuild, not the tag writer (no TrackEntry), and the saver's chapter-snapshot rows carry the language so a language-only edit flips `chaptersChanged`. Note: `ffprobe -show_chapters` does NOT surface ChapterLanguage in its chapter tags — assert it with `mkvinfo` ("Chapter language: …").
|
||||
|
||||
## Cross-cutting concerns
|
||||
|
||||
- **Sandbox vs non-sandbox builds**: `#if SB_SANDBOX` guards App Store code paths (security-scoped bookmarks via `MP42SecurityAccessToken`); the default build is the non-sandboxed variant (`Subler.entitlements` exist for the sandboxed config).
|
||||
- **Localization**: 183 `.strings` files live in per-locale `.lproj` directories scattered next to the code/XIBs they localize (repo root, `Classes/`, `Classes/PropertyView/`), not one central file. Locales: Base (English), it, fr, es-419, pt-BR, zh-CN, zh-Hans. When adding a UI string, find the sibling `.strings` used by that XIB/view.
|
||||
- **Static data**: `Resources/*.json` — `Alpha2.json` (ISO language codes, used by `LanguageTransformer`), `iTunesStores.json`, `Storefronts.json`, `Ratings.json`.
|
||||
@@ -40,7 +40,10 @@ final class DocumentController : NSDocumentController {
|
||||
override func openDocument(withContentsOf url: URL, display displayDocument: Bool, completionHandler: @escaping (NSDocument?, Bool, Error?) -> Void) {
|
||||
let ext = url.pathExtension.lowercased()
|
||||
|
||||
if ["mkv", "mka", "mks", "mov", "264", "h264"].contains(ext) {
|
||||
// Matroska files open directly as tags-only documents (see
|
||||
// Document.read); the remaining formats below can only be converted
|
||||
// to MP4, so offer the import sheet on a fresh untitled document.
|
||||
if ["mov", "264", "h264"].contains(ext) {
|
||||
do {
|
||||
let doc = try self.openUntitledDocumentAndDisplay(displayDocument)
|
||||
completionHandler(doc, false, nil)
|
||||
|
||||
@@ -41,7 +41,7 @@ final class ChapterSearchController: ViewController, NSTableViewDataSource, NSTa
|
||||
|
||||
switch info {
|
||||
|
||||
case .movie(let title):
|
||||
case .movie(let title, _):
|
||||
searchTerm = title
|
||||
case .tvShow, .none:
|
||||
searchTerm = title
|
||||
|
||||
+100
-12
@@ -15,6 +15,17 @@ final class Document: NSDocument {
|
||||
private(set) var mp4: MP42File
|
||||
private var unsupportedMp4Brand: Bool
|
||||
|
||||
// Matroska documents open in tags-only mode: the model is an in-memory
|
||||
// MP42File whose tracks are demuxed for display and whose metadata is
|
||||
// written back into the original file (Tags + cover attachment) by
|
||||
// MP42MkvTagWriter on save.
|
||||
private(set) var isMatroska = false
|
||||
// The pairing/staleness baseline (importer track snapshot, chapter rows,
|
||||
// file size/mtime) and the branching write-back (in-place tag writer vs
|
||||
// stream-copy remuxer) live in MatroskaSaver — shared with QueueItem so a
|
||||
// queued Matroska file saves exactly like the window does.
|
||||
private(set) var mkvSaver: MatroskaSaver?
|
||||
|
||||
override init() {
|
||||
self.cancelled = false
|
||||
self.options = [:]
|
||||
@@ -60,6 +71,11 @@ final class Document: NSDocument {
|
||||
override public var isEntireFileLoaded: Bool { get { return false } }
|
||||
|
||||
override func read(from url: URL, ofType typeName: String) throws {
|
||||
if MP42FileImporter.isMatroskaFileType(url.pathExtension) {
|
||||
try readMatroska(from: url)
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
mp4 = try MP42File(url: url)
|
||||
mp4.undo = undoManager
|
||||
@@ -69,8 +85,12 @@ final class Document: NSDocument {
|
||||
}
|
||||
|
||||
override func revert(toContentsOf url: URL, ofType typeName: String) throws {
|
||||
mp4 = try MP42File(url: url)
|
||||
mp4.undo = undoManager
|
||||
if isMatroska || MP42FileImporter.isMatroskaFileType(url.pathExtension) {
|
||||
try readMatroska(from: url)
|
||||
} else {
|
||||
mp4 = try MP42File(url: url)
|
||||
mp4.undo = undoManager
|
||||
}
|
||||
|
||||
if let docController = windowControllers.first as? DocumentWindowController {
|
||||
docController.reloadData()
|
||||
@@ -80,6 +100,26 @@ final class Document: NSDocument {
|
||||
updateChangeCount(.changeCleared)
|
||||
}
|
||||
|
||||
private func readMatroska(from url: URL) throws {
|
||||
// tagsOnly: the importer mirrors the file's own track flags instead of
|
||||
// applying the MP4 conversion heuristic, so the model matches the file
|
||||
// (MP42MkvTagWriter diffs track fields against it on save).
|
||||
let importer = try MP42FileImporter(url: url, tagsOnly: true)
|
||||
let file = MatroskaSaver.buildModel(from: importer)
|
||||
mp4 = file
|
||||
// (file.undo was not wired during buildModel's addTrack calls, so
|
||||
// those did not open undo groups.)
|
||||
mp4.undo = undoManager
|
||||
isMatroska = true
|
||||
let saver = MatroskaSaver(sourceURL: url, importer: importer, model: file)
|
||||
// The save sheet listens on the model's progress handler (see
|
||||
// DocumentWindowController.startProgressReporting); forward through it.
|
||||
saver.progressHandler = { [weak self] progress in
|
||||
self?.mp4.progressHandler?(progress)
|
||||
}
|
||||
mkvSaver = saver
|
||||
}
|
||||
|
||||
// MARK: Save
|
||||
|
||||
override nonisolated class var autosavesInPlace: Bool { return false }
|
||||
@@ -125,6 +165,12 @@ final class Document: NSDocument {
|
||||
|
||||
if let error = error {
|
||||
completionHandler(error);
|
||||
} else if self.isMatroska {
|
||||
// The file was retagged in place; the tracks in the model are
|
||||
// still the ones on disk, so only the undo stack needs reset.
|
||||
self.undoManager?.removeAllActions()
|
||||
docController?.reloadData()
|
||||
completionHandler(error)
|
||||
} else {
|
||||
do {
|
||||
let reloadedFile = try MP42File(url: url)
|
||||
@@ -148,6 +194,7 @@ final class Document: NSDocument {
|
||||
|
||||
func cancelSave() {
|
||||
cancelled = true
|
||||
mkvSaver?.cancel()
|
||||
mp4.cancel()
|
||||
}
|
||||
|
||||
@@ -173,6 +220,18 @@ final class Document: NSDocument {
|
||||
unblockUserInteraction()
|
||||
preventSleep()
|
||||
|
||||
defer {
|
||||
allowSleep()
|
||||
optimize = false
|
||||
options = [:]
|
||||
}
|
||||
|
||||
if isMatroska {
|
||||
try writeMatroska(to: url, for: saveOperation)
|
||||
cancelled = false
|
||||
return
|
||||
}
|
||||
|
||||
if Prefs.organizeAlternateGroups {
|
||||
mp4.organizeAlternateGroups()
|
||||
if Prefs.inferMediaCharacteristics {
|
||||
@@ -181,19 +240,14 @@ final class Document: NSDocument {
|
||||
}
|
||||
}
|
||||
|
||||
defer {
|
||||
allowSleep()
|
||||
optimize = false
|
||||
options = [:]
|
||||
}
|
||||
|
||||
switch saveOperation {
|
||||
case .saveOperation:
|
||||
try mp4.update(options: options)
|
||||
case .saveAsOperation:
|
||||
try mp4.write(to: url, options: options)
|
||||
default:
|
||||
fatalError("Unsupported save operation")
|
||||
throw NSError(domain: NSCocoaErrorDomain, code: NSFileWriteUnknownError,
|
||||
userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("The save operation is not supported.", comment: "Document unsupported save operation error.")])
|
||||
}
|
||||
|
||||
if optimize && cancelled == false {
|
||||
@@ -207,6 +261,17 @@ final class Document: NSDocument {
|
||||
cancelled = false
|
||||
}
|
||||
|
||||
private func writeMatroska(to url: URL, for saveOperation: NSDocument.SaveOperationType) throws {
|
||||
guard let saver = mkvSaver else {
|
||||
throw NSError(domain: NSCocoaErrorDomain, code: NSFileWriteUnknownError,
|
||||
userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("The Matroska source file is unknown.", comment: "Document MKV remux missing source error.")])
|
||||
}
|
||||
// `optimize` (Save and Optimize) forces the structural rebuild, as
|
||||
// does Save-As; the saver branches in-place tag writer vs stream-copy
|
||||
// remuxer (see MatroskaSaver.save).
|
||||
try saver.save(model: mp4, to: url, forceStructural: optimize || saveOperation != .saveOperation)
|
||||
}
|
||||
|
||||
// MARK: Save panel
|
||||
|
||||
private var accessoryViewController: SaveOptions?
|
||||
@@ -234,6 +299,19 @@ final class Document: NSDocument {
|
||||
guard let windowForSheet = windowForSheet else { return }
|
||||
|
||||
let queue = QueueController.shared
|
||||
// Matroska document: match the window's save semantics — the queue
|
||||
// item writes metadata back into the original file instead of muxing
|
||||
// a converted copy, so the destination is the file itself (no save
|
||||
// panel) and the item inherits the document's Matroska baseline: the
|
||||
// TrackEntry↔track pairing is by object identity and cannot be
|
||||
// rebuilt from the model.
|
||||
if isMatroska, let fileURL = fileURL, let saver = mkvSaver {
|
||||
let item = QueueItem(mp4: mp4, fileURL: fileURL, destURL: fileURL)
|
||||
item.attachMatroskaSaver(saver)
|
||||
queue.add(item)
|
||||
close()
|
||||
return
|
||||
}
|
||||
if mp4.hasFileRepresentation {
|
||||
let item = QueueItem(mp4: mp4)
|
||||
queue.add(item, applyPreset: true)
|
||||
@@ -267,10 +345,20 @@ final class Document: NSDocument {
|
||||
return true
|
||||
case #selector(save(_:)) where isDocumentEdited == true:
|
||||
return true
|
||||
case #selector(saveAs(_:)),
|
||||
#selector(sendToQueue(_:)):
|
||||
case #selector(saveAs(_:)):
|
||||
// MKV Save-As runs through MP42MkvRemuxer (stream copy, same
|
||||
// container — the destination must stay .mkv/.mka/.mks, checked
|
||||
// in writeMatroska).
|
||||
return true
|
||||
case #selector(saveAndOptimize(_:)) where isDocumentEdited == false && mp4.hasFileRepresentation == true:
|
||||
case #selector(sendToQueue(_:)):
|
||||
return true
|
||||
// On a Matroska document optimize = full remuxer rebuild (see
|
||||
// writeMatroska), the container-equivalent of the atom-order optimize.
|
||||
// Tags-only models report hasFileRepresentation == false (their tracks
|
||||
// are never muxed), so the on-disk precondition there is just the
|
||||
// remux source: fileURL.
|
||||
case #selector(saveAndOptimize(_:)) where isDocumentEdited == false
|
||||
&& (isMatroska ? fileURL != nil : mp4.hasFileRepresentation == true):
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
|
||||
@@ -58,11 +58,16 @@ class DocumentToolbarDelegate: NSObject, NSToolbarDelegate {
|
||||
submenu.addItem(menuItem)
|
||||
}
|
||||
|
||||
let insertChapter = NSMenuItem()
|
||||
insertChapter.title = NSLocalizedString("Insert a chapter", comment: "Toolbar")
|
||||
insertChapter.action = #selector(DocumentWindowController.insertChapter(_:))
|
||||
|
||||
let chapters = NSMenuItem()
|
||||
chapters.title = NSLocalizedString("Insert a chapter every", comment: "Toolbar")
|
||||
chapters.submenu = submenu
|
||||
|
||||
let menu = NSMenu()
|
||||
menu.addItem(insertChapter)
|
||||
menu.addItem(chapters)
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(withTitle: NSLocalizedString("Organize alternate groups", comment: "Toolbar"),
|
||||
|
||||
@@ -235,15 +235,37 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
|
||||
trackViewController.view.autoresizingMask = [NSView.AutoresizingMask.width, NSView.AutoresizingMask.height]
|
||||
detailsItem.viewController.view.addSubview(trackViewController.view)
|
||||
|
||||
// Tags-only mode: tracks are displayed but cannot be modified, except
|
||||
// for the fields MP42MkvTagWriter writes back (see allowsTrackEditing)
|
||||
// and the chapters tab (ChapterViewController edits ride the remuxer's
|
||||
// replacementChapters). Set after the view is loaded so it wins over
|
||||
// controls that the view controllers enable during their own updates.
|
||||
trackViewController.isMatroskaDocument = doc.isMatroska
|
||||
if doc.isMatroska, !(trackViewController is MovieViewController),
|
||||
!(trackViewController is ChapterViewController) {
|
||||
trackViewController.allowsTrackEditing = true
|
||||
trackViewController.isReadOnly = true
|
||||
} else {
|
||||
trackViewController.allowsTrackEditing = false
|
||||
trackViewController.isReadOnly = false
|
||||
}
|
||||
|
||||
selectTabViewItem(for: trackViewController)
|
||||
}
|
||||
|
||||
func delete(tracks: [MP42Track]) {
|
||||
// On MKV docs the save path stream-copy-remuxes removed real tracks'
|
||||
// blocks away (MP42MkvRemuxer); a removed chapter pseudo-track makes
|
||||
// the model report "no chapters", which deletes the Chapters element.
|
||||
if tracks.isEmpty == false {
|
||||
mp4.removeTracks(tracks)
|
||||
|
||||
if Prefs.organizeAlternateGroups { mp4.organizeAlternateGroups() }
|
||||
if Prefs.inferMediaCharacteristics { mp4.inferMediaCharacteristics() }
|
||||
if doc.isMatroska == false {
|
||||
// Both heuristics reorder the track model, which would break
|
||||
// the TrackEntry/order pairing the MKV writers depend on.
|
||||
if Prefs.organizeAlternateGroups { mp4.organizeAlternateGroups() }
|
||||
if Prefs.inferMediaCharacteristics { mp4.inferMediaCharacteristics() }
|
||||
}
|
||||
|
||||
tracksViewController.reloadData()
|
||||
}
|
||||
@@ -254,22 +276,33 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
|
||||
func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool {
|
||||
switch item.action {
|
||||
|
||||
case #selector(selectFile(_:)),
|
||||
#selector(selectMetadataFile(_:)),
|
||||
case #selector(selectMetadataFile(_:)),
|
||||
#selector(searchMetadata(_:)),
|
||||
#selector(searchChapters(_:)),
|
||||
#selector(sendToQueue(_:)),
|
||||
#selector(insertChapter(_:)),
|
||||
#selector(addChaptersEvery(_:)),
|
||||
#selector(iTunesFriendlyTrackGroups(_:)),
|
||||
#selector(searchChapters(_:)):
|
||||
return true
|
||||
|
||||
// Matroska documents may import subtitle text files (written as
|
||||
// S_TEXT/UTF8 by the stream-copy remuxer on save).
|
||||
case #selector(selectFile(_:)):
|
||||
return true
|
||||
|
||||
// Track bulk modifications: unavailable in Matroska tags-only mode.
|
||||
// Chapter actions (searchChapters, the Insert-a-chapter commands) are
|
||||
// NOT on this list — chapter changes ride the stream-copy remuxer,
|
||||
// so they work on MKV too.
|
||||
case #selector(iTunesFriendlyTrackGroups(_:)),
|
||||
#selector(clearTrackNames(_:)),
|
||||
#selector(prettifyAudioTrackNames(_:)),
|
||||
#selector(fixAudioFallbacks(_:)),
|
||||
#selector(sendToQueue(_:)):
|
||||
return true
|
||||
#selector(fixAudioFallbacks(_:)):
|
||||
return !doc.isMatroska
|
||||
|
||||
case #selector(sendToExternalApp(_:)) where mp4.hasFileRepresentation && doc.isDocumentEdited == false:
|
||||
return true
|
||||
|
||||
case #selector(showTrackOffsetSheet(_:)) where tracksViewController.selectedTracks.isEmpty == false:
|
||||
case #selector(showTrackOffsetSheet(_:)) where doc.isMatroska == false && tracksViewController.selectedTracks.isEmpty == false:
|
||||
return true
|
||||
|
||||
case #selector(export(_:)) where tracksViewController.selectedTracks.isEmpty == false:
|
||||
@@ -280,6 +313,9 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
|
||||
}
|
||||
|
||||
case #selector(DocumentWindowController.deleteTrack(_:)):
|
||||
// MKV documents allow deleting real tracks (stream-copy remux on
|
||||
// save) and the chapter pseudo-track (the Chapters element is
|
||||
// removed on save), so any non-empty selection is deletable.
|
||||
return tracksViewController.selectedTracks.isEmpty == false && NSApp.isActive
|
||||
|
||||
default:
|
||||
@@ -338,8 +374,58 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
|
||||
delete(tracks: tracksViewController.selectedTracks)
|
||||
}
|
||||
|
||||
// Single-chapter insert that also bootstraps the chapter track, so it
|
||||
// works on documents without any chapters yet (both containers: on MKV
|
||||
// the new rows ride the remuxer on save, like the Chapters tab's edits).
|
||||
@IBAction func insertChapter(_ sender: Any) {
|
||||
let track: MP42ChapterTrack
|
||||
if let existing = mp4.chapters {
|
||||
track = existing
|
||||
} else {
|
||||
track = MP42ChapterTrack()
|
||||
mp4.addTrack(track) // addTrack: replaces any previous chapter track
|
||||
if doc.isMatroska {
|
||||
// addTrack: zeroes trackId; keep the table numbering dense.
|
||||
track.trackId = (mp4.tracks.map { $0.trackId }.max() ?? 0) + 1
|
||||
}
|
||||
}
|
||||
|
||||
// A brand-new track gets its first chapter at 0; inserting into an
|
||||
// existing track places the chapter 1s after the latest start, so it
|
||||
// never ties with a stored chapter (ties get clamped +1ms on write,
|
||||
// which would silently shift the user's own chapter times). The user
|
||||
// retimes/renames the row either way.
|
||||
var newTimestamp: UInt64 = 0
|
||||
if let last = track.chapters.max(by: { $0.timestamp < $1.timestamp }) {
|
||||
newTimestamp = last.timestamp + 1000
|
||||
if track.duration > last.timestamp + 1, newTimestamp >= track.duration {
|
||||
newTimestamp = track.duration - 1
|
||||
}
|
||||
}
|
||||
let index = track.addChapter("Chapter", timestamp: newTimestamp)
|
||||
|
||||
if doc.isMatroska {
|
||||
// The tags-only model has no muxing step to mark the document.
|
||||
doc.updateChangeCount(.changeDone)
|
||||
}
|
||||
|
||||
tracksViewController.reloadData()
|
||||
tracksViewController.selectTracks([track])
|
||||
chapterViewController?.selectChapter(at: Int(index))
|
||||
}
|
||||
|
||||
@IBAction func addChaptersEvery(_ sender: NSMenuItem) {
|
||||
let track: MP42ChapterTrack = mp4.chapters ?? { let track = MP42ChapterTrack(); self.mp4.addTrack(track); return track }()
|
||||
// Creates the chapter track when the document has none (same
|
||||
// bookkeeping as insertChapter: addTrack: zeroes trackId and the
|
||||
// tags-only model has no muxing step to mark the document dirty).
|
||||
let existing = mp4.chapters
|
||||
let track: MP42ChapterTrack = existing ?? MP42ChapterTrack()
|
||||
if existing == nil {
|
||||
mp4.addTrack(track) // addTrack: replaces any previous chapter track
|
||||
if doc.isMatroska {
|
||||
track.trackId = (mp4.tracks.map { $0.trackId }.max() ?? 0) + 1
|
||||
}
|
||||
}
|
||||
let minutes = sender.tag * 60 * 1000
|
||||
|
||||
if minutes > 0 {
|
||||
@@ -351,6 +437,10 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
|
||||
track.addChapter("Chapter 1", timestamp: 0)
|
||||
}
|
||||
|
||||
if doc.isMatroska {
|
||||
doc.updateChangeCount(.changeDone)
|
||||
}
|
||||
|
||||
tracksViewController.reloadData()
|
||||
tracksViewController.selectTracks([track])
|
||||
}
|
||||
@@ -462,7 +552,13 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
|
||||
chapterTrack.addChapter(chapter)
|
||||
}
|
||||
|
||||
mp4.addTrack(chapterTrack)
|
||||
mp4.addTrack(chapterTrack) // addTrack: replaces any previous chapter track
|
||||
if doc.isMatroska {
|
||||
// Tags-only bookkeeping, same as addChapters/insertChapter:
|
||||
// addTrack: zeroes trackId, and nothing else marks the document.
|
||||
chapterTrack.trackId = (mp4.tracks.map { $0.trackId }.max() ?? 0) + 1
|
||||
doc.updateChangeCount(.changeDone)
|
||||
}
|
||||
tracksViewController.reloadData()
|
||||
tracksViewController.selectTracks([chapterTrack])
|
||||
}
|
||||
@@ -471,7 +567,14 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
|
||||
|
||||
private func addChapters(fileURL: URL) {
|
||||
let track = MP42ChapterTrack(fromFile: fileURL)
|
||||
mp4.addTrack(track)
|
||||
mp4.addTrack(track) // replaces any previous chapter track
|
||||
if doc.isMatroska {
|
||||
// addTrack: zeroes trackId; keep the table numbering dense, and
|
||||
// flag the document dirty (the tags-only model has no muxing to
|
||||
// mark it, same as importSubtitleTracksForMatroska).
|
||||
track.trackId = (mp4.tracks.map { $0.trackId }.max() ?? 0) + 1
|
||||
doc.updateChangeCount(.changeDone)
|
||||
}
|
||||
tracksViewController.reloadData()
|
||||
tracksViewController.selectTracks([track])
|
||||
}
|
||||
@@ -482,6 +585,7 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
|
||||
if let track = mp4.chapters {
|
||||
chapterViewController?.track = track
|
||||
tracksViewController.selectTracks([track])
|
||||
if doc.isMatroska { doc.updateChangeCount(.changeDone) }
|
||||
}
|
||||
}
|
||||
catch {
|
||||
@@ -535,6 +639,36 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
|
||||
panel.canChooseFiles = true
|
||||
panel.canChooseDirectories = false
|
||||
|
||||
if doc.isMatroska {
|
||||
// A Matroska document can gain subtitle text tracks (the
|
||||
// stream-copy remuxer writes them as S_TEXT/UTF8) and chapters
|
||||
// (.txt creates/replaces the chapter track, .csv updates an
|
||||
// existing one — same dispatch the MP4 branch uses below).
|
||||
let chapterExtensions = ["txt", "csv"]
|
||||
if #available(macOS 11, *) {
|
||||
panel.allowedContentTypes = (DocumentWindowController.matroskaSubtitleExtensions + chapterExtensions).compactMap {
|
||||
UTType(filenameExtension: $0)
|
||||
}
|
||||
} else {
|
||||
panel.allowedFileTypes = DocumentWindowController.matroskaSubtitleExtensions + chapterExtensions
|
||||
}
|
||||
panel.beginSheetModal(for: windowForSheet) { (response) in
|
||||
guard response == NSApplication.ModalResponse.OK else { return }
|
||||
var subtitleURLs: [URL] = []
|
||||
for url in panel.urls {
|
||||
switch url.pathExtension.lowercased() {
|
||||
case "txt": self.addChapters(fileURL: url)
|
||||
case "csv": self.updateChapters(fileURL: url)
|
||||
default: subtitleURLs.append(url)
|
||||
}
|
||||
}
|
||||
if subtitleURLs.isEmpty == false {
|
||||
self.showImportSheet(fileURLs: subtitleURLs)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if #available(macOS 11, *) {
|
||||
panel.allowedContentTypes = MP42FileImporter.supportedContentTypes() + [.text, .commaSeparatedText]
|
||||
} else {
|
||||
@@ -557,7 +691,16 @@ 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]) {
|
||||
if doc.isMatroska {
|
||||
importSubtitleTracksForMatroska(fileURLs: fileURLs)
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
let controller = try FileImportController(fileURLs: fileURLs, delegate: self)
|
||||
|
||||
@@ -577,9 +720,69 @@ 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]) {
|
||||
// Mirror the open panel's extension routing (selectFile): chapter
|
||||
// text files go to the chapter commands — addChapters bootstraps the
|
||||
// chapter track on both containers — everything else to the regular
|
||||
// track importer.
|
||||
var mediaURLs: [URL] = []
|
||||
for url in fileURLs {
|
||||
switch url.pathExtension.lowercased() {
|
||||
case "txt": addChapters(fileURL: url)
|
||||
case "csv": updateChapters(fileURL: url)
|
||||
default: mediaURLs.append(url)
|
||||
}
|
||||
}
|
||||
guard mediaURLs.isEmpty == false else { return }
|
||||
|
||||
do {
|
||||
let controller = try FileImportController(fileURLs: fileURLs, delegate: self)
|
||||
let controller = try FileImportController(fileURLs: mediaURLs, delegate: self)
|
||||
|
||||
// Call addTracks directly - the Settings initialization logic runs when the controller is created
|
||||
controller.addTracks(self)
|
||||
@@ -598,7 +801,11 @@ 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 the saver's importer-order snapshot 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 {
|
||||
@@ -639,8 +846,18 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac
|
||||
let items = pasteboard.readObjects(forClasses: [NSURL.classForCoder()], options: [:]) as? [URL]
|
||||
else { return false }
|
||||
|
||||
let chapters = items.filter { $0.pathExtension.lowercased() == "txt" }
|
||||
if let url = chapters.first {
|
||||
// Metadata drops are fine in tags-only mode. Chapters ride the
|
||||
// remuxer on Matroska documents, so txt/csv drops route there too;
|
||||
// everything else that would add a track goes through the import
|
||||
// panel (which routes Matroska docs to the subtitle-only path).
|
||||
if doc.isMatroska {
|
||||
if let url = items.first(where: { $0.pathExtension.lowercased() == "txt" }) {
|
||||
addChapters(fileURL: url)
|
||||
}
|
||||
if let url = items.first(where: { $0.pathExtension.lowercased() == "csv" }) {
|
||||
updateChapters(fileURL: url)
|
||||
}
|
||||
} else if let url = items.first(where: { $0.pathExtension.lowercased() == "txt" }) {
|
||||
addChapters(fileURL: url)
|
||||
}
|
||||
|
||||
|
||||
@@ -55,7 +55,16 @@ final class FileImportController: ViewController, NSTableViewDataSource, NSTable
|
||||
tag: 0,
|
||||
enabled: needsConversion == false)
|
||||
actions.append(action)
|
||||
|
||||
|
||||
// PGS can be kept as bitmap subtitles: the muxer converts the
|
||||
// stream to VobSub (sup2vob) and writes a real MP4 subp track.
|
||||
if track.format == kMP42SubtitleCodecType_PGS {
|
||||
let bitmapAction = Action(title: NSLocalizedString("VobSub", comment: "File Import action menu item."),
|
||||
tag: 2,
|
||||
enabled: true)
|
||||
actions.append(bitmapAction)
|
||||
}
|
||||
|
||||
if (needsConversion || track.format == kMP42SubtitleCodecType_VobSub) {
|
||||
let conversionAction = Action(title: NSLocalizedString("Tx3g", comment: "File Import action menu item."),
|
||||
tag: 1,
|
||||
@@ -157,6 +166,11 @@ final class FileImportController: ViewController, NSTableViewDataSource, NSTable
|
||||
}
|
||||
}
|
||||
}
|
||||
// PGS: keep it bitmap — VobSub by default, tx3g only if the
|
||||
// user's bitmap-subtitles-to-tx3g preference says so
|
||||
else if track.format == kMP42SubtitleCodecType_PGS {
|
||||
self.selectedActionTag = Prefs.subtitleConvertBitmap ? 1 : 2
|
||||
}
|
||||
// Vobsub
|
||||
else if track.format == kMP42SubtitleCodecType_VobSub && Prefs.subtitleConvertBitmap {
|
||||
self.selectedActionTag = 1
|
||||
@@ -371,7 +385,10 @@ final class FileImportController: ViewController, NSTableViewDataSource, NSTable
|
||||
|
||||
case let track as MP42SubtitleTrack:
|
||||
|
||||
if trackSettings.selectedActionTag > 0 {
|
||||
if trackSettings.selectedActionTag == 2 {
|
||||
// PGS → VobSub: mux as a bitmap subp track (sup2vob)
|
||||
track.conversionSettings = MP42ConversionSettings.subtitlesVobSubConversion()
|
||||
} else if trackSettings.selectedActionTag > 0 {
|
||||
track.conversionSettings = MP42ConversionSettings.subtitlesConversion()
|
||||
}
|
||||
selectedTracks.append(trackSettings.track)
|
||||
|
||||
@@ -87,7 +87,7 @@ final class Logger : NSObject, MP42Logging {
|
||||
private static func appSupportURL() -> URL {
|
||||
let fileManager = FileManager.default
|
||||
if let url = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask)
|
||||
.first?.appendingPathComponent("Subler") {
|
||||
.first?.appendingPathComponent("SublerMKV") {
|
||||
|
||||
do {
|
||||
if fileManager.fileExists(atPath: url.path) == false {
|
||||
|
||||
@@ -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) }
|
||||
}
|
||||
}
|
||||
@@ -9,9 +9,18 @@ import Foundation
|
||||
|
||||
// MARK: - Filename
|
||||
|
||||
/// A metadata service ID embedded in the file name (e.g. `{tmdb-1015812}`).
|
||||
public enum MetadataFileID: Equatable {
|
||||
case tmdb(Int)
|
||||
case tvdb(Int)
|
||||
/// Normalized to the `tt…` form, leading zeros preserved.
|
||||
case imdb(String)
|
||||
}
|
||||
|
||||
public enum MetadataSearchTerms {
|
||||
case none
|
||||
case movie(title: String)
|
||||
/// `id` is a metadata service ID parsed from the file name, when present.
|
||||
case movie(title: String, id: MetadataFileID? = nil)
|
||||
case tvShow(seriesName: String, season: Int?, episode: Int?)
|
||||
|
||||
public var isMovie: Bool { get {
|
||||
@@ -54,6 +63,30 @@ private func parseAnimeFilename(_ filename: String) -> MetadataSearchTerms? {
|
||||
return result
|
||||
}
|
||||
|
||||
/// Parses the `id:<kind>:<value>` line emitted by ParseFilename.pl, when present.
|
||||
private func parseFileID(_ lines: [Substring]) -> MetadataFileID? {
|
||||
guard let idLine = lines.first(where: { $0.hasPrefix("id:") }) else { return nil }
|
||||
|
||||
let components = idLine.dropFirst(3).split(separator: ":", omittingEmptySubsequences: false)
|
||||
guard components.count == 2, components[1].isEmpty == false else { return nil }
|
||||
|
||||
let kind = components[0]
|
||||
let value = components[1]
|
||||
|
||||
switch kind {
|
||||
case "tmdb":
|
||||
return Int(value).map(MetadataFileID.tmdb)
|
||||
case "tvdb":
|
||||
return Int(value).map(MetadataFileID.tvdb)
|
||||
case "imdb", "tt":
|
||||
// The parser strips the `tt` prefix from IMDb IDs; the find API wants it back.
|
||||
return .imdb("tt" + value)
|
||||
default:
|
||||
// A bare number with no known prefix is too ambiguous for a direct lookup.
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
private func parseFilename(_ filename: String) -> MetadataSearchTerms? {
|
||||
guard let path = Bundle.main.path(forResource: "ParseFilename", ofType: "") else { return nil }
|
||||
|
||||
@@ -86,7 +119,7 @@ private func parseFilename(_ filename: String) -> MetadataSearchTerms? {
|
||||
.replacingOccurrences(of: "[", with: " ")
|
||||
.replacingOccurrences(of: "]", with: " ")
|
||||
.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
|
||||
return MetadataSearchTerms.movie(title: newTitle)
|
||||
return MetadataSearchTerms.movie(title: newTitle, id: parseFileID(lines))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -62,10 +62,22 @@ public protocol MetadataService {
|
||||
func loadTVMetadata(_ metadata: MetadataResult, language: String) -> MetadataResult
|
||||
|
||||
func search(movie: String, language: String) -> [MetadataResult]
|
||||
func search(movieID id: MetadataFileID, language: String) -> [MetadataResult]
|
||||
func loadMovieMetadata(_ metadata: MetadataResult, language: String) -> MetadataResult
|
||||
|
||||
}
|
||||
|
||||
public extension MetadataService {
|
||||
|
||||
/// Direct lookup of a movie by an ID embedded in the file name.
|
||||
/// The default implementation answers an empty result, which callers treat
|
||||
/// as "not supported/not found" and fall back to the title search.
|
||||
func search(movieID id: MetadataFileID, language: String) -> [MetadataResult] {
|
||||
return []
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public enum MetadataNameSearch {
|
||||
case tvNameSearch(service: MetadataService, tvShow: String, language: String)
|
||||
|
||||
@@ -95,6 +107,7 @@ public enum MetadataType : Int, CustomStringConvertible, Codable {
|
||||
|
||||
public enum MetadataSearch {
|
||||
case movieSeach(service: MetadataService, movie: String, language: String)
|
||||
case movieIDSearch(service: MetadataService, id: MetadataFileID, language: String)
|
||||
case tvSearch(service: MetadataService, tvShow: String, season: Int?, episode: Int?, language: String)
|
||||
|
||||
public func search(completionHandler: @escaping ([MetadataResult]) -> Void) -> Runnable {
|
||||
@@ -102,6 +115,9 @@ public enum MetadataSearch {
|
||||
case let .movieSeach(service, movie, language):
|
||||
return RunnableTask(search: service.search(movie: movie, language: language),
|
||||
completionHandler: completionHandler)
|
||||
case let .movieIDSearch(service, id, language):
|
||||
return RunnableTask(search: service.search(movieID: id, language: language),
|
||||
completionHandler: completionHandler)
|
||||
case let .tvSearch(service, tvShow, season, episode, language):
|
||||
return RunnableTask(search: service.search(tvShow: tvShow, language: language, season: season, episode: episode),
|
||||
completionHandler: completionHandler)
|
||||
@@ -113,6 +129,10 @@ public enum MetadataSearch {
|
||||
case let .movieSeach(service, _, language):
|
||||
return RunnableTask(search: service.loadMovieMetadata(metadata, language: language),
|
||||
completionHandler: completionHandler)
|
||||
case .movieIDSearch:
|
||||
// The ID lookup already returns the full movie details.
|
||||
return RunnableTask(search: metadata,
|
||||
completionHandler: completionHandler)
|
||||
case let .tvSearch(service, _, _, _, language):
|
||||
return RunnableTask(search: service.loadTVMetadata(metadata, language: language),
|
||||
completionHandler: completionHandler)
|
||||
@@ -121,7 +141,7 @@ public enum MetadataSearch {
|
||||
|
||||
public var type: MetadataType {
|
||||
switch self {
|
||||
case .movieSeach:
|
||||
case .movieSeach, .movieIDSearch:
|
||||
return .movie
|
||||
case .tvSearch:
|
||||
return .tvShow
|
||||
|
||||
@@ -52,6 +52,20 @@ public struct TheMovieDB: MetadataService {
|
||||
return results.map { metadata(forMoviePartialResult: $0, language: nil) }
|
||||
}
|
||||
|
||||
public func search(movieID id: MetadataFileID, language: String) -> [MetadataResult] {
|
||||
let result: TMDBMovie?
|
||||
switch id {
|
||||
case .tmdb(let movieID):
|
||||
result = session.fetch(movieID: movieID, language: language)
|
||||
case .imdb(let imdbID):
|
||||
result = session.findMovie(id: imdbID, externalSource: "imdb_id", language: language)
|
||||
case .tvdb:
|
||||
// A TVDB ID identifies a series: no direct movie to fetch, fall back to the title search.
|
||||
return []
|
||||
}
|
||||
return result.map { [metadata(forResult: $0, language: language)] } ?? []
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private func cleanList(items: [TMDBTuple]?) -> String? {
|
||||
|
||||
@@ -285,6 +285,21 @@ final public class TheMovieDBService {
|
||||
return result
|
||||
}
|
||||
|
||||
/// Resolves an external ID (e.g. an `tt…` IMDb ID with `external_source=imdb_id`)
|
||||
/// to a movie and fetches its full details.
|
||||
public func findMovie(id externalID: String, externalSource: String, language: String) -> TMDBMovie? {
|
||||
guard let url = URL(string: basePath + "find/" + externalID + "?api_key=" + key + "&external_source=" + externalSource),
|
||||
let result = sendJSONRequest(url: url, language: language, type: FindResults.self),
|
||||
let movieID = result.movie_results?.first?.id
|
||||
else { return nil }
|
||||
|
||||
return fetch(movieID: movieID, language: language)
|
||||
}
|
||||
|
||||
private struct FindResults : Codable {
|
||||
let movie_results: [TMDBMovieSearchResult]?
|
||||
}
|
||||
|
||||
public func search(series: String, language: String) -> [TMDBTVSearchResult] {
|
||||
let encodedName = series.urlEncoded()
|
||||
|
||||
|
||||
@@ -57,6 +57,9 @@ final class MetadataSearchController: NSViewController, NSTableViewDataSource, N
|
||||
|
||||
private var state: MetadataSearchState = .none
|
||||
|
||||
/// Service ID parsed from the file name: consumed by the first automatic movie search.
|
||||
private var pendingMovieID: MetadataFileID?
|
||||
|
||||
private var movieService: MetadataService = MetadataSearch.defaultMovieService
|
||||
private var tvShowService: MetadataService = MetadataSearch.defaultTVService
|
||||
|
||||
@@ -122,10 +125,11 @@ final class MetadataSearchController: NSViewController, NSTableViewDataSource, N
|
||||
case .none:
|
||||
updateUI()
|
||||
|
||||
case .movie(let title):
|
||||
case .movie(let title, let id):
|
||||
searchMode.selectTabViewItem(at: 0)
|
||||
movieName.stringValue = title
|
||||
tvSeriesName.stringValue = title
|
||||
pendingMovieID = id
|
||||
searchForResults(searchMovieButton)
|
||||
|
||||
case .tvShow(let tvShow, let season, let episode):
|
||||
@@ -242,8 +246,27 @@ final class MetadataSearchController: NSViewController, NSTableViewDataSource, N
|
||||
}
|
||||
|
||||
private func searchMovie() {
|
||||
let title = movieName.stringValue
|
||||
let language = movieService.languageType.tag(displayName: movieLanguage.titleOfSelectedItem ?? "en")
|
||||
|
||||
if let id = pendingMovieID {
|
||||
// The file name carried a service ID: try a direct lookup first and
|
||||
// consume it either way, so later searches follow the text field.
|
||||
pendingMovieID = nil
|
||||
let searcher = MetadataSearch.movieIDSearch(service: movieService, id: id, language: language)
|
||||
let task = searcher.search(completionHandler: { results in
|
||||
if results.isEmpty {
|
||||
// Not supported by this provider, or unknown ID: fall back to the title search.
|
||||
DispatchQueue.main.async { self.searchForResults(self.searchMovieButton) }
|
||||
}
|
||||
else {
|
||||
self.searchDone(search: searcher, results: results)
|
||||
}
|
||||
}).runAsync()
|
||||
state = .searching(search: searcher, task: task)
|
||||
return
|
||||
}
|
||||
|
||||
let title = movieName.stringValue
|
||||
let searcher = MetadataSearch.movieSeach(service: movieService, movie: title, language: language)
|
||||
let task = searcher.search(completionHandler: { self.searchDone(search: searcher, results: $0) }).runAsync()
|
||||
state = .searching(search: searcher, task: task)
|
||||
@@ -331,14 +354,14 @@ final class MetadataSearchController: NSViewController, NSTableViewDataSource, N
|
||||
switch state {
|
||||
case .searching(let search, _):
|
||||
switch search {
|
||||
case .movieSeach(let service, _, _):
|
||||
case .movieSeach(let service, _, _), .movieIDSearch(let service, _, _):
|
||||
progressText.stringValue = String.localizedStringWithFormat(NSLocalizedString("Searching %@ for movie information…", comment: ""), service.name)
|
||||
case .tvSearch(let service, _, _ , _, _):
|
||||
progressText.stringValue = String.localizedStringWithFormat(NSLocalizedString("Searching %@ for episode information…", comment: ""), service.name)
|
||||
}
|
||||
case .additionalSearch(let search, _, _):
|
||||
switch search {
|
||||
case .movieSeach:
|
||||
case .movieSeach, .movieIDSearch:
|
||||
progressText.stringValue = NSLocalizedString("Downloading additional movie metadata…", comment: "")
|
||||
case .tvSearch:
|
||||
progressText.stringValue = NSLocalizedString("Downloading additional TV metadata…", comment: "")
|
||||
|
||||
@@ -230,7 +230,7 @@ final class OCRManager {
|
||||
}
|
||||
|
||||
private lazy var destinationURL = {
|
||||
return FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?.appendingPathComponent("Subler", isDirectory: true).appendingPathComponent("tessdata", isDirectory: true).appendingPathComponent("v4", isDirectory: true)
|
||||
return FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?.appendingPathComponent("SublerMKV", isDirectory: true).appendingPathComponent("tessdata", isDirectory: true).appendingPathComponent("v4", isDirectory: true)
|
||||
}()
|
||||
|
||||
private lazy var baseURL = {
|
||||
|
||||
@@ -67,14 +67,14 @@ class PrefsWindowController: NSWindowController, NSWindowDelegate {
|
||||
|
||||
// MARK: Panel switching
|
||||
|
||||
private func view(for identifier: NSToolbarItem.Identifier) -> NSView? {
|
||||
private func view(for identifier: NSToolbarItem.Identifier) -> NSView {
|
||||
if identifier == general { return generalController.view }
|
||||
if identifier == metadata { return metadataController.view }
|
||||
if identifier == presets { return presetController.view }
|
||||
if identifier == output { return outputController.view }
|
||||
if identifier == ocr { return ocrController.view }
|
||||
if identifier == advanced { return advancedController.view }
|
||||
return nil
|
||||
return generalController.view
|
||||
}
|
||||
|
||||
private func animationDuration(view: NSView, previousView: NSView?) -> TimeInterval {
|
||||
@@ -82,34 +82,61 @@ class PrefsWindowController: NSWindowController, NSWindowDelegate {
|
||||
return TimeInterval(abs(previousView.frame.size.height - view.frame.height)) * 0.0011
|
||||
}
|
||||
|
||||
func resizeWindow(toFitView view: NSView) {
|
||||
guard let window, let contentView = window.contentView else {
|
||||
return
|
||||
}
|
||||
|
||||
view.setFrameSize(view.fittingSize)
|
||||
|
||||
let viewFrame = view.frame
|
||||
let windowFrame = window.frame
|
||||
let contentViewFrame = contentView.frame
|
||||
|
||||
let windowWidth = max(windowFrame.width, viewFrame.width)
|
||||
let deltaHeight = contentViewFrame.height - viewFrame.height
|
||||
let heightForWindow = windowFrame.height - deltaHeight
|
||||
let windowOriginY = windowFrame.minY + deltaHeight
|
||||
|
||||
var updatedWindowFrame = windowFrame
|
||||
updatedWindowFrame.size.height = heightForWindow
|
||||
updatedWindowFrame.origin.y = windowOriginY
|
||||
updatedWindowFrame.size.width = windowWidth
|
||||
|
||||
var updatedViewFrame = viewFrame
|
||||
updatedViewFrame.origin = NSPoint.zero
|
||||
updatedViewFrame.size.width = windowWidth
|
||||
if viewFrame != updatedViewFrame {
|
||||
view.frame = updatedViewFrame
|
||||
}
|
||||
|
||||
if windowFrame != updatedWindowFrame {
|
||||
contentView.isHidden = true
|
||||
window.setFrame(updatedWindowFrame, display: true, animate: true)
|
||||
contentView.isHidden = false
|
||||
}
|
||||
}
|
||||
|
||||
var currentView: NSView? {
|
||||
window?.contentView?.subviews.first
|
||||
}
|
||||
|
||||
private func selectItem(_ item: NSToolbarItem, animate: Bool) {
|
||||
guard let window = self.window,
|
||||
let view = self.view(for: item.itemIdentifier),
|
||||
window.contentView != view
|
||||
else { return }
|
||||
guard let window, let contentView = window.contentView else { return }
|
||||
|
||||
let duration = animationDuration(view: view, previousView: window.contentView)
|
||||
window.contentView = view
|
||||
|
||||
if window.isVisible && animate {
|
||||
NSAnimationContext.runAnimationGroup({ context in
|
||||
context.allowsImplicitAnimation = true
|
||||
context.duration = duration
|
||||
window.layoutIfNeeded()
|
||||
|
||||
NSAnimationContext.beginGrouping()
|
||||
NSAnimationContext.current.duration = 0
|
||||
view.isHidden = true
|
||||
NSAnimationContext.endGrouping()
|
||||
}, completionHandler: {
|
||||
view.isHidden = false
|
||||
window.title = item.label
|
||||
self.window?.makeFirstResponder(view.nextKeyView)
|
||||
})
|
||||
}
|
||||
else {
|
||||
window.title = item.label
|
||||
let newView = view(for: item.itemIdentifier)
|
||||
if newView == currentView {
|
||||
return
|
||||
}
|
||||
|
||||
currentView?.removeFromSuperview()
|
||||
|
||||
resizeWindow(toFitView: newView)
|
||||
|
||||
contentView.addSubview(newView)
|
||||
|
||||
window.title = item.label
|
||||
window.makeFirstResponder(newView)
|
||||
}
|
||||
|
||||
@IBAction func setPrefView(_ sender: NSToolbarItem) {
|
||||
|
||||
@@ -18,7 +18,7 @@ protocol Preset: NSSecureCoding, NSCopying {
|
||||
extension Preset {
|
||||
|
||||
private func appSupportURL() -> URL? {
|
||||
return FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?.appendingPathComponent("Subler")
|
||||
return FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?.appendingPathComponent("SublerMKV")
|
||||
}
|
||||
|
||||
var fileURL: URL {
|
||||
|
||||
@@ -99,7 +99,7 @@ final class PresetManager {
|
||||
}
|
||||
|
||||
private func appSupportURL() -> URL? {
|
||||
return FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?.appendingPathComponent("Subler")
|
||||
return FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?.appendingPathComponent("SublerMKV")
|
||||
}
|
||||
|
||||
private func version(of fileURL: URL) -> Int? {
|
||||
|
||||
@@ -76,7 +76,11 @@ final class ChapterViewController : PropertyView, NSTableViewDataSource, NSTable
|
||||
}
|
||||
|
||||
func tableViewSelectionDidChange(_ notification: Notification) {
|
||||
removeChapter.isEnabled = tableView.selectedRow != -1 ? true : false
|
||||
removeChapter.isEnabled = tableView.selectedRow != -1 && isReadOnly == false
|
||||
}
|
||||
|
||||
func tableView(_ tableView: NSTableView, shouldEdit tableColumn: NSTableColumn?, row: Int) -> Bool {
|
||||
return isReadOnly == false
|
||||
}
|
||||
|
||||
@IBAction func setChapterTitle(_ sender: NSTextField) {
|
||||
@@ -101,12 +105,14 @@ final class ChapterViewController : PropertyView, NSTableViewDataSource, NSTable
|
||||
}
|
||||
|
||||
@IBAction func doubleClickAction(_ sender: NSTableView) {
|
||||
guard isReadOnly == false else { return }
|
||||
if sender.clickedRow > -1 && sender.clickedColumn > -1 {
|
||||
sender.editColumn(sender.clickedColumn, row: sender.clickedRow, with: nil, select: true)
|
||||
}
|
||||
}
|
||||
|
||||
func deleteSelection(in tableview: NSTableView) {
|
||||
guard isReadOnly == false else { return }
|
||||
let indexes = tableView.selectedRowIndexes
|
||||
if indexes.isEmpty == false {
|
||||
track.removeChapters(at: indexes)
|
||||
@@ -123,6 +129,18 @@ final class ChapterViewController : PropertyView, NSTableViewDataSource, NSTable
|
||||
deleteSelection(in: tableView)
|
||||
}
|
||||
|
||||
// Selects and scrolls to a row (used after the window controller appends
|
||||
// a chapter from the Actions menu, when the tab may not have shown this
|
||||
// track's table yet).
|
||||
func selectChapter(at index: Int) {
|
||||
guard isViewLoaded, index >= 0, index < track.chapters.count else { return }
|
||||
tableView.reloadData()
|
||||
tableView.scrollRowToVisible(index)
|
||||
let indexSet = IndexSet(integer: index)
|
||||
tableView.selectRowIndexes(indexSet, byExtendingSelection: false)
|
||||
view.window?.makeFirstResponder(tableView)
|
||||
}
|
||||
|
||||
@IBAction func addChapter(_ sender: Any) {
|
||||
let index = track.addChapter("Chapter", timestamp: 0)
|
||||
let indexSet = IndexSet(integer: Int(index))
|
||||
|
||||
@@ -101,6 +101,15 @@ final class MediaTagsController: NSViewController, NSTableViewDataSource, NSTabl
|
||||
}
|
||||
private var tags: [MediaTag]
|
||||
|
||||
/// Propagated from the hosting PropertyView (Matroska tags-only mode).
|
||||
var isReadOnly = false {
|
||||
didSet {
|
||||
if isViewLoaded, isReadOnly != oldValue {
|
||||
tableView.reloadData()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override var nibName: NSNib.Name? {
|
||||
return "MediaTagsController"
|
||||
}
|
||||
@@ -162,6 +171,7 @@ final class MediaTagsController: NSViewController, NSTableViewDataSource, NSTabl
|
||||
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
|
||||
let view = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "SBCheckBoxTableCellView"), owner: self) as? CheckBoxTableCellView
|
||||
view?.representedTag = tags[row]
|
||||
view?.checkBox.isEnabled = !isReadOnly
|
||||
return view
|
||||
}
|
||||
|
||||
|
||||
@@ -122,6 +122,12 @@ class MovieViewController: PropertyView, NSTableViewDataSource, ExpandedTableVie
|
||||
}
|
||||
}
|
||||
|
||||
// The document may already be known to be Matroska (the flag is set
|
||||
// after this view loads in DocumentWindowController, but subclasses
|
||||
// of the preset editor never set it — the viewDidLoad pass keeps
|
||||
// this view correct either way).
|
||||
updateMatroskaFieldHints()
|
||||
|
||||
if #available(macOS 26, *) {
|
||||
setsPopUp.menu?.items.first?.image = NSImage.init(systemSymbolName: "ellipsis", accessibilityDescription: nil)
|
||||
}
|
||||
@@ -165,6 +171,59 @@ class MovieViewController: PropertyView, NSTableViewDataSource, ExpandedTableVie
|
||||
removeTagButton.isEnabled = self.metadataTableView.selectedRow != -1
|
||||
}
|
||||
|
||||
// MARK: Matroska field hints
|
||||
|
||||
/// Fonts used to flag metadata fields that `MP42MkvTagWriter` cannot save
|
||||
/// (MP4-only keys). They stay selectable on purpose: an MKV document can
|
||||
/// still be converted to MP4 via the queue, where these values do apply.
|
||||
private static let italicMenuFont: NSFont = {
|
||||
return NSFontManager.shared.convert(NSFont.menuFont(ofSize: 0), toHaveTrait: .italicFontMask)
|
||||
}()
|
||||
|
||||
private func isPersistedInMatroska(identifier: String) -> Bool {
|
||||
return MP42MkvMetadataKeyIsPersisted(identifier)
|
||||
}
|
||||
|
||||
override func updateMatroskaFieldHints() {
|
||||
guard isViewLoaded else { return }
|
||||
|
||||
if let menu = tagsPopUp.menu {
|
||||
let identifiers = MP42Metadata.writableMetadata
|
||||
for item in menu.items where item.isHidden == false && item.tag >= 0 && item.tag < identifiers.count {
|
||||
if isMatroskaDocument && !isPersistedInMatroska(identifier: identifiers[item.tag]) {
|
||||
item.attributedTitle = NSAttributedString(string: item.title, attributes: [
|
||||
.font: MovieViewController.italicMenuFont,
|
||||
.foregroundColor: NSColor.secondaryLabelColor,
|
||||
])
|
||||
item.toolTip = NSLocalizedString("This field cannot be saved to a Matroska file.",
|
||||
comment: "Metadata tag menu hint for MP4-only fields")
|
||||
// Italics/color are invisible to assistive tech; carry the
|
||||
// hint in the accessibility label too.
|
||||
item.setAccessibilityLabel(item.title + ", " + NSLocalizedString("cannot be saved to a Matroska file",
|
||||
comment: "Metadata tag menu hint for MP4-only fields"))
|
||||
} else {
|
||||
// Empty attributed title: AppKit falls back to `title`.
|
||||
item.attributedTitle = NSAttributedString(string: "")
|
||||
item.toolTip = nil
|
||||
item.setAccessibilityLabel(nil)
|
||||
}
|
||||
}
|
||||
// Track # and TV Episode # share the single PART_NUMBER tag on
|
||||
// Matroska files (see syncMatroskaEpisodeFields) — say so.
|
||||
if isMatroskaDocument {
|
||||
for key in [MP42MetadataKeyTrackNumber, MP42MetadataKeyTVEpisodeNumber] {
|
||||
// items are addressed by tag, not position: the pulls-down
|
||||
// title item occupies position 0
|
||||
if let index = identifiers.firstIndex(of: key),
|
||||
let item = menu.items.first(where: { $0.isHidden == false && $0.tag == index }) {
|
||||
item.toolTip = NSLocalizedString("In Matroska files these two fields share one tag: editing either updates both.",
|
||||
comment: "Metadata tag menu note for Track #/TV Episode #")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Metadata
|
||||
|
||||
private func updateMetadataArray() {
|
||||
@@ -539,6 +598,19 @@ class MovieViewController: PropertyView, NSTableViewDataSource, ExpandedTableVie
|
||||
else {
|
||||
cell?.textField?.textColor = .disabledControlTextColor
|
||||
}
|
||||
if let textField = cell?.textField {
|
||||
// Cells are reused: strip any italic from a previous row first,
|
||||
// then italicize MP4-only fields on Matroska documents.
|
||||
let baseFont = NSFontManager.shared.convert(textField.font ?? NSFont.systemFont(ofSize: 0),
|
||||
toNotHaveTrait: .italicFontMask)
|
||||
let flagField = isMatroskaDocument && !isPersistedInMatroska(identifier: item.identifier)
|
||||
textField.font = flagField ? NSFontManager.shared.convert(baseFont, toHaveTrait: .italicFontMask) : baseFont
|
||||
let label = localizedMetadataKeyName(item.identifier) ?? item.identifier
|
||||
textField.setAccessibilityLabel(flagField ?
|
||||
label + ", " + NSLocalizedString("cannot be saved to a Matroska file",
|
||||
comment: "Metadata field hint for MP4-only fields") :
|
||||
nil)
|
||||
}
|
||||
return cell
|
||||
|
||||
} else if tableColumn?.identifier == valueColumn {
|
||||
@@ -665,6 +737,48 @@ class MovieViewController: PropertyView, NSTableViewDataSource, ExpandedTableVie
|
||||
let editedItem = MP42MetadataItem(identifier: item.identifier, value: value as! NSCopying & NSObjectProtocol, dataType: type, extendedLanguageTag: item.extendedLanguageTag)
|
||||
|
||||
replace(metadataItem: item, withItem: editedItem)
|
||||
syncMatroskaEpisodeFields(from: editedItem)
|
||||
}
|
||||
|
||||
/// Matroska stores a single movie-level `PART_NUMBER` tag, and the importer
|
||||
/// fills both Track # and TV Episode # from it. On Matroska documents the
|
||||
/// two rows must therefore move together: whichever one the user edits
|
||||
/// updates the other, so the edit is what `MP42MkvTagWriter` regenerates
|
||||
/// `PART_NUMBER` from. No-op on MP4 documents, where the two are separate
|
||||
/// atoms.
|
||||
private func syncMatroskaEpisodeFields(from editedItem: MP42MetadataItem) {
|
||||
guard isMatroskaDocument else { return }
|
||||
|
||||
let numbers = (editedItem.arrayValue as? [Any])?.compactMap { ($0 as? NSNumber)?.intValue } ?? []
|
||||
|
||||
switch editedItem.identifier {
|
||||
case MP42MetadataKeyTrackNumber:
|
||||
let newIndex = numbers.first ?? 0
|
||||
guard let episode = metadata.metadataItemsFiltered(byIdentifier: MP42MetadataKeyTVEpisodeNumber).first,
|
||||
episode.numberValue?.intValue != newIndex else { return }
|
||||
let replacement = MP42MetadataItem(identifier: MP42MetadataKeyTVEpisodeNumber,
|
||||
value: NSNumber(value: newIndex) as NSCopying & NSObjectProtocol,
|
||||
dataType: episode.dataType,
|
||||
extendedLanguageTag: episode.extendedLanguageTag)
|
||||
replace(metadataItem: episode, withItem: replacement)
|
||||
|
||||
case MP42MetadataKeyTVEpisodeNumber:
|
||||
let newNumber = editedItem.numberValue?.intValue ?? 0
|
||||
guard let track = metadata.metadataItemsFiltered(byIdentifier: MP42MetadataKeyTrackNumber).first else {
|
||||
return // no Track # row: the writer falls back to TV Episode # itself
|
||||
}
|
||||
let parts = (track.arrayValue as? [Any])?.compactMap { ($0 as? NSNumber)?.intValue } ?? []
|
||||
let total = parts.count > 1 ? parts[1] : 0
|
||||
guard (parts.first ?? 0) != newNumber else { return }
|
||||
let replacement = MP42MetadataItem(identifier: MP42MetadataKeyTrackNumber,
|
||||
value: [NSNumber(value: newNumber), NSNumber(value: total)] as NSCopying & NSObjectProtocol,
|
||||
dataType: .integerArray,
|
||||
extendedLanguageTag: track.extendedLanguageTag)
|
||||
replace(metadataItem: track, withItem: replacement)
|
||||
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
@IBAction func setMetadataBoolValue(_ sender: NSButton) {
|
||||
|
||||
@@ -10,6 +10,40 @@ import Cocoa
|
||||
class PropertyView : NSViewController {
|
||||
@IBOutlet var tabView: NSTabView?
|
||||
|
||||
/// True when the view must be displayed but not edited (Matroska
|
||||
/// tags-only documents). Set by DocumentWindowController; subclasses that
|
||||
/// host tables or re-enable controls dynamically must honor it.
|
||||
var isReadOnly = false {
|
||||
didSet {
|
||||
if isViewLoaded, isReadOnly {
|
||||
view.setAllControlsEnabled(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Companion to `isReadOnly` for Matroska documents: the blanket disable
|
||||
/// still applies, but subclasses may re-enable the handful of controls
|
||||
/// whose values `MP42MkvTagWriter` can write back (currently the subtitle
|
||||
/// forced flag). Never consulted when `isReadOnly` is false.
|
||||
var allowsTrackEditing = false
|
||||
|
||||
/// True when the document is a Matroska tags-only document. Unlike
|
||||
/// `isReadOnly` this is set on *every* property view — including the
|
||||
/// metadata tab, which stays editable — so views can visually flag the
|
||||
/// fields `MP42MkvTagWriter` cannot save. Subclasses override
|
||||
/// `updateMatroskaFieldHints()` to apply the styling.
|
||||
var isMatroskaDocument = false {
|
||||
didSet {
|
||||
if isViewLoaded, isMatroskaDocument != oldValue {
|
||||
updateMatroskaFieldHints()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Hook for `isMatroskaDocument` changes; called by subclasses after
|
||||
/// their views are loaded too. Default: nothing to flag.
|
||||
func updateMatroskaFieldHints() {}
|
||||
|
||||
func navigate(direction: Int) {
|
||||
if direction == NSRightArrowFunctionKey {
|
||||
tabView?.selectNextTabViewItem(self)
|
||||
|
||||
@@ -20,6 +20,10 @@ final class SoundViewController : PropertyView {
|
||||
|
||||
let mediaTagsController: MediaTagsController
|
||||
|
||||
override var isReadOnly: Bool {
|
||||
didSet { mediaTagsController.isReadOnly = isReadOnly }
|
||||
}
|
||||
|
||||
@IBOutlet var mediaTagsView: NSView!
|
||||
@IBOutlet var volume: NSSlider!
|
||||
@IBOutlet var alternateGroup: NSPopUpButton!
|
||||
|
||||
@@ -20,6 +20,24 @@ final class VideoViewController: PropertyView {
|
||||
|
||||
private let mediaTagsController: MediaTagsController
|
||||
|
||||
override var isReadOnly: Bool {
|
||||
didSet {
|
||||
mediaTagsController.isReadOnly = isReadOnly
|
||||
// Matroska tags-only: FlagForced is writable (Never/All — the
|
||||
// per-sample "Any samples" option has no Matroska equivalent).
|
||||
if isReadOnly, allowsTrackEditing, isViewLoaded, track is MP42SubtitleTrack {
|
||||
let anySamplesIndex = forcedSubs.indexOfItem(withTag: 1)
|
||||
if anySamplesIndex >= 0 {
|
||||
forcedSubs.removeItem(at: anySamplesIndex)
|
||||
}
|
||||
if forcedSubs.indexOfSelectedItem == -1 {
|
||||
forcedSubs.selectItem(withTag: 0)
|
||||
}
|
||||
forcedSubs.isEnabled = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override var nibName: NSNib.Name? {
|
||||
return "VideoView"
|
||||
}
|
||||
|
||||
@@ -67,6 +67,15 @@ final class Queue {
|
||||
archiver.encode(items, forKey: NSKeyedArchiveRootObjectKey)
|
||||
archiver.finishEncoding()
|
||||
|
||||
// The Application Support/SublerMKV folder must exist before an
|
||||
// atomic write (a fresh install has none, and the write error is
|
||||
// swallowed below, which would silently disable persistence)
|
||||
let fileManager = FileManager.default
|
||||
let directory = url.deletingLastPathComponent()
|
||||
if fileManager.fileExists(atPath: directory.path) == false {
|
||||
try? fileManager.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [:])
|
||||
}
|
||||
|
||||
try? archiver.encodedData.write(to: url, options: [.atomic])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,6 +106,14 @@ class QueueSubtitlesAction : NSObject, QueueActionProtocol {
|
||||
|
||||
for importer in subtitlesImporters {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -213,14 +221,22 @@ class QueueMetadataAction : NSObject, QueueActionProtocol {
|
||||
var metadata: MetadataResult? = nil
|
||||
|
||||
switch info {
|
||||
case let .movie(title):
|
||||
case let .movie(title, id):
|
||||
let service = MetadataSearch.service(name: self.movieProvider)
|
||||
let movieSearch = MetadataSearch.movieSeach(service: service, movie: title, language: self.movieLanguage)
|
||||
_ = movieSearch.search(completionHandler: {
|
||||
if let result = $0.first {
|
||||
_ = movieSearch.loadAdditionalMetadata(result, completionHandler: { metadata = $0 }).run()
|
||||
}
|
||||
}).run()
|
||||
if let id = id {
|
||||
// The file name carries a service ID: try the direct lookup (which
|
||||
// already returns full details) before searching by title.
|
||||
let idSearch = MetadataSearch.movieIDSearch(service: service, id: id, language: self.movieLanguage)
|
||||
_ = idSearch.search(completionHandler: { metadata = $0.first }).run()
|
||||
}
|
||||
if metadata == nil {
|
||||
let movieSearch = MetadataSearch.movieSeach(service: service, movie: title, language: self.movieLanguage)
|
||||
_ = movieSearch.search(completionHandler: {
|
||||
if let result = $0.first {
|
||||
_ = movieSearch.loadAdditionalMetadata(result, completionHandler: { metadata = $0 }).run()
|
||||
}
|
||||
}).run()
|
||||
}
|
||||
case let .tvShow(seriesName, season, episode):
|
||||
let service = MetadataSearch.service(name: self.tvShowProvider)
|
||||
let tvSearch = MetadataSearch.tvSearch(service: service, tvShow: seriesName, season: season, episode: episode, language: tvShowLanguage)
|
||||
@@ -331,6 +347,12 @@ class QueueOrganizeGroupsAction : NSObject, QueueActionProtocol {
|
||||
override init() {}
|
||||
|
||||
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?.inferTracksLanguages()
|
||||
item.mp4File?.inferMediaCharacteristics()
|
||||
@@ -353,6 +375,9 @@ class QueueFixFallbacksAction : NSObject, QueueActionProtocol {
|
||||
override init() {}
|
||||
|
||||
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()
|
||||
return true
|
||||
}
|
||||
@@ -532,6 +557,10 @@ class QueueColorSpaceAction : NSObject, QueueActionProtocol {
|
||||
}
|
||||
|
||||
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] {
|
||||
for track in tracks {
|
||||
if track.format == kMP42VideoCodecType_H264 ||
|
||||
@@ -573,6 +602,12 @@ class QueueOptimizeAction: NSObject, QueueActionProtocol {
|
||||
override init() {}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -236,7 +236,7 @@ final class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDel
|
||||
updateUI(indexes: IndexSet(integer: queue.index(of: item)))
|
||||
|
||||
DispatchQueue.global().async {
|
||||
if originalStatus != .completed {
|
||||
if originalStatus != .completed, item.isMatroska == false {
|
||||
do {
|
||||
try item.prepare()
|
||||
} catch {
|
||||
@@ -251,6 +251,13 @@ final class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDel
|
||||
var doc: Document?
|
||||
if originalStatus == .completed {
|
||||
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 {
|
||||
doc = Document(mp4: mp4)
|
||||
}
|
||||
@@ -277,6 +284,18 @@ final class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDel
|
||||
//MARK: Items creation
|
||||
|
||||
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])
|
||||
|
||||
var isMpeg4 = false
|
||||
|
||||
+116
-23
@@ -41,6 +41,26 @@ import MP42Foundation
|
||||
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
|
||||
@@ -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
|
||||
|
||||
@objc dynamic var status: Status {
|
||||
@@ -253,28 +288,19 @@ import MP42Foundation
|
||||
#endif
|
||||
|
||||
if mp4File == nil {
|
||||
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)
|
||||
}
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
guard let filePathURL = (fileURL as NSURL?)?.filePathURL else { return }
|
||||
@@ -296,6 +348,7 @@ import MP42Foundation
|
||||
defer {
|
||||
mp4File?.progressHandler = nil
|
||||
mp4File = nil
|
||||
matroskaSaver = nil
|
||||
}
|
||||
|
||||
// The file has been added directly to the queue
|
||||
@@ -310,6 +363,9 @@ import MP42Foundation
|
||||
#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 {
|
||||
@@ -320,7 +376,24 @@ import MP42Foundation
|
||||
}
|
||||
|
||||
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
|
||||
try mp4.update(options: attributes)
|
||||
} else {
|
||||
@@ -345,6 +418,7 @@ import MP42Foundation
|
||||
func cancel() {
|
||||
queue.sync {
|
||||
self.cancelled = true
|
||||
matroskaSaver?.cancel()
|
||||
mp4File?.cancel()
|
||||
}
|
||||
}
|
||||
@@ -378,7 +452,12 @@ import MP42Foundation
|
||||
aCoder.encode(5, forKey: "SBQueueItemTagEncodeVersion")
|
||||
|
||||
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
|
||||
|
||||
@@ -468,6 +547,20 @@ import MP42Foundation
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -214,6 +214,6 @@ final class QueuePreferences: NSObject {
|
||||
}
|
||||
|
||||
var queueURL: URL? {
|
||||
return FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?.appendingPathComponent("Subler").appendingPathComponent("queue.sbqueue", isDirectory: false)
|
||||
return FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?.appendingPathComponent("SublerMKV").appendingPathComponent("queue.sbmkvqueue", isDirectory: false)
|
||||
}
|
||||
}
|
||||
+97
-47
@@ -150,48 +150,66 @@ class SBFetchMetadataScriptCommand: NSScriptCommand, ScriptCommandDocumentTarget
|
||||
let preferredArtworkSize = ArtworkSize(rawValue: queuePrefs.providerArtworkSize) ?? .standard
|
||||
|
||||
switch terms {
|
||||
case let .movie(title):
|
||||
let movieSearch = MetadataSearch.movieSeach(service: movieService, movie: title, language: MetadataSearch.defaultLanguage(service: movieService, type: .movie))
|
||||
_ = movieSearch.search(completionHandler: { results in
|
||||
if let result = results.first {
|
||||
_ = movieSearch.loadAdditionalMetadata(result, completionHandler: { additionalMetadata in
|
||||
metadata = additionalMetadata
|
||||
|
||||
// Handle artwork similar to QueueMetadataAction
|
||||
if let metadataResult = metadata {
|
||||
let artworks = metadataResult.remoteArtworks
|
||||
|
||||
if preferredArtwork != .none && artworks.isEmpty == false {
|
||||
let artwork: Artwork? = {
|
||||
let type = preferredArtwork.isMovieType ? preferredArtwork : .poster
|
||||
if let artwork = artworks.first(by: type, size: preferredArtworkSize, service: movieService.name) {
|
||||
return artwork
|
||||
} else if let artwork = artworks.first(by: .poster, size: .standard, service: movieService.name) {
|
||||
return artwork
|
||||
} else {
|
||||
return artworks.first
|
||||
}
|
||||
}()
|
||||
|
||||
// Load and add artwork to metadata result BEFORE mapping
|
||||
if let url = artwork?.url, let artworkData = URLSession.data(from: url) {
|
||||
let mp42Image = MP42Image(data: artworkData, type: MP42_ART_JPEG)
|
||||
metadataResult.artworks.append(mp42Image)
|
||||
}
|
||||
case let .movie(title, id):
|
||||
let language = MetadataSearch.defaultLanguage(service: movieService, type: .movie)
|
||||
|
||||
// Shared continuation for both the ID lookup and the title search
|
||||
let completeWith: (MetadataResult, MetadataSearch) -> Void = { result, search in
|
||||
_ = search.loadAdditionalMetadata(result, completionHandler: { metadataResult in
|
||||
// Handle artwork similar to QueueMetadataAction
|
||||
let artworks = metadataResult.remoteArtworks
|
||||
|
||||
if preferredArtwork != .none && artworks.isEmpty == false {
|
||||
let artwork: Artwork? = {
|
||||
let type = preferredArtwork.isMovieType ? preferredArtwork : .poster
|
||||
if let artwork = artworks.first(by: type, size: preferredArtworkSize, service: movieService.name) {
|
||||
return artwork
|
||||
} else if let artwork = artworks.first(by: .poster, size: .standard, service: movieService.name) {
|
||||
return artwork
|
||||
} else {
|
||||
return artworks.first
|
||||
}
|
||||
|
||||
// Map the metadata using the same logic as QueueAction (now includes artwork)
|
||||
let map = metadataResult.mediaKind == .movie ? MetadataPrefs.movieResultMap : MetadataPrefs.tvShowResultMap
|
||||
let mappedMetadata = metadataResult.mappedMetadata(to: map, keepEmptyKeys: false)
|
||||
completion(mappedMetadata)
|
||||
} else {
|
||||
completion(nil)
|
||||
}()
|
||||
|
||||
// Load and add artwork to metadata result BEFORE mapping
|
||||
if let url = artwork?.url, let artworkData = URLSession.data(from: url) {
|
||||
let mp42Image = MP42Image(data: artworkData, type: MP42_ART_JPEG)
|
||||
metadataResult.artworks.append(mp42Image)
|
||||
}
|
||||
}).run()
|
||||
} else {
|
||||
completion(nil)
|
||||
}
|
||||
}).run()
|
||||
}
|
||||
|
||||
// Map the metadata using the same logic as QueueAction (now includes artwork)
|
||||
let map = metadataResult.mediaKind == .movie ? MetadataPrefs.movieResultMap : MetadataPrefs.tvShowResultMap
|
||||
let mappedMetadata = metadataResult.mappedMetadata(to: map, keepEmptyKeys: false)
|
||||
completion(mappedMetadata)
|
||||
}).run()
|
||||
}
|
||||
|
||||
let searchByName: () -> Void = {
|
||||
let movieSearch = MetadataSearch.movieSeach(service: movieService, movie: title, language: language)
|
||||
_ = movieSearch.search(completionHandler: { results in
|
||||
if let result = results.first {
|
||||
completeWith(result, movieSearch)
|
||||
} else {
|
||||
completion(nil)
|
||||
}
|
||||
}).run()
|
||||
}
|
||||
|
||||
if let id = id {
|
||||
// The file name carries a service ID: try the direct lookup first,
|
||||
// falling back to the title search when it doesn't resolve.
|
||||
let idSearch = MetadataSearch.movieIDSearch(service: movieService, id: id, language: language)
|
||||
_ = idSearch.search(completionHandler: { results in
|
||||
if let result = results.first {
|
||||
completeWith(result, idSearch)
|
||||
} else {
|
||||
searchByName()
|
||||
}
|
||||
}).run()
|
||||
} else {
|
||||
searchByName()
|
||||
}
|
||||
|
||||
case let .tvShow(seriesName, season, episode):
|
||||
let tvSearch = MetadataSearch.tvSearch(service: tvShowService, tvShow: seriesName, season: season, episode: episode, language: MetadataSearch.defaultLanguage(service: tvShowService, type: .tvShow))
|
||||
@@ -342,15 +360,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
|
||||
@@ -439,8 +476,19 @@ class SBSendToQueueScriptCommand: NSScriptCommand, ScriptCommandDocumentTargetin
|
||||
options[MP4264BitData] = Prefs.mp464bitOffset
|
||||
options[MP4264BitTime] = Prefs.mp464bitTimes
|
||||
|
||||
// Create queue item and add to queue
|
||||
let item = QueueItem(mp4: sublerDoc.mp4, destURL: destinationURL, attributes: options, optimize: Prefs.mp4SaveAsOptimize)
|
||||
// Create queue item and add to queue. A Matroska document keeps its
|
||||
// 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
|
||||
QueueController.shared.add(item)
|
||||
@@ -615,7 +663,7 @@ class SBFetchMetadataResultsScriptCommand: NSScriptCommand, ScriptCommandDocumen
|
||||
|
||||
// Perform the search based on media type
|
||||
switch terms {
|
||||
case .movie(let title):
|
||||
case .movie(let title, _):
|
||||
let results = movieService.search(movie: title, language: searchLanguage)
|
||||
|
||||
// Convert MetadataResult to SBMetadataResult
|
||||
@@ -765,8 +813,10 @@ class SBFetchAndSetMetadataResultScriptCommand: NSScriptCommand, ScriptCommandDo
|
||||
let preferredArtworkSize = ArtworkSize(rawValue: queuePrefs.providerArtworkSize) ?? .standard
|
||||
|
||||
// Perform the search based on media type
|
||||
// (Title search by design: the caller indexes into the list returned by the
|
||||
// earlier fetch-metadata-results command, so no ID shortcut here.)
|
||||
switch terms {
|
||||
case let .movie(title):
|
||||
case let .movie(title, _):
|
||||
let movieSearch = MetadataSearch.movieSeach(service: movieService, movie: title, language: searchLanguage)
|
||||
_ = movieSearch.search(completionHandler: { results in
|
||||
if resultIndex >= 0 && resultIndex < results.count {
|
||||
|
||||
@@ -31,6 +31,29 @@ final class TracksViewController: NSViewController, NSTableViewDataSource, NSTab
|
||||
|
||||
@IBOutlet var tracksTable: ExpandedTableView!
|
||||
|
||||
// In Matroska tags-only mode the track list cannot be structurally
|
||||
// changed: no deletion, reordering or import.
|
||||
private var isReadOnly: Bool {
|
||||
return document.isMatroska
|
||||
}
|
||||
|
||||
// The per-track fields whose values MP42MkvTagWriter writes back into the
|
||||
// file's Tracks element (name, language, enabled, subtitle forced) stay
|
||||
// editable even in tags-only mode; the chapter pseudo-track has no
|
||||
// Matroska counterpart.
|
||||
private func isFieldEditable(_ track: MP42Track?) -> Bool {
|
||||
guard let track = track else { return false }
|
||||
return document.isMatroska == false || track.isMember(of: MP42ChapterTrack.self) == false
|
||||
}
|
||||
|
||||
// The chapter pseudo-track has no TrackEntry for the tag writer, but it
|
||||
// carries the language the remuxer stamps into every ChapterDisplay on
|
||||
// save, so its language popup is editable on Matroska documents too.
|
||||
private func isLanguageEditable(_ track: MP42Track?) -> Bool {
|
||||
guard let track = track else { return false }
|
||||
return isFieldEditable(track) || track.isMember(of: MP42ChapterTrack.self)
|
||||
}
|
||||
|
||||
private static let languagesMenu: NSMenu = {
|
||||
let menu = NSMenu()
|
||||
menu.autoenablesItems = false
|
||||
@@ -100,16 +123,32 @@ final class TracksViewController: NSViewController, NSTableViewDataSource, NSTab
|
||||
|
||||
@IBAction func doubleClickAction(_ sender: NSTableView) {
|
||||
// make sure they clicked a real cell and not a header or empty row
|
||||
if sender.clickedRow >= 1 {
|
||||
if sender.clickedRow >= 1, let track = track(at: sender.clickedRow) {
|
||||
let column = sender.tableColumns[sender.clickedColumn]
|
||||
if column.identifier == trackNameColumn {
|
||||
if column.identifier == trackNameColumn, isFieldEditable(track) {
|
||||
sender.editColumn(sender.clickedColumn, row: sender.clickedRow, with: nil, select: true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func deleteSelection(in tableview: NSTableView) {
|
||||
delegate?.delete(tracks: selectedTracks)
|
||||
// On MKV documents real tracks are deletable too (the remuxer drops
|
||||
// their blocks on save) and so is the chapter pseudo-track: with it
|
||||
// gone the model reports "no chapters", so the save remuxes and the
|
||||
// Chapters element is deleted (same as emptying the Chapters tab).
|
||||
let deletable = document.isMatroska
|
||||
? selectedTracks.filter { isFieldEditable($0) || $0.isMember(of: MP42ChapterTrack.self) }
|
||||
: selectedTracks
|
||||
guard deletable.isEmpty == false else { return }
|
||||
delegate?.delete(tracks: deletable)
|
||||
}
|
||||
|
||||
func tableView(_ tableView: NSTableView, shouldEdit tableColumn: NSTableColumn?, row: Int) -> Bool {
|
||||
if isReadOnly == false {
|
||||
return true
|
||||
}
|
||||
// tags-only mode still allows inline renaming of real tracks
|
||||
return tableColumn?.identifier == trackNameColumn && isFieldEditable(track(at: row))
|
||||
}
|
||||
|
||||
// MARK: Actions
|
||||
@@ -180,12 +219,13 @@ final class TracksViewController: NSViewController, NSTableViewDataSource, NSTab
|
||||
case trackEnabledColumn?:
|
||||
let cell = tableView.makeView(withIdentifier: trackEnabledColumn, owner:self) as? CheckBoxCellView
|
||||
cell?.checkboxButton?.state = track.isEnabled ? NSControl.StateValue.on : NSControl.StateValue.off
|
||||
cell?.checkboxButton?.isEnabled = isFieldEditable(track)
|
||||
return cell
|
||||
|
||||
case trackNameColumn?:
|
||||
let cell = tableView.makeView(withIdentifier: trackNameColumn, owner:self) as? NSTableCellView
|
||||
cell?.textField?.stringValue = track.name
|
||||
cell?.textField?.isEditable = true
|
||||
cell?.textField?.isEditable = isFieldEditable(track)
|
||||
return cell
|
||||
|
||||
case trackDurationColumn?:
|
||||
@@ -208,11 +248,25 @@ final class TracksViewController: NSViewController, NSTableViewDataSource, NSTab
|
||||
}
|
||||
|
||||
cell?.textField?.stringValue = MP42Languages.defaultManager.localizedLang(forExtendedTag: track.language)
|
||||
cell?.popUpButton?.isEnabled = isLanguageEditable(track)
|
||||
return cell
|
||||
|
||||
case trackInfoColumn?:
|
||||
let cell = tableView.makeView(withIdentifier: trackInfoColumn, owner:self) as? NSTableCellView
|
||||
cell?.textField?.stringValue = track.formatSummary
|
||||
if isReadOnly {
|
||||
// Tags-only documents never mux, and the default conversion
|
||||
// settings attached at import (see Document.readMatroska)
|
||||
// would make formatSummary advertise a conversion target
|
||||
// instead of the actual source codec.
|
||||
var summary = localizedDisplayName(track.mediaType, track.format) ?? "Unknown"
|
||||
if let audioTrack = track as? MP42AudioTrack, audioTrack.channels > 0,
|
||||
track.format != kMP42AudioCodecType_DTS {
|
||||
summary = "\(summary), \(audioTrack.channels) ch"
|
||||
}
|
||||
cell?.textField?.stringValue = summary
|
||||
} else {
|
||||
cell?.textField?.stringValue = track.formatSummary
|
||||
}
|
||||
return cell
|
||||
|
||||
default:
|
||||
@@ -260,6 +314,9 @@ final class TracksViewController: NSViewController, NSTableViewDataSource, NSTab
|
||||
|
||||
func tableView(_ tableView: NSTableView,
|
||||
pasteboardWriterForRow row: Int) -> (any NSPasteboardWriting)? {
|
||||
if isReadOnly {
|
||||
return nil
|
||||
}
|
||||
if let track = track(at: row), track.isMuxed == false {
|
||||
return PasteboardItem(index: row, type: .tableViewIndex)
|
||||
} else {
|
||||
@@ -271,6 +328,7 @@ final class TracksViewController: NSViewController, NSTableViewDataSource, NSTab
|
||||
validateDrop info: NSDraggingInfo,
|
||||
proposedRow row: Int,
|
||||
proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation {
|
||||
if isReadOnly { return [] }
|
||||
guard dropOperation == .above else { return [] }
|
||||
|
||||
guard let source = info.draggingSource as? NSTableView,
|
||||
|
||||
@@ -128,3 +128,17 @@ extension String {
|
||||
return matrix[m][n]
|
||||
}
|
||||
}
|
||||
|
||||
extension NSView {
|
||||
/// Enables or disables every NSControl in this view hierarchy. Used to
|
||||
/// present the track property views read-only in Matroska (tags-only)
|
||||
/// documents, where the tracks cannot be modified.
|
||||
func setAllControlsEnabled(_ enabled: Bool) {
|
||||
if let control = self as? NSControl {
|
||||
control.isEnabled = enabled
|
||||
}
|
||||
for subview in subviews {
|
||||
subview.setAllControlsEnabled(enabled)
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-7
@@ -104,7 +104,7 @@
|
||||
<key>CFBundleTypeName</key>
|
||||
<string>Matroska video</string>
|
||||
<key>CFBundleTypeRole</key>
|
||||
<string>Viewer</string>
|
||||
<string>Editor</string>
|
||||
<key>LSHandlerRank</key>
|
||||
<string>Alternate</string>
|
||||
<key>NSDocumentClass</key>
|
||||
@@ -171,12 +171,6 @@
|
||||
<string>NSApplication</string>
|
||||
<key>OSAScriptingDefinition</key>
|
||||
<string>Subler.sdef</string>
|
||||
<key>SUAllowsAutomaticUpdates</key>
|
||||
<false/>
|
||||
<key>SUFeedURL</key>
|
||||
<string>https://subler.org/appcast/appcast.xml</string>
|
||||
<key>SUPublicEDKey</key>
|
||||
<string>9M0JrgMq+5MrpLqTu7lT+ffThP8dRp78OQNTklwK/WE=</string>
|
||||
<key>NSAutoFillRequiresTextContentTypeForOneTimeCodeOnMac</key>
|
||||
<true/>
|
||||
<key>UTImportedTypeDeclarations</key>
|
||||
|
||||
+1
-1
Submodule MP42Foundation updated: 4648f9d585...72e879e316.
@@ -1,26 +1,87 @@
|
||||
# README #
|
||||
|
||||
### What is this repository for? ###
|
||||
|
||||
Subler is an Mac OS X app created to mux and tag mp4 files. The main features includes:
|
||||
|
||||
* Creation of tx3g subtitles tracks, compatible with all Apple's devices (iPod, AppleTV, iPhone, QuickTime?).
|
||||
* Mux video, audio, chapters, subtitles and closed captions tracks from mov, mp4 and mkv.
|
||||
* Raw formats: H.264 Elementary streams (.h264, .264), AAC (.aac), AC3 (.ac3), Scenarist (.scc), VobSub? (.idx).
|
||||
* metadata editing and TMDb, TVDB and iTunes Store support.
|
||||
|
||||
### Build and run
|
||||
|
||||
Clone the repository and include all submodules
|
||||
```
|
||||
git clone --recurse-submodules https://github.com/SublerApp/Subler.git
|
||||
```
|
||||
If you already cloned without submodules and need to add the submodules manually, `cd` into the `./Subler` directory and clone the dependency submodules with
|
||||
```
|
||||
git submodule update --init --recursive
|
||||
```
|
||||
Open `Subler.xcodeproj` in XCode
|
||||
|
||||
Build and run the project by selecting the 'Subler' scheme (`Product` -> `Scheme` -> `Subler`) and clicking the 'Run' button in Xcode’s toolbar.
|
||||
|
||||
|
||||
# Subler #
|
||||
|
||||
Subler is a macOS app for muxing and tagging MP4/M4V/M4A files. The main features include:
|
||||
|
||||
* Creation of tx3g subtitle tracks, compatible with all Apple devices (iPod, Apple TV, iPhone, QuickTime).
|
||||
* Mux video, audio, chapters, subtitles and closed-caption tracks from mov, mp4 and mkv sources.
|
||||
* Raw formats: H.264 elementary streams (.h264, .264), AAC (.aac), AC3 (.ac3), Scenarist (.scc), VobSub (.idx).
|
||||
* Metadata editing with TMDb, TVDB and iTunes Store lookups.
|
||||
|
||||
## About this fork
|
||||
|
||||
This is a standalone working copy maintained at [git.technomancer.com](https://git.technomancer.com) in
|
||||
*Scott Garrett's Misc Files and Scripts*; it is not a staging ground for pull requests against upstream.
|
||||
The original project is [SublerApp/Subler](https://github.com/SublerApp/Subler) by Damiano Galassi, and
|
||||
this tree starts from its history.
|
||||
|
||||
### Changes on top of upstream
|
||||
|
||||
**Native Matroska support** — the headline change. `.mkv`/`.mka`/`.mks` files open directly and are edited
|
||||
in place instead of being converted to MP4:
|
||||
|
||||
* Tags and the four per-track fields Matroska stores (name, language, enabled, forced subtitle) rewrite
|
||||
the file in place (mkvpropedit-style), never touching the media clusters.
|
||||
* Deleted or added tracks, and Save-As, go through a stream-copy remuxer that copies every block verbatim
|
||||
and rebuilds the container bookkeeping (SeekHead, Cues, Duration).
|
||||
* Chapters are editable: update via `.csv`, add via `.txt` (mp4chaps) import, insert one chapter or add
|
||||
them at a fixed interval; chapter changes ride the remuxer.
|
||||
* Subtitle tracks (`.srt`/`.ssa`/`.ass`) can be added to an open Matroska document.
|
||||
* File ▸ Optimize performs a full structural rebuild on Matroska documents; the AppleScript `save as`
|
||||
command routes Matroska correctly.
|
||||
* The companion `MP42Foundation` submodule carries the engine for all of this (EBML scanner, tag mapping,
|
||||
in-place tag writer, stream-copy remuxer, importer changes).
|
||||
|
||||
**VobSub muxing** — added VobSub tracks are muxed at the frame size declared in their `.idx` file.
|
||||
|
||||
**Metadata search from file names** — names carrying embedded IDs such as
|
||||
`The Movie (2024) {tmdb-1015812}` or `{imdb-tt15239678}` now parse to a clean title, and the ID drives a
|
||||
direct TMDb lookup (with title-search fallback) in the metadata search sheet, in queue jobs, and in the
|
||||
AppleScript metadata fetch command.
|
||||
|
||||
**No auto-updates** — the upstream Sparkle integration is removed (updater menu item, appcast keys, SPM
|
||||
package): a fork build pointed at subler.org's appcast would offer upstream builds signed with someone
|
||||
else's key. The fork version is `1.9.5mkv`, and the app has no third-party package dependencies.
|
||||
|
||||
## Build and run
|
||||
|
||||
Everything the app builds from lives on this server: the `MP42Foundation` submodule, and inside it a
|
||||
nested `contrib` submodule (the vendored mp4v2 sources). All three repos are public and clone over
|
||||
HTTPS — no account or key needed.
|
||||
|
||||
Clone the repository with all submodules
|
||||
|
||||
```
|
||||
git clone --recurse-submodules https://git.technomancer.com/Scott-Files/SublerMKV.git
|
||||
```
|
||||
|
||||
Contributors with push access use the SSH clone URL instead
|
||||
(`gitea@git.technomancer.com:Scott-Files/SublerMKV.git` — the SSH user is `gitea`); to keep submodule
|
||||
operations on SSH too, add
|
||||
`git config --global url."gitea@git.technomancer.com:".insteadOf https://git.technomancer.com/`.
|
||||
|
||||
If you already cloned without submodules, `cd` into the `SublerMKV` directory and fetch them (including the
|
||||
nested one) with
|
||||
|
||||
```
|
||||
git submodule update --init --recursive
|
||||
```
|
||||
|
||||
To bring an existing checkout up to date:
|
||||
|
||||
```
|
||||
git pull --rebase
|
||||
git submodule update --init --recursive
|
||||
```
|
||||
|
||||
There are no other dependencies — no Swift packages are fetched; everything above is the full build
|
||||
input.
|
||||
|
||||
Open `Subler.xcodeproj` in Xcode, select the *Subler* scheme (`Product` → `Scheme` → `Subler`) and press
|
||||
Run. Command-line builds work as-is (the projects target the toolchain-recommended deployment target,
|
||||
unlike upstream's 10.13, which recent toolchains refuse):
|
||||
|
||||
```
|
||||
xcodebuild -project Subler.xcodeproj -scheme Subler -configuration Debug build
|
||||
```
|
||||
|
||||
There is no test target; changes are verified by building and running the app.
|
||||
@@ -3,7 +3,7 @@
|
||||
archiveVersion = 1;
|
||||
classes = {
|
||||
};
|
||||
objectVersion = 54;
|
||||
objectVersion = 56;
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
@@ -46,7 +46,6 @@
|
||||
A93105391F9758EC00605146 /* FileImportController.xib in Resources */ = {isa = PBXBuildFile; fileRef = A93105351F9758EC00605146 /* FileImportController.xib */; };
|
||||
A932C9F3205C268A004E52FE /* QueueScriptCommand.swift in Sources */ = {isa = PBXBuildFile; fileRef = A932C9F2205C268A004E52FE /* QueueScriptCommand.swift */; };
|
||||
A9395E351F8B9ACA004C402B /* MP42FileAdditions.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9395E341F8B9ACA004C402B /* MP42FileAdditions.swift */; };
|
||||
A9405AF2275E282500776561 /* Sparkle in Frameworks */ = {isa = PBXBuildFile; productRef = A9405AF1275E282500776561 /* Sparkle */; };
|
||||
A9433A8D1F2F5C3600BB38CA /* ChapterResult.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9433A8C1F2F5C3600BB38CA /* ChapterResult.swift */; };
|
||||
A9433A911F2F5D8A00BB38CA /* ChapterDB.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9433A901F2F5D8A00BB38CA /* ChapterDB.swift */; };
|
||||
A944E5921F498FC4002E43F6 /* PresetPrefsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A944E5911F498FC4002E43F6 /* PresetPrefsViewController.swift */; };
|
||||
@@ -128,6 +127,7 @@
|
||||
A9DA03E322A0211C0056AE7B /* OCRPrefsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9DA03E122A0211C0056AE7B /* OCRPrefsViewController.swift */; };
|
||||
A9E385782C316FBE000A050D /* CollectionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9E385772C316FBE000A050D /* CollectionView.swift */; };
|
||||
A9E3857C2C317010000A050D /* FilePromiseProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9E3857B2C317010000A050D /* FilePromiseProvider.swift */; };
|
||||
A9E77B152E5C0FF1E0000001 /* extractsubs in Resources */ = {isa = PBXBuildFile; fileRef = A9E77B152E5C0FF2E0000002 /* extractsubs */; };
|
||||
A9E97F141F274F1100DBA586 /* iTunesStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9E97F131F274F1100DBA586 /* iTunesStore.swift */; };
|
||||
A9ECA0532029948900D5F30C /* OffsetViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9ECA0512029948900D5F30C /* OffsetViewController.swift */; };
|
||||
A9ECA0572029A10B00D5F30C /* DocumentWindowController.xib in Resources */ = {isa = PBXBuildFile; fileRef = A9ECA0592029A10B00D5F30C /* DocumentWindowController.xib */; };
|
||||
@@ -142,6 +142,7 @@
|
||||
A9F680A81FD06E0200018371 /* OutputPrefsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9F680A61FD06E0200018371 /* OutputPrefsViewController.swift */; };
|
||||
A9F7F8E01837C44B0036AE7E /* IOKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A9ED7B21180067A2008FD3A8 /* IOKit.framework */; };
|
||||
A9FC6FF61EF2E3280034CCED /* TheTVDBService.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9FC6FF51EF2E3280034CCED /* TheTVDBService.swift */; };
|
||||
AD2611292900000000FACE01 /* MatroskaSaver.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD2611292900000000FACE02 /* MatroskaSaver.swift */; };
|
||||
CD71FEA612F1B62600F0A98D /* MetadataSearch.xib in Resources */ = {isa = PBXBuildFile; fileRef = CD71FEA412F1B62600F0A98D /* MetadataSearch.xib */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
@@ -200,7 +201,7 @@
|
||||
610362271E76D66A000DAE60 /* it */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = it; path = Classes/PropertyView/it.lproj/MultiSelectView.strings; sourceTree = "<group>"; };
|
||||
61CEC0CD1E7569E4000FECC1 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Classes/PropertyView/Base.lproj/MultiSelectView.xib; sourceTree = "<group>"; };
|
||||
8D15AC360486D014006FF6A4 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
8D15AC370486D014006FF6A4 /* Subler.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Subler.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
8D15AC370486D014006FF6A4 /* SublerMKV.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SublerMKV.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
A90057B51F99DE2700FA4ED1 /* ComboBoxCellView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = ComboBoxCellView.swift; path = Classes/ComboBoxCellView.swift; sourceTree = "<group>"; };
|
||||
A90057BB1F99E20B00FA4ED1 /* CheckBoxCellView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = CheckBoxCellView.swift; path = Classes/CheckBoxCellView.swift; sourceTree = "<group>"; };
|
||||
A90057BD1F99E2D800FA4ED1 /* TokenFieldCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = TokenFieldCell.swift; path = Classes/TokenFieldCell.swift; sourceTree = "<group>"; };
|
||||
@@ -499,6 +500,7 @@
|
||||
A9E059CD2529DCAA000E0E9A /* zh-Hans */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = "zh-Hans"; path = "zh-Hans.lproj/MetadataPrefsViewController.strings"; sourceTree = "<group>"; };
|
||||
A9E385772C316FBE000A050D /* CollectionView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = CollectionView.swift; path = Classes/CollectionView.swift; sourceTree = "<group>"; };
|
||||
A9E3857B2C317010000A050D /* FilePromiseProvider.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = FilePromiseProvider.swift; path = Classes/FilePromiseProvider.swift; sourceTree = "<group>"; };
|
||||
A9E77B152E5C0FF2E0000002 /* extractsubs */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.script.shell; name = extractsubs; path = Utilities/extractsubs; sourceTree = "<group>"; };
|
||||
A9E97F131F274F1100DBA586 /* iTunesStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = iTunesStore.swift; path = Classes/MetadataImporters/iTunesStore.swift; sourceTree = "<group>"; };
|
||||
A9E9E5291FB21B4000BCC49D /* it */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = it; path = it.lproj/FileImportController.strings; sourceTree = "<group>"; };
|
||||
A9ECA0512029948900D5F30C /* OffsetViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = OffsetViewController.swift; path = Classes/OffsetViewController.swift; sourceTree = "<group>"; };
|
||||
@@ -513,6 +515,7 @@
|
||||
A9F5820B1DCC861F005F3E92 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
|
||||
A9F680A61FD06E0200018371 /* OutputPrefsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = OutputPrefsViewController.swift; path = Classes/OutputPrefsViewController.swift; sourceTree = "<group>"; };
|
||||
A9FC6FF51EF2E3280034CCED /* TheTVDBService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = TheTVDBService.swift; path = Classes/MetadataImporters/TheTVDBService.swift; sourceTree = "<group>"; };
|
||||
AD2611292900000000FACE02 /* MatroskaSaver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = MatroskaSaver.swift; path = Classes/MatroskaSaver.swift; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
@@ -523,7 +526,6 @@
|
||||
8D15AC340486D014006FF6A4 /* Cocoa.framework in Frameworks */,
|
||||
A9F7F8E01837C44B0036AE7E /* IOKit.framework in Frameworks */,
|
||||
A925AA8518378D8A00BE84D4 /* MP42Foundation.framework in Frameworks */,
|
||||
A9405AF2275E282500776561 /* Sparkle in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -543,7 +545,7 @@
|
||||
19C28FB0FE9D524F11CA2CBB /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
8D15AC370486D014006FF6A4 /* Subler.app */,
|
||||
8D15AC370486D014006FF6A4 /* SublerMKV.app */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
@@ -609,6 +611,7 @@
|
||||
A9C498C2306BC6B9009F332A /* Ratings.json */,
|
||||
A9C498C3306BC6B9009F332A /* Storefronts.json */,
|
||||
A94A6A581ED1C5CA00049F7D /* ParseFilename */,
|
||||
A9E77B152E5C0FF2E0000002 /* extractsubs */,
|
||||
);
|
||||
name = Resources;
|
||||
sourceTree = "<group>";
|
||||
@@ -710,6 +713,7 @@
|
||||
A9BC410618D9ABC000F8C92C /* QueueItem.xib */,
|
||||
A98D6BAA21FDC62800F0D886 /* Queue.swift */,
|
||||
A9EFB8CB21FF40C500129FDD /* QueueItem.swift */,
|
||||
AD2611292900000000FACE02 /* MatroskaSaver.swift */,
|
||||
A91B196B1F2B0DCB0008675F /* QueueAction.swift */,
|
||||
A932C9F2205C268A004E52FE /* QueueScriptCommand.swift */,
|
||||
);
|
||||
@@ -799,28 +803,26 @@
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
8D15AC270486D014006FF6A4 /* Subler */ = {
|
||||
8D15AC270486D014006FF6A4 /* SublerMKV */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = C05733C708A9546B00998B17 /* Build configuration list for PBXNativeTarget "Subler" */;
|
||||
buildConfigurationList = C05733C708A9546B00998B17 /* Build configuration list for PBXNativeTarget "SublerMKV" */;
|
||||
buildPhases = (
|
||||
8D15AC2B0486D014006FF6A4 /* Resources */,
|
||||
8D15AC300486D014006FF6A4 /* Sources */,
|
||||
8D15AC330486D014006FF6A4 /* Frameworks */,
|
||||
A984DB5E0F52D68E001A20B2 /* Copy Files */,
|
||||
A922E0272233C9AC0072FD1B /* Copy Files */,
|
||||
A9E77B152E5C0FF4E0000004 /* Build sup2vob CLI */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
A925AA8718378DC400BE84D4 /* PBXTargetDependency */,
|
||||
);
|
||||
name = Subler;
|
||||
packageProductDependencies = (
|
||||
A9405AF1275E282500776561 /* Sparkle */,
|
||||
);
|
||||
name = SublerMKV;
|
||||
productInstallPath = "$(HOME)/Applications";
|
||||
productName = MP4Sub;
|
||||
productReference = 8D15AC370486D014006FF6A4 /* Subler.app */;
|
||||
productReference = 8D15AC370486D014006FF6A4 /* SublerMKV.app */;
|
||||
productType = "com.apple.product-type.application";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
@@ -830,7 +832,7 @@
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = YES;
|
||||
LastUpgradeCheck = 2700;
|
||||
LastUpgradeCheck = 2720;
|
||||
TargetAttributes = {
|
||||
8D15AC270486D014006FF6A4 = {
|
||||
LastSwiftMigration = 1020;
|
||||
@@ -847,7 +849,7 @@
|
||||
};
|
||||
};
|
||||
buildConfigurationList = C05733CB08A9546B00998B17 /* Build configuration list for PBXProject "Subler" */;
|
||||
compatibilityVersion = "Xcode 11.0";
|
||||
compatibilityVersion = "Xcode 14.0";
|
||||
developmentRegion = en;
|
||||
hasScannedForEncodings = 1;
|
||||
knownRegions = (
|
||||
@@ -861,9 +863,6 @@
|
||||
"zh-CN",
|
||||
);
|
||||
mainGroup = 2A37F4AAFDCFA73011CA2CEA /* MP4Sub */;
|
||||
packageReferences = (
|
||||
A9405AF0275E282500776561 /* XCRemoteSwiftPackageReference "Sparkle" */,
|
||||
);
|
||||
projectDirPath = "";
|
||||
projectReferences = (
|
||||
{
|
||||
@@ -873,7 +872,7 @@
|
||||
);
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
8D15AC270486D014006FF6A4 /* Subler */,
|
||||
8D15AC270486D014006FF6A4 /* SublerMKV */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
@@ -943,12 +942,35 @@
|
||||
A90CD5C51FD177280070A067 /* OutputPrefsViewController.xib in Resources */,
|
||||
A9A4A966202F51FA00482D12 /* SaveOptions.xib in Resources */,
|
||||
A94A6A591ED1C5CC00049F7D /* ParseFilename in Resources */,
|
||||
A9E77B152E5C0FF1E0000001 /* extractsubs in Resources */,
|
||||
A9ECA05D2029A11500D5F30C /* DetailsViewController.xib in Resources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXResourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXShellScriptBuildPhase section */
|
||||
A9E77B152E5C0FF4E0000004 /* Build sup2vob CLI */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
alwaysOutOfDate = 1;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
inputFileListPaths = (
|
||||
);
|
||||
inputPaths = (
|
||||
);
|
||||
name = "Build sup2vob CLI";
|
||||
outputFileListPaths = (
|
||||
);
|
||||
outputPaths = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
shellPath = /bin/zsh;
|
||||
shellScript = "# The sup2vob CLI ships inside the app bundle (Contents/MacOS) so it\n# updates with every Subler build; make is incremental, so this is a\n# no-op unless the conversion sources or main.swift changed. The recipe\n# lives in the submodule's Makefile — do not duplicate it here.\nset -eu\nmake -C \"${SRCROOT}/MP42Foundation/sup2vob\"\ninstall -m 755 \"${SRCROOT}/MP42Foundation/sup2vob/sup2vob\" \"${TARGET_BUILD_DIR}/${CONTENTS_FOLDER_PATH}/MacOS/sup2vob\"\n";
|
||||
};
|
||||
/* End PBXShellScriptBuildPhase section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
8D15AC300486D014006FF6A4 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
@@ -969,6 +991,7 @@
|
||||
A9A91B5D1FB6FBB700250D93 /* ChapterViewController.swift in Sources */,
|
||||
A9676A301FB6E85300C1E300 /* LanguageTransformer.swift in Sources */,
|
||||
A9EFB8CC21FF40C500129FDD /* QueueItem.swift in Sources */,
|
||||
AD2611292900000000FACE01 /* MatroskaSaver.swift in Sources */,
|
||||
A97FBE3C21FC7F1C00F1FD35 /* QueueController.swift in Sources */,
|
||||
A9907E192063DAA000DB992E /* VideoViewController.swift in Sources */,
|
||||
A98D98461F0280CB00A77ABC /* TheMovieDB.swift in Sources */,
|
||||
@@ -1537,11 +1560,12 @@
|
||||
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "-";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
CURRENT_PROJECT_VERSION = 1.9.5;
|
||||
CURRENT_PROJECT_VERSION = 1.9.5mkv1;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
DEVELOPMENT_TEAM = "";
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = NO; /* the "Build sup2vob CLI" phase runs the submodule Makefile over MP42/Sup2Vob */
|
||||
FRAMEWORK_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"$(SRCROOT)",
|
||||
@@ -1551,18 +1575,20 @@
|
||||
GCC_OPTIMIZATION_LEVEL = 0;
|
||||
GCC_VERSION = "";
|
||||
INFOPLIST_FILE = Info.plist;
|
||||
INFOPLIST_KEY_CFBundleDisplayName = Subler;
|
||||
INFOPLIST_KEY_CFBundleDisplayName = SublerMKV;
|
||||
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.video";
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/../Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 1.9.5;
|
||||
MACOSX_DEPLOYMENT_TARGET = "$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)";
|
||||
MARKETING_VERSION = 1.9.5mkv1;
|
||||
OTHER_CFLAGS = "";
|
||||
OTHER_LDFLAGS = "-Wl,-rpath,@loader_path/../Frameworks";
|
||||
OTHER_SWIFT_FLAGS = "";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = "org.galad.${PRODUCT_NAME:identifier}";
|
||||
PRODUCT_NAME = Subler;
|
||||
PRODUCT_MODULE_NAME = Subler; /* XIB bindings reference classes as "Subler.LanguageTransformer" etc. — Swift registers runtime names by module, so the module stays pinned whatever the product is called */
|
||||
PRODUCT_NAME = SublerMKV;
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
SWIFT_INCLUDE_PATHS = "$(SRCROOT)/MP42Foundation/contrib/mp4v2/";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
@@ -1583,11 +1609,12 @@
|
||||
CODE_SIGN_IDENTITY = "Mac Developer";
|
||||
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "-";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 1.9.5;
|
||||
CURRENT_PROJECT_VERSION = 1.9.5mkv1;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
DEVELOPMENT_TEAM = "";
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = NO; /* the "Build sup2vob CLI" phase runs the submodule Makefile over MP42/Sup2Vob */
|
||||
FRAMEWORK_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"$(SRCROOT)",
|
||||
@@ -1596,18 +1623,20 @@
|
||||
GCC_DYNAMIC_NO_PIC = YES;
|
||||
GCC_VERSION = "";
|
||||
INFOPLIST_FILE = Info.plist;
|
||||
INFOPLIST_KEY_CFBundleDisplayName = Subler;
|
||||
INFOPLIST_KEY_CFBundleDisplayName = SublerMKV;
|
||||
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.video";
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/../Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 1.9.5;
|
||||
MACOSX_DEPLOYMENT_TARGET = "$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)";
|
||||
MARKETING_VERSION = 1.9.5mkv1;
|
||||
OTHER_CFLAGS = "";
|
||||
OTHER_LDFLAGS = "-Wl,-rpath,@loader_path/../Frameworks";
|
||||
OTHER_SWIFT_FLAGS = "";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = "org.galad.${PRODUCT_NAME:identifier}";
|
||||
PRODUCT_NAME = Subler;
|
||||
PRODUCT_MODULE_NAME = Subler; /* XIB bindings reference classes as "Subler.LanguageTransformer" etc. — Swift registers runtime names by module, so the module stays pinned whatever the product is called */
|
||||
PRODUCT_NAME = SublerMKV;
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
SWIFT_INCLUDE_PATHS = "$(SRCROOT)/MP42Foundation/contrib/mp4v2/";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
@@ -1693,11 +1722,12 @@
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
HEADER_SEARCH_PATHS = "";
|
||||
LIBRARY_SEARCH_PATHS = "";
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.13;
|
||||
MACOSX_DEPLOYMENT_TARGET = "$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)";
|
||||
MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "c11 gnu++14";
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
OTHER_CFLAGS = "";
|
||||
RUN_CLANG_STATIC_ANALYZER = NO;
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||
SWIFT_STRICT_CONCURRENCY = targeted;
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
@@ -1750,6 +1780,7 @@
|
||||
CODE_SIGN_IDENTITY = "";
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
DEFINES_MODULE = YES;
|
||||
ENABLE_MODULE_VERIFIER = YES;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
@@ -1779,10 +1810,12 @@
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
HEADER_SEARCH_PATHS = "";
|
||||
LIBRARY_SEARCH_PATHS = "";
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.13;
|
||||
MACOSX_DEPLOYMENT_TARGET = "$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)";
|
||||
MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "c11 gnu++14";
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
OTHER_CFLAGS = "";
|
||||
RUN_CLANG_STATIC_ANALYZER = NO;
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
SWIFT_STRICT_CONCURRENCY = targeted;
|
||||
@@ -1793,7 +1826,7 @@
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
C05733C708A9546B00998B17 /* Build configuration list for PBXNativeTarget "Subler" */ = {
|
||||
C05733C708A9546B00998B17 /* Build configuration list for PBXNativeTarget "SublerMKV" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
C05733C808A9546B00998B17 /* Debug */,
|
||||
@@ -1812,25 +1845,6 @@
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
|
||||
/* Begin XCRemoteSwiftPackageReference section */
|
||||
A9405AF0275E282500776561 /* XCRemoteSwiftPackageReference "Sparkle" */ = {
|
||||
isa = XCRemoteSwiftPackageReference;
|
||||
repositoryURL = "https://github.com/sparkle-project/Sparkle";
|
||||
requirement = {
|
||||
kind = exactVersion;
|
||||
version = 2.9.6;
|
||||
};
|
||||
};
|
||||
/* End XCRemoteSwiftPackageReference section */
|
||||
|
||||
/* Begin XCSwiftPackageProductDependency section */
|
||||
A9405AF1275E282500776561 /* Sparkle */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = A9405AF0275E282500776561 /* XCRemoteSwiftPackageReference "Sparkle" */;
|
||||
productName = Sparkle;
|
||||
};
|
||||
/* End XCSwiftPackageProductDependency section */
|
||||
};
|
||||
rootObject = 2A37F4A9FDCFA73011CA2CEA /* Project object */;
|
||||
}
|
||||
@@ -20,6 +20,10 @@ if ($file->isTVshow()) {
|
||||
} elsif ($file->isMovie()) {
|
||||
print "movie" . "\n";
|
||||
print $file->{movie} . "\n";
|
||||
if (defined $file->{imdb}) {
|
||||
my $idkind = defined $file->{idkind} ? $file->{idkind} : "";
|
||||
print "id:" . $idkind . ":" . $file->{imdb} . "\n";
|
||||
}
|
||||
} else {
|
||||
print "unknown" . "\n";
|
||||
}
|
||||
|
||||
@@ -88,11 +88,11 @@ $VERSION = "0.35.1";
|
||||
},
|
||||
{ # Movie IMDB Support
|
||||
# Perl > v5.10
|
||||
re => '^(?<movie>.*?)?(?:[\/\s._-]*(?<openb>\[)?(?<year>(?:19|20)\d{2})(?(<openb>)\]))?(?:[\/\s._-]*(?<openc>\[)?(?:(?:imdb|tt)[\s._-]*)*(?<imdb>\d{7})(?(<openc>)\]))(?:[\s._-]*(?<title>[^\/]+?))?$',
|
||||
re => '^(?<movie>.*?)?(?:[\/\s._-]*(?<openb>[\[(])?(?<year>(?:19|20)\d{2})(?(<openb>)[\])]))?(?:[\/\s._-]*(?<openc>[\[{])?(?:(?<idkind>imdb|tmdb|tvdb|tt)[\s._-]*)*(?<imdb>\d{7,9})(?(<openc>)[\]}]))(?:[\s._-]*(?<title>[^\/]+?))?$',
|
||||
|
||||
# Perl < v5.10
|
||||
re_compat => '^(.*?)?(?:[\/\s._-]*\[?((?:19|20)\d{2})\]?)?(?:[\/\s._-]*\[?(?:(?:imdb|tt)[\s._-]*)*(\d{7})\]?)(?:[\s._-]*([^\/]+?))?$',
|
||||
keys_compat => [qw(movie year imdb title)],
|
||||
re_compat => '^(.*?)?(?:[\/\s._-]*[\[(]?((?:19|20)\d{2})[\])])?(?:[\/\s._-]*[\[{]?(?:(imdb|tmdb|tvdb|tt)[\s._-]*)*(\d{7,9})[\]}]?)(?:[\s._-]*([^\/]+?))?$',
|
||||
keys_compat => [qw(movie year idkind imdb title)],
|
||||
|
||||
test_funcs => [0, 0, 0, 1], # DVD TV Episode Movie
|
||||
test_keys => [qw(filename movie guess-movie year imdb title ext)],
|
||||
@@ -113,6 +113,12 @@ $VERSION = "0.35.1";
|
||||
['tt0096657.mov', undef, undef, undef, '0096657', undef, 'mov'],
|
||||
['tt0096857', undef, undef, undef, '0096857', undef, undef],
|
||||
['1234576', undef, undef, undef, '1234576', undef, undef],
|
||||
['The Point Pleasant Tapes (2024) {tmdb-1015812}.mp4', 'The Point Pleasant Tapes', undef, 2024, 1015812, undef, 'mp4'],
|
||||
['Some Movie (2024) {imdb-tt1234567}.mkv', 'Some Movie', undef, 2024, 1234567, undef, 'mkv'],
|
||||
['Some Movie (2024) {tvdb-1234567}.mkv', 'Some Movie', undef, 2024, 1234567, undef, 'mkv'],
|
||||
['Some.Movie.{tmdb-1015812}.mkv', 'Some.Movie', undef, undef, 1015812, undef, 'mkv'],
|
||||
['The Matrix (1999) {imdb-tt0133093}.mkv', 'The Matrix', undef, 1999, '0133093', undef, 'mkv'],
|
||||
['Dune: Part Two (2024) {imdb-tt15239678}.mp4', 'Dune: Part Two', undef, 2024, '15239678', undef, 'mp4'],
|
||||
],
|
||||
#warning => 'Found year instead of season+episode',
|
||||
},
|
||||
|
||||
Executable
+377
@@ -0,0 +1,377 @@
|
||||
#!/bin/bash
|
||||
|
||||
trap 'rc=$? ; rm -f /tmp/*.$$ ; exit "${rc}"' 0 1 2 3 13 15
|
||||
|
||||
# --- options ---------------------------------------------------------------
|
||||
# --all, -a extract subtitle tracks in every language
|
||||
# (default) English tracks only
|
||||
# -h, --help show usage and exit
|
||||
|
||||
lang_mode="eng"
|
||||
input=""
|
||||
while [ "$#" -gt 0 ]
|
||||
do
|
||||
case "${1}" in
|
||||
--all|-a)
|
||||
lang_mode="all"
|
||||
;;
|
||||
-h|--help)
|
||||
printf 'usage: extractsubs [--all|-a] <media-file>\n (default: English tracks only)\n' >&2
|
||||
exit 0
|
||||
;;
|
||||
-*)
|
||||
printf 'unknown option: %s\n' "${1}" >&2
|
||||
exit 1
|
||||
;;
|
||||
*)
|
||||
[ -z "${input}" ] && input="${1}"
|
||||
;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
if [ -z "${input}" ]
|
||||
then
|
||||
printf 'usage: extractsubs [--all|-a] <media-file>\n (default: English tracks only)\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# --- dependency checks ------------------------------------------------------
|
||||
# ffprobe and ffmpeg must be on PATH (sup2vob too, or it is taken from the
|
||||
# Subler.app bundle beside this script), and the ffmpeg build must
|
||||
# include muxers for every extension stage 2 can write ("sup" is the one
|
||||
# minimal builds strip). Check up front so a missing or broken tool prints a
|
||||
# clear message and exits 1 instead of failing per track mid-pipeline.
|
||||
# (--help has already exited, so these run only for real jobs.)
|
||||
|
||||
die()
|
||||
{
|
||||
printf 'extractsubs: %s\n' "${1}" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
missing=()
|
||||
for tool in ffprobe ffmpeg
|
||||
do
|
||||
command -v "${tool}" >/dev/null 2>&1 || missing+=("${tool}")
|
||||
done
|
||||
|
||||
# sup2vob is looked up on PATH first (a `make install` copy, or a symlink to
|
||||
# the one bundled with Subler.app), then as this script's bundle sibling:
|
||||
# the app build compiles sup2vob into Contents/MacOS beside this script's
|
||||
# Contents/Resources home, so running the bundled script needs no install.
|
||||
|
||||
sup2vob_bin=""
|
||||
if command -v sup2vob >/dev/null 2>&1
|
||||
then
|
||||
sup2vob_bin="sup2vob"
|
||||
else
|
||||
sibling="$(dirname "$0")/../MacOS/sup2vob"
|
||||
[ -x "${sibling}" ] && sup2vob_bin="${sibling}"
|
||||
fi
|
||||
[ -n "${sup2vob_bin}" ] || missing+=("sup2vob")
|
||||
|
||||
if [ "${#missing[@]}" -gt 0 ]
|
||||
then
|
||||
printf 'extractsubs: missing dependency on PATH: %s\n' "${missing[*]}" >&2
|
||||
for tool in "${missing[@]}"
|
||||
do
|
||||
case "${tool}" in
|
||||
ffprobe)
|
||||
printf ' ffprobe ships with ffmpeg: e.g. brew install ffmpeg\n' >&2
|
||||
;;
|
||||
ffmpeg)
|
||||
printf ' e.g. brew install ffmpeg\n' >&2
|
||||
;;
|
||||
sup2vob)
|
||||
printf ' build and install it: cd MP42Foundation/sup2vob && make && sudo make install\n' >&2
|
||||
printf ' (or run the copy bundled in Subler.app/Contents/Resources — the app\n' >&2
|
||||
printf ' carries sup2vob at Contents/MacOS/sup2vob and needs no install)\n' >&2
|
||||
;;
|
||||
esac
|
||||
done
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Found is not enough — a broken install (bad arch, half-updated Homebrew)
|
||||
# must fail here too, so give each tool a cheap smoke run.
|
||||
|
||||
ffprobe -version >/dev/null 2>&1 || die "ffprobe is on PATH but does not run (ffprobe -version failed)"
|
||||
ffmpeg -version >/dev/null 2>&1 || die "ffmpeg is on PATH but does not run (ffmpeg -version failed)"
|
||||
"${sup2vob_bin}" --help >/dev/null 2>&1 || die "sup2vob (${sup2vob_bin}) does not run (${sup2vob_bin} --help failed)"
|
||||
|
||||
# Feature check: ffmpeg must be able to mux every format stage 2 can write —
|
||||
# "sup" for pgs, "srt", "ass" and "webvtt" for text. There is no "ssa" muxer
|
||||
# to check: the "ass" muxer declares extensions "ass,ssa" (assenc.c
|
||||
# .p.extensions — :241 in the subs/ffmpeg master clone, :234 in old 4.2.4)
|
||||
# and picks SSA mode from the extradata, so .ssa rides on ass.
|
||||
# (ttf/otf/unknown_type have never had a muxer and still fail per-track as
|
||||
# before.) In the "ffmpeg -muxers" list the flag column reads D/E/d — E means
|
||||
# muxing supported — and the format name follows it; -h muxer=x cannot be
|
||||
# used because it exits 0 even for unknown names.
|
||||
|
||||
muxout=$( ffmpeg -hide_banner -muxers 2>/dev/null )
|
||||
muxfail=()
|
||||
for muxer in sup srt ass webvtt
|
||||
do
|
||||
printf '%s\n' "${muxout}" | awk -v m="${muxer}" \
|
||||
'$1 ~ /E/ && $2 == m { found = 1 } END { exit !found }' \
|
||||
|| muxfail+=("${muxer}")
|
||||
done
|
||||
if [ "${#muxfail[@]}" -gt 0 ]
|
||||
then
|
||||
die "this ffmpeg build cannot write: ${muxfail[*]} (needs muxers sup/srt/ass/webvtt; .ssa rides on ass)"
|
||||
fi
|
||||
|
||||
ffprobe "${input}" 2>&1 | grep Stream | grep "Subtitle:" | while read line
|
||||
do
|
||||
# The "Stream #0:3(eng):" prefix carries the track number and, when present,
|
||||
# the language code in parentheses. Tracks without a language code get "und"
|
||||
# (undetermined), e.g. "Stream #0:2: Subtitle: ass (ssa)".
|
||||
|
||||
idpart=$( echo "${line}" | cut -f 2 -d ':' )
|
||||
tracknum=$( echo "${idpart}" | egrep -o "^[0-9]+" )
|
||||
lang=$( echo "${idpart}" | sed -n 's/.*(\([^)]*\)).*/\1/p' )
|
||||
[ -z "${lang}" ] && lang="und"
|
||||
type=$( echo "${line}" | awk '{ print $4;}' )
|
||||
|
||||
case "${type}"
|
||||
in
|
||||
"hdmv_pgs_subtitle" | "hdmv_pgs_subtitle,")
|
||||
ext="sup"
|
||||
;;
|
||||
"subrip")
|
||||
ext="srt"
|
||||
;;
|
||||
"dvd_subtitle" | "dvd_subtitle,")
|
||||
ext="sub"
|
||||
;;
|
||||
"ass")
|
||||
ext="ass"
|
||||
;;
|
||||
"ssa")
|
||||
ext="ssa"
|
||||
;;
|
||||
"webvtt" | "webvtt,")
|
||||
ext="vtt"
|
||||
;;
|
||||
"ttf")
|
||||
ext="ttf"
|
||||
;;
|
||||
"otf")
|
||||
ext="otf"
|
||||
;;
|
||||
*)
|
||||
ext="unknown_type"
|
||||
;;
|
||||
esac
|
||||
|
||||
# English tracks only by default; --all emits every language. "en" and "eng"
|
||||
# are both the English code (2- vs 3-letter forms, e.g. DVD vs Blu-ray).
|
||||
|
||||
if [ "${lang_mode}" = "all" ] || [ "${lang}" = "eng" ] || [ "${lang}" = "en" ]
|
||||
then
|
||||
# Descriptive tags such as "hearing impaired", "comment", or "forced"
|
||||
# appear in parentheses after the codec's own extra-info paren (e.g.
|
||||
# "(pgssub)" or "(srt)"). Collect every tag after that first paren,
|
||||
# lowercase them and squash spaces/'.'/'-' to "_", then map the whole
|
||||
# set onto ONE short type token in the importer's closed set
|
||||
# (sdh, cc, commentary, lyrics, forced), trying its priority order
|
||||
# SDH > CC > Commentary > Lyrics > Forced. Tags that match nothing
|
||||
# ("default", a bare "caption"/"subtitle", unknown flags) emit no
|
||||
# type token — the track imports unnamed, which is what the importer
|
||||
# does with an unrecognized token anyway. The bucket patterns cover
|
||||
# the importer's own token table ("visual impaired" rides the
|
||||
# impaired pattern into sdh, matching its bare-"impaired" row) plus
|
||||
# ffprobe's flag spellings: its "comment" flag (the MKV comment
|
||||
# flag) means commentary, and the importer knows "commentary" but
|
||||
# not "comment".
|
||||
|
||||
tags=$( printf '%s' "${line}" | sed 's/.*: Subtitle: *//' \
|
||||
| grep -oE '\([^)]+\)' | sed '1d; s/[()]//g' | paste -sd' ' - \
|
||||
| tr '[:upper:]' '[:lower:]' | tr ' .-' '_' )
|
||||
|
||||
subtype=""
|
||||
case "_${tags}_" in
|
||||
*_sdh_* | *_impaired_* | *_deaf_* | *_hearingimpaired_*)
|
||||
subtype="sdh"
|
||||
;;
|
||||
*_cc_* | *_closed_caption_* | *_closed_captions_* \
|
||||
| *_closedcaption_* | *_closedcaptions_*)
|
||||
subtype="cc"
|
||||
;;
|
||||
*_commentary_* | *_commentaries_* | *_comment_*)
|
||||
subtype="commentary"
|
||||
;;
|
||||
*_lyrics_* | *_lyric_*)
|
||||
subtype="lyrics"
|
||||
;;
|
||||
*_forced_*)
|
||||
subtype="forced"
|
||||
;;
|
||||
esac
|
||||
|
||||
# Naming shape the importer probes: language LAST (right before the
|
||||
# extension — the position it scans first, right-to-left) and the
|
||||
# short type token immediately before it, as its own dot-separated
|
||||
# token, with the extension still trailing both:
|
||||
# <basename>.<tracknum>[.<type>].<lang>.<ext> e.g. Movie.mkv.3.sdh.eng.sup
|
||||
|
||||
outname="$( basename "${input}" ).${tracknum}"
|
||||
[ -n "${subtype}" ] && outname="${outname}.${subtype}"
|
||||
outname="${outname}.${lang}.${ext}"
|
||||
# Temp line format: <tracknum>:<tool>:<outname>; <tool> is "ff"
|
||||
# (extract with ffmpeg) or "mkv" (extract with mkvextract, where
|
||||
# <tracknum> is then the MKV track *ID* mkvextract wants, not the
|
||||
# ffprobe index). Split with %%:* / #*: — never with cut/word
|
||||
# splitting, the name may contain spaces.
|
||||
echo "${tracknum}:ff:${outname}"
|
||||
fi
|
||||
done > /tmp/extractsubs.$$
|
||||
|
||||
# --- unrecognized-codec WebVTT rescue ----------------------------------------
|
||||
# WebVTT-in-MKV exists under two codec IDs: the WebM-profile "D_WEBVTT/*"
|
||||
# (which ffprobe reports as type "webvtt" and ffmpeg copies fine — handled
|
||||
# above), and the current Matroska-spec "S_TEXT/WEBVTT" that recent
|
||||
# mkvtoolnix writes. ffmpeg 9.1 and the master clone map ONLY D_WEBVTT/*
|
||||
# (matroska.c has no S_TEXT/WEBVTT entry), so such a track shows up as
|
||||
# "Subtitle: none" -> unknown_type here, and ffmpeg emits no packets for it
|
||||
# at all — no extension or mapping change can make the ffmpeg path work.
|
||||
# If mkvtoolnix is available, ask mkvmerge which unrecognized tracks really
|
||||
# are WebVTT and route those to mkvextract (it reconstructs the "WEBVTT"
|
||||
# header from the track's CodecPrivate).
|
||||
#
|
||||
# Mapping between the two tools: ffprobe's "#0:N" index is the track's
|
||||
# position in the file (0-based); mkvmerge's properties."number" is the same
|
||||
# position (1-based), while its "id" is the raw TrackNumber mkvextract
|
||||
# selects by — the two coincide only when IDs are sequential.
|
||||
|
||||
if grep -q '\.unknown_type$' /tmp/extractsubs.$$
|
||||
then
|
||||
if command -v mkvmerge >/dev/null 2>&1 && command -v mkvextract >/dev/null 2>&1 \
|
||||
&& command -v python3 >/dev/null 2>&1
|
||||
then
|
||||
vttmap=$( mkvmerge -J "${input}" 2>/dev/null | python3 -c '
|
||||
import json, sys
|
||||
try:
|
||||
info = json.load(sys.stdin)
|
||||
except Exception:
|
||||
sys.exit(1)
|
||||
for t in info.get("tracks", []):
|
||||
cid = t.get("properties", {}).get("codec_id", "")
|
||||
if t.get("type") == "subtitles" and "WEBVTT" in cid.upper():
|
||||
print(t["properties"]["number"], t["id"])' )
|
||||
if [ -n "${vttmap}" ]
|
||||
then
|
||||
newlist="/tmp/extractsubs.new.$$"
|
||||
while IFS= read -r line
|
||||
do
|
||||
case "${line}" in
|
||||
*.unknown_type)
|
||||
tracknum="${line%%:*}"
|
||||
outname="${line#*:}"; outname="${outname#*:}"
|
||||
mkvid=$( printf '%s\n' "${vttmap}" | awk \
|
||||
-v n=$(( tracknum + 1 )) '$1 == n { print $2 }' )
|
||||
if [ -n "${mkvid}" ]
|
||||
then
|
||||
outname="${outname%.unknown_type}.vtt"
|
||||
line="${mkvid}:mkv:${outname}"
|
||||
printf 'track %s is WebVTT (ffmpeg cannot read its codec id); extracting via mkvextract\n' \
|
||||
"${tracknum}" >&2
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
printf '%s\n' "${line}"
|
||||
done < /tmp/extractsubs.$$ > "${newlist}"
|
||||
mv "${newlist}" /tmp/extractsubs.$$
|
||||
fi
|
||||
else
|
||||
printf 'extractsubs: unrecognized subtitle codec(s); install mkvtoolnix and python3 to check whether they are WebVTT\n' >&2
|
||||
fi
|
||||
fi
|
||||
|
||||
# Read the temp file one line at a time into an array, then split each entry
|
||||
# with parameter expansion (no word-splitting of the whole list). That is what
|
||||
# lets the output filename match the input, spaces included.
|
||||
|
||||
subargs=()
|
||||
while IFS= read -r line
|
||||
do
|
||||
subargs+=("${line}")
|
||||
done < /tmp/extractsubs.$$
|
||||
|
||||
# Extract the selected tracks with ffmpeg's stream copy in ONE invocation.
|
||||
# "0:N" maps the same global stream index ffprobe reported in the "Stream #0:N"
|
||||
# prefix, so the track numbers line up without translation, and "-c copy"
|
||||
# writes each track bit-for-bit (no re-encode) into whatever the output
|
||||
# extension promises. Repeating "-map ... -c copy <out>" adds another output
|
||||
# file, and ffmpeg demuxes the input once for all of them — the old one-call-
|
||||
# per-track loop reopened and re-read the whole file each time. Outputs are
|
||||
# byte-identical either way (verified with cmp on a four-PGS-track remux);
|
||||
# measured 3.5 s combined vs 13.6 s per-track. The trade is failure isolation:
|
||||
# if one output cannot initialize, ffmpeg aborts all of them — so the
|
||||
# per-track loop remains as a retry path.
|
||||
|
||||
if [ "${#subargs[@]}" -gt 0 ]
|
||||
then
|
||||
ffargs=( -nostdin -hide_banner -loglevel error -y -i "${input}" )
|
||||
selected=()
|
||||
for trackfile in "${subargs[@]}"
|
||||
do
|
||||
tracknum="${trackfile%%:*}"
|
||||
rest="${trackfile#*:}"
|
||||
tool="${rest%%:*}"
|
||||
outname="${rest#*:}"
|
||||
|
||||
# FFmpeg has no VobSub muxer, so dvd_subtitle tracks cannot be written
|
||||
# as .sub; say so and carry on with the remaining tracks.
|
||||
|
||||
case "${outname}" in
|
||||
*.sub)
|
||||
printf 'skipping track %s (%s): ffmpeg cannot write VobSub .sub\n' \
|
||||
"${tracknum}" "${outname}" >&2
|
||||
continue
|
||||
;;
|
||||
esac
|
||||
|
||||
# S_TEXT/WEBVTT tracks (see the rescue pass above): ffmpeg cannot even
|
||||
# demux them, so run mkvextract per track right away instead of adding
|
||||
# them to the combined call. "tracks <ID>:<out>" selects by raw MKV
|
||||
# track ID, which is what <tracknum> holds for these lines.
|
||||
|
||||
if [ "${tool}" = "mkv" ]
|
||||
then
|
||||
printf 'extracting track %s as %s (mkvextract)\n' "${tracknum}" "${outname}" >&2
|
||||
mkvextract -q "${input}" tracks "${tracknum}:${outname}" \
|
||||
|| printf 'failed to extract track %s (%s)\n' \
|
||||
"${tracknum}" "${outname}" >&2
|
||||
continue
|
||||
fi
|
||||
|
||||
printf 'extracting track %s as %s\n' "${tracknum}" "${outname}" >&2
|
||||
ffargs+=( -map "0:${tracknum}" -c copy "${outname}" )
|
||||
selected+=( "${trackfile}" )
|
||||
done
|
||||
|
||||
if [ "${#selected[@]}" -gt 0 ] && ! ffmpeg "${ffargs[@]}"
|
||||
then
|
||||
printf 'combined extraction failed; retrying one track at a time\n' >&2
|
||||
for trackfile in "${selected[@]}"
|
||||
do
|
||||
tracknum="${trackfile%%:*}"
|
||||
outname="${trackfile#*:}"; outname="${outname#*:}"
|
||||
ffmpeg -nostdin -hide_banner -loglevel error -y \
|
||||
-i "${input}" -map "0:${tracknum}" -c copy "${outname}" \
|
||||
|| printf 'failed to extract track %s (%s)\n' \
|
||||
"${tracknum}" "${outname}" >&2
|
||||
done
|
||||
fi
|
||||
fi
|
||||
|
||||
# Convert every extracted .sup into a .sub with BDSup2Sub. (Temp lines are
|
||||
# <tracknum>:<tool>:<outname>, so the name starts at field 3.)
|
||||
cat /tmp/extractsubs.$$ | egrep "\.sup$" | cut -f 3- -d ':' | while IFS= read -r supfile
|
||||
do
|
||||
[ -z "${supfile}" ] && continue
|
||||
"${sup2vob_bin}" --full "${supfile}"
|
||||
done
|
||||
Executable
+22
@@ -0,0 +1,22 @@
|
||||
#!/bin/bash
|
||||
# Personal Release build. NOT a distribution build.
|
||||
#
|
||||
# Upstream's project settings enable the hardened runtime with no Team ID,
|
||||
# which (ad-hoc signed) makes dyld's library validation kill the app over its
|
||||
# own embedded MP42Foundation.framework. ENABLE_HARDENED_RUNTIME=NO restores
|
||||
# the Debug-style behavior that actually runs locally. Part of the repo so
|
||||
# every machine gets the same local-release recipe.
|
||||
set -euo pipefail
|
||||
ROOT="$(cd "$(dirname "$0")" && pwd)"
|
||||
|
||||
xcodebuild -project "$ROOT/MP42Foundation/MP42Foundation.xcodeproj" \
|
||||
-scheme MP42Foundation -configuration Release build \
|
||||
SYMROOT="$ROOT/MP42Foundation/Build/Products" \
|
||||
ENABLE_HARDENED_RUNTIME=NO
|
||||
|
||||
xcodebuild -project "$ROOT/Subler.xcodeproj" \
|
||||
-scheme Subler -configuration Release build \
|
||||
SYMROOT="$ROOT/Build/Products" \
|
||||
ENABLE_HARDENED_RUNTIME=NO
|
||||
|
||||
echo "Done: $ROOT/Build/Products/Release/SublerMKV.app"
|
||||
@@ -266,6 +266,7 @@ Undo tag insert. */
|
||||
"Insert" = "insertar";
|
||||
|
||||
/* Toolbar */
|
||||
"Insert a chapter" = "Insertar un capítulo";
|
||||
"Insert a chapter every" = "Insertar un capítulo cada";
|
||||
|
||||
/* color profile */
|
||||
@@ -614,6 +615,7 @@ Toolbar */
|
||||
|
||||
/* File Import action menu item. */
|
||||
"Tx3g" = "Tx3g";
|
||||
"VobSub" = "VobSub";
|
||||
|
||||
/* color profile */
|
||||
"Undefined (2-2-2)" = "No definido (2-2-2)";
|
||||
|
||||
@@ -193,8 +193,6 @@
|
||||
/* Class = "NSMenuItem"; title = "Optimize"; ObjectID = "451"; */
|
||||
"451.title" = "Optimizar";
|
||||
|
||||
/* Class = "NSMenuItem"; title = "Check for Updates…"; ObjectID = "529"; */
|
||||
"529.title" = "Buscar actualizaciones…";
|
||||
|
||||
/* Class = "NSMenuItem"; title = "Import"; ObjectID = "544"; */
|
||||
"544.title" = "Importar";
|
||||
|
||||
@@ -249,6 +249,7 @@ Undo tag insert. */
|
||||
"Insert" = "Insérer";
|
||||
|
||||
/* Toolbar */
|
||||
"Insert a chapter" = "Insérer un chapitre";
|
||||
"Insert a chapter every" = "Insérer un chapitre à chaque";
|
||||
|
||||
/* nil */
|
||||
@@ -558,6 +559,7 @@ Toolbar */
|
||||
|
||||
/* File Import action menu item. */
|
||||
"Tx3g" = "Tx3g";
|
||||
"VobSub" = "VobSub";
|
||||
|
||||
/* No comment provided by engineer. */
|
||||
"Unknown" = "Inconnu";
|
||||
|
||||
@@ -193,8 +193,6 @@
|
||||
/* Class = "NSMenuItem"; title = "Optimize"; ObjectID = "451"; */
|
||||
"451.title" = "Optimiser";
|
||||
|
||||
/* Class = "NSMenuItem"; title = "Check for Updates…"; ObjectID = "529"; */
|
||||
"529.title" = "Vérifier les mises à jour ...";
|
||||
|
||||
/* Class = "NSMenuItem"; title = "Import"; ObjectID = "544"; */
|
||||
"544.title" = "Importer";
|
||||
|
||||
@@ -251,6 +251,7 @@ Enable subtitles track local description */
|
||||
"Import tracks from external files" = "Importa le tracce da un file esterno";
|
||||
|
||||
/* Toolbar */
|
||||
"Insert a chapter" = "Inserisci un capitolo";
|
||||
"Insert a chapter every" = "Inserisci un capitolo ogni";
|
||||
|
||||
/* color profile */
|
||||
@@ -593,6 +594,7 @@ Toolbar */
|
||||
|
||||
/* File Import action menu item. */
|
||||
"Tx3g" = "Tx3g";
|
||||
"VobSub" = "VobSub";
|
||||
|
||||
/* color profile */
|
||||
"Undefined (2-2-2)" = "Non definito (2-2-2)";
|
||||
|
||||
@@ -193,8 +193,6 @@
|
||||
/* Class = "NSMenuItem"; title = "Optimize"; ObjectID = "451"; */
|
||||
"451.title" = "Ottimizza";
|
||||
|
||||
/* Class = "NSMenuItem"; title = "Check for Updates…"; ObjectID = "529"; */
|
||||
"529.title" = "Ricerca aggiornamenti…";
|
||||
|
||||
/* Class = "NSMenuItem"; title = "Import"; ObjectID = "544"; */
|
||||
"544.title" = "Importa";
|
||||
|
||||
@@ -266,6 +266,7 @@ Undo tag insert. */
|
||||
"Insert" = "Inserir";
|
||||
|
||||
/* Toolbar */
|
||||
"Insert a chapter" = "Inserir um capítulo";
|
||||
"Insert a chapter every" = "Inserir um Capítulo a Cada";
|
||||
|
||||
/* color profile */
|
||||
@@ -614,6 +615,7 @@ Toolbar */
|
||||
|
||||
/* File Import action menu item. */
|
||||
"Tx3g" = "Tx3g";
|
||||
"VobSub" = "VobSub";
|
||||
|
||||
/* color profile */
|
||||
"Undefined (2-2-2)" = "Indefinido (2-2-2)";
|
||||
|
||||
@@ -193,8 +193,6 @@
|
||||
/* Class = "NSMenuItem"; title = "Optimize"; ObjectID = "451"; */
|
||||
"451.title" = "Otimizar";
|
||||
|
||||
/* Class = "NSMenuItem"; title = "Check for Updates…"; ObjectID = "529"; */
|
||||
"529.title" = "Buscar Atualizações…";
|
||||
|
||||
/* Class = "NSMenuItem"; title = "Import"; ObjectID = "544"; */
|
||||
"544.title" = "Importar";
|
||||
|
||||
@@ -237,6 +237,7 @@ Undo tag insert. */
|
||||
"Insert" = "插入";
|
||||
|
||||
/* Toolbar */
|
||||
"Insert a chapter" = "插入一个章节标记";
|
||||
"Insert a chapter every" = "插入章节标记 每隔";
|
||||
|
||||
/* nil */
|
||||
@@ -534,6 +535,7 @@ Toolbar */
|
||||
|
||||
/* File Import action menu item. */
|
||||
"Tx3g" = "Tx3g";
|
||||
"VobSub" = "VobSub";
|
||||
|
||||
/* No comment provided by engineer. */
|
||||
"Unknown" = "未知";
|
||||
|
||||
@@ -193,8 +193,6 @@
|
||||
/* Class = "NSMenuItem"; title = "Optimize"; ObjectID = "451"; */
|
||||
"451.title" = "优化";
|
||||
|
||||
/* Class = "NSMenuItem"; title = "Check for Updates…"; ObjectID = "529"; */
|
||||
"529.title" = "检查更新…";
|
||||
|
||||
/* Class = "NSMenuItem"; title = "Import"; ObjectID = "544"; */
|
||||
"544.title" = "导入";
|
||||
|
||||
@@ -237,6 +237,7 @@
|
||||
"Insert" = "插入";
|
||||
|
||||
/* Toolbar */
|
||||
"Insert a chapter" = "插入一个章节标记";
|
||||
"Insert a chapter every" = "插入章节标记 每隔";
|
||||
|
||||
/* No comment provided by engineer. */
|
||||
@@ -537,6 +538,7 @@
|
||||
|
||||
/* File Import action menu item. */
|
||||
"Tx3g" = "Tx3g";
|
||||
"VobSub" = "VobSub";
|
||||
|
||||
/* No comment provided by engineer. */
|
||||
"Unknown" = "未知";
|
||||
|
||||
@@ -199,8 +199,6 @@
|
||||
/* Class = "NSMenuItem"; title = "Optimize"; ObjectID = "451"; */
|
||||
"451.title" = "优化";
|
||||
|
||||
/* Class = "NSMenuItem"; title = "Check for Updates…"; ObjectID = "529"; */
|
||||
"529.title" = "检查更新…";
|
||||
|
||||
/* Class = "NSMenuItem"; title = "Import"; ObjectID = "544"; */
|
||||
"544.title" = "导入";
|
||||
|
||||
Reference in new issue
Block a user