60 Commits
Author SHA1 Message Date
Scott GarrettandClaude Code a153763019 Stamp the fork version 1.9.5mkv1 with a scheme for counting fork changes
The trailing counter in MARKETING_VERSION/CURRENT_PROJECT_VERSION now
counts batches of fork changes over a fixed upstream base (1.9.5), so
fork builds are distinguishable without pretending upstream released
it. Increment the counter with each committed batch; restart at 1 when
upstream's base version moves.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-29 20:58:15 -05:00
Scott GarrettandClaude Code 85d8ac6dcb Document queue parity and the rename; keep build-release.sh in the repo
CLAUDE.md and CHANGES.md record the shared MatroskaSaver, queue Matroska
semantics, the SublerMKV storage folder, and the module-name trap any
future rename must respect. build-release.sh (local Release build without
hardened runtime) loses its .git/info/exclude entry so it travels to every
machine, and its output line now names SublerMKV.app.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-29 20:34:24 -05:00
Scott GarrettandClaude Code 723db31fc0 Rename the build to SublerMKV.app, fully isolated from upstream
PRODUCT_NAME becomes SublerMKV (the interpolated bundle id follows to
org.galad.SublerMKV) and all Application Support data moves to its own
SublerMKV/ folder with the queue renamed queue.sbmkvqueue, so fork builds
and an installed upstream Subler.app never share prefs, files, or a
LaunchServices registration.

PRODUCT_MODULE_NAME stays pinned to "Subler" deliberately: XIB bindings
reference Swift classes module-qualified (Subler.LanguageTransformer), and
letting the module follow the product made the queue-options nib throw
"cannot find value transformer" mid-binding-load, freezing every checkbox
and popup in that window at XIB design state.

Queue.saveToDisk now creates its parent folder before the atomic write;
the write error is swallowed, so on a fresh install the queue would
otherwise silently never persist.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-29 20:34:24 -05:00
Scott GarrettandClaude Code 80ca3970ec Retag queued Matroska files in place instead of converting to MP4
The queue now mirrors the document window for .mkv/.mka/.mks sources.
The window's whole save branching (importer-order track snapshot, chapter
row snapshot, staleness guard, tag-writer-vs-remuxer choice) moved out of
Document into a shared MatroskaSaver used by both Document and QueueItem
so the two paths cannot drift. Queue items import tags-only, keep the
Matroska extension (in place, or stream-copy into a destination folder),
MP4-only actions no-op on them, and send-to-queue hands the item the
document's model plus its identity pairing baseline via attachMatroskaSaver.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-29 20:33:47 -05:00
Scott Garrett a1da1c8106 Added a CHANGES.md document to keep track of what I have changed since forking. 2026-11-29 14:27:08 -05:00
Scott GarrettandClaude Code 51112947fb Build sup2vob into the app bundle so it ships and stays fresh
A "Build sup2vob CLI" run-script phase on the Subler target runs the
submodule's Makefile (incremental — a no-op unless the conversion
sources changed) and installs the product to Contents/MacOS/sup2vob.
Every Subler build refreshes the CLI; a terminal sup2vob can be a
symlink into the bundle instead of a copied `make install`.

extractsubs finds that bundle-internal sup2vob automatically: PATH
first, then the script's own ../MacOS/sup2vob sibling, so running the
copy inside Subler.app/Contents/Resources works with no install at all
(verified with sup2vob absent from PATH: same 1920x1080 .sub/.idx).

The phase walks the source tree, so it opts the Subler target out of
ENABLE_USER_SCRIPT_SANDBOXING — a build-time shell-script file-access
setting only, no effect on the app's runtime security posture.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-28 23:25:40 -05:00
Scott GarrettandClaude Code 56d843c044 Document the slim sup2vob CLI in the submodule
MP42Foundation/sup2vob/ builds the CLI from the framework's vendored
Sup2Vob sources (one copy of the conversion code; the CLI --full output
stays the converter's byte-identical oracle), which is also where the
app-bundled extractsubs gets its sup2vob dependency from. Bumps the
submodule pointer.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-28 23:06:50 -05:00
Scott GarrettandClaude Code c08d607baa Ship the extractsubs subtitle-extraction helper with the app
extractsubs pulls the subtitle tracks out of mkv/mp4 files with ffmpeg
stream copy — .srt/.ass/.ssa/.vtt text, .sup for PGS (then converted to
.sub/.idx with sup2vob --full) — defaulting to English tracks, --all for
every language. Output names follow the shape the app's importers probe
(<input>.<track>[.<type>].<lang>.<ext>), so extracted files drag back
into Subler already named and tagged.

The script lives in Utilities/ beside ParseFilename and is copied into
the app bundle's Resources by the build (like ParseFilename, but nothing
in the app invokes it — it's for terminal use). Dependencies are checked
up front (ffprobe/ffmpeg/sup2vob on PATH; mkvtoolnix plus python3 only
for the S_TEXT/WEBVTT rescue path).

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-28 22:58:27 -05:00
Scott GarrettandClaude Code 87e0c82bbb Document the sup2vob full-frame passthrough for PGS conversions
PGS→VobSub output now keeps the source's PCS canvas (e.g. 1920x1080)
instead of the downscaled 720x480 DVD frame, on both the .sup drag and
the PGS-from-MKV paths. Bumps the MP42Foundation submodule.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-28 21:14:21 -05:00
Scott GarrettandClaude Code dd956fa783 Offer VobSub conversion for PGS subtitle tracks
The subtitle import sheet gains a VobSub action for PGS-format tracks
(default following the bitmap-subtitle conversion preference), which
muxes them as real subp tracks via the framework's new
MP42PgsToVobSubConverter instead of only offering OCR'd tx3g text.
Localized for all six shipping languages.

Also names any flagged subtitle track "SDH" (the recognized community
tokens now share one name) and documents the MKV conversion-path naming
and the PGS-to-VobSub machinery in CLAUDE.md.

Bumps the MP42Foundation submodule for the converter and the
filename/TrackName SDH recognizer.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-28 20:01:04 -05:00
Scott GarrettandClaude Code 5d6c0cd84c Add PGS .sup subtitle import and filename flag recognition
Bumps the MP42Foundation gitlink: sup2vob is vendored into the framework so .sup files import as muxable VobSub tracks, and the subtitle importers now read language and community type tokens (SDH/CC/Forced/...) out of filenames, naming tracks with the bare type per convention.

CLAUDE.md documents the .sup pipeline and the filename heuristics; README fixes the clone URLs to SublerMKV.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-28 18:18:37 -05:00
Scott GarrettandClaude Code e96773f3d0 Point the submodule and README at the public HTTPS URLs
Anonymous users can clone all three repos over HTTPS; the SSH clone URL
stays documented for contributors with push access.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-28 14:00:21 -05:00
Scott GarrettandClaude Code 475737a6ad Drop the Sparkle updater and stamp the fork version 1.9.5mkv
A standalone fork must not pull its updates from subler.org's appcast:
the feed serves upstream builds signed with the upstream Ed key, so the
whole integration goes — the Check for Updates menu item and the
SPUStandardUpdaterController, the SUFeedURL/SUAllowsAutomaticUpdates/
SUPublicEDKey Info.plist entries, their six localized titles, and the
Sparkle SPM package reference. The app now has no package dependencies.

Also captures the Xcode 27.2 settings migration (deployment target now
$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET), so plain xcodebuild works with
no CLI override — verified with a clean build), the 1.9.5mkv marketing
version, and the matching MP42Foundation submodule bump. README and
CLAUDE.md lose the now-stale Sparkle and 10.13 notes.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-28 13:54:31 -05:00
Scott GarrettandClaude Code 20438f310d Pull the contrib dependency from Gitea too
Bumps MP42Foundation to its .gitmodules rewrite and rewrites the build
docs: clone/update instructions for the nested submodules, the SSH key
prerequisite, and a note that Sparkle still comes from upstream via SPM.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-28 13:46:30 -05:00
Scott GarrettandClaude Code 628ccfefb5 Use the gitea SSH login in clone URLs
The Gitea SSH endpoint serves git under the "gitea" user, not "git"; the
retargeted submodule URL and README clone instructions must use it.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-28 13:34:00 -05:00
Scott GarrettandClaude Code 0f8d251391 Point the project at Gitea and document the fork
Rewrite the MP42Foundation submodule URL to the Scott-Files organization on
git.technomancer.com so a clone builds standalone, and rewrite the README to
describe the fork: native Matroska editing, VobSub frame-size muxing, and
file-name-embedded metadata ID lookup, on top of the upstream SublerApp tree.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-28 13:24:31 -05:00
Scott GarrettandClaude Code f20ad7ee45 Search metadata directly from IDs embedded in file names
ParseFilename's movie-IMDB pattern now recognizes parenthesized years and
brace-wrapped service IDs, so names like "Movie (2024) {tmdb-1015812}" no
longer truncate to "Movie (2024) {tmdb". The ID kind is captured (imdb,
tmdb, tvdb, tt; IDs widened to 7-9 digits for modern IMDb IDs) and
emitted as an "id:<kind>:<value>" line.

Parsed IDs ride along in MetadataSearchTerms.movie as a MetadataFileID.
TheMovieDB answers direct lookups (movie/{id} for TMDb IDs, find +
external_source=imdb_id for IMDb IDs) as a movieIDSearch; the search
sheet, the queue metadata action, and the AppleScript fetch-metadata
command try the direct lookup first and fall back to the title search
when the ID is unknown or the provider doesn't support it. Index-based
AppleScript result commands keep the name search by design.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-28 13:10:25 -05:00
Scott GarrettandClaude Code 401584a376 Mux added VobSub tracks at the frame size declared in the idx
Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-27 02:41:26 -05:00
Scott GarrettandClaude Code 06ecb0af5f Route AppleScript chapter imports and make File > Optimize work on MKV
importFilesDirectly mirrors the open panel's extension dispatch, so
AppleScript `import file` now sends .txt/.csv to addChapters/
updateChapters and everything else to FileImportController; the chapter
track created on an MKV doc gets the tags-only trackId/
updateChangeCount bookkeeping in didSelect(chapters:). searchChapters
moves to the always-valid validation group, though CLAUDE.md now
records that it is orphaned dead code with no UI entry point.

File > Optimize on a Matroska document forces writeMatroska's
structural branch: a full remuxer rebuild from the existing tracks,
the container-equivalent of atom-order optimize. Its validation uses
fileURL instead of hasFileRepresentation, which is always false for
tags-only models and kept the menu disabled forever.

Bump MP42Foundation for the tagsOnly importer fix that mirrors the
file's chapter atoms verbatim (offset first starts and tied zero
starts survive an edit); harness matrix PASS=324/0.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-26 19:14:59 -05:00
Scott GarrettandClaude Code f457b4e89c Make chapter tracks deletable, insertable, and language-editable
Delete: the phase-1 gate against deleting the chapter pseudo-track on
Matroska documents is obsolete now that chapter changes ride the
stream-copy remuxer — a removed pseudo-track simply makes the model
report "no chapters", which removes the Chapters element on save (the
same path emptying the Chapters tab already took). The toolbar Delete
button's validation is corrected too; it still rejected chapter-only
selections after deleteSelection was opened up.

Insert: the Actions toolbar gets a single "Insert a chapter" item, and
"Insert a chapter every" (previously MP4-only) is enabled on Matroska.
Both create the chapter track when the document has none, doing the
tags-only bookkeeping the model needs (dense display trackId,
updateChangeCount). A single insert lands 1s after the latest start,
clamped to the track duration, so it can never tie with a stored
chapter — ties get clamped +1ms on write and would silently shift the
user's own chapter times.

Language: the chapter row's language popup stays editable on MKV
documents (the value rides the remuxer's chapter rebuild, not the tag
writer, since the pseudo-track has no TrackEntry), and the Matroska
chapters snapshot carries it so a language-only edit triggers the
remux. Pairs with the submodule's ChapterLanguage round trip.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-26 18:17:37 -05:00
Scott GarrettandClaude Code 8520d729c6 Edit and add chapters in Matroska documents
The chapters tab leaves read-only jail on MKV docs: didSelect exempts
ChapterViewController from the tags-only blanket, and chapter-less docs
can gain chapters through the same txt/csv dispatch MP4 documents use
(selectFile's MKV branch and drag-drop now allow .txt/.csv alongside
the subtitle extensions; addChapters/updateChapters assign the display
trackId and flag the document dirty on MKV).

Chapter edits ride the remuxer, never the tag writer: Chapters sits
before the Clusters, so any size change shifts every following byte.
Document.mkvChaptersSnapshot holds the baseline rows and drives a
chaptersChanged check against the model (model-vs-model, because the
reader itself drops duplicate zero-timestamp atoms and those must not
look like user edits); when changed, remuxMatroska passes mp4.chapters
(or an empty track to delete every chapter) as the remuxer's
replacementChapters, then refreshes the snapshot so an untouched save
goes back to the byte-stable tag-writer path.

Verified live: add a chapter row in the UI, File>Save — the file gains
the atom (ties clamped to 1ms), mkvmerge/ffmpeg both read it, a
forced no-op re-save is byte-identical, and reopening shows all rows.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-26 12:54:58 -05:00
Scott GarrettandClaude Code 330236735d Add subtitle tracks to open Matroska documents
MKV docs can now import .srt/.ssa/.ass subtitle files, written as
S_TEXT/UTF8 by MP42MkvRemuxer (submodule bump). Video/audio adds and
other subtitle formats stay refused by both sides.

- DocumentWindowController: split selectFile: validation so MKV docs
  get an Import panel restricted to matroskaSubtitleExtensions (kept
  in sync with the remuxer's gate); showImportSheet routes MKV docs
  to importSubtitleTracksForMatroska, which imports each file with a
  plain MP42FileImporter (no track-selection sheet), attaches the
  conversion-settings defaults addTrack: asserts on, and assigns the
  next display trackId. Drag-drop already funnels through
  showImportSheet. didSelect skips
  organizeAlternateGroups/inferMediaCharacteristics on MKV docs —
  same TrackEntry-pairing protection as delete.
- Document: the tagsChanged check already caught additions; the
  post-remux snapshot now appends the added tracks behind the kept
  ones, matching the TrackEntry order in the written file, so a
  later tags-only save pairs correctly instead of double-appending.
- ScriptCommand: the AppleScript "save as" command called
  mp4.write(to:) directly, which muxed a QuickTime MP4 over a
  Matroska document. Route isMatroska documents through
  Document.save(saveAsOperation) so writeMatroska picks the
  tag-writer/remux path and enforces the mkv destination.

Verified with the /tmp/subler-mkv-test harness (matrix PASS=276: add
srt/ass, add+drop mix, no-cues source, bad-file and drop-all
refusals, idempotent re-save, post-add tag edit) and against the
live app (scripted import + save on a fixture copy; output checked
with mkvmerge/mkvextract/ffmpeg and reopened cleanly).

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-26 11:53:50 -05:00
Scott GarrettandClaude Code eb386a52c3 Open and edit Matroska files in place, including track removal
.mkv/.mka/.mks now open directly into a tags-only document instead of
forcing the convert-import sheet:

- Metadata, cover art, and the four per-track fields Matroska stores
  (name, language, enabled, subtitle forced) save back into the same
  file via MP42MkvTagWriter; MP4-only properties stay read-only.
- Real tracks can be deleted and Save-As is enabled; both go through
  MP42MkvRemuxer's stream-copy rebuild (Document keeps an importer-order
  track snapshot and pairs TrackEntry elements by object identity).
  Destinations must stay .mkv/.mka/.mks.
- Info.plist: the Matroska document type becomes Editor so NSDocument
  offers .mkv Save-As instead of defaulting to the MP4 type.
- Delete on MKV docs skips organizeAlternateGroups/
  inferMediaCharacteristics because they reorder the model, which the
  TrackEntry pairing depends on; chapter rows stay undeletable.

Bumps MP42Foundation for the Matroska tagging/remux support.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-25 19:48:34 -05:00
Damiano Galassi 0c3d7de364 Fix wobbling preference panels switch animation caused by macOS 27.2 2026-10-20 15:06:01 +02:00
Damiano Galassi 9077b6d149 Bump version to 1.9.5 2026-10-05 08:56:50 +02:00
Damiano Galassi a3e15e725a Update Italian localization 2026-10-05 08:16:39 +02:00
Damiano Galassi 839b47cd9e Update NEWS 2026-10-05 08:09:19 +02:00
Damiano Galassi b58346eda7 Improve selection restoration 2026-10-05 08:07:52 +02:00
Damiano Galassi 4c7a26a175 Move the 4k checkbox to the metadata preferences panel 2026-10-05 08:07:14 +02:00
Brett Pynn 85854a2f06 Add preference to allow 4k hd video metadata auto detection (#164) 2026-10-05 07:57:25 +02:00
Damiano Galassi a3f73cf1f8 Add missing classes to actions decoder
Fix #163.
2026-10-03 20:23:18 +02:00
Damiano Galassi a7739840ee Improve TVDB tv series name match 2026-10-03 20:17:52 +02:00
Damiano Galassi d0cd519460 Improve track view selection after an import 2026-10-03 17:59:29 +02:00
Damiano Galassi 1040f0dab6 Switch to the appropriate view after an action 2026-10-03 17:52:22 +02:00
Damiano Galassi dfdffb9332 Better preserve the UI state after an undo 2026-10-03 17:20:42 +02:00
Damiano Galassi 530ea2ed20 Use the newer actions icon on macOS 26 and later 2026-10-03 14:06:24 +02:00
Damiano Galassi 23f683626d Improve tracks and chapters undo 2026-10-03 14:06:06 +02:00
Damiano Galassi 934ae63b95 Expand undo/redo to all the document UI 2026-10-03 11:49:04 +02:00
Damiano Galassi 1cb5fb59dc Remove the '…' at the end of the 'Load more artworks' button 2026-10-01 10:55:11 +02:00
Damiano Galassi 81d5f8902c Add artworks in a deterministic order 2026-10-01 10:54:42 +02:00
Brett Pynn a48cb77aac Strip leading zeroes while preserving a real numeric zero (for example, S00 specials). (#160)
I always forget the regex syntax, so I can't really review the changes, but if it works…
2026-10-01 08:08:49 +02:00
Damiano Galassi d930bdb0a6 Do not retrieve the iTunes Store artworks when using a different provider
The iTunes Store API seems quite broken lately, and it doesn't add anything of value
2026-09-30 18:01:34 +02:00
Damiano Galassi 8c0d366764 Increase the default metadata search sheet width 2026-09-30 17:22:04 +02:00
Damiano Galassi 33a7665c5a Order the top artworks to make to make the various size options easier to pick 2026-09-30 17:21:35 +02:00
Damiano Galassi 43a768a187 Update NEWS 2026-09-30 12:05:56 +02:00
Damiano Galassi 8290bf7c52 Bump versio to 1.9.4 2026-09-30 11:57:24 +02:00
Damiano Galassi b250450966 Use the localized folder names 2026-09-30 11:55:48 +02:00
Damiano Galassi c84cfd47e3 Update localization 2026-09-30 11:48:22 +02:00
Damiano Galassi 53e46d8095 Update submodule 2026-09-30 11:40:50 +02:00
Damiano Galassi d9131ffc3b Update submodule 2026-09-29 16:19:20 +02:00
Damiano Galassi 0305d5371c Clean up project folder 2026-09-29 12:14:37 +02:00
Damiano Galassi 257e412987 Fix typos 2026-09-29 12:13:46 +02:00
Damiano Galassi 73e27ef56c Disable drag & drop for muxed tracks 2026-09-29 10:41:57 +02:00
Damiano Galassi 59f085a7e4 Rename the 'Last used' save position to 'Automatic'
It's not always the last used position
2026-09-25 07:50:06 +02:00
Damiano Galassi 40107a9db1 Fix the jpeg check on macOS 11 and later
Fix #151.
2026-09-25 07:48:42 +02:00
Damiano Galassi ce011a4d37 Cleanup the Save As destination feature a bit 2026-09-23 21:29:18 +02:00
mindprint c8fb950854 Add a Save As location preference (#145)
Add a General preferences option controlling where the Save As panel
opens: the last used folder (default), the same folder as the
imported file, or a custom folder chosen by the user.
2026-09-23 21:15:08 +02:00
Damiano Galassi 151530d6ab Fix things 2026-09-23 15:55:36 +02:00
Damiano Galassi 94255d6e17 Add an additional space in the default toolbar set 2026-09-23 15:55:17 +02:00
Damiano Galassi a65fcf9bf2 Set the document window to use fullSizeContentView to avoid AppKit bugs 2026-09-23 15:54:48 +02:00
82 changed files with 2847 additions and 672 deletions

No files matched your search

+1 -1
View File
@@ -1,3 +1,3 @@
[submodule "MP42Foundation"]
path = MP42Foundation
url = https://github.com/SublerApp/MP42Foundation.git
url = https://git.technomancer.com/Scott-Files/MP42Foundation.git
+12 -12
View File
@@ -1,8 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="24127" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES">
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="25098" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES">
<dependencies>
<deployment identifier="macosx"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="24127"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="25098"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
@@ -25,7 +25,7 @@
<autoresizingMask key="autoresizingMask"/>
<subviews>
<button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="fCL-eV-Fib">
<rect key="frame" x="436" y="13" width="122" height="32"/>
<rect key="frame" x="440" y="20" width="111" height="24"/>
<buttonCell key="cell" type="push" title="Set as artwork" bezelStyle="rounded" alignment="center" enabled="NO" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="rMb-PC-yTA">
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="system"/>
@@ -38,7 +38,7 @@ DQ
</connections>
</button>
<slider verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="fMj-Ew-Qej">
<rect key="frame" x="449" y="48" width="104" height="20"/>
<rect key="frame" x="451" y="54" width="100" height="18"/>
<constraints>
<constraint firstAttribute="width" constant="100" id="o7H-4a-ogx"/>
</constraints>
@@ -49,8 +49,8 @@ DQ
</connections>
</slider>
<button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="iH5-SJ-sDV">
<rect key="frame" x="13" y="13" width="159" height="32"/>
<buttonCell key="cell" type="push" title="Load more artwork..." bezelStyle="rounded" alignment="center" enabled="NO" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="40h-Rv-m31">
<rect key="frame" x="20" y="20" width="145" height="24"/>
<buttonCell key="cell" type="push" title="Load more artworks" bezelStyle="rounded" alignment="center" enabled="NO" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="40h-Rv-m31">
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="system"/>
<string key="keyEquivalent">l</string>
@@ -61,7 +61,7 @@ DQ
</connections>
</button>
<button horizontalHuggingPriority="249" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="Zyu-WY-ltM">
<rect key="frame" x="371" y="13" width="67" height="32"/>
<rect key="frame" x="371" y="20" width="57" height="24"/>
<buttonCell key="cell" type="push" title="None" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="UDG-fN-bQH">
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="system"/>
@@ -74,13 +74,13 @@ Gw
</connections>
</button>
<scrollView wantsLayer="YES" autohidesScrollers="YES" horizontalLineScroll="10" horizontalPageScroll="10" verticalLineScroll="10" verticalPageScroll="10" hasHorizontalScroller="NO" usesPredominantAxisScrolling="NO" translatesAutoresizingMaskIntoConstraints="NO" id="c0O-We-pZd">
<rect key="frame" x="20" y="74" width="531" height="461"/>
<rect key="frame" x="20" y="80" width="531" height="455"/>
<clipView key="contentView" id="cHe-z7-drT">
<rect key="frame" x="1" y="1" width="529" height="459"/>
<rect key="frame" x="1" y="1" width="529" height="453"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<collectionView selectable="YES" allowsMultipleSelection="YES" id="234-cJ-3Un" customClass="ArtworkCollectionView" customModule="Subler" customModuleProvider="target">
<rect key="frame" x="0.0" y="0.0" width="529" height="459"/>
<rect key="frame" x="0.0" y="0.0" width="529" height="453"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES"/>
<collectionViewFlowLayout key="collectionViewLayout" minimumInteritemSpacing="10" minimumLineSpacing="10" id="lte-fF-bVi">
<size key="itemSize" width="154" height="194"/>
@@ -99,14 +99,14 @@ Gw
<autoresizingMask key="autoresizingMask"/>
</scroller>
<scroller key="verticalScroller" hidden="YES" wantsLayer="YES" verticalHuggingPriority="750" horizontal="NO" id="nbX-9d-w82">
<rect key="frame" x="486" y="1" width="16" height="457"/>
<rect key="frame" x="513" y="1" width="17" height="453"/>
<autoresizingMask key="autoresizingMask"/>
</scroller>
</scrollView>
<progressIndicator hidden="YES" wantsLayer="YES" horizontalHuggingPriority="750" verticalHuggingPriority="750" maxValue="100" bezeled="NO" indeterminate="YES" controlSize="small" style="spinning" translatesAutoresizingMaskIntoConstraints="NO" id="AYL-Jp-agY">
<rect key="frame" x="20" y="20" width="16" height="16"/>
</progressIndicator>
<textField hidden="YES" horizontalHuggingPriority="249" verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="NEi-uU-Lh7">
<textField hidden="YES" focusRingType="none" horizontalHuggingPriority="249" verticalHuggingPriority="750" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="NEi-uU-Lh7">
<rect key="frame" x="41" y="21" width="86" height="14"/>
<textFieldCell key="cell" controlSize="small" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="Progress status" id="TbL-2H-ra9">
<font key="font" metaFont="smallSystem"/>
+82 -34
View File
@@ -1,13 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="24127" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="25098" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<dependencies>
<deployment identifier="macosx"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="24127"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="25098"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<customObject id="-2" userLabel="File's Owner" customClass="GeneralPrefsViewController" customModule="Subler" customModuleProvider="target">
<connections>
<outlet property="saveLocationPopUp" destination="saveLocationPopUp" id="saveLocationOutlet"/>
<outlet property="view" destination="76" id="u5x-9E-WAf"/>
</connections>
</customObject>
@@ -25,22 +26,22 @@
</declaredKeys>
</userDefaultsController>
<customView id="76">
<rect key="frame" x="0.0" y="0.0" width="660" height="328"/>
<rect key="frame" x="0.0" y="0.0" width="660" height="374"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<customView translatesAutoresizingMaskIntoConstraints="NO" id="dxI-5Q-gDD">
<rect key="frame" x="133" y="0.0" width="394" height="328"/>
<rect key="frame" x="132" y="0.0" width="397" height="374"/>
<subviews>
<textField horizontalHuggingPriority="251" verticalHuggingPriority="750" horizontalCompressionResistancePriority="754" translatesAutoresizingMaskIntoConstraints="NO" id="XPF-Mh-XYC">
<rect key="frame" x="147" y="156" width="57" height="14"/>
<textField focusRingType="none" horizontalHuggingPriority="251" verticalHuggingPriority="750" horizontalCompressionResistancePriority="754" translatesAutoresizingMaskIntoConstraints="NO" id="XPF-Mh-XYC">
<rect key="frame" x="152" y="172" width="57" height="14"/>
<textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="Beginning" id="3Vs-qA-7Z6">
<font key="font" metaFont="message" size="11"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
<textField verticalHuggingPriority="1000" verticalCompressionResistancePriority="752" translatesAutoresizingMaskIntoConstraints="NO" id="249">
<rect key="frame" x="129" y="110" width="165" height="14"/>
<textField focusRingType="none" verticalHuggingPriority="1000" verticalCompressionResistancePriority="752" translatesAutoresizingMaskIntoConstraints="NO" id="249">
<rect key="frame" x="134" y="122" width="165" height="14"/>
<textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="USA ratings are always shown." id="250">
<font key="font" metaFont="message" size="11"/>
<color key="textColor" name="secondaryLabelColor" catalog="System" colorSpace="catalog"/>
@@ -48,7 +49,7 @@
</textFieldCell>
</textField>
<button verticalHuggingPriority="1000" translatesAutoresizingMaskIntoConstraints="NO" id="133">
<rect key="frame" x="124" y="43" width="182" height="32"/>
<rect key="frame" x="136" y="54" width="172" height="24"/>
<buttonCell key="cell" type="push" title="Clear recent searches" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="134">
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="system"/>
@@ -58,7 +59,7 @@
</connections>
</button>
<button verticalHuggingPriority="1000" translatesAutoresizingMaskIntoConstraints="NO" id="80">
<rect key="frame" x="129" y="229" width="121" height="18"/>
<rect key="frame" x="136" y="276" width="117" height="16"/>
<buttonCell key="cell" type="check" title="Remember Size" bezelStyle="regularSquare" imagePosition="left" alignment="left" state="on" inset="2" id="86">
<behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/>
<font key="font" metaFont="system"/>
@@ -71,8 +72,8 @@
</binding>
</connections>
</button>
<textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="1000" translatesAutoresizingMaskIntoConstraints="NO" id="139">
<rect key="frame" x="18" y="53" width="107" height="16"/>
<textField focusRingType="none" verticalHuggingPriority="750" horizontalCompressionResistancePriority="1000" translatesAutoresizingMaskIntoConstraints="NO" id="139">
<rect key="frame" x="18" y="58" width="112" height="16"/>
<textFieldCell key="cell" sendsActionOnEndEditing="YES" alignment="right" title="Privacy:" id="140">
<font key="font" metaFont="system"/>
<color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/>
@@ -80,7 +81,7 @@
</textFieldCell>
</textField>
<button verticalHuggingPriority="1000" verticalCompressionResistancePriority="752" translatesAutoresizingMaskIntoConstraints="NO" id="82">
<rect key="frame" x="129" y="203" width="236" height="18"/>
<rect key="frame" x="136" y="216" width="232" height="16"/>
<buttonCell key="cell" type="check" title="Create Preview Images at position:" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="84">
<behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/>
<font key="font" metaFont="system"/>
@@ -94,15 +95,15 @@
</connections>
</button>
<slider verticalHuggingPriority="1000" verticalCompressionResistancePriority="752" translatesAutoresizingMaskIntoConstraints="NO" id="JhA-jk-CGt">
<rect key="frame" x="147" y="170" width="220" height="28"/>
<rect key="frame" x="154" y="192" width="214" height="16"/>
<sliderCell key="cell" state="on" alignment="left" maxValue="1" doubleValue="0.5" tickMarkPosition="below" numberOfTickMarks="7" sliderType="linear" id="iKX-dX-4IV"/>
<connections>
<binding destination="3" name="value" keyPath="values.SBChaptersPreviewPosition" id="JtQ-lM-MNU"/>
<binding destination="3" name="enabled" keyPath="values.chaptersPreviewTrack" id="hNU-uO-zsL"/>
</connections>
</slider>
<textField horizontalHuggingPriority="249" verticalHuggingPriority="1000" horizontalCompressionResistancePriority="1000" translatesAutoresizingMaskIntoConstraints="NO" id="206">
<rect key="frame" x="18" y="129" width="107" height="16"/>
<textField focusRingType="none" horizontalHuggingPriority="249" verticalHuggingPriority="1000" horizontalCompressionResistancePriority="1000" translatesAutoresizingMaskIntoConstraints="NO" id="206">
<rect key="frame" x="18" y="142" width="112" height="16"/>
<textFieldCell key="cell" sendsActionOnEndEditing="YES" alignment="right" title="Show ratings for:" id="207">
<font key="font" metaFont="system"/>
<color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/>
@@ -110,7 +111,7 @@
</textFieldCell>
</textField>
<button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="136">
<rect key="frame" x="124" y="13" width="182" height="32"/>
<rect key="frame" x="136" y="20" width="172" height="24"/>
<buttonCell key="cell" type="push" title="Delete cached metadata" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="137">
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="system"/>
@@ -119,8 +120,8 @@
<action selector="deleteCachedMetadata:" target="-2" id="141"/>
</connections>
</button>
<textField horizontalHuggingPriority="249" verticalHuggingPriority="1000" horizontalCompressionResistancePriority="1000" setsMaxLayoutWidthAtFirstLayout="YES" translatesAutoresizingMaskIntoConstraints="NO" id="81">
<rect key="frame" x="18" y="204" width="107" height="16"/>
<textField focusRingType="none" horizontalHuggingPriority="249" verticalHuggingPriority="1000" horizontalCompressionResistancePriority="1000" setsMaxLayoutWidthAtFirstLayout="YES" translatesAutoresizingMaskIntoConstraints="NO" id="81">
<rect key="frame" x="18" y="216" width="112" height="16"/>
<textFieldCell key="cell" sendsActionOnEndEditing="YES" alignment="right" title="Chapters:" id="85">
<font key="font" metaFont="system"/>
<color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/>
@@ -128,7 +129,7 @@
</textFieldCell>
</textField>
<button verticalHuggingPriority="1000" translatesAutoresizingMaskIntoConstraints="NO" id="B5v-6Q-3Qa">
<rect key="frame" x="129" y="269" width="246" height="18"/>
<rect key="frame" x="136" y="316" width="242" height="16"/>
<buttonCell key="cell" type="check" title="Automatically check for update daily" bezelStyle="regularSquare" imagePosition="left" alignment="left" state="on" inset="2" id="2Pf-pq-4IX">
<behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/>
<font key="font" metaFont="system"/>
@@ -137,24 +138,24 @@
<binding destination="3" name="value" keyPath="values.SUEnableAutomaticChecks" id="6AF-uh-wt7"/>
</connections>
</button>
<textField horizontalHuggingPriority="249" verticalHuggingPriority="1000" horizontalCompressionResistancePriority="1000" translatesAutoresizingMaskIntoConstraints="NO" id="77">
<rect key="frame" x="18" y="292" width="107" height="16"/>
<textField focusRingType="none" horizontalHuggingPriority="249" verticalHuggingPriority="1000" horizontalCompressionResistancePriority="1000" translatesAutoresizingMaskIntoConstraints="NO" id="77">
<rect key="frame" x="18" y="338" width="112" height="16"/>
<textFieldCell key="cell" sendsActionOnEndEditing="YES" alignment="right" title="At Launch:" id="89">
<font key="font" metaFont="system"/>
<color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
<textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="tVb-Qq-sU7">
<rect key="frame" x="343" y="156" width="24" height="14"/>
<textField focusRingType="none" horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="tVb-Qq-sU7">
<rect key="frame" x="346" y="172" width="24" height="14"/>
<textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="right" title="End" id="He0-rl-DBi">
<font key="font" metaFont="message" size="11"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
<textField horizontalHuggingPriority="249" verticalHuggingPriority="1000" horizontalCompressionResistancePriority="1000" translatesAutoresizingMaskIntoConstraints="NO" id="78">
<rect key="frame" x="18" y="230" width="107" height="16"/>
<textField focusRingType="none" horizontalHuggingPriority="249" verticalHuggingPriority="1000" horizontalCompressionResistancePriority="1000" translatesAutoresizingMaskIntoConstraints="NO" id="78">
<rect key="frame" x="18" y="276" width="112" height="16"/>
<textFieldCell key="cell" sendsActionOnEndEditing="YES" alignment="right" title="Window:" id="88">
<font key="font" metaFont="system"/>
<color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/>
@@ -162,7 +163,7 @@
</textFieldCell>
</textField>
<popUpButton verticalHuggingPriority="1000" translatesAutoresizingMaskIntoConstraints="NO" id="logFormatPopup">
<rect key="frame" x="128" y="78" width="167" height="25"/>
<rect key="frame" x="136" y="90" width="160" height="24"/>
<popUpButtonCell key="cell" type="push" bezelStyle="rounded" alignment="left" lineBreakMode="truncatingTail" borderStyle="borderAndBezel" imageScaling="proportionallyDown" inset="2" id="logFormatCell">
<behavior key="behavior" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="message"/>
@@ -178,7 +179,7 @@
</connections>
</popUpButton>
<button verticalHuggingPriority="1000" translatesAutoresizingMaskIntoConstraints="NO" id="79">
<rect key="frame" x="129" y="291" width="130" height="18"/>
<rect key="frame" x="136" y="338" width="126" height="16"/>
<buttonCell key="cell" type="check" title="Show open panel" bezelStyle="regularSquare" imagePosition="left" alignment="left" state="on" inset="2" id="87">
<behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/>
<font key="font" metaFont="system"/>
@@ -188,7 +189,7 @@
</connections>
</button>
<popUpButton verticalHuggingPriority="1000" verticalCompressionResistancePriority="752" translatesAutoresizingMaskIntoConstraints="NO" id="236">
<rect key="frame" x="128" y="122" width="187" height="25"/>
<rect key="frame" x="136" y="138" width="180" height="24"/>
<popUpButtonCell key="cell" type="push" bezelStyle="rounded" alignment="left" lineBreakMode="truncatingTail" borderStyle="borderAndBezel" imageScaling="proportionallyDown" inset="2" id="237">
<behavior key="behavior" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="message"/>
@@ -204,22 +205,63 @@
<binding destination="123" name="selectedValue" keyPath="values.SBRatingsCountry" previousBinding="245" id="248"/>
</connections>
</popUpButton>
<textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="mNP-6I-gV4">
<rect key="frame" x="235" y="156" width="44" height="14"/>
<textField focusRingType="none" horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="mNP-6I-gV4">
<rect key="frame" x="239" y="172" width="44" height="14"/>
<textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="center" title="Middle" id="2o1-dB-mt1">
<font key="font" metaFont="message" size="11"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
<textField horizontalHuggingPriority="249" verticalHuggingPriority="1000" horizontalCompressionResistancePriority="1000" translatesAutoresizingMaskIntoConstraints="NO" id="logFormatLabel">
<rect key="frame" x="18" y="85" width="107" height="16"/>
<textField focusRingType="none" horizontalHuggingPriority="249" verticalHuggingPriority="1000" horizontalCompressionResistancePriority="1000" translatesAutoresizingMaskIntoConstraints="NO" id="logFormatLabel">
<rect key="frame" x="18" y="94" width="112" height="16"/>
<textFieldCell key="cell" sendsActionOnEndEditing="YES" alignment="right" title="Log Format:" id="logFormatLabelCell">
<font key="font" metaFont="system"/>
<color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
<textField focusRingType="none" horizontalHuggingPriority="249" verticalHuggingPriority="1000" horizontalCompressionResistancePriority="1000" translatesAutoresizingMaskIntoConstraints="NO" id="saveLocationLabel">
<rect key="frame" x="18" y="246" width="112" height="16"/>
<textFieldCell key="cell" sendsActionOnEndEditing="YES" alignment="right" title="Save As Location:" id="saveLocationLabelCell">
<font key="font" metaFont="system"/>
<color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
<popUpButton verticalHuggingPriority="1000" translatesAutoresizingMaskIntoConstraints="NO" id="saveLocationPopUp">
<rect key="frame" x="136" y="242" width="180" height="24"/>
<popUpButtonCell key="cell" type="push" title="Automatic" bezelStyle="rounded" alignment="left" lineBreakMode="truncatingTail" state="on" borderStyle="borderAndBezel" imageScaling="proportionallyDown" inset="2" selectedItem="saveLocationLastUsed" id="saveLocationCell">
<behavior key="behavior" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="message"/>
<menu key="menu" id="saveLocationMenu">
<items>
<menuItem title="Automatic" state="on" id="saveLocationLastUsed">
<connections>
<action selector="setSaveLocation:" target="-2" id="saveLocationLastUsedAction"/>
</connections>
</menuItem>
<menuItem title="Same as File" tag="1" id="saveLocationSameAsFile">
<connections>
<action selector="setSaveLocation:" target="-2" id="saveLocationSameAsFileAction"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="saveLocationSeparator"/>
<menuItem title="Other…" tag="3" id="saveLocationOther">
<connections>
<action selector="chooseSaveLocation:" target="-2" id="saveLocationOtherAction"/>
</connections>
</menuItem>
</items>
</menu>
</popUpButtonCell>
<constraints>
<constraint firstAttribute="width" relation="greaterThanOrEqual" constant="180" id="saveLocationWidth"/>
</constraints>
<connections>
<accessibilityConnection property="title" destination="saveLocationLabel" id="saveLocationAccessibility"/>
</connections>
</popUpButton>
</subviews>
<constraints>
<constraint firstItem="133" firstAttribute="width" secondItem="136" secondAttribute="width" id="05F-cw-fMw"/>
@@ -237,7 +279,7 @@
<constraint firstItem="XPF-Mh-XYC" firstAttribute="firstBaseline" secondItem="mNP-6I-gV4" secondAttribute="firstBaseline" id="AFc-cn-ab1"/>
<constraint firstItem="77" firstAttribute="top" secondItem="dxI-5Q-gDD" secondAttribute="top" constant="20" symbolic="YES" id="D9x-E1-HxF"/>
<constraint firstItem="82" firstAttribute="leading" secondItem="JhA-jk-CGt" secondAttribute="leading" constant="-18" id="E8S-ti-ghL"/>
<constraint firstItem="82" firstAttribute="top" secondItem="80" secondAttribute="bottom" constant="10" id="ELH-2G-UJe"/>
<constraint firstItem="82" firstAttribute="top" secondItem="saveLocationPopUp" secondAttribute="bottom" constant="10" id="ELH-2G-UJe"/>
<constraint firstItem="mNP-6I-gV4" firstAttribute="firstBaseline" secondItem="tVb-Qq-sU7" secondAttribute="firstBaseline" id="ElQ-mv-Pfd"/>
<constraint firstItem="206" firstAttribute="width" secondItem="logFormatLabel" secondAttribute="width" id="G5L-ax-8Io"/>
<constraint firstAttribute="trailing" relation="greaterThanOrEqual" secondItem="B5v-6Q-3Qa" secondAttribute="trailing" id="Ies-Bx-zqg"/>
@@ -272,6 +314,12 @@
<constraint firstItem="JhA-jk-CGt" firstAttribute="centerX" secondItem="mNP-6I-gV4" secondAttribute="centerX" id="oJD-2R-bDt"/>
<constraint firstItem="logFormatLabel" firstAttribute="width" secondItem="139" secondAttribute="width" id="rof-yU-4Yg"/>
<constraint firstAttribute="trailing" relation="greaterThanOrEqual" secondItem="136" secondAttribute="trailing" id="s3j-nY-Z3K"/>
<constraint firstItem="saveLocationLabel" firstAttribute="firstBaseline" secondItem="saveLocationPopUp" secondAttribute="firstBaseline" id="saveLocationBaseline"/>
<constraint firstItem="saveLocationPopUp" firstAttribute="leading" secondItem="saveLocationLabel" secondAttribute="trailing" constant="8" symbolic="YES" id="saveLocationHorizontalSpace"/>
<constraint firstItem="saveLocationLabel" firstAttribute="width" secondItem="206" secondAttribute="width" id="saveLocationLabelWidth"/>
<constraint firstItem="saveLocationLabel" firstAttribute="leading" secondItem="206" secondAttribute="leading" id="saveLocationLeading"/>
<constraint firstItem="saveLocationPopUp" firstAttribute="top" secondItem="80" secondAttribute="bottom" constant="10" id="saveLocationTop"/>
<constraint firstAttribute="trailing" relation="greaterThanOrEqual" secondItem="saveLocationPopUp" secondAttribute="trailing" id="saveLocationTrailing"/>
<constraint firstItem="77" firstAttribute="width" secondItem="78" secondAttribute="width" id="uK9-gt-tF8"/>
<constraint firstItem="80" firstAttribute="leading" secondItem="78" secondAttribute="trailing" constant="8" symbolic="YES" id="v25-j6-krj"/>
<constraint firstItem="139" firstAttribute="firstBaseline" secondItem="133" secondAttribute="firstBaseline" id="w1s-Sg-fws"/>
-7
View File
@@ -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
View File
@@ -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.)*
+69
View File
@@ -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`.
+4 -1
View File
@@ -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)
+4 -3
View File
@@ -186,7 +186,7 @@ final class ArtworkSelectorController: NSViewController, NSCollectionViewDataSou
view.wantsLayer = true
imageBrowser.register(ArtworkSelectorViewItem.self, forItemWithIdentifier: ArtworkSelectorController.itemView)
loadMoreArtworks(count: 8)
loadMoreArtworks(count: 11)
let type = metadata.mediaKind.description
@@ -245,7 +245,7 @@ final class ArtworkSelectorController: NSViewController, NSCollectionViewDataSou
imageBrowser.reloadItems(at: [indexPath])
}
imageBrowser.selectionIndexPaths = selectionIndexPaths
imageBrowser.selectionIndexPaths = selectionIndexPaths
}
private func selectArtwork(at index: Int) {
@@ -294,7 +294,8 @@ final class ArtworkSelectorController: NSViewController, NSCollectionViewDataSou
}
private func selectedArtworks() -> [ArtworkImageObject] {
return imageBrowser.selectionIndexPaths.map { artworks[$0.item] }
let indexes = imageBrowser.selectionIndexPaths.map { $0.item } .sorted()
return indexes.map { artworks[$0] }
}
// MARK - UI state
@@ -1,8 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="24127" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="25098" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<dependencies>
<deployment identifier="macosx"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="24127"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="25098"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
@@ -14,10 +13,10 @@
<customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
<customObject id="-3" userLabel="Application" customClass="NSObject"/>
<window title="Window" allowsToolTipsWhenApplicationIsInactive="NO" releasedWhenClosed="NO" visibleAtLaunch="NO" frameAutosaveName="" animationBehavior="default" toolbarStyle="expanded" id="s5f-yH-26m" userLabel="Window">
<windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" resizable="YES"/>
<windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" resizable="YES" fullSizeContentView="YES"/>
<windowPositionMask key="initialPositionMask" leftStrut="YES" rightStrut="YES" topStrut="YES" bottomStrut="YES"/>
<rect key="contentRect" x="200" y="500" width="520" height="510"/>
<rect key="screenRect" x="0.0" y="0.0" width="1920" height="1055"/>
<rect key="screenRect" x="0.0" y="0.0" width="1920" height="1049"/>
<value key="minSize" type="size" width="520" height="510"/>
<view key="contentView" id="rip-YL-WpY">
<rect key="frame" x="0.0" y="0.0" width="520" height="510"/>
@@ -1,8 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="24506" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="25098" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<dependencies>
<deployment identifier="macosx"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="24506"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="25098"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
@@ -19,17 +19,17 @@
<customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
<customObject id="-3" userLabel="Application" customClass="NSObject"/>
<customView id="Hz6-mo-xeY">
<rect key="frame" x="0.0" y="0.0" width="642" height="497"/>
<rect key="frame" x="0.0" y="0.0" width="642" height="518"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<scrollView autohidesScrollers="YES" horizontalLineScroll="19" horizontalPageScroll="10" verticalLineScroll="19" verticalPageScroll="10" usesPredominantAxisScrolling="NO" translatesAutoresizingMaskIntoConstraints="NO" id="1XK-zr-YdW">
<rect key="frame" x="166" y="142" width="456" height="311"/>
<rect key="frame" x="166" y="167" width="456" height="307"/>
<clipView key="contentView" id="mho-zw-2Ud">
<rect key="frame" x="1" y="1" width="454" height="309"/>
<rect key="frame" x="1" y="1" width="454" height="305"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<tableView verticalHuggingPriority="750" allowsExpansionToolTips="YES" tableStyle="plain" columnReordering="NO" multipleSelection="NO" autosaveColumns="NO" rowSizeStyle="automatic" headerView="REl-53-Sku" viewBased="YES" id="Tid-Rc-Ljr">
<rect key="frame" x="0.0" y="0.0" width="454" height="286"/>
<rect key="frame" x="0.0" y="0.0" width="454" height="282"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<size key="intercellSpacing" width="3" height="2"/>
<color key="backgroundColor" name="controlBackgroundColor" catalog="System" colorSpace="catalog"/>
@@ -139,7 +139,7 @@
</tableHeaderView>
</scrollView>
<tokenField focusRingType="none" verticalHuggingPriority="750" setsMaxLayoutWidthAtFirstLayout="YES" translatesAutoresizingMaskIntoConstraints="NO" id="Y15-gP-AOw">
<rect key="frame" x="18" y="67" width="606" height="15"/>
<rect key="frame" x="18" y="88" width="606" height="15"/>
<tokenFieldCell key="cell" selectable="YES" allowsUndo="NO" alignment="left" allowsEditingTextAttributes="YES" id="rG5-g2-YmU">
<font key="font" metaFont="cellTitle"/>
<color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/>
@@ -151,7 +151,7 @@
</connections>
</tokenField>
<button toolTip="Remove selected item" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="sd5-qb-K5v">
<rect key="frame" x="207" y="107" width="44" height="32"/>
<rect key="frame" x="229" y="135" width="38" height="24"/>
<buttonCell key="cell" type="push" bezelStyle="rounded" image="NSRemoveTemplate" imagePosition="only" alignment="center" lineBreakMode="truncatingTail" state="on" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="9UV-xM-L5F">
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="system"/>
@@ -161,7 +161,7 @@
</connections>
</button>
<popUpButton toolTip="Add annotation" verticalHuggingPriority="249" horizontalCompressionResistancePriority="751" translatesAutoresizingMaskIntoConstraints="NO" id="Jdh-Cj-6ef">
<rect key="frame" x="163" y="110" width="53" height="25"/>
<rect key="frame" x="166" y="135" width="61" height="24"/>
<popUpButtonCell key="cell" type="push" bezelStyle="rounded" alignment="center" lineBreakMode="truncatingTail" borderStyle="border" inset="2" pullsDown="YES" selectedItem="5wF-Yq-18d" id="Hfq-XE-kzZ">
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="message"/>
@@ -178,13 +178,13 @@
</connections>
</popUpButton>
<scrollView autohidesScrollers="YES" horizontalLineScroll="19" horizontalPageScroll="10" verticalLineScroll="19" verticalPageScroll="10" usesPredominantAxisScrolling="NO" translatesAutoresizingMaskIntoConstraints="NO" id="h1q-Xr-y6R">
<rect key="frame" x="20" y="142" width="138" height="311"/>
<rect key="frame" x="20" y="167" width="138" height="307"/>
<clipView key="contentView" ambiguous="YES" id="KId-fX-q1q">
<rect key="frame" x="1" y="1" width="136" height="309"/>
<rect key="frame" x="1" y="1" width="136" height="305"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<tableView verticalHuggingPriority="750" ambiguous="YES" allowsExpansionToolTips="YES" columnAutoresizingStyle="lastColumnOnly" tableStyle="plain" columnReordering="NO" multipleSelection="NO" emptySelection="NO" autosaveColumns="NO" rowSizeStyle="automatic" headerView="Eh9-8P-dr0" viewBased="YES" id="nXW-oy-rtu">
<rect key="frame" x="0.0" y="0.0" width="136" height="286"/>
<rect key="frame" x="0.0" y="0.0" width="136" height="282"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<size key="intercellSpacing" width="3" height="2"/>
<color key="backgroundColor" name="controlBackgroundColor" catalog="System" colorSpace="catalog"/>
@@ -256,7 +256,7 @@
</tableHeaderView>
</scrollView>
<textField focusRingType="none" horizontalHuggingPriority="251" verticalHuggingPriority="750" setsMaxLayoutWidthAtFirstLayout="YES" translatesAutoresizingMaskIntoConstraints="NO" id="8sr-aI-VZy">
<rect key="frame" x="18" y="90" width="606" height="16"/>
<rect key="frame" x="18" y="111" width="606" height="16"/>
<textFieldCell key="cell" sendsActionOnEndEditing="YES" title="Available values:" id="OYx-Dd-YIf">
<font key="font" metaFont="system"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
@@ -264,7 +264,7 @@
</textFieldCell>
</textField>
<button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="BkU-sx-jUf">
<rect key="frame" x="494" y="107" width="135" height="32"/>
<rect key="frame" x="498" y="135" width="124" height="24"/>
<buttonCell key="cell" type="push" title="Restore Defaults" bezelStyle="rounded" alignment="center" lineBreakMode="truncatingTail" state="on" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="nBh-jv-KDG">
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="system"/>
@@ -277,7 +277,7 @@
</connections>
</button>
<textField focusRingType="none" horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="ZpH-Zy-mAt">
<rect key="frame" x="18" y="461" width="323" height="16"/>
<rect key="frame" x="18" y="482" width="323" height="16"/>
<textFieldCell key="cell" lineBreakMode="clipping" title="Map the providers' metadata to the MP4 annotations" id="cUW-9F-EvO">
<font key="font" usesAppearanceFont="YES"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
@@ -285,7 +285,7 @@
</textFieldCell>
</textField>
<button horizontalHuggingPriority="249" translatesAutoresizingMaskIntoConstraints="NO" id="ZMK-Xt-bJh">
<rect key="frame" x="18" y="42" width="173" height="18"/>
<rect key="frame" x="20" y="64" width="169" height="16"/>
<buttonCell key="cell" type="check" title="Keep empty annotations" bezelStyle="regularSquare" imagePosition="left" state="on" inset="2" id="7Ek-lI-5Lo">
<behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/>
<font key="font" metaFont="system"/>
@@ -295,7 +295,7 @@
</connections>
</button>
<button horizontalHuggingPriority="249" translatesAutoresizingMaskIntoConstraints="NO" id="SZd-pK-hWX">
<rect key="frame" x="18" y="20" width="210" height="18"/>
<rect key="frame" x="20" y="42" width="206" height="16"/>
<buttonCell key="cell" type="check" title="Overwrite existing annotations" bezelStyle="regularSquare" imagePosition="left" state="on" inset="2" id="7KC-Up-hGn">
<behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/>
<font key="font" metaFont="system"/>
@@ -304,6 +304,16 @@
<binding destination="LQR-UU-5Gl" name="value" keyPath="values.SBMetadataOverwriteExistingAnnotations" id="gMZ-eG-GV4"/>
</connections>
</button>
<button toolTip="4K metadata may cause streaming issues with some Apple TV and iTunes configurations" translatesAutoresizingMaskIntoConstraints="NO" id="cEs-iS-fwI">
<rect key="frame" x="20" y="20" width="232" height="16"/>
<buttonCell key="cell" type="check" title="Autodetect 4K HD Video Metadata" bezelStyle="regularSquare" imagePosition="left" inset="2" id="vyR-ib-B9Q">
<behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/>
<font key="font" metaFont="system"/>
</buttonCell>
<connections>
<binding destination="LQR-UU-5Gl" name="value" keyPath="values.SBSet4KHDVideoMetadata" id="OKn-J3-W8a"/>
</connections>
</button>
</subviews>
<constraints>
<constraint firstItem="SZd-pK-hWX" firstAttribute="leading" secondItem="ZMK-Xt-bJh" secondAttribute="leading" id="00b-Uc-cOS"/>
@@ -319,15 +329,16 @@
<constraint firstAttribute="trailing" relation="greaterThanOrEqual" secondItem="ZMK-Xt-bJh" secondAttribute="trailing" constant="20" id="GLC-tk-eTl"/>
<constraint firstItem="8sr-aI-VZy" firstAttribute="leading" secondItem="Hz6-mo-xeY" secondAttribute="leading" constant="20" id="HFP-B1-ScR"/>
<constraint firstItem="h1q-Xr-y6R" firstAttribute="leading" secondItem="Y15-gP-AOw" secondAttribute="leading" id="HMX-Qb-8MC"/>
<constraint firstAttribute="bottom" secondItem="cEs-iS-fwI" secondAttribute="bottom" constant="20" symbolic="YES" id="HUg-bO-NbS"/>
<constraint firstItem="h1q-Xr-y6R" firstAttribute="centerY" secondItem="1XK-zr-YdW" secondAttribute="centerY" id="JHk-tE-xQI"/>
<constraint firstAttribute="trailing" relation="greaterThanOrEqual" secondItem="SZd-pK-hWX" secondAttribute="trailing" constant="20" symbolic="YES" id="MBW-h8-eD8"/>
<constraint firstItem="Jdh-Cj-6ef" firstAttribute="top" secondItem="h1q-Xr-y6R" secondAttribute="bottom" constant="8" id="NcZ-Os-USj"/>
<constraint firstAttribute="trailing" relation="greaterThanOrEqual" secondItem="ZpH-Zy-mAt" secondAttribute="trailing" constant="20" symbolic="YES" id="P7f-Fl-xTL"/>
<constraint firstItem="h1q-Xr-y6R" firstAttribute="top" secondItem="ZpH-Zy-mAt" secondAttribute="bottom" constant="8" symbolic="YES" id="S2n-Cv-TwB"/>
<constraint firstAttribute="bottom" secondItem="SZd-pK-hWX" secondAttribute="bottom" constant="21" id="WKQ-4s-IWN"/>
<constraint firstItem="BkU-sx-jUf" firstAttribute="centerY" secondItem="sd5-qb-K5v" secondAttribute="centerY" id="ZWW-ZP-Xp1"/>
<constraint firstItem="BkU-sx-jUf" firstAttribute="trailing" secondItem="1XK-zr-YdW" secondAttribute="trailing" id="bp9-bU-BRc"/>
<constraint firstItem="1XK-zr-YdW" firstAttribute="leading" secondItem="h1q-Xr-y6R" secondAttribute="trailing" constant="8" symbolic="YES" id="cCT-Qp-Bxz"/>
<constraint firstItem="cEs-iS-fwI" firstAttribute="top" secondItem="SZd-pK-hWX" secondAttribute="bottom" constant="6" symbolic="YES" id="d8X-hu-sZn"/>
<constraint firstItem="Jdh-Cj-6ef" firstAttribute="top" secondItem="sd5-qb-K5v" secondAttribute="top" id="ewc-at-D5g"/>
<constraint firstItem="BkU-sx-jUf" firstAttribute="leading" relation="greaterThanOrEqual" secondItem="Hz6-mo-xeY" secondAttribute="leading" constant="20" symbolic="YES" id="fdW-8M-iew"/>
<constraint firstItem="8sr-aI-VZy" firstAttribute="top" secondItem="Jdh-Cj-6ef" secondAttribute="bottom" constant="8" id="gVT-X2-Zcu"/>
@@ -337,9 +348,11 @@
<constraint firstItem="Y15-gP-AOw" firstAttribute="trailing" secondItem="8sr-aI-VZy" secondAttribute="trailing" id="mXF-1R-Sbp"/>
<constraint firstItem="ZpH-Zy-mAt" firstAttribute="leading" secondItem="Hz6-mo-xeY" secondAttribute="leading" constant="20" symbolic="YES" id="ttK-B9-wyu"/>
<constraint firstItem="sd5-qb-K5v" firstAttribute="leading" secondItem="Jdh-Cj-6ef" secondAttribute="trailing" constant="2" id="vIk-e5-WB3"/>
<constraint firstItem="cEs-iS-fwI" firstAttribute="leading" secondItem="SZd-pK-hWX" secondAttribute="leading" id="wdD-k6-Agx"/>
<constraint firstAttribute="trailing" relation="greaterThanOrEqual" secondItem="cEs-iS-fwI" secondAttribute="trailing" constant="20" symbolic="YES" id="we6-QF-WHA"/>
<constraint firstItem="1XK-zr-YdW" firstAttribute="leading" secondItem="Hz6-mo-xeY" secondAttribute="leading" constant="166" id="yZg-V9-bxH"/>
</constraints>
<point key="canvasLocation" x="-296" y="-469.5"/>
<point key="canvasLocation" x="-296" y="-459"/>
</customView>
<arrayController objectClassName="NSString" id="RId-BH-Y2G" userLabel="Types Controller">
<classReference key="objectClass" className="NSString"/>
+1 -1
View File
@@ -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
+106 -11
View File
@@ -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 = [:]
@@ -22,6 +33,7 @@ final class Document: NSDocument {
self.unsupportedMp4Brand = false
self.mp4 = MP42File()
super.init()
self.mp4.undo = undoManager
}
init(mp4: MP42File) {
@@ -37,6 +49,7 @@ final class Document: NSDocument {
} else {
updateChangeCount(.changeDone)
}
self.mp4.undo = undoManager
}
override func makeWindowControllers() {
@@ -58,23 +71,55 @@ 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
} catch {
unsupportedMp4Brand = true
}
}
override func revert(toContentsOf url: URL, ofType typeName: String) throws {
mp4 = try MP42File(url: url)
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()
undoManager?.removeAllActions()
}
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 }
@@ -120,10 +165,18 @@ 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)
self.mp4 = reloadedFile
self.mp4.undo = self.undoManager
self.undoManager?.removeAllActions()
docController?.reloadData()
completionHandler(error)
} catch {
@@ -141,6 +194,7 @@ final class Document: NSDocument {
func cancelSave() {
cancelled = true
mkvSaver?.cancel()
mp4.cancel()
}
@@ -166,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 {
@@ -174,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 {
@@ -200,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?
@@ -227,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)
@@ -260,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
+6 -1
View File
@@ -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"),
@@ -149,7 +154,7 @@ class DocumentToolbarDelegate: NSObject, NSToolbarDelegate {
}
@MainActor func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] {
return [.importTracks, .searchMetadata, .actions, .space, .deleteTracks, .flexibleSpace, .sendToQueue, .showQueue,]
return [.importTracks, .searchMetadata, .space, .actions, .space, .deleteTracks, .flexibleSpace, .sendToQueue, .showQueue,]
}
@MainActor func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] {
+293 -49
View File
@@ -9,7 +9,7 @@ import Cocoa
import MP42Foundation
import UniformTypeIdentifiers
final class DocumentWindowController: NSWindowController, TracksViewControllerDelegate, MetadataSearchViewControllerDelegate, ChapterSearchControllerDelegate, FileImportControllerDelegate, ProgressViewControllerDelegate, NSDraggingDestination, NSUserInterfaceValidations {
final class DocumentWindowController: NSWindowController, NSWindowDelegate, TracksViewControllerDelegate, MetadataSearchViewControllerDelegate, ChapterSearchControllerDelegate, FileImportControllerDelegate, ProgressViewControllerDelegate, NSDraggingDestination, NSUserInterfaceValidations {
private var doc: Document {
return document as! Document
@@ -68,11 +68,26 @@ final class DocumentWindowController: NSWindowController, TracksViewControllerDe
splitViewController.splitView.identifier = DocumentWindowController.splitViewResorationIdentifier
}
else {
window.setContentSize(NSSize(width: 692, height: 510))
splitViewController.splitView.setPosition(160, ofDividerAt: 0)
window.setContentSize(NSSize(width: 692, height: 600))
splitViewController.splitView.setPosition(240, ofDividerAt: 0)
}
didSelect(tracks: [])
let update: (Notification) -> Void = { [weak self] notification in
guard let s = self else { return }
s.reloadDataAfterAnUndo()
}
NotificationCenter.default.addObserver(forName: NSNotification.Name.NSUndoManagerDidUndoChange,
object: doc.undoManager,
queue: OperationQueue.main,
using: update)
NotificationCenter.default.addObserver(forName: NSNotification.Name.NSUndoManagerDidRedoChange,
object: doc.undoManager,
queue: OperationQueue.main,
using: update)
}
private static let splitViewResorationIdentifier = NSUserInterfaceItemIdentifier(rawValue: "splitViewSave")
@@ -128,16 +143,20 @@ final class DocumentWindowController: NSWindowController, TracksViewControllerDe
}
private func clearDetailsViewControllers() {
saveTabIndex(metadataViewController)
saveTabIndexes()
metadataViewController = nil
saveTabIndex(videoViewController)
videoViewController = nil
saveTabIndex(soundViewController)
soundViewController = nil
chapterViewController = nil
multiViewController = nil
}
private func saveTabIndexes() {
saveTabIndex(metadataViewController)
saveTabIndex(videoViewController)
saveTabIndex(soundViewController)
}
private func detailsViewController(_ tracks: [MP42Track]) -> PropertyView {
if tracks.count > 1 {
let controller = MultiSelectViewController(numberOfTracks: UInt(tracks.count))
@@ -176,7 +195,10 @@ final class DocumentWindowController: NSWindowController, TracksViewControllerDe
return emptyViewController!
default:
if metadataViewController == nil {
if let metadataViewController = metadataViewController {
metadataViewController.metadata = mp4.metadata
}
else {
metadataViewController = MovieViewController(mp4: mp4, metadata: mp4.metadata)
}
return metadataViewController!
@@ -189,12 +211,20 @@ final class DocumentWindowController: NSWindowController, TracksViewControllerDe
tracksViewController.mp4 = doc.mp4
}
func reloadDataAfterAnUndo() {
let firstResponder = self.window?.firstResponder;
saveTabIndexes()
tracksViewController.reloadData()
if let firstResponder = firstResponder as? NSView, firstResponder.window != nil {
self.window?.makeFirstResponder(firstResponder)
}
}
// MARK: Tracks controller delegate
func didSelect(tracks: [MP42Track]) {
let detailsItem = splitViewController.splitViewItems[1]
if let detailsViewController = detailsItem.viewController.children.first {
doc.undoManager?.removeAllActions(withTarget: detailsViewController)
detailsViewController.view.removeFromSuperviewWithoutNeedingDisplay()
detailsItem.viewController.removeChild(at: 0)
}
@@ -205,17 +235,38 @@ final class DocumentWindowController: NSWindowController, TracksViewControllerDe
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() }
}
doc.updateChangeCount(.changeDone)
tracksViewController.reloadData()
}
}
@@ -225,22 +276,33 @@ final class DocumentWindowController: NSWindowController, TracksViewControllerDe
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:
@@ -251,6 +313,9 @@ final class DocumentWindowController: NSWindowController, TracksViewControllerDe
}
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:
@@ -309,8 +374,58 @@ final class DocumentWindowController: NSWindowController, TracksViewControllerDe
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 {
@@ -322,8 +437,12 @@ final class DocumentWindowController: NSWindowController, TracksViewControllerDe
track.addChapter("Chapter 1", timestamp: 0)
}
doc.updateChangeCount(.changeDone)
if doc.isMatroska {
doc.updateChangeCount(.changeDone)
}
tracksViewController.reloadData()
tracksViewController.selectTracks([track])
}
@IBAction func iTunesFriendlyTrackGroups(_ sender: Any) {
@@ -331,7 +450,6 @@ final class DocumentWindowController: NSWindowController, TracksViewControllerDe
mp4.inferTracksLanguages()
mp4.inferMediaCharacteristics()
doc.updateChangeCount(.changeDone)
tracksViewController.reloadData()
}
@@ -340,7 +458,6 @@ final class DocumentWindowController: NSWindowController, TracksViewControllerDe
track.name = ""
}
doc.updateChangeCount(.changeDone)
tracksViewController.reloadData()
}
@@ -350,13 +467,11 @@ final class DocumentWindowController: NSWindowController, TracksViewControllerDe
track.name = track.prettyTrackName
}
doc.updateChangeCount(.changeDone)
tracksViewController.reloadData()
}
@IBAction func fixAudioFallbacks(_ sender: Any) {
mp4.setAutoFallback()
doc.updateChangeCount(.changeDone)
tracksViewController.reloadData()
}
@@ -417,8 +532,8 @@ final class DocumentWindowController: NSWindowController, TracksViewControllerDe
mp4.metadata.addItem(MP42MetadataItem(identifier: MP42MetadataKeyHDVideo, value: NSNumber(value: hdType.rawValue),
dataType: .integer, extendedLanguageTag: nil))
}
doc.updateChangeCount(.changeDone)
metadataViewController?.metadata = mp4.metadata
tracksViewController.selectTracks([])
}
@IBAction func searchChapters(_ sender: Any?) {
@@ -432,31 +547,45 @@ final class DocumentWindowController: NSWindowController, TracksViewControllerDe
}
func didSelect(chapters: [MP42TextSample]) {
let chapterTrack = MP42ChapterTrack()
for chapter in chapters {
chapterTrack.addChapter(chapter)
}
let chapterTrack = MP42ChapterTrack()
for chapter in chapters {
chapterTrack.addChapter(chapter)
}
mp4.addTrack(chapterTrack)
doc.updateChangeCount(.changeDone)
tracksViewController.reloadData()
}
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])
}
// MARK: File import
private func addChapters(fileURL: URL) {
mp4.addTrack(MP42ChapterTrack(fromFile: fileURL))
doc.updateChangeCount(.changeDone)
let track = MP42ChapterTrack(fromFile: fileURL)
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])
}
private func updateChapters(fileURL: URL) {
do {
try mp4.chapters?.update(fromCSVFile: fileURL)
doc.updateChangeCount(.changeDone)
if let track = mp4.chapters {
chapterViewController?.track = track
tracksViewController.selectTracks([track])
if doc.isMatroska { doc.updateChangeCount(.changeDone) }
}
}
catch {
@@ -472,12 +601,12 @@ final class DocumentWindowController: NSWindowController, TracksViewControllerDe
let ext = fileURL.pathExtension.lowercased()
if ext == "xml" || ext == "nfo", let metadata = MP42Metadata(url: fileURL) {
mp4.metadata.merge(metadata, overwrite: true)
doc.updateChangeCount(.changeDone)
metadataViewController?.metadata = mp4.metadata
tracksViewController.selectTracks([])
} else if let file = try? MP42File(url: fileURL) {
mp4.metadata.merge(file.metadata, overwrite: true)
doc.updateChangeCount(.changeDone)
metadataViewController?.metadata = mp4.metadata
tracksViewController.selectTracks([])
}
}
@@ -510,6 +639,36 @@ final class DocumentWindowController: NSWindowController, TracksViewControllerDe
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 {
@@ -532,7 +691,16 @@ final class DocumentWindowController: NSWindowController, TracksViewControllerDe
}
}
/// 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)
@@ -552,9 +720,69 @@ final class DocumentWindowController: NSWindowController, TracksViewControllerDe
}
}
// 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)
@@ -573,9 +801,11 @@ final class DocumentWindowController: NSWindowController, TracksViewControllerDe
mp4.addTrack(track)
}
if tracks.isEmpty == false {
doc.updateChangeCount(.changeDone)
// 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 {
@@ -585,13 +815,17 @@ final class DocumentWindowController: NSWindowController, TracksViewControllerDe
}
}
if let metadata = metadata {
if let metadata, metadata.items.isEmpty == false {
mp4.metadata.merge(metadata, overwrite: true)
doc.updateChangeCount(.changeDone)
metadataViewController?.metadata = mp4.metadata
}
tracksViewController.reloadData()
if let metadata, metadata.items.isEmpty == false {
tracksViewController.selectTracks([])
} else if tracks.isEmpty == false {
tracksViewController.selectTracks(tracks)
}
}
// MARK: Drag & drop
@@ -612,8 +846,18 @@ final class DocumentWindowController: NSWindowController, TracksViewControllerDe
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)
}
+19 -2
View File
@@ -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)
+78
View File
@@ -23,6 +23,84 @@ class GeneralPrefsViewController: NSViewController {
return "GeneralPrefsViewController"
}
// MARK: Save As location popUp
@IBOutlet var saveLocationPopUp: NSPopUpButton!
private let customLocationTag = 2
override func viewDidLoad() {
super.viewDidLoad()
prepareSaveLocationPopUp()
}
private func menuItem(url: URL) -> NSMenuItem {
let icon = NSWorkspace.shared.icon(forFile: url.path)
icon.size = NSSize(width: 16, height: 16)
let values = try? url.resourceValues(forKeys: [.localizedNameKey])
let title = values?.localizedName ?? url.lastPathComponent
let item = NSMenuItem(title: title, action: #selector(setSaveLocation(_:)), keyEquivalent: "")
item.image = icon
item.target = self
item.representedObject = url
item.toolTip = url.path
item.tag = customLocationTag
return item
}
/// Rebuilds the custom folder item, then selects the current location.
private func prepareSaveLocationPopUp() {
guard let menu = saveLocationPopUp.menu else { return }
if let item = menu.items.first(where: { $0.tag == customLocationTag }) {
menu.removeItem(item)
}
if let url = Prefs.saveAsCustomLocation {
menu.insertItem(NSMenuItem.separator(), at: 2)
menu.insertItem(menuItem(url: url), at: 3)
}
selectCurrentSaveLocation()
}
private func selectCurrentSaveLocation() {
let location = Prefs.saveAsLocation
if location == .custom && Prefs.saveAsCustomLocation == nil {
saveLocationPopUp.selectItem(withTag: SaveAsLocation.automatic.rawValue)
} else {
saveLocationPopUp.selectItem(withTag: location.rawValue)
}
}
@IBAction func setSaveLocation(_ sender: NSMenuItem) {
if let url = sender.representedObject as? URL {
Prefs.saveAsCustomLocation = url
Prefs.saveAsLocation = .custom
} else {
Prefs.saveAsLocation = SaveAsLocation(rawValue: sender.tag) ?? .automatic
}
}
@IBAction func chooseSaveLocation(_ sender: Any) {
let panel = NSOpenPanel()
panel.allowsMultipleSelection = false
panel.canChooseFiles = false
panel.canChooseDirectories = true
panel.canCreateDirectories = true
panel.begin { response in
if response == .OK, let url = panel.url {
Prefs.saveAsCustomLocation = url
Prefs.saveAsLocation = .custom
}
self.prepareSaveLocationPopUp()
}
}
@IBAction func clearRecentSearches(_ sender: Any) {
MetadataSearchController.clearRecentSearches()
}
+1 -1
View File
@@ -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 {
+5 -1
View File
@@ -27,7 +27,7 @@ extension MP42File {
var hdType: TrackHDType? {
for track in tracks(withMediaType: kMP42MediaType_Video) as! [MP42VideoTrack] {
if (track.width > 1920 && track.height > 1088) {
return nil // .hd4k 4k breaks AppleTV streaming
return Prefs.set4KHDVideoMetadata ? .hd4k : nil
} else if (track.width > 1280 || track.height > 720) && track.width <= 1920 && track.height <= 1088 {
return .hd1080p
} else if track.width >= 960 && track.height >= 720 || track.width >= 1280 {
@@ -91,6 +91,10 @@ extension MP42File {
}
}
func firstSourceDirectoryURL() -> URL? {
return tracks.compactMap { $0.url }.first?.deletingLastPathComponent()
}
func formattedFileName() -> String? {
guard let mediaKindValue = metadata.metadataItemsFiltered(byIdentifier: MP42MetadataKeyMediaKind).first?.numberValue?.intValue,
let mediaKind = MediaKind(rawValue: mediaKindValue)
+229
View File
@@ -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) }
}
}
+29 -8
View File
@@ -66,6 +66,7 @@ private extension MetadataResult {
}
self.remoteArtworks = [item.images.coverArt16X9, item.images.coverArt].compactMap { $0?.artwork(type: .poster) }
self.remoteArtworks += [item.images.previewFrame].compactMap { $0?.artwork(type: .backdrop) }
self.remoteArtworks += [episode.seasonImages.coverArt16X9, episode.seasonImages.coverArt].compactMap { $0?.artwork(type: .season) }
self.remoteArtworks += [episode.images.previewFrame].compactMap { $0?.artwork(type: .episode) }
}
@@ -163,9 +164,14 @@ public struct AppleTV: MetadataService {
if let season = metadata[.season] as? Int {
let index = metadata.remoteArtworks.count > 1 ? 1 : 0
metadata.remoteArtworks.insert(contentsOf: searchSeasons(id: id, season: season, store: store), at: index)
let seasonArtworks = searchSeasons(id: id, season: season, store: store)
if let season16x9 = seasonArtworks.first(where: { $0.size == .rectangle } ) {
metadata.remoteArtworks.insert(season16x9, at: index)
}
}
metadata.remoteArtworks.sortTopPicks(service: self.name)
return metadata
}
@@ -221,7 +227,8 @@ public struct AppleTV: MetadataService {
let urlString = "\(seasonsURL)\(id)/itunesSeasons?sf=\(store.storeCode)&locale=\(store.language2)\(options)"
if let url = URL(string: urlString), let results = sendJSONRequest(url: url, type: Wrapper<Seasons>.self) {
let filteredResults = results.data.seasons.values.joined().filter { $0.seasonNumber == season }
return filteredResults.compactMap { $0.images.coverArt16X9?.artwork(type: .season) }
return filteredResults.compactMap { $0.images.coverArt16X9?.artwork(type: .season) } +
filteredResults.compactMap { $0.images.coverArt?.artwork(type: .season) }
}
return []
}
@@ -236,7 +243,7 @@ public struct AppleTV: MetadataService {
let items = results.data.canvas?.shelves.first?.items
.filter { $0.type == type.description }
if let result = items?.filter({ $0.title == normalizedTerm }).first {
if let result = items?.filter({ $0.title?.caseInsensitiveCompare(normalizedTerm) == .orderedSame }).first {
return result
} else if let result = items?.filter({ $0.title?.minimumEditDistance(other: normalizedTerm) ?? Int.max < 8 }).first {
return result
@@ -247,15 +254,29 @@ public struct AppleTV: MetadataService {
if let filteredResult = filteredResult {
if let artworks = filteredResult.images.coverArt16X9?.artwork(type: .poster) {
var artworksSet = Set<Artwork>()
if case let MediaType.tvShow(season) = type {
if let season = season {
return [artworks] + searchSeasons(id: filteredResult.id, season: season, store: store)
if let poster = filteredResult.images.coverArt16X9?.artwork(type: .poster) {
artworksSet.insert(poster)
}
if let poster = filteredResult.images.coverArt?.artwork(type: .poster) {
artworksSet.insert(poster)
}
if case let MediaType.tvShow(season) = type {
if let season = season {
let seasonArtworks = searchSeasons(id: filteredResult.id, season: season, store: store)
if let season16x9 = seasonArtworks.first(where: { $0.size == .rectangle } ) {
artworksSet.insert(season16x9)
}
if let seasonSquare = seasonArtworks.first(where: { $0.size == .square } ) {
artworksSet.insert(seasonSquare)
}
}
return [artworks]
}
return Array(artworksSet)
}
}
return []
+35 -2
View File
@@ -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
@@ -113,6 +113,55 @@ public struct Artwork: Equatable, Hashable {
}
}
extension Array where Element == Artwork {
func first(by type: ArtworkType, size: ArtworkSize, service: String) -> Artwork? {
if type == .backdrop || type == .episode {
let serviceArtwork = self.filter { $0.type == type && $0.service == service }.first
let artwork = self.filter { $0.type == type }.first
return serviceArtwork != nil ? serviceArtwork : artwork
}
else {
let serviceArtwork = self.filter { $0.type == type && $0.size == size && $0.service == service }.first
let artwork = self.filter { $0.type == type && $0.size == size}.first
return serviceArtwork != nil ? serviceArtwork : artwork
}
}
mutating func sortTopPicks(service: String) {
let poster = first(by: .poster, size: .standard, service: service)
let posterRect = first(by: .poster, size: .rectangle, service: AppleTV().name)
let posterSquare = first(by: .poster, size: .square, service: AppleTV().name)
let season = first(by: .season, size: .standard, service: service)
let seasonRect = first(by: .season, size: .rectangle, service: AppleTV().name)
let seasonSquare = first(by: .season, size: .square, service: AppleTV().name)
let backdrop = first(by: .backdrop, size: .standard, service: service)
let episode = first(by: .episode, size: .standard, service: service)
let topPicks = [poster, posterRect, posterSquare,
season, seasonRect, seasonSquare,
backdrop, episode]
for pick in topPicks {
if let pick, let index = firstIndex(of: pick) {
remove(at: index)
}
}
for pick in topPicks.reversed() {
if let pick {
insert(pick, at: 0)
}
}
}
func sortedTopPicks(service: String) -> [Self.Element] {
var sorted = self
sorted.sortTopPicks(service: service)
return sorted
}
}
public enum MediaKind: Int {
case tvShow = 10
case movie = 9
+18 -22
View File
@@ -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? {
@@ -111,16 +125,9 @@ public struct TheMovieDB: MetadataService {
private func loadMovieArtworks(result: TMDBMovie) -> [Artwork] {
var artworks: [Artwork] = []
var iTunesImage = [Artwork](), appleTV = [Artwork]()
var appleTV = [Artwork]()
let group = DispatchGroup()
DispatchQueue.global().async(group: group) {
// add iTunes artwork
if let title = result.title, let iTunesMetadata = iTunesStore.quickiTunesSearch(movieName: title) {
iTunesImage = iTunesMetadata.remoteArtworks
}
}
DispatchQueue.global().async(group: group) {
if let title = result.title,
let store = iTunesStore.Store(language: "USA (English)") {
@@ -130,7 +137,6 @@ public struct TheMovieDB: MetadataService {
group.wait()
artworks.append(contentsOf: appleTV)
artworks.append(contentsOf: iTunesImage)
// Add TheMovieDB artworks
if let config = session.fetchConfiguration()?.images,
@@ -154,7 +160,7 @@ public struct TheMovieDB: MetadataService {
}
return artworks
return artworks.sortedTopPicks(service: self.name)
}
private func metadata(forResult result: TMDBMovie, language: String?) -> MetadataResult {
@@ -379,17 +385,8 @@ public struct TheMovieDB: MetadataService {
artworks.insert(contentsOf: metadata.remoteArtworks, at: 0)
var iTunesImage = [Artwork](), appleTV = [Artwork](), squareTVArt = [Artwork]()
var appleTV = [Artwork](), squareTVArt = [Artwork]()
let group = DispatchGroup()
DispatchQueue.global().async(group: group) {
// add iTunes artwork
if let name = metadata[.seriesName] as? String,
let iTunesMetadata = iTunesStore.quickiTunesSearch(tvSeriesName: name,
seasonNum: metadata[.season] as? Int,
episodeNum: metadata[.episodeNumber] as? Int) {
iTunesImage = iTunesMetadata.remoteArtworks
}
}
DispatchQueue.global().async(group: group) {
if let name = metadata[.seriesName] as? String,
let season = metadata[.season] as? Int,
@@ -404,11 +401,10 @@ public struct TheMovieDB: MetadataService {
}
group.wait()
artworks.insert(contentsOf: iTunesImage, at: 0)
artworks.insert(contentsOf: squareTVArt, at: 0)
artworks.insert(contentsOf: appleTV, at: 0)
metadata.remoteArtworks = artworks
metadata.remoteArtworks = artworks.sortedTopPicks(service: self.name)
return metadata
}
@@ -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()
+13 -30
View File
@@ -38,7 +38,7 @@ public struct TheTVDB : MetadataService {
var results: Set<String> = Set()
let series = session.fetch(series: tvShow)
results.formUnion(series.compactMap { $0.translations?[language] } )
results.formUnion(series.compactMap { $0.translations?[language] ?? $0.name } )
if results.isEmpty {
return TheMovieDB().search(tvShow: tvShow, language: language)
@@ -49,8 +49,9 @@ public struct TheTVDB : MetadataService {
// MARK: - TV Series ID search
private func match(series: TVDBSearchResult, name: String) -> Bool {
if let seriesName = series.name, seriesName.caseInsensitiveCompare(name) == .orderedSame {
private func match(series: TVDBSearchResult, name: String, language: String) -> Bool {
if let seriesName = series.translations?[language] ?? series.name,
seriesName.caseInsensitiveCompare(name) == .orderedSame {
return true
}
@@ -72,7 +73,9 @@ public struct TheTVDB : MetadataService {
let order = name?.caseInsensitiveCompare(seriesName)
return order == .orderedSame ? true : false
}
let filteredSeries = sorted.filter { $0.status?.isEmpty == false && match(series: $0, name: seriesName) }.map { $0.tvdb_id }
let filteredSeries = sorted.filter {
$0.status?.isEmpty == false && match(series: $0, name: seriesName, language: language)
}.map { $0.tvdb_id }
if filteredSeries.isEmpty == false {
return filteredSeries
@@ -369,16 +372,6 @@ public struct TheTVDB : MetadataService {
// MARK: - Additional metadata
private func loadiTunesArtwork(_ metadata: MetadataResult) -> [Artwork] {
guard let name = metadata[.seriesName] as? String,
let seasonNum = metadata[.season] as? Int,
let episodeNum = metadata[.episodeNumber] as? Int,
let result = iTunesStore.quickiTunesSearch(tvSeriesName: name, seasonNum: seasonNum, episodeNum: episodeNum)
else { return [] }
return result.remoteArtworks
}
private func loadSquareTVArtwork(_ metadata: MetadataResult) -> [Artwork] {
guard let tvShow = metadata[.seriesName] as? String,
let seasonNum = metadata[.season] as? Int,
@@ -421,11 +414,8 @@ public struct TheTVDB : MetadataService {
// Get additionals images
if ((metadata[.season] as? Int) != nil) {
var iTunesImage = [Artwork](), appleTV = [Artwork](), squareTVArt = [Artwork]()
var appleTV = [Artwork](), squareTVArt = [Artwork]()
let group = DispatchGroup()
DispatchQueue.global().async(group: group) {
iTunesImage = self.loadiTunesArtwork(metadata)
}
DispatchQueue.global().async(group: group) {
squareTVArt = self.loadSquareTVArtwork(metadata)
}
@@ -434,12 +424,12 @@ public struct TheTVDB : MetadataService {
}
group.wait()
artworks.insert(contentsOf: iTunesImage, at: 0)
artworks.insert(contentsOf: squareTVArt, at: 0)
artworks.insert(contentsOf: appleTV, at: 0)
}
metadata.remoteArtworks.insert(contentsOf: artworks, at: 0)
metadata.remoteArtworks.sortTopPicks(service: self.name)
return metadata
}
@@ -467,6 +457,7 @@ public struct TheTVDB : MetadataService {
public func loadMovieMetadata(_ metadata: MetadataResult, language: String) -> MetadataResult {
guard let movieID = metadata[.serviceContentID] as? String,
let name = metadata[.name] as? String,
let info = session.fetch(movieInfo: movieID)
else { return metadata }
@@ -486,28 +477,20 @@ public struct TheTVDB : MetadataService {
var artworks: [Artwork] = []
artworks += cleanArtworks(info.artworks)
var iTunesImage = [Artwork](), appleTV = [Artwork]()
var appleTV = [Artwork]()
let group = DispatchGroup()
let queue = DispatchQueue.global()
queue.async(group: group) {
// add iTunes artwork
if let iTunesMetadata = iTunesStore.quickiTunesSearch(movieName: info.name) {
iTunesImage = iTunesMetadata.remoteArtworks
}
}
queue.async(group: group) {
if let store = iTunesStore.Store(language: "USA (English)") {
appleTV = AppleTV().searchArtwork(term: info.name, store: store, type: .movie)
appleTV = AppleTV().searchArtwork(term: name, store: store, type: .movie)
}
}
group.wait()
artworks.insert(contentsOf: iTunesImage, at: 0)
artworks.insert(contentsOf: appleTV, at: 0)
metadata.remoteArtworks = artworks
metadata.remoteArtworks = artworks.sortedTopPicks(service: self.name)
return metadata
}
+27 -4
View File
@@ -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: "")
+4 -4
View File
@@ -1,8 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="24127" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="25098" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<dependencies>
<deployment identifier="macosx"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="24127"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="25098"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
@@ -14,9 +14,9 @@
<customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
<customObject id="-3" userLabel="Application" customClass="NSObject"/>
<view wantsLayer="YES" id="HYk-Hf-rvN">
<rect key="frame" x="0.0" y="0.0" width="540" height="520"/>
<rect key="frame" x="0.0" y="0.0" width="590" height="520"/>
<autoresizingMask key="autoresizingMask"/>
<point key="canvasLocation" x="220" y="74"/>
<point key="canvasLocation" x="327" y="14"/>
</view>
</objects>
</document>
+1 -1
View File
@@ -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 = {
-1
View File
@@ -37,7 +37,6 @@ final class OffsetViewController: NSViewController {
@IBAction func setOffset(_ sender: Any) {
if track.startOffset != offsetField.doubleValue {
track.startOffset = offsetField.doubleValue
doc.updateChangeCount(.changeDone)
}
presentingViewController?.dismiss(self)
}
+5 -1
View File
@@ -124,7 +124,11 @@ final class OptionsViewController: NSViewController, NSUserInterfaceValidations
private func menuItem(url: URL) -> NSMenuItem {
let icon = NSWorkspace.shared.icon(forFile: url.path)
icon.size = NSSize(width: 16, height: 16)
let item = NSMenuItem(title: url.lastPathComponent, action: #selector(destination(_:)), keyEquivalent: "")
let values = try? url.resourceValues(forKeys: [.localizedNameKey])
let title = values?.localizedName ?? url.lastPathComponent
let item = NSMenuItem(title: title, action: #selector(destination(_:)), keyEquivalent: "")
item.image = icon
item.target = self
item.representedObject = url
File renamed without changes.
+47 -11
View File
@@ -26,11 +26,6 @@ struct Stored<T> : Registable {
let key: String
let defaultValue: T
init(key: String, defaultValue: T) {
self.key = key
self.defaultValue = defaultValue
}
var wrappedValue: T {
get { ud.object(forKey: key) as? T ?? defaultValue }
set { ud.set(newValue, forKey: key) }
@@ -41,16 +36,41 @@ struct Stored<T> : Registable {
}
}
@propertyWrapper
struct StoredEnum<T: RawRepresentable> : Registable {
let key: String
let defaultValue: T
var wrappedValue: T {
get { T(rawValue: (ud.object(forKey: key) as? T.RawValue) ?? defaultValue.rawValue) ?? defaultValue }
set { ud.set(newValue.rawValue, forKey: key) }
}
func register(in dictionary: inout [String :Any]) {
dictionary[key] = defaultValue.rawValue
}
}
@propertyWrapper
struct StoredURL : Registable {
let key: String
let defaultValue: URL?
var wrappedValue: URL? {
get { ud.url(forKey: key) ?? defaultValue }
set { ud.set(newValue, forKey: key) }
}
func register(in dictionary: inout [String :Any]) {
dictionary[key] = defaultValue
}
}
@propertyWrapper
struct StoredCodable<T: Codable> : Registable {
let key: String
let defaultValue: T
init(key: String, defaultValue: T) {
self.key = key
self.defaultValue = defaultValue
}
var wrappedValue: T {
get {
guard let data = ud.data(forKey: key) else { return defaultValue }
@@ -70,6 +90,12 @@ struct StoredCodable<T: Codable> : Registable {
}
}
enum SaveAsLocation: Int {
case automatic = 0
case sameAsFile = 1
case custom = 2
}
enum Prefs {
static func register() {
@@ -78,7 +104,7 @@ enum Prefs {
_audioBitrate, _audioDRC, _audioConvertAC3, _audioKeepAC3, _audioConvertDts,
_audioDtsOptions, _subtitleConvertBitmap, _ratingsCountry, _chaptersPreviewPosition,
_chaptersPreviewTrack, _mp464bitOffset, _mp464bitTimes, _mp4SaveAsOptimize, _forceHvc1,
_logFormat])
_logFormat, _saveAsLocation, _set4KHDVideoMetadata])
}
@Stored(key: "NSApplicationCrashOnException", defaultValue: true)
@@ -150,6 +176,9 @@ enum Prefs {
@Stored(key: "SBForceHvc1", defaultValue: true)
static var forceHvc1: Bool
@Stored(key: "SBSet4KHDVideoMetadata", defaultValue: false)
static var set4KHDVideoMetadata: Bool
@Stored(key: "SBArtworkSelectorZoomLevel", defaultValue: 50)
static var artworkSelectorZoomLevel: Float
@@ -161,6 +190,13 @@ enum Prefs {
@Stored(key: "SBLogFormat", defaultValue: 0)
static var logFormat: Int // 0 = Time Only, 1 = Date and Time
@StoredEnum(key: "SBSaveAsLocationMode", defaultValue: .automatic)
static var saveAsLocation: SaveAsLocation
/// The folder used when saveAsLocation is set to custom.
@StoredURL(key: "SBSaveAsCustomLocation", defaultValue: nil)
static var saveAsCustomLocation: URL?
}
enum MetadataPrefs {
+54 -27
View File
@@ -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) {
+1 -1
View File
@@ -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 {
+1 -1
View File
@@ -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? {
+4 -1
View File
@@ -159,7 +159,10 @@ class PresetPrefsViewController: NSViewController, SectionsTableViewDataSource,
}
}
tableView.selectRowIndexes(rowIndexes, byExtendingSelection: false)
let count = presetManager.metadataPresets.count + presetManager.queuePresets.count
if let index = rowIndexes.last, index < count {
tableView.selectRowIndexes(rowIndexes, byExtendingSelection: false)
}
}
@IBAction func editPreset(_ sender: NSView) {
@@ -1,13 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="24127" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES">
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="25098" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES">
<dependencies>
<deployment identifier="macosx"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="24127"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="25098"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<customObject id="-2" userLabel="File's Owner" customClass="ChapterViewController" customModule="Subler" customModuleProvider="target">
<connections>
<outlet property="actions" destination="IvH-Ff-dyN" id="EiR-xB-dq9"/>
<outlet property="removeChapter" destination="31" id="faJ-CI-g36"/>
<outlet property="tabView" destination="10" id="CC8-n9-JPu"/>
<outlet property="tableView" destination="22" id="7Za-v5-yKx"/>
@@ -30,13 +31,13 @@
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<scrollView autohidesScrollers="YES" horizontalLineScroll="16" horizontalPageScroll="10" verticalLineScroll="16" verticalPageScroll="10" usesPredominantAxisScrolling="NO" translatesAutoresizingMaskIntoConstraints="NO" id="19">
<rect key="frame" x="17" y="40" width="719" height="191"/>
<rect key="frame" x="17" y="44" width="719" height="187"/>
<clipView key="contentView" id="gfP-N5-8Ji">
<rect key="frame" x="1" y="1" width="717" height="189"/>
<rect key="frame" x="1" y="1" width="717" height="185"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<tableView verticalHuggingPriority="750" allowsExpansionToolTips="YES" columnAutoresizingStyle="lastColumnOnly" tableStyle="plain" columnSelection="YES" multipleSelection="NO" autosaveColumns="NO" rowHeight="14" headerView="23" viewBased="YES" id="22" customClass="ExpandedTableView" customModule="Subler" customModuleProvider="target">
<rect key="frame" x="0.0" y="0.0" width="717" height="172"/>
<tableView verticalHuggingPriority="750" allowsExpansionToolTips="YES" columnAutoresizingStyle="lastColumnOnly" tableStyle="plain" columnSelection="YES" autosaveColumns="NO" rowHeight="14" headerView="23" viewBased="YES" id="22" customClass="ExpandedTableView" customModule="Subler" customModuleProvider="target">
<rect key="frame" x="0.0" y="0.0" width="717" height="168"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<size key="intercellSpacing" width="3" height="2"/>
<color key="backgroundColor" name="controlBackgroundColor" catalog="System" colorSpace="catalog"/>
@@ -383,7 +384,7 @@
</tableHeaderView>
</scrollView>
<button toolTip="Add chapter" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="42">
<rect key="frame" x="11" y="9" width="36" height="27"/>
<rect key="frame" x="17" y="16" width="32" height="20"/>
<buttonCell key="cell" type="push" bezelStyle="rounded" image="NSAddTemplate" imagePosition="only" alignment="center" controlSize="small" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="43">
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="smallSystem"/>
@@ -393,7 +394,7 @@
</connections>
</button>
<popUpButton verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="IvH-Ff-dyN">
<rect key="frame" x="70" y="12" width="45" height="22"/>
<rect key="frame" x="90" y="16" width="53" height="20"/>
<popUpButtonCell key="cell" type="push" bezelStyle="rounded" alignment="center" controlSize="small" lineBreakMode="truncatingTail" borderStyle="border" imageScaling="proportionallyDown" inset="2" pullsDown="YES" id="frw-Vk-Gwo">
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="controlContent" size="11"/>
@@ -413,7 +414,7 @@
</popUpButtonCell>
</popUpButton>
<button toolTip="Delete selected chapter" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="31">
<rect key="frame" x="36" y="9" width="36" height="27"/>
<rect key="frame" x="50" y="16" width="32" height="20"/>
<buttonCell key="cell" type="push" bezelStyle="rounded" image="NSRemoveTemplate" imagePosition="only" alignment="center" controlSize="small" enabled="NO" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="32">
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="smallSystem"/>
@@ -8,16 +8,21 @@
import Cocoa
import MP42Foundation
final class ChapterViewController : PropertyView, NSTableViewDataSource, NSTableViewDelegate {
final class ChapterViewController : PropertyView, NSTableViewDataSource, NSTableViewDelegate, ExpandedTableViewDelegate {
var track: MP42ChapterTrack {
didSet {
let indexes = tableView.selectedRowIndexes
tableView.reloadData()
if let last = indexes.last, last < track.chapters.count {
tableView.selectRowIndexes(indexes, byExtendingSelection: false)
}
}
}
@IBOutlet var tableView: ExpandedTableView!
@IBOutlet var removeChapter: NSButton!
@IBOutlet var actions: NSPopUpButton!
override var nibName: NSNib.Name? {
return "ChapterView"
@@ -36,6 +41,10 @@ final class ChapterViewController : PropertyView, NSTableViewDataSource, NSTable
super.viewDidLoad()
tableView.defaultEditingColumn = 1
tableView.doubleAction = #selector(doubleClickAction(_:))
if #available(macOS 26, *) {
actions.menu?.items.first?.image = NSImage.init(systemSymbolName: "ellipsis", accessibilityDescription: nil)
}
}
// MARK: Table View
@@ -67,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) {
@@ -77,7 +90,6 @@ final class ChapterViewController : PropertyView, NSTableViewDataSource, NSTable
track.setTitle(sender.stringValue, forChapter: chapter)
tableView.reloadData(forRowIndexes: IndexSet(integer: row), columnIndexes: IndexSet(integer: 1))
updateChangeCount()
}
}
@@ -89,40 +101,52 @@ final class ChapterViewController : PropertyView, NSTableViewDataSource, NSTable
track.setTimestamp(timestamp, forChapter: chapter)
tableView.reloadData()
updateChangeCount()
}
}
@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)
}
}
// MARK: Actions
private func updateChangeCount() {
view.window?.windowController?.document?.updateChangeCount(NSDocument.ChangeType.changeDone)
}
@IBAction func removeChapter(_ sender: Any) {
let currentIndex = tableView.selectedRow
if currentIndex < track.chapterCount() {
track.removeChapter(at: UInt(currentIndex))
let indexes = IndexSet(integer: currentIndex)
func deleteSelection(in tableview: NSTableView) {
guard isReadOnly == false else { return }
let indexes = tableView.selectedRowIndexes
if indexes.isEmpty == false {
track.removeChapters(at: indexes)
tableView.removeRows(at: indexes, withAnimation: NSTableView.AnimationOptions.slideUp)
tableView.selectRowIndexes(indexes, byExtendingSelection: false)
updateChangeCount()
if let index = indexes.first, index < track.chapters.count {
tableView.selectRowIndexes(IndexSet(integer: index), byExtendingSelection: false)
}
}
}
@IBAction func addChapter(_ sender: Any) {
track.addChapter("Chapter", timestamp: 0)
// MARK: Actions
@IBAction func removeChapter(_ sender: Any) {
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()
updateChangeCount()
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))
tableView.insertRows(at: indexSet, withAnimation: .slideDown)
tableView.selectRowIndexes(indexSet, byExtendingSelection: false)
view.window?.makeFirstResponder(tableView)
}
@IBAction func renameChapters(_ sender: Any) {
@@ -131,7 +155,6 @@ final class ChapterViewController : PropertyView, NSTableViewDataSource, NSTable
track.setTitle(title, forChapter: chapter)
}
tableView.reloadData()
updateChangeCount()
}
}
+10 -2
View File
@@ -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
}
@@ -176,7 +186,5 @@ final class MediaTagsController: NSViewController, NSTableViewDataSource, NSTabl
private func updateTrack() {
let updatedTags = tags.filter { $0.state }.map { $0.value }
track.mediaCharacteristicTags = Set(updatedTags)
view.window?.windowController?.document?.updateChangeCount(.changeDone)
}
}
+133 -73
View File
@@ -18,7 +18,13 @@ class MovieViewController: PropertyView, NSTableViewDataSource, ExpandedTableVie
var metadata: MP42Metadata {
didSet {
let metadataIndexes = self.metadataTableView.selectedRowIndexes
// let artworkIndexes = self.artworksView.selectionIndexPaths;
reloadData()
if let last = metadataIndexes.last, last < tags.count {
self.metadataTableView.selectRowIndexes(metadataIndexes, byExtendingSelection: false)
}
// self.artworksView.selectItems(at: artworkIndexes, scrollPosition: .top)
}
}
@@ -116,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)
}
@@ -152,7 +164,64 @@ class MovieViewController: PropertyView, NSTableViewDataSource, ExpandedTableVie
metadataTableView.reloadData()
updateArtworksArray()
artworksView.reloadData()
view.undoManager?.removeAllActions(withTarget: self)
updateUI()
}
private func updateUI() {
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
@@ -180,17 +249,6 @@ class MovieViewController: PropertyView, NSTableViewDataSource, ExpandedTableVie
metadata.addItem(item)
rowHeights[item.identifier] = nil
}
if let undo = view.undoManager {
undo.registerUndo(withTarget: self) { (target) in
target.remove(metadataItems: items)
}
if undo.isUndoing == false {
undo.setActionName(NSLocalizedString("Insert", comment: "Undo tag insert."))
}
}
updateMetadataArray()
metadataTableView.reloadData()
}
@@ -199,38 +257,19 @@ class MovieViewController: PropertyView, NSTableViewDataSource, ExpandedTableVie
for item in items {
metadata.removeItem(item)
}
if let undo = view.undoManager {
undo.registerUndo(withTarget: self) { (target) in
target.add(metadataItems: items)
}
if undo.isUndoing == false {
undo.setActionName(NSLocalizedString("Delete", comment: "Undo tag delete."))
}
}
updateMetadataArray()
let index = metadataTableView.selectedRowIndexes.first ?? 0
metadataTableView.reloadData()
if index < tags.count {
metadataTableView.selectRowIndexes(IndexSet(integer: index), byExtendingSelection: false)
}
updateUI()
}
private func replace(metadataItem item: MP42MetadataItem, withItem newItem: MP42MetadataItem) {
metadata.removeItem(item)
metadata.addItem(newItem)
if let undo = view.undoManager {
undo.registerUndo(withTarget: self) { (target) in
target.replace(metadataItem: newItem, withItem: item)
}
if undo.isUndoing == false {
undo.setActionName(NSLocalizedString("Editing", comment: "Undo tag editing."))
view.window?.windowController?.document?.updateChangeCount(.changeDone)
} else {
view.window?.windowController?.document?.updateChangeCount(.changeUndone)
}
}
updateMetadataArray()
NSAnimationContext.beginGrouping()
@@ -559,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 {
@@ -685,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) {
@@ -834,8 +928,7 @@ class MovieViewController: PropertyView, NSTableViewDataSource, ExpandedTableVie
}
func tableViewSelectionDidChange(_ notification: Notification) {
let enabled = metadataTableView.selectedRow != -1 ? true : false
removeTagButton.isEnabled = enabled
updateUI()
}
// MARK: Artworks
@@ -846,34 +939,12 @@ class MovieViewController: PropertyView, NSTableViewDataSource, ExpandedTableVie
private func add(metadataArtworks items: [MP42MetadataItem]) {
metadata.addItems(items)
if let undo = view.undoManager {
undo.registerUndo(withTarget: self) { (target) in
target.remove(metadataArtworks: items)
}
if undo.isUndoing == false {
undo.setActionName(NSLocalizedString("Insert", comment: "Undo cover art insert."))
}
}
updateArtworksArray()
artworksView.reloadData()
}
private func remove(metadataArtworks items: [MP42MetadataItem]) {
metadata.removeItems(items)
if let undo = view.undoManager {
undo.registerUndo(withTarget: self) { (target) in
target.add(metadataArtworks: items)
}
if undo.isUndoing == false {
undo.setActionName(NSLocalizedString("Delete", comment: "Undo cover art delete"))
}
}
updateArtworksArray()
artworksView.reloadData()
updateSelection()
@@ -882,17 +953,6 @@ class MovieViewController: PropertyView, NSTableViewDataSource, ExpandedTableVie
private func replace(metadataArtworks items: [MP42MetadataItem], withItems newItems: [MP42MetadataItem]) {
metadata.removeItems(items)
metadata.addItems(newItems)
if let undo = view.undoManager {
undo.registerUndo(withTarget: self) { (target) in
target.replace(metadataArtworks: newItems, withItems: items)
}
if undo.isUndoing == false {
undo.setActionName(NSLocalizedString("Move", comment: "Undo cover art delete"))
}
}
updateArtworksArray()
artworksView.reloadData()
updateSelection()
@@ -905,12 +965,12 @@ class MovieViewController: PropertyView, NSTableViewDataSource, ExpandedTableVie
private func add(artworks: [Any], toIndexPath: IndexPath) -> Bool {
let items = artworks.compactMap { (artwork: Any) -> MP42Image? in
if let url = artwork as? URL {
let value = try? url.resourceValues(forKeys: [URLResourceKey.typeIdentifierKey])
var isJpeg = false
if #available(macOS 11, *) {
let value = try? url.resourceValues(forKeys: [URLResourceKey.contentTypeKey])
isJpeg = value?.contentType?.conforms(to: .jpeg) ?? false
} else {
let value = try? url.resourceValues(forKeys: [URLResourceKey.typeIdentifierKey])
if let type = value?.typeIdentifier, UTTypeConformsTo(type as CFString, "public.jpeg" as CFString) {
isJpeg = true
}
+34
View File
@@ -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)
+4 -10
View File
@@ -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!
@@ -118,15 +122,10 @@ final class SoundViewController : PropertyView {
// MARK: Actions
private func updateChangeCount() {
view.window?.windowController?.document?.updateChangeCount(NSDocument.ChangeType.changeDone)
}
@IBAction func setTrackVolume(_ sender: NSSlider) {
let value = sender.floatValue / 100
if value != track.volume {
track.volume = value
updateChangeCount()
}
}
@@ -134,12 +133,10 @@ final class SoundViewController : PropertyView {
if let newFallbackTrack = sender.representedObject as? MP42AudioTrack {
if newFallbackTrack != track.fallbackTrack {
track.fallbackTrack = newFallbackTrack
updateChangeCount()
}
}
else {
track.fallbackTrack = nil
updateChangeCount()
}
}
@@ -147,12 +144,10 @@ final class SoundViewController : PropertyView {
if let newFollowsTrack = sender.representedObject as? MP42SubtitleTrack {
if newFollowsTrack != track.followsTrack {
track.followsTrack = newFollowsTrack
updateChangeCount()
}
}
else {
track.followsTrack = nil
updateChangeCount()
}
}
@@ -160,7 +155,6 @@ final class SoundViewController : PropertyView {
if let group = sender.selectedItem?.tag {
if track.alternateGroup != group {
track.alternateGroup = UInt64(group)
updateChangeCount()
}
}
}
+18 -16
View File
@@ -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"
}
@@ -254,10 +272,6 @@ final class VideoViewController: PropertyView {
// MARK: Actions
private func updateChangeCount() {
view.window?.windowController?.document?.updateChangeCount(NSDocument.ChangeType.changeDone)
}
@IBAction func setSize(_ sender: NSTextField) {
if sender == trackWidth {
let value = trackWidth.floatValue
@@ -267,13 +281,11 @@ final class VideoViewController: PropertyView {
trackHeight.floatValue = track.trackHeight
}
track.trackWidth = value
updateChangeCount()
}
} else if sender == trackHeight {
let value = trackHeight.floatValue
if track.trackHeight != value {
track.trackHeight = value
updateChangeCount()
}
} else if sender == offsetX {
let value = CGFloat(offsetX.integerValue)
@@ -281,7 +293,6 @@ final class VideoViewController: PropertyView {
var transform = track.transform
transform.tx = value
track.transform = transform
updateChangeCount()
}
} else if sender == offsetY {
let value = CGFloat(offsetY.integerValue)
@@ -289,7 +300,6 @@ final class VideoViewController: PropertyView {
var transform = track.transform
transform.ty = value
track.transform = transform
updateChangeCount()
}
}
}
@@ -299,14 +309,12 @@ final class VideoViewController: PropertyView {
let value = UInt64(hSpacing.integerValue)
if track.hSpacing != value {
track.hSpacing = value
updateChangeCount()
}
}
else if sender == vSpacing {
let value = UInt64(vSpacing.intValue)
if track.vSpacing != value {
track.vSpacing = value
updateChangeCount()
}
}
}
@@ -346,7 +354,6 @@ final class VideoViewController: PropertyView {
track.colorPrimaries = colorTag.0
track.transferCharacteristics = colorTag.1
track.matrixCoefficients = colorTag.2
updateChangeCount()
}
}
@@ -370,7 +377,6 @@ final class VideoViewController: PropertyView {
default:
return
}
updateChangeCount()
}
@IBAction func setForcedSubtitles(_ sender: NSPopUpButton) {
@@ -391,7 +397,6 @@ final class VideoViewController: PropertyView {
if track.someSamplesAreForced != value.0 || track.allSamplesAreForced != value.1 {
track.someSamplesAreForced = value.0
track.allSamplesAreForced = value.1
updateChangeCount()
}
}
}
@@ -401,12 +406,10 @@ final class VideoViewController: PropertyView {
if let newForcedTrack = sender.representedObject as? MP42SubtitleTrack {
if newForcedTrack != track.forcedTrack {
track.forcedTrack = newForcedTrack
updateChangeCount()
}
}
else {
track.forcedTrack = nil
updateChangeCount()
}
}
}
@@ -415,7 +418,6 @@ final class VideoViewController: PropertyView {
if let group = sender.selectedItem?.tag {
if track.alternateGroup != group {
track.alternateGroup = UInt64(group)
updateChangeCount()
}
}
}
+10
View File
@@ -54,6 +54,7 @@ final class Queue {
}
unarchiver.finishDecoding()
} catch {
self.logger.writeError(toLog: error)
items = []
}
@@ -66,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])
}
}
+45 -27
View File
@@ -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)
}
}
@@ -176,23 +184,6 @@ class QueueSetAction : NSObject, QueueActionProtocol {
}
extension Array where Element == Artwork {
func filter(by type: ArtworkType, size: ArtworkSize, service: String) -> Artwork? {
if type == .backdrop || type == .episode {
let serviceArtwork = self.filter { $0.type == type && $0.service == service }.first
let artwork = self.filter { $0.type == type }.first
return serviceArtwork != nil ? serviceArtwork : artwork
}
else {
let serviceArtwork = self.filter { $0.type == type && $0.size == size && $0.service == service }.first
let artwork = self.filter { $0.type == type && $0.size == size}.first
return serviceArtwork != nil ? serviceArtwork : artwork
}
}
}
/// An action that fetches metadata online.
class QueueMetadataAction : NSObject, QueueActionProtocol {
@@ -230,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)
@@ -263,13 +262,13 @@ class QueueMetadataAction : NSObject, QueueActionProtocol {
let artwork: Artwork? = {
let provider = terms.isMovie ? self.movieProvider : self.tvShowProvider
let type = terms.isMovie && preferredArtwork.isMovieType == false ? .poster : preferredArtwork
if let artwork = artworks.filter(by: type, size: preferredArtworkSize, service: provider) {
if let artwork = artworks.first(by: type, size: preferredArtworkSize, service: provider) {
return artwork
}
else if let artwork = artworks.filter(by: .season, size: preferredArtworkSize, service: provider) {
else if let artwork = artworks.first(by: .season, size: preferredArtworkSize, service: provider) {
return artwork
}
else if let artwork = artworks.filter(by: .poster, size: .standard, service: provider) {
else if let artwork = artworks.first(by: .poster, size: .standard, service: provider) {
return artwork
}
else {
@@ -348,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()
@@ -370,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
}
@@ -549,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 ||
@@ -590,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
}
+23 -2
View File
@@ -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
@@ -455,7 +474,9 @@ final class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDel
}
table.removeRows(at: indexes, withAnimation: .slideUp)
table.selectRowIndexes(IndexSet(integer: indexes.first!), byExtendingSelection: false)
if let index = indexes.first, index < queue.count {
table.selectRowIndexes(IndexSet(integer: index), byExtendingSelection: false)
}
table.endUpdates()
updateState()
+128 -28
View File
@@ -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
@@ -415,8 +494,8 @@ import MP42Foundation
statusInternal = QueueItem.Status(rawValue: Int(aDecoder.decodeInt32(forKey: "SBQueueItemStatus"))) ?? .failed
mp4File = aDecoder.decodeObject(of: [MP42File.classForCoder()], forKey: "SBQueueItemMp4File") as? MP42File
uniqueID = aDecoder.decodeObject(of: [NSString.classForCoder()], forKey: "SBQueueItemID") as! String
attributes = aDecoder.decodeObject(of: [NSDictionary.classForCoder(), NSString.classForCoder(), NSNumber.classForCoder()], forKey: "SBQueueItemAttributes") as! [String : Any]
uniqueID = aDecoder.decodeObject(of: [NSString.classForCoder()], forKey: "SBQueueItemID") as? String ?? UUID().uuidString
attributes = aDecoder.decodeObject(of: [NSDictionary.classForCoder(), NSString.classForCoder(), NSNumber.classForCoder()], forKey: "SBQueueItemAttributes") as? [String : Any] ?? [:]
#if SB_SANDBOX
if var bookmark = aDecoder.decodeObject(of: [NSData.classForCoder()], forKey: "SBQueueItemFileURLBookmark") as? Data {
@@ -449,8 +528,14 @@ import MP42Foundation
return nil
}
#else
fileURL = aDecoder.decodeObject(of: [NSURL.classForCoder()], forKey: "SBQueueItemFileURL") as! URL
destURLInternal = aDecoder.decodeObject(of: [NSURL.classForCoder()], forKey: "SBQueueItemDestURL") as! URL
if let fileURL = aDecoder.decodeObject(of: [NSURL.classForCoder()], forKey: "SBQueueItemFileURL") as? URL,
let destURLInternal = aDecoder.decodeObject(of: [NSURL.classForCoder()], forKey: "SBQueueItemDestURL") as? URL {
self.fileURL = fileURL
self.destURLInternal = destURLInternal
} else {
return nil
}
#endif
actionsInternal = aDecoder.decodeObject(of: [NSArray.classForCoder(), QueueSetAction.classForCoder(),
@@ -460,7 +545,22 @@ import MP42Foundation
QueueRenameChaptersAction.classForCoder(),
QueueOrganizeGroupsAction.classForCoder(), QueueColorSpaceAction.classForCoder(),
QueueSetOutputFilenameAction.classForCoder(), QueueClearExistingMetadataAction.classForCoder(),
QueueOptimizeAction.classForCoder(), QueueSendToiTunesAction.classForCoder()], forKey: "SBQueueItemActions") as! [QueueActionProtocol]
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
}
}
}
}
+1 -1
View File
@@ -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)
}
}
+17
View File
@@ -55,6 +55,19 @@ final class SaveOptions: NSViewController {
}
}
/// The folder the save panel should open at, or nil to leave it
/// at the last folder used.
private func preferredDirectory(for doc: Document) -> URL? {
switch Prefs.saveAsLocation {
case .automatic:
return nil
case .sameAsFile:
return doc.fileURL?.deletingLastPathComponent() ?? doc.mp4.firstSourceDirectoryURL()
case .custom:
return Prefs.saveAsCustomLocation
}
}
override func viewDidLoad() {
super.viewDidLoad()
@@ -70,6 +83,10 @@ final class SaveOptions: NSViewController {
savePanel?.nameFieldStringValue = filename
}
if let url = preferredDirectory(for: doc) {
savePanel?.directoryURL = url
}
setFileType(filenameExtension: fileType)
_64bit_data.state = Prefs.mp464bitOffset ? .on : .off
+107 -62
View File
@@ -119,8 +119,7 @@ class SBFetchMetadataScriptCommand: NSScriptCommand, ScriptCommandDocumentTarget
if let metadata = metadata {
// Apply the metadata to the file
mp4File.metadata.merge(metadata, overwrite: true)
sublerDoc.updateChangeCount(.changeDone)
// Trigger UI refresh by calling reloadData on the window controller
if let windowController = sublerDoc.windowControllers.first as? DocumentWindowController {
windowController.reloadData()
@@ -151,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.filter(by: type, size: preferredArtworkSize, service: movieService.name) {
return artwork
} else if let artwork = artworks.filter(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))
@@ -207,11 +224,11 @@ class SBFetchMetadataScriptCommand: NSScriptCommand, ScriptCommandDocumentTarget
if preferredArtwork != .none && artworks.isEmpty == false {
let artwork: Artwork? = {
if let artwork = artworks.filter(by: preferredArtwork, size: preferredArtworkSize, service: tvShowService.name) {
if let artwork = artworks.first(by: preferredArtwork, size: preferredArtworkSize, service: tvShowService.name) {
return artwork
} else if let artwork = artworks.filter(by: .season, size: preferredArtworkSize, service: tvShowService.name) {
} else if let artwork = artworks.first(by: .season, size: preferredArtworkSize, service: tvShowService.name) {
return artwork
} else if let artwork = artworks.filter(by: .poster, size: .standard, service: tvShowService.name) {
} else if let artwork = artworks.first(by: .poster, size: .standard, service: tvShowService.name) {
return artwork
} else {
return artworks.first
@@ -343,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
@@ -386,8 +422,7 @@ class SBSaveAsScriptCommand: NSScriptCommand, ScriptCommandDocumentTargeting {
// Update the document's file URL and mark as saved
sublerDoc.fileURL = destinationURL
sublerDoc.updateChangeCount(.changeCleared)
// End progress reporting and refresh the UI
windowController.endProgressReporting()
windowController.reloadData()
@@ -396,8 +431,7 @@ class SBSaveAsScriptCommand: NSScriptCommand, ScriptCommandDocumentTargeting {
} else {
// Update the document's file URL and mark as saved
sublerDoc.fileURL = destinationURL
sublerDoc.updateChangeCount(.changeCleared)
// End progress reporting and refresh the UI
windowController.endProgressReporting()
windowController.reloadData()
@@ -442,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)
@@ -618,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
@@ -768,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 {
@@ -783,9 +830,9 @@ class SBFetchAndSetMetadataResultScriptCommand: NSScriptCommand, ScriptCommandDo
if preferredArtwork != .none && artworks.isEmpty == false {
let artwork: Artwork? = {
let type = preferredArtwork.isMovieType ? preferredArtwork : .poster
if let artwork = artworks.filter(by: type, size: preferredArtworkSize, service: movieService.name) {
if let artwork = artworks.first(by: type, size: preferredArtworkSize, service: movieService.name) {
return artwork
} else if let artwork = artworks.filter(by: .poster, size: .standard, service: movieService.name) {
} else if let artwork = artworks.first(by: .poster, size: .standard, service: movieService.name) {
return artwork
} else {
return artworks.first
@@ -807,7 +854,6 @@ class SBFetchAndSetMetadataResultScriptCommand: NSScriptCommand, ScriptCommandDo
DispatchQueue.main.async {
if let sublerDoc = self.targetedDocument() {
sublerDoc.mp4.metadata.merge(mappedMetadata, overwrite: true)
sublerDoc.updateChangeCount(.changeDone)
completion(true)
} else {
completion(false)
@@ -833,9 +879,9 @@ class SBFetchAndSetMetadataResultScriptCommand: NSScriptCommand, ScriptCommandDo
if preferredArtwork != .none && artworks.isEmpty == false {
let artwork: Artwork? = {
let type = preferredArtwork.isMovieType ? preferredArtwork : .poster
if let artwork = artworks.filter(by: type, size: preferredArtworkSize, service: tvShowService.name) {
if let artwork = artworks.first(by: type, size: preferredArtworkSize, service: tvShowService.name) {
return artwork
} else if let artwork = artworks.filter(by: .poster, size: .standard, service: tvShowService.name) {
} else if let artwork = artworks.first(by: .poster, size: .standard, service: tvShowService.name) {
return artwork
} else {
return artworks.first
@@ -857,7 +903,6 @@ class SBFetchAndSetMetadataResultScriptCommand: NSScriptCommand, ScriptCommandDo
DispatchQueue.main.async {
if let sublerDoc = self.targetedDocument() {
sublerDoc.mp4.metadata.merge(mappedMetadata, overwrite: true)
sublerDoc.updateChangeCount(.changeDone)
completion(true)
} else {
completion(false)
+87 -10
View File
@@ -23,7 +23,7 @@ final class TracksViewController: NSViewController, NSTableViewDataSource, NSTab
didSet {
let selectedIndexes = tracksTable.selectedRowIndexes
reloadData()
if let max = selectedIndexes.max(), mp4.tracks.count >= max {
if let last = selectedIndexes.last, last <= mp4.tracks.count {
tracksTable.selectRowIndexes(selectedIndexes, byExtendingSelection: false)
}
}
@@ -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
@@ -66,10 +89,28 @@ final class TracksViewController: NSViewController, NSTableViewDataSource, NSTab
}
func reloadData() {
let indexes = tracksTable.selectedRowIndexes
tracksTable.reloadData()
if let last = indexes.last, last <= mp4.tracks.count {
tracksTable.selectRowIndexes(indexes, byExtendingSelection: false)
}
delegate?.didSelect(tracks: selectedTracks)
}
func selectTracks(_ tracks: [MP42Track]) {
var indexes = IndexSet()
for track in tracks {
if let trackIndex = mp4.tracks.firstIndex(of: track) {
indexes.insert(trackIndex + 1)
}
}
if indexes.isEmpty && tracksTable.selectedRow == 0 {
indexes.insert(0)
}
tracksTable.selectRowIndexes(indexes, byExtendingSelection: false)
}
var selectedTracks: [MP42Track] {
return tracksTable != nil ? tracksTable.selectedRowIndexes.compactMap { track(at: $0) } : []
}
@@ -82,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
@@ -100,7 +157,6 @@ final class TracksViewController: NSViewController, NSTableViewDataSource, NSTab
let row = tracksTable.row(for: sender)
if let track = track(at: row) {
track.isEnabled = sender.state == NSControl.StateValue.on ? true : false
document.updateChangeCount(.changeDone)
}
}
@@ -108,7 +164,6 @@ final class TracksViewController: NSViewController, NSTableViewDataSource, NSTab
let row = tracksTable.row(for: sender)
if let track = track(at: row), track.name != sender.stringValue {
track.name = sender.stringValue
document.updateChangeCount(.changeDone)
let column = tracksTable.column(for: sender)
tracksTable.reloadData(forRowIndexes: IndexSet(integer: row), columnIndexes: IndexSet(integer: column))
}
@@ -127,7 +182,6 @@ final class TracksViewController: NSViewController, NSTableViewDataSource, NSTab
if let track = track(at: row), track.language != language {
track.language = language ?? "und"
document.updateChangeCount(.changeDone)
}
}
@@ -165,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?:
@@ -193,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:
@@ -245,13 +314,21 @@ final class TracksViewController: NSViewController, NSTableViewDataSource, NSTab
func tableView(_ tableView: NSTableView,
pasteboardWriterForRow row: Int) -> (any NSPasteboardWriting)? {
return PasteboardItem(index: row, type: .tableViewIndex)
if isReadOnly {
return nil
}
if let track = track(at: row), track.isMuxed == false {
return PasteboardItem(index: row, type: .tableViewIndex)
} else {
return nil
}
}
func tableView(_ tableView: NSTableView,
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,
+14
View File
@@ -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)
}
}
}
@@ -10,6 +10,9 @@
/* Class = "NSTableColumn"; headerCell.title = "Value"; ObjectID = "Aj4-bk-6RK"; */
"Aj4-bk-6RK.headerCell.title" = "Valore";
/* Class = "NSButton"; ibShadowedToolTip = "4K metadata may cause streaming issues with some Apple TV and iTunes configurations"; ObjectID = "cEs-iS-fwI"; */
"cEs-iS-fwI.ibShadowedToolTip" = "Il metadata 4K può causare problemi di trasmissione con certe configurazioni di Apple TV e iTunes";
/* Class = "NSTextFieldCell"; title = "Map the providers' metadata to the MP4 annotations"; ObjectID = "cUW-9F-EvO"; */
"cUW-9F-EvO.title" = "Associa i metadati dei fornitori alle annotazioni MP4";
@@ -34,3 +37,6 @@
/* Class = "NSTableView"; ibExternalAccessibilityDescription = "Metadata map"; ObjectID = "Tid-Rc-Ljr"; */
"Tid-Rc-Ljr.ibExternalAccessibilityDescription" = "Mappa metadata";
/* Class = "NSButtonCell"; title = "Autodetect 4K HD Video Metadata"; ObjectID = "vyR-ib-B9Q"; */
"vyR-ib-B9Q.title" = "Rileva metadata 4K Video HD";
+1 -7
View File
@@ -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>
+28 -7
View File
@@ -1,12 +1,33 @@
# Subler News
## Subler 1.9.5
- Expanded undo/redo support
- Improved artworks order in the artwork selector
- Improved specials (season 0) lookup from file names [brettpynn]
- Improved TVDB tv shows name search
- Added an option to set the 4k HD Video tag when needed [brettpynn]
- Fixed a crash that happened if a queue item contained a "Set language" action
- Minor UI improvements and bug fixes
## Subler 1.9.4
- Added an option to select a default "Save as" location [mindprint]
- Fixed manually added JPEG artworks being saved as PNG
- Fixed mismatching track languages when two different languages are defined for the same track [brettpynn]
- Fixed some minor UI issues
- Updated localizations
## Subler 1.9.3
- Improved TVDB scraper
- Added a settings to the Metadata preferences to not override the existing metadata
- Improved TVDB scraper
- Added a setting to the Metadata preferences to not override the existing metadata
- Minor UI improvements and bug fixes
- Updated localizations
## Subler 1.9.2
- Updated the TVDB scraper to use the v4 API
@@ -33,7 +54,7 @@
- Added additional keyboard shortcuts [Mock1]
- Added support for unofficial metadata often used for Audiobooks
- Make it possible to use the services ids in the metadata map
- Fixed the "Insert a chaper at the beginning" menu item action
- Fixed the "Insert a chapter at the beginning" menu item action
- Fixed Swedish Ratings
- Fixed the "None" artwork option in the Queue
@@ -138,7 +159,7 @@
## Subler 1.6.11
* Fixed an issue in the Matroska importer that could cause wrong tracks durations.
* Added HLG and more colorspaces to the video property view.
* Added HLG and more color spaces to the video property view.
## Subler 1.6.10
@@ -161,7 +182,7 @@
## Subler 1.6.7
* Improves AppleTV TV Shows seasons matching.
* Fixes a regression that prevented Atmos tracks from being properly signaled.
* Fixes a regression that prevented Atmos tracks from being properly signalled.
* Adds Chinese localization.
@@ -179,7 +200,7 @@
## Subler 1.6.4
* Fixes an issue that prevented uncheking tracks in the import sheet.
* Fixes an issue that prevented unchecking tracks in the import sheet.
* Fixes an issue that prevented the parsing of some metadata.
* Improves Srt export. Subtitles tracks with edit lists are properly exported.
* Improved VobSub OCR subtitles timing.
@@ -411,7 +432,7 @@
* Restored 10.9 compatibility.
* Fixed a crash when importing some mov files.
* Fixed the subtitles "forced" option, it was not saved propertly in some cases.
* Fixed the subtitles "forced" option, it was not saved properly in some cases.
## Subler 1.3.7 (2017-9-19)
+87 -26
View File
@@ -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.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+82 -68
View File
@@ -3,7 +3,7 @@
archiveVersion = 1;
classes = {
};
objectVersion = 54;
objectVersion = 56;
objects = {
/* Begin PBXBuildFile section */
@@ -35,7 +35,6 @@
A91B196C1F2B0DCB0008675F /* QueueAction.swift in Sources */ = {isa = PBXBuildFile; fileRef = A91B196B1F2B0DCB0008675F /* QueueAction.swift */; };
A91EB969205ABAF400392E1C /* NSWindowAdditions.swift in Sources */ = {isa = PBXBuildFile; fileRef = A91EB968205ABAF400392E1C /* NSWindowAdditions.swift */; };
A91F0FA023797F2800C9DCC9 /* PropertyView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A91F0F9F23797F2800C9DCC9 /* PropertyView.swift */; };
A92395043062A588008061F3 /* PasteboardItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = A92395023062A584008061F3 /* PasteboardItem.swift */; };
A924A51E1D4B9E93008301A7 /* MetadataPrefsViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = A924A5201D4B9E93008301A7 /* MetadataPrefsViewController.xib */; };
A925AA8518378D8A00BE84D4 /* MP42Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A925AA8218378D7900BE84D4 /* MP42Foundation.framework */; };
A925AA8818378DD000BE84D4 /* MP42Foundation.framework in Copy Files */ = {isa = PBXBuildFile; fileRef = A925AA8218378D7900BE84D4 /* MP42Foundation.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
@@ -47,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 */; };
@@ -67,7 +65,6 @@
A97C3AA5204F18C90007AD38 /* TokenCellView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A97C3AA4204F18C90007AD38 /* TokenCellView.swift */; };
A97D99DA22A0240C001FA3A7 /* OCRManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A97D99D922A0240C001FA3A7 /* OCRManager.swift */; };
A97FA41E23E9837000EE5833 /* Ratings.swift in Sources */ = {isa = PBXBuildFile; fileRef = A97FA41D23E9837000EE5833 /* Ratings.swift */; };
A97FA42223E9877900EE5833 /* Ratings.json in Resources */ = {isa = PBXBuildFile; fileRef = A97FA42123E9877900EE5833 /* Ratings.json */; };
A97FBE3C21FC7F1C00F1FD35 /* QueueController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A97FBE3B21FC7F1C00F1FD35 /* QueueController.swift */; };
A983E80B22365B5400221BAE /* MovieViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A983E80A22365B5400221BAE /* MovieViewController.swift */; };
A98542D720D197D300EB9803 /* ArtworkSelector.xib in Resources */ = {isa = PBXBuildFile; fileRef = A98542D520D197D300EB9803 /* ArtworkSelector.xib */; };
@@ -115,11 +112,14 @@
A9C31E602029A80F00CEF474 /* AdvancedPrefsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9C31E5E2029A80F00CEF474 /* AdvancedPrefsViewController.swift */; };
A9C31E642029A82200CEF474 /* AdvancedPrefsViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = A9C31E622029A82200CEF474 /* AdvancedPrefsViewController.xib */; };
A9C3E44A205C07F4004DE24E /* OptionsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9C3E449205C07F4004DE24E /* OptionsViewController.swift */; };
A9C4989C306BC624009F332A /* PasteboardItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9C4989B306BC624009F332A /* PasteboardItem.swift */; };
A9C498C4306BC6B9009F332A /* Ratings.json in Resources */ = {isa = PBXBuildFile; fileRef = A9C498C2306BC6B9009F332A /* Ratings.json */; };
A9C498C5306BC6B9009F332A /* Alpha2.json in Resources */ = {isa = PBXBuildFile; fileRef = A9C498C0306BC6B9009F332A /* Alpha2.json */; };
A9C498C6306BC6B9009F332A /* iTunesStores.json in Resources */ = {isa = PBXBuildFile; fileRef = A9C498C1306BC6B9009F332A /* iTunesStores.json */; };
A9C498C7306BC6B9009F332A /* Storefronts.json in Resources */ = {isa = PBXBuildFile; fileRef = A9C498C3306BC6B9009F332A /* Storefronts.json */; };
A9C51DF42E4B4548003E82E6 /* ScriptCommand.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9C51DF32E4B4548003E82E6 /* ScriptCommand.swift */; };
A9C5FA7419FA2FEC0051F3FF /* SBActivityWindow.xib in Resources */ = {isa = PBXBuildFile; fileRef = A9C5FA7219FA2FEC0051F3FF /* SBActivityWindow.xib */; };
A9C73536206B8F9900794673 /* QueuePreferences.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9C73535206B8F9900794673 /* QueuePreferences.swift */; };
A9CB19022D10415D0074DC9F /* Storefronts.json in Resources */ = {isa = PBXBuildFile; fileRef = A9CB19012D10415D0074DC9F /* Storefronts.json */; };
A9CB19052D10417D0074DC9F /* Alpha2.json in Resources */ = {isa = PBXBuildFile; fileRef = A9CB19042D10417D0074DC9F /* Alpha2.json */; };
A9CBAB1E1F29C083001C26B3 /* MetadataImporter.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CBAB1D1F29C083001C26B3 /* MetadataImporter.swift */; };
A9D4B8671C05BD04007845C4 /* SBChapterSearch.xib in Resources */ = {isa = PBXBuildFile; fileRef = A9D4B8651C05BD04007845C4 /* SBChapterSearch.xib */; };
A9D64527202CA92400BA172B /* SaveOptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9D64525202CA92400BA172B /* SaveOptions.swift */; };
@@ -127,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 */; };
@@ -141,8 +142,8 @@
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 */; };
CDE8E452174CBBD4009410B5 /* iTunesStores.json in Resources */ = {isa = PBXBuildFile; fileRef = CDE8E451174CBBD4009410B5 /* iTunesStores.json */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy 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>"; };
@@ -253,7 +254,6 @@
A91B196B1F2B0DCB0008675F /* QueueAction.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = QueueAction.swift; path = Classes/QueueAction.swift; sourceTree = "<group>"; };
A91EB968205ABAF400392E1C /* NSWindowAdditions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = NSWindowAdditions.swift; path = Classes/NSWindowAdditions.swift; sourceTree = "<group>"; };
A91F0F9F23797F2800C9DCC9 /* PropertyView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = PropertyView.swift; path = Classes/PropertyView/PropertyView.swift; sourceTree = "<group>"; };
A92395023062A584008061F3 /* PasteboardItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PasteboardItem.swift; sourceTree = "<group>"; };
A924A50D1D4B9E66008301A7 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Classes/PropertyView/Base.lproj/ChapterView.xib; sourceTree = "<group>"; };
A924A50E1D4B9E66008301A7 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Classes/PropertyView/Base.lproj/EmptyView.xib; sourceTree = "<group>"; };
A924A50F1D4B9E66008301A7 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Classes/PropertyView/Base.lproj/MovieView.xib; sourceTree = "<group>"; };
@@ -397,7 +397,6 @@
A97C3AA4204F18C90007AD38 /* TokenCellView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = TokenCellView.swift; path = Classes/TokenCellView.swift; sourceTree = "<group>"; };
A97D99D922A0240C001FA3A7 /* OCRManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = OCRManager.swift; path = Classes/OCRManager.swift; sourceTree = "<group>"; };
A97FA41D23E9837000EE5833 /* Ratings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = Ratings.swift; path = Classes/MetadataImporters/Ratings.swift; sourceTree = "<group>"; };
A97FA42123E9877900EE5833 /* Ratings.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = Ratings.json; sourceTree = "<group>"; };
A97FBE3B21FC7F1C00F1FD35 /* QueueController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = QueueController.swift; path = Classes/QueueController.swift; sourceTree = "<group>"; };
A983E80A22365B5400221BAE /* MovieViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = MovieViewController.swift; path = Classes/PropertyView/MovieViewController.swift; sourceTree = "<group>"; };
A98542D620D197D300EB9803 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/ArtworkSelector.xib; sourceTree = "<group>"; };
@@ -458,10 +457,13 @@
A9C31E5E2029A80F00CEF474 /* AdvancedPrefsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = AdvancedPrefsViewController.swift; path = Classes/AdvancedPrefsViewController.swift; sourceTree = "<group>"; };
A9C31E632029A82200CEF474 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/AdvancedPrefsViewController.xib; sourceTree = "<group>"; };
A9C3E449205C07F4004DE24E /* OptionsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = OptionsViewController.swift; path = Classes/OptionsViewController.swift; sourceTree = "<group>"; };
A9C4989B306BC624009F332A /* PasteboardItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = PasteboardItem.swift; path = Classes/PasteboardItem.swift; sourceTree = "<group>"; };
A9C498C0306BC6B9009F332A /* Alpha2.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; name = Alpha2.json; path = Resources/Alpha2.json; sourceTree = "<group>"; };
A9C498C1306BC6B9009F332A /* iTunesStores.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; name = iTunesStores.json; path = Resources/iTunesStores.json; sourceTree = "<group>"; };
A9C498C2306BC6B9009F332A /* Ratings.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; name = Ratings.json; path = Resources/Ratings.json; sourceTree = "<group>"; };
A9C498C3306BC6B9009F332A /* Storefronts.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; name = Storefronts.json; path = Resources/Storefronts.json; sourceTree = "<group>"; };
A9C51DF32E4B4548003E82E6 /* ScriptCommand.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = ScriptCommand.swift; path = Classes/ScriptCommand.swift; sourceTree = "<group>"; };
A9C73535206B8F9900794673 /* QueuePreferences.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = QueuePreferences.swift; path = Classes/QueuePreferences.swift; sourceTree = "<group>"; };
A9CB19012D10415D0074DC9F /* Storefronts.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = Storefronts.json; sourceTree = "<group>"; };
A9CB19042D10417D0074DC9F /* Alpha2.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = Alpha2.json; sourceTree = "<group>"; };
A9CBAB1D1F29C083001C26B3 /* MetadataImporter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = MetadataImporter.swift; path = Classes/MetadataImporters/MetadataImporter.swift; sourceTree = "<group>"; };
A9D64525202CA92400BA172B /* SaveOptions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = SaveOptions.swift; path = Classes/SaveOptions.swift; sourceTree = "<group>"; };
A9D8CA812E798CBD007C7B59 /* AppIcon.icon */ = {isa = PBXFileReference; lastKnownFileType = folder.iconcomposer.icon; path = AppIcon.icon; sourceTree = "<group>"; };
@@ -498,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>"; };
@@ -512,7 +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>"; };
CDE8E451174CBBD4009410B5 /* iTunesStores.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = iTunesStores.json; 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>";
@@ -589,7 +591,7 @@
A9A77C4D1F306FA70018023B /* AttributedStyles.swift */,
A956CE681F99E93D00093992 /* ButtonToolbarItem.swift */,
A9E385772C316FBE000A050D /* CollectionView.swift */,
A92395023062A584008061F3 /* PasteboardItem.swift */,
A9C4989B306BC624009F332A /* PasteboardItem.swift */,
A9E3857B2C317010000A050D /* FilePromiseProvider.swift */,
);
name = "Other Sources";
@@ -604,11 +606,12 @@
2A37F4B9FDCFA73011CA2CEA /* Credits.rtf */,
089C165FFE840EACC02AAC07 /* InfoPlist.strings */,
8D15AC360486D014006FF6A4 /* Info.plist */,
CDE8E451174CBBD4009410B5 /* iTunesStores.json */,
A9CB19012D10415D0074DC9F /* Storefronts.json */,
A9CB19042D10417D0074DC9F /* Alpha2.json */,
A97FA42123E9877900EE5833 /* Ratings.json */,
A9C498C0306BC6B9009F332A /* Alpha2.json */,
A9C498C1306BC6B9009F332A /* iTunesStores.json */,
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 */
@@ -901,7 +900,6 @@
buildActionMask = 2147483647;
files = (
A9EEA5F818D654B9008B54B4 /* QueueOptions.xib in Resources */,
A9CB19022D10415D0074DC9F /* Storefronts.json in Resources */,
A9AB486617F0AEFD000AA72E /* MovieView.xib in Resources */,
A9C31E5D2029A79000CEF474 /* GeneralPrefsViewController.xib in Resources */,
A98542DD20D1A7E500EB9803 /* ArtworkSelectorViewItem.xib in Resources */,
@@ -932,23 +930,47 @@
A98542D720D197D300EB9803 /* ArtworkSelector.xib in Resources */,
A9ECA0602029A13800D5F30C /* OffsetViewController.xib in Resources */,
A9ACF03222A2BCF200AD5B12 /* OCRPrefsViewController.xib in Resources */,
A9CB19052D10417D0074DC9F /* Alpha2.json in Resources */,
A97FA42223E9877900EE5833 /* Ratings.json in Resources */,
A961476713F568210068F161 /* Queue.xib in Resources */,
A9C498C4306BC6B9009F332A /* Ratings.json in Resources */,
A9C498C5306BC6B9009F332A /* Alpha2.json in Resources */,
A9C498C6306BC6B9009F332A /* iTunesStores.json in Resources */,
A9C498C7306BC6B9009F332A /* Storefronts.json in Resources */,
A9BA1AF31DBF7DD800FD0B38 /* Localizable.strings in Resources */,
A9ECA0572029A10B00D5F30C /* DocumentWindowController.xib in Resources */,
CDE8E452174CBBD4009410B5 /* iTunesStores.json in Resources */,
A924A51E1D4B9E93008301A7 /* MetadataPrefsViewController.xib in Resources */,
A92BBABE1F5584EA007EA182 /* PresetEditorViewController.xib in Resources */,
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 */,
@@ -1010,7 +1033,7 @@
A98D44102036F661005CB092 /* AppDelegate.swift in Sources */,
A9C31E572029A75F00CEF474 /* GeneralPrefsViewController.swift in Sources */,
A9AE26C01F3B66470041A57D /* SquaredTVArt.swift in Sources */,
A92395043062A588008061F3 /* PasteboardItem.swift in Sources */,
A9C4989C306BC624009F332A /* PasteboardItem.swift in Sources */,
A9B1056E2025D9B9009E91FC /* TracksViewController.swift in Sources */,
A9C51DF42E4B4548003E82E6 /* ScriptCommand.swift in Sources */,
A99B7FD82D53764F0027BCB5 /* AppleTVv3.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.3;
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.3;
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.3;
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.3;
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 */;
}
+4
View File
@@ -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";
}
+10 -4
View File
@@ -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',
},
@@ -337,7 +343,7 @@ sub new {
# Cosmetics
for my $key (qw(dvd season episode endep part)) {
$self->{$key} =~ s/^0+// if defined $self->{$key};
$self->{$key} =~ s/^0+(?=\d)// if defined $self->{$key};
}
$self->{endep} = undef if $self->{endep} == $self->{episode};
+377
View File
@@ -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
+22
View File
@@ -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"
+2
View File
@@ -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)";
-2
View File
@@ -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";
+2
View File
@@ -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";
-2
View File
@@ -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";
+2 -2
View File
@@ -1,5 +1,5 @@
/* Class = "NSButtonCell"; title = "Load more artwork..."; ObjectID = "40h-Rv-m31"; */
"40h-Rv-m31.title" = "Carica più illustrazioni…";
/* Class = "NSButtonCell"; title = "Load more artworks"; ObjectID = "40h-Rv-m31"; */
"40h-Rv-m31.title" = "Carica più illustrazioni";
/* Class = "NSSlider"; ibExternalAccessibilityDescription = "Zoom"; ObjectID = "fMj-Ew-Qej"; */
"fMj-Ew-Qej.ibExternalAccessibilityDescription" = "Ingrandisci";
@@ -46,3 +46,15 @@
/* Class = "NSTextFieldCell"; title = "Log Format:"; ObjectID = "logFormatLabelCell"; */
"logFormatLabelCell.title" = "Formato resoconto:";
/* Class = "NSTextFieldCell"; title = "Save As Location:"; ObjectID = "saveLocationLabelCell"; */
"saveLocationLabelCell.title" = "Posizione Salva col nome:";
/* Class = "NSMenuItem"; title = "Automatic"; ObjectID = "saveLocationLastUsed"; */
"saveLocationLastUsed.title" = "Automatica";
/* Class = "NSMenuItem"; title = "Other…"; ObjectID = "saveLocationOther"; */
"saveLocationOther.title" = "Altro…";
/* Class = "NSMenuItem"; title = "Same as File"; ObjectID = "saveLocationSameAsFile"; */
"saveLocationSameAsFile.title" = "Stessa del file";
+3 -13
View File
@@ -140,9 +140,7 @@ Toolbar */
/* No comment provided by engineer. */
"Day" = "Giorno";
/* Toolbar
Undo cover art delete
Undo tag delete. */
/* Toolbar */
"Delete" = "Elimina";
/* Toolbar */
@@ -190,9 +188,6 @@ Undo tag delete. */
/* Media characteristic. */
"Easy To Read" = "Semplice da leggere";
/* Undo tag editing. */
"Editing" = "Modifico";
/* Enable audio track action description
Enable audio track local description */
"Enabling audio track with selected language" = "Abilito traccia audio con lingua";
@@ -255,11 +250,8 @@ Enable subtitles track local description */
/* Toolbar */
"Import tracks from external files" = "Importa le tracce da un file esterno";
/* Undo cover art insert.
Undo tag insert. */
"Insert" = "Inserisci";
/* Toolbar */
"Insert a chapter" = "Inserisci un capitolo";
"Insert a chapter every" = "Inserisci un capitolo ogni";
/* color profile */
@@ -304,9 +296,6 @@ Undo tag insert. */
/* No comment provided by engineer. */
"Month" = "Mese";
/* Undo cover art delete */
"Move" = "Muovi";
/* Queue -> move add item. */
"Move Queue Item" = "sposta elemento coda";
@@ -605,6 +594,7 @@ Toolbar */
/* File Import action menu item. */
"Tx3g" = "Tx3g";
"VobSub" = "VobSub";
/* color profile */
"Undefined (2-2-2)" = "Non definito (2-2-2)";
-2
View File
@@ -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";
-6
View File
@@ -37,9 +37,6 @@
/* Class = "NSTextFieldCell"; title = "Season #"; ObjectID = "kz7-mH-DuT"; */
"kz7-mH-DuT.title" = "# Stagione";
/* Class = "NSTextFieldCell"; title = "TV Show:"; ObjectID = "lE4-J1-ySV"; */
"lE4-J1-ySV.title" = "Serie TV:";
/* Class = "NSMenuItem"; title = "iTunes Store"; ObjectID = "nn6-mR-Bh1"; */
"nn6-mR-Bh1.title" = "iTunes Store";
@@ -55,9 +52,6 @@
/* Class = "NSPopUpButton"; ibExternalAccessibilityDescription = "Metadata provider"; ObjectID = "UTG-O0-5RG"; */
"UTG-O0-5RG.ibExternalAccessibilityDescription" = "Provider metadata";
/* Class = "NSTextFieldCell"; title = "Movie:"; ObjectID = "uyt-vh-nv6"; */
"uyt-vh-nv6.title" = "Film:";
/* Class = "NSTableColumn"; headerCell.title = "Annotation"; ObjectID = "XgL-ec-DEt"; */
"XgL-ec-DEt.headerCell.title" = "Annotazione";
+2
View File
@@ -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)";
-2
View File
@@ -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";
+2
View File
@@ -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" = "未知";
-2
View File
@@ -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" = "导入";
+2
View File
@@ -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" = "未知";
-2
View File
@@ -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" = "导入";