Files
unshackle/search/search_index.json
T
2026-07-15 20:50:47 +00:00

1 line
587 KiB
JSON

{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"],"fields":{"title":{"boost":1000.0},"text":{"boost":1.0},"tags":{"boost":1000000.0}}},"docs":[{"location":"","title":"unshackle","text":"<p>unshackle is a modular archival tool for movies, TV, and music. It fetches media from streaming manifests, handles the DRM, and muxes everything into clean, well-tagged files, all driven from a single command-line tool, or served over a REST API for automation.</p> <p>It is a fork of Devine with first-class DASH, HLS, and Smooth Streaming (ISM) parsing, both Widevine and PlayReady DRM support, and a built-in HTTP server.</p> <p>Use responsibly</p> <p>unshackle is licensed under GPL-3.0. Do not use it for content you do not have the rights to. Keep the core free and open, keep service code private, and be kind.</p>"},{"location":"#what-it-does","title":"What it does","text":"<p>Point unshackle at a title on a streaming service and it will:</p> <ul> <li>Fetch the title metadata (movies, full series, seasons, episodes, albums, tracks).</li> <li>Parse the streaming manifest: DASH, HLS, or Smooth Streaming (ISM).</li> <li>Select the tracks you asked for by resolution, codec, bitrate, range, language, and channel layout.</li> <li>Acquire decryption keys via a Widevine or PlayReady CDM, with optional key vaults so keys are reused instead of re-licensed.</li> <li>Decrypt, extract closed captions, repack, and mux the result into a Matroska (<code>.mkv</code>) file with correct language, forced, and default flags.</li> <li>Tag and name the output using configurable filename templates.</li> </ul>"},{"location":"#feature-highlights","title":"Feature highlights","text":"Area What you get Media types Movies, TV series/seasons/episodes, and music albums/tracks Manifests DASH, HLS, and Smooth Streaming (ISM) DRM Widevine and PlayReady, with ClearKey support Video AVC, HEVC, VC-1, VP8, VP9, AV1; SDR, HLG, HDR10, HDR10+, Dolby Vision, and Dolby Vision hybrid merging Audio AAC, AC-3, E-AC-3, AC-4, Opus, Vorbis, DTS, ALAC, FLAC; Dolby Atmos handling; per-channel-layout selection Subtitles SRT, WebVTT, ASS/SSA, TTML and more, with optional SDH stripping and format conversion Key vaults SQLite, MySQL, and HTTP/API vaults to store and share content keys Proxies Basic proxies plus NordVPN, ProtonVPN, Surfshark, Windscribe, ExpressVPN, Gluetun, and Hola providers Services Pluggable service modules, loadable from local folders or git repositories Automation A REST API with a job queue, live progress, history, and remote-download sessions"},{"location":"#installation-at-a-glance","title":"Installation at a glance","text":"Install as a toolRun from a clone <pre><code>uv tool install git+https://github.com/unshackle-dl/unshackle.git\nunshackle --help\n</code></pre> <pre><code>git clone https://github.com/unshackle-dl/unshackle.git\ncd unshackle\nuv run unshackle --help\n</code></pre> <p>External tools</p> <p>unshackle shells out to FFmpeg, MKVToolNix, shaka-packager, Bento4, and <code>dovi_tool</code> for decryption, repacking, muxing, and Dolby Vision work. See Installation for the full list and recommended versions.</p>"},{"location":"#a-first-download","title":"A first download","text":"<p>Every download is three parts: the <code>dl</code> command, a service tag, and the service's title argument (a URL, ID, or slug).</p> Download a 1080p title with English audio and subtitles<pre><code>unshackle dl -q 1080 -l en EXAMPLE 81234567\n</code></pre> <p>The <code>dl</code> command carries all the quality, language, and output flags; the service tag (<code>EXAMPLE</code> above) selects which streaming service to talk to, and the value after it is passed to that service. See the Quickstart to go from a fresh install to your first file.</p>"},{"location":"#where-to-go-next","title":"Where to go next","text":"<ul> <li>Installation. Install unshackle and the external tools it depends on.</li> <li>Quickstart. Configure <code>unshackle.yaml</code> and run your first download.</li> <li>Downloading. The full <code>dl</code> command guide: quality, codecs, languages, track selection, and output.</li> <li>Configuration. Every <code>unshackle.yaml</code> key, directories, vaults, proxies, and naming templates.</li> <li>REST API. Run the <code>serve</code> HTTP server and drive downloads programmatically.</li> </ul> <p>Getting help</p> <p>Run <code>unshackle --help</code> or <code>unshackle dl --help</code> at any time. The community Discord is the fastest place to ask questions.</p>"},{"location":"dev/creating-a-service/","title":"Creating a Service","text":"<p>A service is a plugin that teaches unshackle how to talk to one streaming provider: how to log in, how to look up a title, what video/audio/subtitle tracks exist, and how to license any DRM. Everything else (track selection, downloading, decryption, muxing, naming) is handled by the unshackle core.</p> <p>Who this page is for</p> <p>This is a developer guide. If you only want to use services, see downloading and configuration. Nothing here is required to run the CLI. Service code is deliberately kept separate from the core so it can live in its own private repository.</p> <p>Unshackle ships one reference service, EXAMPLE, at <code>unshackle/services/EXAMPLE/</code>. It is a deliberately exhaustive, non-runnable showcase of every framework feature in a single file. Read it alongside this page; most snippets below are drawn from it.</p>"},{"location":"dev/creating-a-service/#how-a-service-is-discovered","title":"How a service is discovered","text":"<p>At startup unshackle scans every path in the <code>directories.services</code> config key (a list). Each entry is either a local directory of services or a remote repo spec (a git URL or <code>owner/repo</code> shorthand, which is cloned automatically). The default is the bundled <code>unshackle/services</code> directory.</p> <p>Within a services directory, every subfolder that contains an <code>__init__.py</code> is a service, and the folder name is the service tag:</p> <pre><code>services/\n\u2514\u2500\u2500 EXAMPLE/\n \u251c\u2500\u2500 __init__.py # required - defines the service class\n \u2514\u2500\u2500 config.yaml # optional - per-service configuration\n</code></pre> <p>Two rules the loader enforces:</p> <ol> <li>The class name must exactly match the folder/tag name. Folder <code>EXAMPLE</code> must define <code>class EXAMPLE</code>. A mismatch raises a <code>RuntimeError</code>.</li> <li>List order is priority. The first services path to define a given tag wins; later duplicates are shadowed. Put your own local overrides last to use them as fallbacks, or first to override a repo.</li> </ol> <p>Once installed, a service is invoked as a subcommand of <code>dl</code>:</p> <pre><code>unshackle dl EXAMPLE 20914\nunshackle dl EX 20914 # via an ALIAS\n</code></pre> <p>Config lives next to the code</p> <p>A service's own settings go in <code>config.yaml</code> inside the service folder (<code>directories.services/&lt;TAG&gt;/config.yaml</code>). This is separate from the global <code>unshackle.yaml</code>. Access it in code as <code>self.config[...]</code>. Never hardcode URLs, user agents, or certificates; put them here.</p> <p><code>config.yaml</code> is shared: keep secrets out of it</p> <p>Treat <code>config.yaml</code> as a checked-in file of defaults: it belongs in the service repo and is shared by everyone who runs the service. Per-user secrets (API keys, device IDs, account tokens) must not live here. Those go in the user's own <code>unshackle.yaml</code> under <code>services.&lt;TAG&gt;</code>, which is merged into <code>self.config</code> at runtime. That checked-in-defaults / per-user-overrides split is exactly why every URL lives in <code>config.yaml</code> with <code>{}</code>/<code>{name}</code> placeholders while the secrets that fill them stay out of it. Both halves read back through the same <code>self.config[...]</code>.</p> <p>Split across files? Use relative imports</p> <p>If your service grows beyond a single <code>__init__.py</code>, import your own modules relatively:</p> <pre><code>from .helpers import parse_manifest # correct\nfrom unshackle.services.TAG.helpers import parse_manifest # breaks from a repo\n</code></pre> <p>A service loaded from a remote repo lives outside the <code>unshackle</code> package, so the absolute <code>unshackle.services.&lt;TAG&gt;.*</code> path does not resolve and the import fails with <code>no known parent package</code>. Relative imports work both locally and from a cloned repo.</p>"},{"location":"dev/creating-a-service/#the-service-base-class","title":"The Service base class","text":"<p>Every service subclasses <code>unshackle.core.service.Service</code>. The minimum is a Click <code>cli</code> entry point plus three abstract methods.</p>"},{"location":"dev/creating-a-service/#class-variables","title":"Class variables","text":"<p>Declared at class level to configure framework behaviour:</p> Variable Type Purpose <code>ALIASES</code> <code>tuple[str, ...]</code> Extra tags that resolve to this service (e.g. <code>(\"EX\", \"DOMAIN\")</code>). Default <code>()</code>. <code>GEOFENCE</code> <code>tuple[str, ...]</code> IP region codes the service requires. Empty = no geofence. The first entry is treated as the main region for auto-proxy. <code>VAULT_TAG</code> <code>Optional[str]</code> Overrides the key-vault namespace so sibling services can share one vault. Default <code>None</code> (use the service's own tag). <code>AUTH_METHODS</code> <code>Optional[tuple[str, ...]]</code> Auth methods accepted (<code>\"cookies\"</code> / <code>\"credentials\"</code>). When <code>None</code>, the REST <code>/services</code> endpoint infers them from <code>authenticate()</code>. <code>NO_SUBTITLES</code> <code>bool</code> Set <code>True</code> on a service with no subtitle tracks to skip subtitle handling entirely. <p><code>NO_SUBTITLES</code> is a convention, not a base-class attribute</p> <p><code>NO_SUBTITLES</code> is checked by <code>dl.py</code> via <code>hasattr</code> and is deliberately not declared on the <code>Service</code> base class, so it only exists if your service defines it. Setting <code>NO_SUBTITLES = True</code> is what makes the pipeline skip subtitle work for services that never carry subtitles; leave it off otherwise.</p> <p><code>GEOFENCE</code> drives an automatic proxy: on startup, if you did not pass an explicit <code>--proxy</code>, the base class does a live IP check and, if your region is blocked, fetches a proxy to <code>GEOFENCE[0]</code> from your configured proxy providers.</p> <pre><code>class EXAMPLE(Service):\n ALIASES = (\"EX\", \"DOMAIN\")\n GEOFENCE = (\"US\", \"UK\")\n VAULT_TAG = \"DIFFERENT_NAME\"\n</code></pre>"},{"location":"dev/creating-a-service/#what-service__init__-wires-up","title":"What <code>Service.__init__</code> wires up","text":"<p>When you call <code>super().__init__(ctx)</code>, the base class sets up the attributes you will use throughout the service:</p> Attribute What it is <code>self.config</code> This service's <code>config.yaml</code> contents (a dict), or <code>None</code> if absent. <code>self.log</code> A <code>logging.Logger</code> named after your class. <code>self.session</code> A prepared <code>requests.Session</code> with config headers and a retry adapter (5 retries, backoff 0.2, retries on 429/500/502/503/504). <code>self.cache</code> A <code>Cacher</code> for arbitrary key/value data (tokens, etc.). <code>self.title_cache</code> A region/account-aware <code>TitleCacher</code> used by <code>get_titles_cached</code>. <code>self.cache_dir</code> <code>config.directories.cache / &lt;ClassName&gt;</code>. <code>self.track_request</code> A <code>TrackRequest</code> built from the CLI <code>--vcodec</code> / <code>--range</code> / <code>--best-available</code> flags. <code>self.credential</code> <code>None</code> until <code>authenticate()</code> runs. <code>self.current_region</code> The two-letter region resolved from proxy/IP. <p><code>self.track_request</code> is a small dataclass you can read and rewrite before fetching tracks:</p> <pre><code>@dataclass\nclass TrackRequest:\n codecs: list[Video.Codec] = [] # empty == accept any codec\n ranges: list[Video.Range] = [Video.Range.SDR]\n best_available: bool = False\n</code></pre> <p>Read the request, don't second-guess the user</p> <p>Services may narrow <code>track_request</code> for hard technical constraints (e.g. \"HDR on this service is only delivered as HEVC\"), but must not filter the tracks they return by resolution, bitrate, or language. All selection is done by the core after <code>get_tracks</code> returns.</p> <p>Override <code>get_session()</code> to defeat TLS-fingerprint bot detection</p> <p>The base <code>get_session()</code> returns a plain <code>requests.Session</code> (config headers + retry adapter) and deliberately does not do TLS impersonation. When a provider blocks you on TLS fingerprint alone, override it to return <code>session(\"Chrome131\")</code> (any <code>rnet.Impersonate</code> preset). <code>RnetSession</code> is a drop-in <code>requests.Session</code> replacement (same <code>.get</code>/<code>.post</code>/cookie-jar interface), so nothing else in the service changes. If instead you need specific SSL cipher behaviour, mount <code>unshackle.core.utils.sslciphers.SSLCiphers</code> onto a plain <code>requests.Session</code>.</p>"},{"location":"dev/creating-a-service/#the-methods-you-implement","title":"The methods you implement","text":"<p>Methods run in the order shown. Only the three abstract ones are mandatory.</p> <pre><code>graph LR\n A[cli] --&gt; B[__init__] --&gt; C[authenticate] --&gt; D[get_titles] --&gt; E[get_tracks] --&gt; F[get_chapters]</code></pre>"},{"location":"dev/creating-a-service/#cli-the-click-entry-point","title":"<code>cli</code>: the Click entry point","text":"<p>A static method decorated as a Click command. It defines the CLI arguments and returns an instance of your service. Keep the command <code>name=</code> matching the tag.</p> <p><code>name=</code> is cosmetic: the directory name is what resolves the command</p> <p><code>unshackle dl EXAMPLE</code> is dispatched by the folder/class name, not by the <code>name=</code> in <code>@click.command</code>. A mismatched <code>name=</code> still loads and runs; it just produces confusing <code>--help</code>/usage output that names the wrong command. That confusing output is the reason to keep it in sync, not any dispatch requirement.</p> <pre><code>@staticmethod\n@click.command(name=\"EXAMPLE\", short_help=\"https://domain.com\", help=__doc__)\n@click.argument(\"title\", type=str)\n@click.option(\"-m\", \"--movie\", is_flag=True, default=False, help=\"Treat the title as a movie.\")\n@click.option(\"-d\", \"--device\", type=click.Choice([\"android_tv\", \"web\", \"ios\"]), default=\"android_tv\")\n@click.pass_context\ndef cli(ctx: click.Context, **kwargs: Any) -&gt; EXAMPLE:\n return EXAMPLE(ctx, **kwargs)\n\ndef __init__(self, ctx: click.Context, title: str, movie: bool, device: str):\n self.title = title\n self.movie = movie\n self.device = device\n super().__init__(ctx) # wires up config, log, session, caches, track_request...\n self.cdm = ctx.obj.cdm\n</code></pre> <p>Your docstring becomes the CLI <code>--help</code> text (<code>help=__doc__</code>), so document the accepted URL/ID formats and options there.</p> <p>CDM-aware behaviour</p> <p>The resolved CDM is on <code>ctx.obj.cdm</code> (may be <code>None</code> for DRM-free runs). Use <code>is_widevine_cdm()</code> / <code>is_playready_cdm()</code> from <code>unshackle.core.cdm.detect</code> to classify it. These correctly handle local and remote CDMs, so never hand-roll an <code>isinstance</code> check. Services often pick a device profile or manifest endpoint based on which DRM the CDM speaks.</p>"},{"location":"dev/creating-a-service/#authenticate-optional-login","title":"<code>authenticate</code>: optional login","text":"<p>Override to log in with cookies and/or credentials. Call <code>super().authenticate()</code> first: the base implementation loads the cookie jar into <code>self.session.cookies</code> and stores <code>self.credential</code>. Do all token fetching here; it runs before <code>get_titles</code>.</p> <pre><code>def authenticate(self, cookies=None, credential=None) -&gt; None:\n super().authenticate(cookies, credential)\n self.session.headers.update({\"user-agent\": self.config[\"client\"][self.device][\"user_agent\"]})\n\n cache = self.cache.get(f\"tokens_{self.device}_{self.profile}\")\n if cache and cache.data.get(\"expires_in\", 0) &gt; int(datetime.now().timestamp()):\n self.log.info(\" + Using cached tokens\")\n else:\n token = self.session.post(self.config[\"endpoints\"][\"login\"], data=body).json()\n cache.set(data=token, expiration=token.get(\"expires_in\"))\n self.token = cache.data[\"token\"]\n</code></pre> <p>Cookies come from files under <code>directories.cookies</code>; credentials from the <code>credentials</code> map in <code>unshackle.yaml</code>. For interactive prompts (OTP, captcha) use <code>self.request_input(prompt)</code>, never a bare <code>input()</code>. Under <code>serve</code> mode there is no local terminal, so a bare <code>input()</code> would hang the server waiting on stdin that never arrives; <code>request_input</code> instead relays the prompt to the remote client through the attached <code>InputBridge</code>. Locally it routes through the shared Rich console (<code>console.input</code>) so the prompt renders correctly alongside progress and log output.</p> <p>Key token caches by whatever varies per session</p> <p>The cache key above is <code>tokens_{device}_{profile}</code> on purpose. A token cache must include every dimension that changes the token (device, profile, or <code>credential.sha1</code>), or two profiles/devices will share one cache entry and stomp each other's tokens. This isn't obvious from the caching API, which happily lets you use a single flat key.</p> <p>Handle the credential carefully</p> <p>Use the <code>Credential</code> only inside <code>authenticate()</code> to obtain tokens; don't stash it or the raw cookie jar elsewhere. The base class already caches identity for you.</p>"},{"location":"dev/creating-a-service/#get_titles-required","title":"<code>get_titles</code>: required","text":"<p>Return a titles collection for the given ID. The return type depends on content:</p> Return Contains Use for <code>Movies</code> <code>Movie</code> objects Films <code>Series</code> <code>Episode</code> objects Shows (flatten seasons into episodes) <code>Album</code> <code>Song</code> objects Music <p>Every title carries a <code>language</code> (its original recorded language) and an arbitrary <code>data</code> dict you can use to stash metadata for later methods. At least one title must be returned, or the ID is treated as invalid.</p> <pre><code>def get_titles(self) -&gt; Titles_T:\n match = re.match(self.TITLE_RE, self.title)\n if not match:\n raise ValueError(\"Could not parse a title ID - is the URL/ID correct?\")\n metadata = self.session.get(\n self.config[\"endpoints\"][\"metadata\"].format(title_id=match.group(\"title_id\")),\n params={\"token\": self.token},\n ).json()\n original_lang = Language.find(metadata[\"languages\"][0])\n\n return Movies([\n Movie(\n id_=metadata[\"id\"],\n service=self.__class__,\n name=metadata[\"title\"],\n year=metadata.get(\"releaseYear\") or None,\n language=original_lang, # ORIGINAL audio language, not the -l preference\n data=metadata, # read later as title.data\n )\n ])\n</code></pre> <p>Common constructor fields:</p> MovieEpisodeSong <pre><code>Movie(id_, service, name, year=None, language=None, data=None, description=None)\n</code></pre> <pre><code>Episode(id_, service, title, season, number, name=None, year=None,\n language=None, data=None, description=None, air_date=None)\n</code></pre> <p>Pass <code>air_date</code> for daily/sports content to name by date instead of <code>SxxExx</code>. Return a <code>Series([...])</code> of episodes.</p> <pre><code>Song(id_, service, name, artist, album, track, disc, year,\n language=None, data=None)\n</code></pre> <p>Return an <code>Album([...])</code> of songs.</p> <p>The ID must be unique and stable</p> <p><code>id_</code> must be truthy and, if it has a length, at least 4 characters, to avoid clashes. Use the service's own stable IDs.</p> <p>Title caching</p> <p>You can call <code>self.get_titles_cached()</code> instead of <code>get_titles()</code> from the framework path to reuse cached results and gracefully fall back to stale data when the API errors. It also applies the per-service <code>title_map</code> config.</p>"},{"location":"dev/creating-a-service/#get_tracks-required","title":"<code>get_tracks</code>: required","text":"<p>Given one title, return a <code>Tracks</code> object holding <code>Video</code>, <code>Audio</code>, and <code>Subtitle</code> tracks. In almost all cases you build these by parsing a manifest, not by hand.</p> <p>The manifest parsers live in <code>unshackle.core.manifests</code>:</p> <pre><code>from unshackle.core.manifests import DASH, HLS, ISM\n</code></pre> <p>Each exposes <code>from_url(url, session=...)</code> (or <code>from_text(text, url)</code>) and then <code>.to_tracks(language=...)</code>:</p> DASH (.mpd)HLS (.m3u8)ISM (Smooth Streaming) <pre><code>def get_tracks(self, title: Title_T) -&gt; Tracks:\n return DASH.from_url(manifest_url, session=self.session) \\\n .to_tracks(language=title.language)\n</code></pre> <pre><code>def get_tracks(self, title: Title_T) -&gt; Tracks:\n return HLS.from_url(manifest_url, session=self.session) \\\n .to_tracks(language=title.language)\n</code></pre> <p>The URL must be a variant (master) playlist, not a media playlist.</p> <pre><code>def get_tracks(self, title: Title_T) -&gt; Tracks:\n return ISM.from_url(manifest_url, session=self.session) \\\n .to_tracks(language=title.language)\n</code></pre> <p>Always pass <code>language=</code></p> <p>Pass the title's original language to <code>to_tracks(language=...)</code>. For DASH and HLS this is required as a fallback. If a track's language can't be derived and no valid fallback was given, <code>to_tracks</code> raises <code>ValueError</code>. It's also what lets the parser flag <code>is_original_lang</code> on each track (via <code>is_close_match</code>), driving <code>-l best/all</code> selection and the filename language token.</p> <p>Some services deliver a separate manifest per codec/range. The base class provides <code>_get_tracks_for_variants(title, fetch_fn)</code> to fan out over every codec\u00d7range in the <code>TrackRequest</code>, including <code>HYBRID</code> (fetch HDR10 + DV and merge) and <code>--best-available</code> skip-on-error handling:</p> <pre><code>def get_tracks(self, title: Title_T) -&gt; Tracks:\n def _fetch_variant(title, codec, range_) -&gt; Tracks:\n vcodec = \"H265\" if codec == Video.Codec.HEVC else \"H264\"\n return self._fetch_dash_manifest(title, vcodec=vcodec, range_=range_)\n return self._get_tracks_for_variants(title, _fetch_variant)\n</code></pre> <p>After parsing, you may correct track metadata the manifest gets wrong: stamp the real <code>video.range</code>, fix odd audio channel counts, mark descriptive audio, add hand-built subtitles or an <code>Attachment</code> (e.g. cover art). Do not filter for resolution/bitrate. See <code>_fetch_dash_manifest</code> in the EXAMPLE service for a thorough demonstration.</p> <p>Flip HDR10 \u2192 HDR10+ by hand when you know the platform embeds it</p> <p>HDR10+ is a bitstream (SEI) feature. The HLS parser intentionally does not sniff it from the stream, so a manifest that embeds HDR10+ SEI but labels the variant plain HDR10 will parse as HDR10. The label is the only signal the parser has, and it's wrong. Only the service author knows the platform embeds HDR10+, so it's on you to correct <code>video.range</code> to HDR10+ here for those services.</p> <p><code>get_tracks</code> is your only chance to capture license inputs</p> <p>The license callbacks (<code>get_widevine_license</code>, etc.) fire much later, in the download/decrypt step, long after <code>get_tracks</code> has returned, and they receive only <code>challenge</code>, <code>title</code>, and <code>track</code>. Nothing else from the manifest response reaches them. So anything a license call needs (the license URL, <code>dt-custom-data</code>, a session token) has to be stashed now, during <code>get_tracks</code>, onto <code>self.license_data</code> or <code>title.data</code>. This is a lifecycle-timing consequence you can't infer from the callback signatures.</p> <p>Provide the KID if you cheaply can</p> <p>If you can obtain a track's Key ID (32-char hex) without downloading stream data, set <code>track.kid</code>; it speeds up the decryption/key-lookup path. And be sure encrypted tracks carry the correct <code>drm</code> so the core licenses them.</p>"},{"location":"dev/creating-a-service/#get_chapters-required","title":"<code>get_chapters</code>: required","text":"<p>Return a <code>Chapters</code> object (0 or more <code>Chapter</code>s). You don't need to number or sort them; <code>Chapters</code> does that automatically and inserts a <code>00:00:00.000</code> marker if missing. A <code>Chapter</code> timestamp accepts <code>\"HH:MM:SS[.mmm]\"</code>, an int in milliseconds, or a float in seconds.</p> <pre><code>def get_chapters(self, title: Title_T) -&gt; Chapters:\n chapters = Chapters()\n seen: set[int] = set()\n for ch in title.data.get(\"chapters\", []):\n chapter = Chapter(timestamp=ch[\"start\"], name=ch.get(\"name\"))\n if chapter.timestamp == 0 or chapter.timestamp in seen:\n continue # see the warning below\n seen.add(chapter.timestamp)\n chapters.add(chapter)\n return chapters\n</code></pre> <p>Skip markers at 0 and de-duplicate timestamps before <code>add()</code></p> <p><code>Chapters.add()</code> auto-injects a <code>Chapter(0)</code> at <code>00:00:00.000</code> the first time you add any chapter, and it raises <code>ValueError</code> if a chapter already exists at an exact timestamp. So an API marker reported at <code>0</code> (an intro or recap that starts at the very beginning) collides with that auto-inserted opening chapter, and two markers sharing a timestamp collide with each other. Guard both cases: drop any marker at timestamp <code>0</code> and de-duplicate timestamps before adding, as above.</p> <p>An unnamed chapter is the idiom for closing a named range</p> <p>A <code>Chapter</code> with no name is perfectly valid. Inserting an unnamed marker is the standard way to close out a named range: e.g. add <code>Chapter(name=\"Intro\")</code> at the start and an unnamed <code>Chapter</code> where the intro ends, so the \"Intro\" label applies only to that span.</p> <p>Don't invent chapter names</p> <p>Never name chapters <code>\"Chapter 1\"</code> yourself. Leave unnamed markers unnamed; users who want generic names set <code>chapter_fallback_name</code> (e.g. <code>\"Chapter {i:02}\"</code>) in their config.</p>"},{"location":"dev/creating-a-service/#handling-drm","title":"Handling DRM","text":"<p>The core drives licensing. Your job is to answer the license challenges the CDM produces. Mark encrypted tracks with the right DRM in <code>get_tracks</code> (the manifest parsers do this automatically for PSSH/<code>EXT-X-KEY</code> found in the manifest), then implement the license callbacks you need. Each receives the challenge plus the current <code>title</code> and <code>track</code>:</p> Method For Returns <code>get_widevine_service_certificate</code> Widevine privacy mode The service certificate (bytes or base64 str), or <code>None</code>. <code>get_widevine_license</code> Widevine The raw license response (bytes or base64 str), unmodified. <code>get_playready_license</code> PlayReady The license response. Defaults to delegating to <code>get_widevine_license</code>. <code>get_clearkey_license</code> DASH <code>org.w3.clearkey</code> The JWK Set (dict/JSON/bytes), or <code>None</code> to let the framework POST the challenge to the manifest's Laurl. <pre><code>def get_widevine_license(self, *, challenge: bytes, title, track):\n response = self.session.post(\n self.license_data[\"url\"],\n data=challenge, # POST the challenge as-is\n headers={\"dt-custom-data\": self.license_data[\"data\"]},\n )\n response.raise_for_status()\n try:\n return response.json()[\"license\"] # some services wrap it in JSON\n except (ValueError, KeyError):\n return response.content # others return raw bytes\n</code></pre> <p>Return the license untouched</p> <p>Do not base64-encode or decode the challenge or response. Pass them through verbatim. A malformed license request can get your CDM/device flagged, banned, or downgraded.</p> <p><code>ClearKeyCENC</code> (<code>org.w3.clearkey</code>) has three escalating integration levels</p> <p>Pick the lowest level that works for the platform:</p> <ol> <li>The manifest carries a <code>&lt;Laurl&gt;</code>: implement nothing. The framework POSTs the challenge to that URL itself.</li> <li>A custom endpoint or extra headers are needed: override <code>get_clearkey_license</code> to do the POST yourself.</li> <li>Keys arrive obfuscated or through a bespoke channel: fetch and unwrap the key in <code>get_tracks</code> and pre-populate <code>drm.content_keys[kid] = key_hex</code> on the track's <code>ClearKeyCENC</code>. The non-obvious payoff: when every KID is already keyed, the framework skips the license round-trip entirely.</li> </ol> <p>Things you don't handle:</p> <ul> <li>HLS AES-128 (<code>ClearKey</code>) and DRM-free content have no license callback. The key comes from the manifest and is applied directly.</li> <li>Key vaults cache <code>KID:KEY</code> pairs across runs, so repeat downloads skip the license round-trip entirely.</li> <li>Decryption tooling (shaka-packager or mp4decrypt) and the choice of local vs remote CDM are user configuration, not service concerns.</li> </ul> <p>See the DRM &amp; CDM reference for the full picture.</p>"},{"location":"dev/creating-a-service/#optional-event-hooks","title":"Optional event hooks","text":"<p>Override any of these to react to pipeline stages (all no-ops by default): <code>on_segment_downloaded</code>, <code>on_track_downloaded</code>, <code>on_track_decrypted</code>, <code>on_track_repacked</code>, <code>on_track_multiplex</code>. Also override <code>search()</code> to yield <code>SearchResult</code> objects for <code>unshackle search</code>.</p> <pre><code>def search(self) -&gt; Generator[SearchResult, None, None]:\n results = self.session.get(self.config[\"endpoints\"][\"search\"],\n params={\"q\": self.title}).json()\n for r in results[\"entries\"]:\n yield SearchResult(id_=r[\"id\"], title=r[\"title\"],\n description=r.get(\"description\"), url=r.get(\"url\"))\n</code></pre>"},{"location":"dev/creating-a-service/#minimal-service-skeleton","title":"Minimal service skeleton","text":"<p>A complete, minimal single-manifest service. Save as <code>services/MYSVC/__init__.py</code> (class name <code>MYSVC</code>), with an optional <code>services/MYSVC/config.yaml</code> beside it.</p> services/MYSVC/__init__.py<pre><code>from __future__ import annotations\n\nimport re\nfrom typing import Any, Optional\n\nimport click\n\nfrom unshackle.core.manifests import DASH\nfrom unshackle.core.service import Service\nfrom unshackle.core.titles import Movie, Movies, Title_T, Titles_T\nfrom unshackle.core.tracks import Chapters, Tracks\n\n\nclass MYSVC(Service):\n \"\"\"\n MyService - https://myservice.com\n\n \\b\n Usage: unshackle dl MYSVC &lt;title-id-or-url&gt;\n \"\"\"\n\n ALIASES = (\"MY\",)\n GEOFENCE = (\"US\",)\n TITLE_RE = r\"^(?:https?://myservice\\.com/watch/)?(?P&lt;id&gt;[\\w-]+)\"\n\n @staticmethod\n @click.command(name=\"MYSVC\", short_help=\"https://myservice.com\", help=__doc__)\n @click.argument(\"title\", type=str)\n @click.pass_context\n def cli(ctx: click.Context, **kwargs: Any) -&gt; \"MYSVC\":\n return MYSVC(ctx, **kwargs)\n\n def __init__(self, ctx: click.Context, title: str):\n self.title = title\n super().__init__(ctx)\n\n def authenticate(self, cookies=None, credential=None) -&gt; None:\n super().authenticate(cookies, credential)\n # obtain any tokens here, e.g. self.token = ...\n\n def get_titles(self) -&gt; Titles_T:\n match = re.match(self.TITLE_RE, self.title)\n if not match:\n raise ValueError(\"Could not parse a title ID.\")\n meta = self.session.get(\n self.config[\"endpoints\"][\"metadata\"].format(id=match.group(\"id\"))\n ).json()\n return Movies([\n Movie(\n id_=meta[\"id\"],\n service=self.__class__,\n name=meta[\"title\"],\n year=meta.get(\"year\") or None,\n language=meta.get(\"originalLanguage\"),\n data=meta,\n )\n ])\n\n def get_tracks(self, title: Title_T) -&gt; Tracks:\n playback = self.session.get(\n self.config[\"endpoints\"][\"playback\"].format(id=title.id)\n ).json()\n return DASH.from_url(\n url=playback[\"manifest_url\"], session=self.session\n ).to_tracks(language=title.language)\n\n def get_chapters(self, title: Title_T) -&gt; Chapters:\n return Chapters()\n\n def get_widevine_license(self, *, challenge: bytes, title, track):\n res = self.session.post(self.config[\"endpoints\"][\"license\"], data=challenge)\n res.raise_for_status()\n return res.content\n</code></pre> services/MYSVC/config.yaml<pre><code>endpoints:\n metadata: https://api.myservice.com/v1/metadata/{id}\n playback: https://api.myservice.com/v1/playback/{id}\n license: https://api.myservice.com/v1/license/widevine\n</code></pre> <p>Test it with:</p> <pre><code>unshackle dl MYSVC https://myservice.com/watch/abc123\n</code></pre>"},{"location":"dev/creating-a-service/#checklist","title":"Checklist","text":"<ul> <li> Folder name, class name, and Click <code>name=</code> all match the tag exactly.</li> <li> <code>cli</code> is a <code>@staticmethod</code> returning an instance; <code>__init__</code> calls <code>super().__init__(ctx)</code>.</li> <li> <code>get_titles</code>, <code>get_tracks</code>, <code>get_chapters</code> implemented; titles carry the original <code>language</code>.</li> <li> Tracks come from a manifest parser with <code>to_tracks(language=title.language)</code>; no filtering by quality/language.</li> <li> Encrypted tracks are marked with DRM; the license callbacks you need return responses unmodified.</li> <li> URLs, user agents, and certificates live in <code>config.yaml</code>, read via <code>self.config[...]</code>.</li> <li> Multi-file services import their own modules relatively (<code>from .helpers import x</code>), so they work when loaded from a repo.</li> </ul> <p>Read <code>unshackle/services/EXAMPLE/</code> end to end; it annotates every feature touched above in one place.</p>"},{"location":"dev/service-architecture/","title":"Service Architecture","text":"<p>This page is the conceptual map of the internal object model that a service author works against. It ties together the moving parts: the <code>Service</code> base class, the <code>Title</code> hierarchy a service returns, the <code>Track</code> model those titles carry, the manifest parsers that produce tracks, the DRM hooks that license and decrypt them, and the request/session objects wired up for you at construction time.</p> <p>Who this page is for</p> <p>This is a developer reference. If you only want to run downloads, you never touch these classes directly; see Downloading and the CLI reference instead. If you are writing or reading a service plugin, this page explains what each object is and how the pieces connect. For a guided, step-by-step build, see Creating a Service; for exact signatures, see the auto-generated Service API, Titles API, and Tracks API.</p>"},{"location":"dev/service-architecture/#the-shape-of-a-download","title":"The shape of a download","text":"<p>A service is a translator between one streaming platform and unshackle's generic pipeline. It never downloads or decrypts anything itself; it just answers questions. The <code>dl</code> command drives the whole flow and only ever calls three required methods on your service, in order:</p> <pre><code>Service.get_titles \u2192 which movies / episodes / songs exist\n \u2502\nService.get_tracks \u2192 fetch a manifest for one title ...\n \u2502\nmanifest.to_tracks \u2192 ... parsed into Video / Audio / Subtitle tracks\n \u2502\nTrack.download \u2192 fetch + merge segments (core-driven)\n \u2502\nDRM license + decrypt \u2192 service license hooks \u2192 CDM \u2192 decrypt tool\n \u2502\nTracks.mux \u2192 mkvmerge \u2192 tagged .mkv\n</code></pre> <ol> <li><code>get_titles()</code> returns a <code>Titles</code> collection: the movies, episodes, or songs the platform exposes for the requested ID.</li> <li><code>get_tracks(title)</code> returns a <code>Tracks</code> object for a single chosen title. In practice this means fetching a manifest and handing it to a parser, which builds the <code>Video</code>/<code>Audio</code>/<code>Subtitle</code> objects.</li> <li><code>get_chapters(title)</code> returns any chapter markers.</li> </ol> <p>Everything after that (track selection, licensing, decryption, repacking, subtitle conversion, and muxing) is handled by the core using the objects your service returned. Your job is to produce accurate <code>Title</code> and <code>Track</code> objects; the framework does the rest.</p>"},{"location":"dev/service-architecture/#the-service-base-class","title":"The <code>Service</code> base class","text":"<p>Every service subclasses <code>unshackle.core.service.Service</code>, an abstract base class. Two kinds of members matter: class variables that describe the service, and methods that the pipeline calls.</p>"},{"location":"dev/service-architecture/#class-variables","title":"Class variables","text":"<p>Declared at the top of your service class, these are static descriptors:</p> Class variable Type Purpose <code>ALIASES</code> <code>tuple[str, ...]</code> Alternate tags the service answers to (resolved by <code>Services.get_tag</code>). <code>GEOFENCE</code> <code>tuple[str, ...]</code> ISO region codes the service requires; empty means no geofence. The first entry is treated as the \"main region\" for automatic proxy selection. <code>VAULT_TAG</code> <code>Optional[str]</code> Overrides the key-vault namespace; defaults to the service's own tag. <code>AUTH_METHODS</code> <code>Optional[tuple[str, ...]]</code> Accepted auth methods (<code>\"cookies\"</code> / <code>\"credentials\"</code>). When <code>None</code>, the REST <code>/services</code> endpoint infers them from <code>authenticate()</code>."},{"location":"dev/service-architecture/#required-methods","title":"Required methods","text":"<p>These are abstract; a service will not load unless it implements all three:</p> <ul> <li><code>get_titles() -&gt; Titles_T</code>: resolve the requested ID into a title collection.</li> <li><code>get_tracks(title) -&gt; Tracks</code>: build the track set for one title.</li> <li><code>get_chapters(title) -&gt; Chapters</code>: return chapter markers (may be empty).</li> </ul>"},{"location":"dev/service-architecture/#optional-methods-and-hooks","title":"Optional methods and hooks","text":"<ul> <li><code>authenticate(cookies=None, credential=None)</code>: the base implementation loads a <code>CookieJar</code> into <code>self.session.cookies</code> and stores <code>self.credential</code>. Override it to perform a real login handshake.</li> <li><code>search()</code>: raises <code>NotImplementedError</code> by default; implement it to support the <code>search</code> command.</li> <li>DRM license hooks: <code>get_widevine_service_certificate</code>, <code>get_widevine_license</code>, <code>get_playready_license</code> (delegates to Widevine by default), and <code>get_clearkey_license</code> (returns <code>None</code> by default). See DRM hooks below.</li> <li><code>request_input(prompt)</code>: prompts the user; routed through the serve-mode input bridge or the rich console.</li> <li>Event callbacks: <code>on_segment_downloaded</code>, <code>on_track_downloaded</code>, <code>on_track_decrypted</code>, <code>on_track_repacked</code>, <code>on_track_multiplex</code> let a service react to pipeline events (for example, MonaLisa decrypts each segment in <code>on_segment_downloaded</code>).</li> <li><code>resolve_server_keys(title)</code>: an escape hatch for services whose decryption keys are resolved server-side ahead of the normal per-track license flow. Unlike everything else here it is not declared on the <code>Service</code> base class at all: <code>dl.py</code> probes for it with <code>hasattr</code> and calls it (once, after track selection) only if your service defines it. Use it when keys must be fetched or injected in bulk before download, separate from the per-track license callbacks below.</li> </ul>"},{"location":"dev/service-architecture/#what-__init__-wires-up-for-you","title":"What <code>__init__</code> wires up for you","text":"<p>You rarely override <code>__init__</code>; the base constructor takes the Click context and sets up the objects your methods rely on:</p> Attribute What it is <code>self.config</code> The per-service config slice (see Request and session objects). <code>self.log</code> A <code>logging.Logger</code> named after your class. <code>self.session</code> A ready-to-use HTTP session (headers, retries, and proxy applied). <code>self.cache</code> A generic key/value <code>Cacher</code> namespaced to the service. <code>self.title_cache</code> A region- and account-aware <code>TitleCacher</code>. <code>self.cache_dir</code> <code>config.directories.cache / &lt;ServiceName&gt;</code>. <code>self.credential</code> The active <code>Credential</code>, or <code>None</code> until authenticated. <code>self.track_request</code> A <code>TrackRequest</code> describing the requested codecs, ranges, and best-available flag (see below). <p>The constructor also resolves proxies: it reads <code>--proxy</code> / <code>--proxy-query</code> / <code>--proxy-provider</code>, consults the per-service <code>proxy_map</code>, and, if <code>GEOFENCE</code> is set and no explicit proxy was given, does a live IP check and auto-fetches a proxy to <code>GEOFENCE[0]</code> when it detects a geoblock. See Proxies and VPN.</p> <p><code>TrackRequest</code></p> <p><code>self.track_request</code> is a small dataclass built from the CLI: <code>codecs</code> (from <code>--vcodec</code>, empty means \"accept any\"), <code>ranges</code> (from <code>--range</code>, default <code>[Video.Range.SDR]</code>), and <code>best_available</code>. Use it in <code>get_tracks</code> to decide which variants to fetch.</p>"},{"location":"dev/service-architecture/#titles-and-the-title-hierarchy","title":"Titles and the <code>Title</code> hierarchy","text":"<p><code>get_titles()</code> returns a title collection, one of the <code>Titles_T</code> types. Each collection holds one or more <code>Title</code> objects (<code>Title_T</code>). There are three parallel families, one per media kind:</p> Media kind Item (<code>Title_T</code>) Collection (<code>Titles_T</code>) Movies <code>Movie</code> <code>Movies</code> TV <code>Episode</code> <code>Series</code> Music <code>Song</code> <code>Album</code>, and <code>Music</code> (the base collection) <p>All items subclass <code>Title</code>, which carries the shared identity: a unique <code>id</code>, the originating <code>service</code> class, an optional original <code>language</code>, arbitrary <code>data</code>, and a freshly-constructed <code>self.tracks = Tracks()</code> that <code>get_tracks</code> will fill. Collections are sorted lists, so titles stay in a stable order.</p> <p>The unique ID is validated</p> <p><code>Title.__init__</code> rejects a falsy <code>id_</code>, and rejects any ID shorter than 4 characters (<code>\"The unique ID is not large enough, clash likely.\"</code>). Pick a stable, sufficiently unique identifier from the platform.</p>"},{"location":"dev/service-architecture/#constructors-at-a-glance","title":"Constructors at a glance","text":"<p>Each subclass adds its own required fields on top of <code>id_</code> and <code>service</code>:</p> MovieEpisodeSong <pre><code>Movie(id_, service, name, year=None, language=None, data=None, description=None)\n</code></pre> <p><code>name</code> is required; <code>year</code> is optional but must be a positive integer if given.</p> <pre><code>Episode(id_, service, title, season, number,\n name=None, year=None, language=None, data=None,\n description=None, air_date=None)\n</code></pre> <p><code>title</code> is the show name; <code>season</code> and <code>number</code> are required (0 is allowed). An <code>air_date</code> is normalized to a <code>date</code> so the <code>{date}</code> naming token stays clean, and a placeholder episode <code>name</code> like <code>\"Episode 4\"</code> is discarded automatically.</p> <pre><code>Song(id_, service, name, artist, album, track, disc, year,\n language=None, data=None)\n</code></pre> <p><code>name</code>, <code>artist</code>, <code>album</code>, <code>track</code>, <code>disc</code>, and <code>year</code> are all required and validated.</p>"},{"location":"dev/service-architecture/#title-remapping","title":"Title remapping","text":"<p>After titles are fetched (and after any cache), the framework applies <code>remap_titles(titles, title_map)</code> using the per-service <code>title_map</code> config. This does an exact-string rename (<code>Episode</code>s are matched on their show <code>title</code>, <code>Movie</code>s and <code>Song</code>s on their <code>name</code>), so a platform's odd naming can be normalized to what your library expects. Titles are also cache-wrapped via <code>get_titles_cached()</code>, which is region- and account-aware; see the TitleCacher notes.</p> <p>The ordering here is deliberate on both sides. <code>title_map</code> is applied after the title cache so that editing the map takes effect immediately, without forcing a cache reset, and before metadata enrichment (<code>--enrich</code>) so that an explicit enrich override still wins over a mapped name.</p>"},{"location":"dev/service-architecture/#tracks-and-the-track-model","title":"Tracks and the <code>Track</code> model","text":"<p>A <code>Tracks</code> object is the container <code>get_tracks</code> returns. It has typed buckets (<code>videos</code>, <code>audio</code>, <code>subtitles</code>, <code>chapters</code>, and <code>attachments</code>) plus a <code>manifest_url</code>. Iterating a <code>Tracks</code> yields only video, audio, and subtitle tracks (not chapters or attachments), and the canonical display/mux order is Video \u2192 Audio \u2192 Subtitle \u2192 Chapter \u2192 Attachment.</p> <p>Track IDs must be deterministic</p> <p><code>Tracks.add</code> refuses duplicate IDs. Track IDs are CRC32-derived from the track's identity (URL, codec, language, bitrate) and must be stable across requests, never random. The manifest parsers already do this correctly; if you build tracks by hand, keep IDs deterministic or <code>add</code> will raise.</p>"},{"location":"dev/service-architecture/#the-base-track","title":"The base <code>Track</code>","text":"<p><code>Track</code> is the base for <code>Video</code>, <code>Audio</code>, and <code>Subtitle</code>. (<code>Chapter</code>, <code>Chapters</code>, and <code>Attachment</code> are standalone classes, not <code>Track</code> subclasses.) Every track knows how it is delivered, via <code>Track.Descriptor</code>:</p> Descriptor Delivery <code>URL</code> A single direct URL. <code>HLS</code> HTTP Live Streaming. <code>DASH</code> Dynamic Adaptive Streaming over HTTP. <code>ISM</code> Smooth Streaming. <p>Key attributes include <code>url</code> (a string or list of strings), <code>language</code> (a <code>langcodes.Language</code>), <code>drm</code> (an optional iterable of DRM objects), <code>needs_repack</code>, and descriptor-specific state stashed in <code>track.data[\"hls\"]</code> / <code>track.data[\"dash\"]</code>. When <code>name</code> is omitted, a human-readable name is derived from the language automatically.</p>"},{"location":"dev/service-architecture/#video","title":"<code>Video</code>","text":"<p><code>Video</code> adds <code>codec</code>, <code>range</code>, <code>bitrate</code>, <code>width</code>, <code>height</code>, <code>fps</code>, <code>scan_type</code>, and closed-caption descriptors. The relevant enums:</p> <ul> <li><code>Video.Codec</code>: <code>AVC</code> (H.264), <code>HEVC</code> (H.265), <code>VC1</code>, <code>VP8</code>, <code>VP9</code>, <code>AV1</code>.</li> <li><code>Video.Range</code>: <code>SDR</code>, <code>HLG</code>, <code>HDR10</code>, <code>HDR10P</code> (HDR10+), <code>DV</code> (Dolby Vision), and <code>HYBRID</code>. <code>HYBRID</code> is special: it tells the pipeline to select both an HDR10(+) base and a DV track and merge the DV RPU onto the HDR10 stream with <code>dovi_tool</code> (see Dolby Vision hybrid).</li> </ul> <p>Bitrate units</p> <p>Both <code>Video</code> and <code>Audio</code> store <code>bitrate</code> in bytes per second (rounded up), even though the string form displays kb/s.</p>"},{"location":"dev/service-architecture/#audio","title":"<code>Audio</code>","text":"<p><code>Audio</code> adds <code>bitrate</code>, <code>channels</code>, <code>joc</code> (Joint Object Coding, the Atmos indicator), and <code>descriptive</code>. <code>Audio.Codec</code> covers <code>AAC</code>, <code>AC3</code> (<code>DD</code>), <code>EC3</code> (<code>DD+</code>), <code>AC4</code>, <code>OPUS</code>, <code>OGG</code> (Vorbis), <code>DTS</code>, <code>ALAC</code>, and <code>FLAC</code>. The <code>atmos</code> property is <code>True</code> when <code>joc</code> is set (or when <code>extra</code> flags it).</p>"},{"location":"dev/service-architecture/#subtitle","title":"<code>Subtitle</code>","text":"<p><code>Subtitle</code> adds three mutually-constrained flags: <code>cc</code> (closed captions), <code>sdh</code> (subtitles for the deaf and hard-of-hearing), and <code>forced</code>. A track cannot be both <code>cc</code> and <code>sdh</code>, and <code>forced</code> cannot combine with either. <code>Subtitle.Codec</code> includes <code>SubRip</code> (SRT), <code>WebVTT</code> (VTT), <code>SubStationAlpha</code>/<code>SubStationAlphav4</code> (SSA/ASS), <code>TimedTextMarkupLang</code> (TTML), <code>SAMI</code>, and the box-encapsulated DASH formats <code>fTTML</code> (STPP) and <code>fVTT</code> (WVTT). Subtitles receive post-download normalization (segment merging, WebVTT sanitization, format conversion, and optional SDH stripping), all documented for users in Subtitles.</p>"},{"location":"dev/service-architecture/#chapters-and-attachments","title":"Chapters and attachments","text":"<ul> <li><code>Chapter(timestamp, name=None)</code>: a single marker; the timestamp accepts <code>HH:MM:SS[.mmm]</code>, integer milliseconds, or float seconds.</li> <li><code>Chapters</code>: a sorted collection that auto-inserts a <code>00:00:00.000</code> chapter and reads/writes OGM Simple format.</li> <li><code>Attachment</code>: a font or image attached to the mux (e.g. fonts an ASS subtitle references), built from a local <code>path</code> or a <code>url</code>.</li> </ul>"},{"location":"dev/service-architecture/#selection-sorting-and-muxing","title":"Selection, sorting, and muxing","text":"<p><code>Tracks</code> is also the selection engine the <code>dl</code> command uses. It offers <code>sort_videos</code> / <code>sort_audio</code> / <code>sort_subtitles</code> (P2P-standard ordering), predicate-based <code>select_*</code> filters, <code>by_resolutions</code>, and <code>by_language</code>. When downloads finish, the same object multiplexes everything: <code>Tracks.mux(title, ...)</code> builds and runs an <code>mkvmerge</code> command, applying language, default-track, forced, and hearing-impaired flags, attaching chapters and fonts, and writing a <code>.muxed.mkv</code> (or <code>.mka</code> / <code>.mks</code> for audio- or subtitle-only sets). As a service author you never call <code>mux</code> yourself; you just return correct tracks.</p>"},{"location":"dev/service-architecture/#manifest-parsers","title":"Manifest parsers","text":"<p>Most services do not build tracks by hand; they hand a manifest to one of three parsers in <code>unshackle.core.manifests</code>. Each parser has the same three-part contract:</p> Format Class Notes MPEG-DASH (<code>.mpd</code>) <code>DASH</code> Parses <code>&lt;MPD&gt;</code>; enumerates tracks from the first content period. HLS (<code>.m3u8</code>) <code>HLS</code> Requires a variant (master) playlist, not a media playlist. Smooth Streaming (<code>.ism</code>) <code>ISM</code> Synthesizes init segments from <code>CodecPrivateData</code>."},{"location":"dev/service-architecture/#the-parser-contract","title":"The parser contract","text":"<ol> <li>Construct: <code>DASH.from_url(url, session=...)</code> or <code>DASH.from_text(text, url)</code> (and likewise for <code>HLS</code> / <code>ISM</code>). A <code>url</code> is always required, even for <code>from_text</code>, because relative segment paths are resolved against it.</li> <li><code>to_tracks(...)</code>: parses the manifest into a <code>Tracks</code> container of <code>Video</code>, <code>Audio</code>, and <code>Subtitle</code> objects, each carrying descriptor-specific state.</li> <li><code>download_track(...)</code>: a staticmethod the core calls to fetch, decrypt, and merge segments. You do not call it; you just return the tracks it will operate on.</li> </ol> <p>A typical <code>get_tracks</code> therefore looks like fetching the manifest text with <code>self.session</code> and returning <code>DASH.from_text(mpd, url).to_tracks(language=title.language)</code>.</p> <p>Pass the original language</p> <p>DASH and HLS <code>to_tracks</code> raise <code>ValueError</code> if a track's language cannot be derived and no valid fallback was supplied. Always pass the title's original recorded language. For HLS this fallback is used directly for the primary track, since HLS variants carry no language.</p>"},{"location":"dev/service-architecture/#segment-filtering-hooks","title":"Segment-filtering hooks","text":"<ul> <li>HLS: set <code>track.OnSegmentFilter(segment)</code> to drop unwanted segments (ads/bumpers).</li> <li>DASH: pass a <code>period_filter</code> callable to <code>to_tracks</code> to drop whole periods. Caching-breadth periods some services emit and non-<code>content</code> segment types are dropped automatically.</li> </ul>"},{"location":"dev/service-architecture/#format-gotchas-worth-knowing","title":"Format gotchas worth knowing","text":"<ul> <li>DASH enumerates tracks from only the first content period, but downloads segments from all content periods matching the representation. <code>SegmentTemplate</code>, <code>SegmentList</code>, and <code>SegmentBase</code> addressing and <code>$Number%0Nd$</code> padding are handled.</li> <li>HLS re-fetches the media playlist at download time, recovers <code>SUPPLEMENTAL-CODECS</code> from raw text (python-m3u8 drops it) to detect Dolby Vision composite streams, and uses the media-sequence-number IV for AES-128 keys that omit an explicit IV.</li> <li>ISM has no segment list and no init segments: segment URLs are synthesized from the <code>&lt;c&gt;</code> fragment timeline, and a <code>moov</code>/<code>ftyp</code> init box is rebuilt from <code>CodecPrivateData</code> (supported for AVC, HEVC, DV-over-HEVC, AAC, EC-3, and TTML).</li> </ul>"},{"location":"dev/service-architecture/#drm-hooks","title":"DRM hooks","text":"<p>If a track carries DRM, the framework licenses and decrypts it, but it needs your service to talk to the platform's license server. unshackle recognizes five DRM systems:</p> DRM class System License flow <code>Widevine</code> Widevine CDM challenge \u2192 license server \u2192 content keys (<code>.wvd</code> device) <code>PlayReady</code> PlayReady CDM challenge (WRM header) \u2192 license server \u2192 content keys (<code>.prd</code> device) <code>ClearKeyCENC</code> W3C <code>org.w3.clearkey</code> over CENC JSON KID request \u2192 JWK set; no CDM <code>ClearKey</code> HLS AES-128 key fetched directly from a URI; no CDM, no challenge <code>MonaLisa</code> Proprietary WASM DRM keys extracted locally; no license server <p><code>ClearKey</code> vs <code>ClearKeyCENC</code></p> <p>Despite the shared prefix these are entirely different systems. <code>ClearKey</code> is HLS AES-128, decrypted in-process. <code>ClearKeyCENC</code> is the W3C EME JWK flow over MPEG-CENC, decrypted with shaka-packager or mp4decrypt like Widevine.</p>"},{"location":"dev/service-architecture/#the-service-side-hooks","title":"The service-side hooks","text":"<p>The framework supplies the CDM and the decryption tool; your service provides the network calls that the CDM's challenge must be sent through. Override the hooks that your platform needs:</p> Hook Return Purpose <code>get_widevine_service_certificate(title, track, challenge)</code> cert bytes Optional privacy-mode service certificate. <code>get_widevine_license(title, track, challenge)</code> license bytes POST the Widevine challenge to the license server, return the response. <code>get_playready_license(title, track, challenge)</code> license Same for PlayReady; defaults to delegating to Widevine. <code>get_clearkey_license(title, track, challenge)</code> dict / str / bytes / <code>None</code> For <code>ClearKeyCENC</code>; return <code>None</code> to let the framework POST to the manifest <code>Laurl</code>. <p>You do not open CDM sessions or run shaka-packager yourself. The <code>Widevine</code>/<code>PlayReady</code> classes drive the CDM handshake and invoke the decryption tool. Your hook is just the \"send this challenge, give me back the license\" step.</p>"},{"location":"dev/service-architecture/#how-a-cdm-is-chosen-and-keys-are-found","title":"How a CDM is chosen and keys are found","text":"<p>CDM selection is config-driven: the <code>cdm</code> map resolves a service tag (and optionally the track quality or DRM type) to a device name, which <code>load_cdm</code> instantiates as a local <code>.wvd</code>/<code>.prd</code> or a remote CDM. Before ever requesting a license, the framework tries an in-process key cache and the configured key vaults; only unresolved KIDs trigger an actual license request, and newly licensed keys are written back to every vault. This is why the same key is rarely re-licensed twice. Users configure all of this in DRM and CDM and Key vaults; the API surface is documented in the DRM API reference.</p>"},{"location":"dev/service-architecture/#dolby-vision-and-hybrid","title":"Dolby Vision and hybrid","text":"<p>Two DV mechanisms sit on top of the track model. DV fixup re-exposes DV signaling on HLS streams that carry a valid DV RPU but advertise plain HEVC (<code>dv_compatible_bitstream</code>). Hybrid processing (<code>Video.Range.HYBRID</code>) selects an HDR10(+) base and a DV donor, extracts the RPU with <code>dovi_tool</code>, and injects it onto the base layer, producing a single stream with both HDR10 and DV metadata. Both are automatic once the right tracks are selected; a service only needs to expose accurate ranges.</p>"},{"location":"dev/service-architecture/#request-and-session-objects","title":"Request and session objects","text":"<p>Everything a service does over the network flows through objects the base constructor prepared, all derived from the Click context (<code>ctx</code>) that <code>dl</code> passes in.</p> <ul> <li><code>self.config</code>: your service's slice of <code>unshackle.yaml</code>, i.e. <code>config.services[&lt;ServiceName&gt;]</code>. This is a plain dict; use it for per-service settings like base URLs, an API key, or a <code>title_map</code>. See Configuration.</li> <li><code>self.session</code>: a <code>requests.Session</code> with <code>config.headers</code> applied, a retry policy (<code>total=5</code>, backoff, retry on 429/5xx), and any resolved proxy already mounted. Pass this session into the manifest parsers and DRM calls so headers, cookies, and proxies flow everywhere. (unshackle also ships an rnet-based TLS-fingerprinting session used by the newer <code>session()</code> factory and configured via the <code>network</code> config key.)</li> <li><code>self.credential</code>: the active <code>Credential</code> (<code>username:password[:extra]</code>), populated by <code>authenticate</code>. Its <code>sha1</code> is used as the account hash for cache keys.</li> <li><code>self.cache</code>: a generic <code>Cacher</code>: JSON key/value storage under the service's cache dir, with CRC32 integrity checks, versioning, and optional expiry (auto-derived from a JWT <code>exp</code> claim when present). Good for auth tokens and API responses.</li> <li><code>self.title_cache</code>: a <code>TitleCacher</code> that wraps <code>get_titles</code> results, keyed by title ID, region, and account hash. It serves fresh data within <code>title_cache_time</code>, falls back to stale data within <code>title_cache_max_retention</code> when an API call fails, and is bypassed by <code>--no-cache</code>.</li> <li><code>self.track_request</code>: the <code>TrackRequest</code> describing what the user asked for (codecs, ranges, best-available), for use inside <code>get_tracks</code>.</li> </ul> <p>A minimal service skeleton</p> services/EXMP/__init__.py<pre><code>from unshackle.core.service import Service\nfrom unshackle.core.manifests import DASH\nfrom unshackle.core.titles import Movie, Movies\n\n\nclass EXMP(Service):\n ALIASES = (\"example\",)\n GEOFENCE = (\"us\",)\n\n def get_titles(self) -&gt; Movies:\n data = self.session.get(f\"https://api.example.com/title/{self.title}\").json()\n return Movies([\n Movie(\n id_=data[\"id\"],\n service=self.__class__,\n name=data[\"name\"],\n year=data.get(\"year\"),\n language=data.get(\"language\"),\n )\n ])\n\n def get_tracks(self, title) -&gt; \"Tracks\":\n mpd_url = self.session.get(...).json()[\"manifest\"]\n mpd = self.session.get(mpd_url).text\n return DASH.from_text(mpd, mpd_url).to_tracks(language=title.language)\n\n def get_chapters(self, title):\n return []\n\n def get_widevine_license(self, *, challenge, title, track):\n return self.session.post(\"https://lic.example.com/wv\", data=challenge).content\n</code></pre> <p>The directory name (<code>EXMP</code>) must exactly match the class name; that stem is the service tag. Put your service in one of the <code>directories.services</code> paths.</p>"},{"location":"dev/service-architecture/#where-to-go-next","title":"Where to go next","text":"<ul> <li>Creating a Service: a guided walkthrough that builds on this model.</li> <li>Service API: exact signatures for the <code>Service</code> base class.</li> <li>Titles API and Tracks API: the full object reference.</li> <li>DRM API: the DRM and CDM classes in detail.</li> <li>Downloading: how the flags a user passes map onto track selection.</li> </ul>"},{"location":"dev/rest-api/","title":"REST API Overview","text":"<p>unshackle ships with a built-in HTTP server. Alongside the command-line tool, you can run <code>unshackle serve</code> and drive the same download engine over a REST API: searching services, listing titles and tracks, queueing downloads, watching live progress, and browsing history, all as JSON over HTTP.</p> <p>This page explains what the API is for, how to start the server, where it listens, and how the endpoints are organised. Later pages cover each area in depth.</p> <p>Who this section is for</p> <p>The REST API is aimed at people building automation, dashboards, or remote clients on top of unshackle. If you only download the occasional title, the command-line tool does everything the API does and is simpler to use. Reach for the API when you want a long-running service, a job queue, or a web front-end.</p>"},{"location":"dev/rest-api/#what-the-api-is-for","title":"What the API is for","text":"<p>The server exposes the same capabilities as the <code>dl</code> command, but as discrete HTTP calls you can script against:</p> <ul> <li>Discovery: list the services available on the server, run a service's search, and enumerate the titles and tracks behind a title ID.</li> <li>Downloading: submit a download as a background job, then poll its status and live progress, cancel it, retry it, or bump it to the front of the queue.</li> <li>History and housekeeping: read the log of finished jobs, inspect the server's effective (redacted) configuration, check external tool versions, and clear caches or temp files.</li> <li>Remote-download sessions: a thin local client can authenticate against a service on the server, then pull titles, tracks, and segment info back, and proxy DRM licensing. This is how one machine with the credentials and CDMs can serve downloads to another. See Remote Sessions.</li> </ul> <p>Because every download runs as a queued job in a separate worker process, the API is well suited to running unattended: submit work, come back later, and read the result.</p>"},{"location":"dev/rest-api/#running-the-server","title":"Running the server","text":"<p>Start the server with the <code>serve</code> command:</p> Start the REST API on the default host and port<pre><code>unshackle serve\n</code></pre> <p>By default the server binds to <code>127.0.0.1:8786</code> and requires an API key on every request. It also serves the local Widevine and PlayReady CDM endpoints (for pywidevine / pyplayready clients) in addition to the REST API.</p> <p>An API key is required by default</p> <p>Unless you pass <code>--no-key</code>, the server needs an API secret configured under the <code>serve</code> section of your config. If none is set, <code>unshackle serve</code> refuses to start. See Authentication for how to set <code>api_secret</code> and how the <code>X-Secret-Key</code> header works.</p>"},{"location":"dev/rest-api/#common-options","title":"Common options","text":"<p>The <code>serve</code> command accepts the following flags:</p> Option Default Effect <code>-h</code>, <code>--host</code> <code>127.0.0.1</code> Address to bind to. Use <code>0.0.0.0</code> to accept connections from other machines. <code>-p</code>, <code>--port</code> <code>8786</code> Port to bind to. <code>--api-only</code> off Serve only the REST API, without the Widevine/PlayReady CDM HTTP endpoints. <code>--no-widevine</code> off Disable the Widevine CDM endpoints. Cannot be combined with <code>--api-only</code>. <code>--no-playready</code> off Disable the PlayReady CDM endpoints. Cannot be combined with <code>--api-only</code>. <code>--no-key</code> off Disable API-key authentication entirely; every request is allowed. <code>--remote-only</code> off Expose only the remote-session subset of routes. Implies <code>--api-only</code>. <code>--debug-api</code> off Include tracebacks and worker stderr in error responses. <code>--debug</code> off Enable debug-level logging. <code>--caddy</code> off Also launch Caddy as a reverse proxy, using the <code>Caddyfile</code> in your user-config directory. Serve the REST API only, on all interfaces<pre><code>unshackle serve --api-only --host 0.0.0.0 --port 8786\n</code></pre> <p>Binding to a public interface</p> <p><code>--no-key</code> disables authentication completely. Anyone who can reach the port can search, download, and read your configuration. Only combine it with a host like <code>127.0.0.1</code>, or keep the default key-based auth when binding to <code>0.0.0.0</code>. Put a TLS-terminating reverse proxy (Caddy, nginx) in front for anything internet-facing.</p>"},{"location":"dev/rest-api/#server-modes","title":"Server modes","text":"<p>The set of routes that is actually mounted depends on how you start the server:</p> Default (CDM + REST)<code>--api-only</code><code>--remote-only</code> <p>Both the pywidevine/pyplayready CDM endpoints and the full REST API are mounted. This is the mode used when you run <code>unshackle serve</code> with no mode flags.</p> <p>Only the REST API is mounted; the CDM HTTP endpoints are omitted. Authentication uses the single configured API key (or none, with <code>--no-key</code>).</p> <p>Only the remote-session subset of routes is exposed (health, services, search, and everything under <code>/api/session/*</code>). This mode implies <code>--api-only</code>, and the interactive Swagger UI is not mounted.</p>"},{"location":"dev/rest-api/#base-url","title":"Base URL","text":"<p>All REST endpoints live under the <code>/api</code> prefix. With the default bind address the base URL is:</p> <pre><code>http://127.0.0.1:8786/api\n</code></pre> <p>Every path in this documentation is relative to the host and port. For example, the health check is <code>GET http://127.0.0.1:8786/api/health</code>.</p> <p>Interactive API docs</p> <p>Unless you started the server with <code>--remote-only</code>, an interactive Swagger UI is available at <code>/api/docs/</code>. It is generated from the same route table the server actually serves, so it stays in sync with the running build. Note that in <code>--api-only</code> mode the docs page is itself behind the API key; only <code>/api/health</code> is exempt from authentication.</p> <p>A quick smoke test that needs no key:</p> Confirm the server is up<pre><code>curl http://127.0.0.1:8786/api/health\n</code></pre> Response<pre><code>{\n \"status\": \"ok\",\n \"version\": \"5.3.0\",\n \"update_check\": {\n \"update_available\": false,\n \"current_version\": \"5.3.0\",\n \"latest_version\": \"5.3.0\"\n }\n}\n</code></pre>"},{"location":"dev/rest-api/#endpoint-map","title":"Endpoint map","text":"<p>Every REST path uses JSON request and response bodies and lives under <code>/api</code>. The table below is a map of the surface; the Endpoints page documents each request and response in full.</p>"},{"location":"dev/rest-api/#discovery","title":"Discovery","text":"Method Path Purpose <code>GET</code> <code>/api/health</code> Liveness and version check. Never requires a key. <code>GET</code> <code>/api/services</code> List the services available on this server. <code>POST</code> <code>/api/search</code> Run a service's search for a query. <code>POST</code> <code>/api/list-titles</code> List the titles behind a service title ID. <code>POST</code> <code>/api/list-tracks</code> List the video, audio, and subtitle tracks for a title."},{"location":"dev/rest-api/#downloads-and-jobs","title":"Downloads and jobs","text":"Method Path Purpose <code>POST</code> <code>/api/download</code> Queue a download; returns a <code>job_id</code>. <code>GET</code> <code>/api/download/jobs</code> List jobs, with filtering and sorting. <code>POST</code> <code>/api/download/jobs/clear-finished</code> Remove all finished jobs. <code>GET</code> <code>/api/download/jobs/{job_id}</code> Full detail for one job. <code>DELETE</code> <code>/api/download/jobs/{job_id}</code> Cancel a running job, or remove a finished one. <code>POST</code> <code>/api/download/jobs/{job_id}/retry</code> Re-queue a finished job's parameters as a new job. <code>POST</code> <code>/api/download/jobs/{job_id}/priority</code> Move a queued job to the front."},{"location":"dev/rest-api/#history-and-server-info","title":"History and server info","text":"Method Path Purpose <code>GET</code> <code>/api/history</code> Read the persisted log of finished jobs. <code>DELETE</code> <code>/api/history/{job_id}</code> Delete a history entry. <code>GET</code> <code>/api/profiles</code> Named credential profiles per service. <code>GET</code> <code>/api/config</code> The server's effective, redacted configuration. <code>GET</code> <code>/api/env/check</code> Presence and versions of external tools."},{"location":"dev/rest-api/#maintenance","title":"Maintenance","text":"Method Path Purpose <code>POST</code> <code>/api/maintenance/clear-cache</code> Clear the cache directory. <code>POST</code> <code>/api/maintenance/clear-temp</code> Clear the temp directory. <code>POST</code> <code>/api/maintenance/refresh-services</code> <code>git pull</code> each configured service repository."},{"location":"dev/rest-api/#remote-download-sessions","title":"Remote-download sessions","text":"Method Path Purpose <code>POST</code> <code>/api/session/create</code> Start a server-side, authenticated service session. <code>GET</code> <code>/api/session/{session_id}</code> Session info and time-to-live. <code>DELETE</code> <code>/api/session/{session_id}</code> Tear down a session. <code>GET</code> <code>/api/session/{session_id}/titles</code> Titles for the session's title ID. <code>POST</code> <code>/api/session/{session_id}/tracks</code> Tracks (with URLs) for a chosen title. <code>POST</code> <code>/api/session/{session_id}/segments</code> Per-track segment/download details. <code>POST</code> <code>/api/session/{session_id}/license</code> Proxy or server-side DRM licensing. <code>GET</code> <code>/api/session/{session_id}/prompt</code> Poll for interactive auth status/prompt. <code>POST</code> <code>/api/session/{session_id}/prompt</code> Submit an answer to an auth prompt. <p>Remote-only routes</p> <p>The health, services, search, and <code>/api/session/*</code> routes are the ones exposed when the server runs with <code>--remote-only</code>. Everything else (downloads, jobs, history, config, maintenance) is only available in the full or <code>--api-only</code> modes.</p>"},{"location":"dev/rest-api/#authentication-in-one-line","title":"Authentication in one line","text":"<p>With the default configuration, send your API secret in the <code>X-Secret-Key</code> header on every request except <code>/api/health</code>:</p> An authenticated request<pre><code>curl -X POST http://127.0.0.1:8786/api/search \\\n -H \"X-Secret-Key: your-api-secret\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"service\": \"EXAMPLE\", \"query\": \"example\"}'\n</code></pre> <p>A missing or unknown key returns <code>401</code>. The full model, including per-key service allowlists, is covered in Authentication.</p>"},{"location":"dev/rest-api/#where-to-go-next","title":"Where to go next","text":"<ul> <li>Quick Start: start the server, set a key, and run your first end-to-end download over the API.</li> <li>Authentication: the <code>X-Secret-Key</code> header, <code>--no-key</code>, per-key service allowlists, and CORS.</li> <li>Endpoints: every request body, query parameter, and response shape, endpoint by endpoint.</li> <li>Job Lifecycle: how a download moves from <code>queued</code> to a terminal state, live progress, cancellation, and retries.</li> <li>Remote Sessions: the <code>/api/session/*</code> flow for driving a service from a thin remote client.</li> <li>Error Responses: the standard error envelope, error codes, and their HTTP statuses.</li> </ul>"},{"location":"dev/rest-api/authentication/","title":"REST API Authentication","text":"<p>The unshackle REST API protects every endpoint (with one exception) behind a single API key. Clients present that key in a request header, and the server checks it against the keys defined in your configuration. This page explains how that check works, how to configure keys, how clients send them, and the extra controls that build on top of the key: per-key service allowlists, per-key CDM device access, and session IP binding.</p> <p>The API is started with the <code>unshackle serve</code> command. Authentication is on by default: if you start the server without an API key configured, it refuses to launch.</p> <p>Which server am I running?</p> <p><code>unshackle serve</code> can run in two shapes, and each uses a slightly different piece of code to check your key:</p> <ul> <li>The integrated server (the default) exposes the REST API and the pywidevine / pyplayready CDM HTTP endpoints.</li> <li>The API-only server (<code>--api-only</code>, also implied by <code>--remote-only</code>) exposes only the REST API.</li> </ul> <p>The header, the config, and the behaviour you see as a client are the same in both. The differences are internal and are called out in the developer notes below.</p>"},{"location":"dev/rest-api/authentication/#the-short-version","title":"The short version","text":"<ol> <li>Add an <code>api_secret</code> to the <code>serve</code> section of your <code>unshackle.yaml</code>.</li> <li>Start the server with <code>unshackle serve</code>.</li> <li>Send that secret in the <code>X-Secret-Key</code> header on every request except <code>GET /api/health</code>.</li> </ol> A minimal authenticated request<pre><code>curl -H \"X-Secret-Key: your-secret-key-here\" \\\n http://127.0.0.1:8786/api/services\n</code></pre>"},{"location":"dev/rest-api/authentication/#configuring-authentication","title":"Configuring authentication","text":"<p>All authentication settings live under the <code>serve</code> section of your unshackle config file (<code>unshackle.yaml</code>).</p>"},{"location":"dev/rest-api/authentication/#a-single-api-key","title":"A single API key","text":"<p>The simplest setup defines one shared secret with <code>api_secret</code>:</p> unshackle.yaml<pre><code>serve:\n api_secret: \"a-long-random-secret-string\"\n</code></pre> <p>This value becomes the one and only key that the server accepts. Requests that present it in the <code>X-Secret-Key</code> header are allowed; everything else is rejected.</p> <p>The server will not start without a key</p> <p>If you start <code>unshackle serve</code> with no <code>api_secret</code> configured, and you have not passed <code>--no-key</code>, the command fails immediately with:</p> <pre><code>API secret key is not configured. Please add 'api_secret' to the 'serve' section in your config.\n</code></pre> <p>Choose a long, unpredictable value. The key is the only thing standing between the internet and your CDM and download endpoints.</p>"},{"location":"dev/rest-api/authentication/#multiple-keys-with-users","title":"Multiple keys with <code>users</code>","text":"<p>For finer control you can define named users, each with their own key. A user entry can also grant CDM device access and restrict which services that key may touch:</p> unshackle.yaml<pre><code>serve:\n api_secret: \"the-primary-admin-key\"\n users:\n a-secret-key-for-alice:\n username: alice\n devices: [\"my_widevine_device\"] # Widevine (.wvd) devices this key may use\n playready_devices: [\"my_playready_prd\"] # PlayReady (.prd) devices this key may use\n services: [\"EXAMPLE1\", \"EXAMPLE2\"] # optional per-key service allowlist\n a-secret-key-for-bob:\n username: bob\n devices: [\"my_widevine_device\"]\n</code></pre> <p>The key of each entry under <code>users</code> (for example <code>a-secret-key-for-alice</code>) is the secret that client sends in <code>X-Secret-Key</code>. The <code>username</code> is a human-readable label used in logs and in job/history metadata.</p> <p>How <code>api_secret</code> and <code>users</code> combine (integrated server)</p> <p>On the integrated server, the configured <code>api_secret</code> is automatically added as an extra accepted key alongside everyone in <code>users</code>. It is granted access to all loaded Widevine and PlayReady devices and is labelled <code>api_user</code>. So <code>api_secret</code> behaves as an admin-level key in addition to any named users you define.</p> <p>On the API-only server, only <code>api_secret</code> is accepted: the single-key model. (See the developer notes for the exact difference.)</p>"},{"location":"dev/rest-api/authentication/#cdm-device-access-per-key","title":"CDM device access per key","text":"<p>Under the integrated server, a key can only run DRM licensing through a CDM device that its user entry lists:</p> Config key Grants access to <code>devices</code> Widevine <code>.wvd</code> devices, by name <code>playready_devices</code> PlayReady <code>.prd</code> devices, by name <p>PlayReady access is opt-in per user</p> <p>If a user entry omits <code>playready_devices</code>, that key is given no PlayReady access, and the server logs a warning at startup. You must list PlayReady devices explicitly for any key that needs them. Widevine and PlayReady device files themselves are auto-loaded from your WVDs and PRDs directories.</p> <p>Device lists are the server-side-decryption switch</p> <p>There is no separate tier, capability flag, or permission toggle for whether the server will hand back keys (<code>KID:KEY</code>) for a session download. The presence of devices on the calling key decides it. With empty <code>devices</code> and <code>playready_devices</code>, the server can only proxy CDM challenges, so the client must run its own CDM. Once those lists are populated, the client may request <code>mode:server_cdm</code> and receive keys back. Don't go looking for a tier setting; configuring devices is what enables server-side decryption.</p>"},{"location":"dev/rest-api/authentication/#disabling-authentication","title":"Disabling authentication","text":"<p>The <code>--no-key</code> flag turns authentication off entirely. Every request is allowed, <code>X-Secret-Key</code> is ignored, and no key needs to be configured.</p> <pre><code>unshackle serve --no-key\n</code></pre> <p>Only use <code>--no-key</code> on a trusted, isolated network</p> <p>With <code>--no-key</code> there is nothing stopping any client that can reach the port from listing your services, starting downloads, or using your CDM devices. Never expose a <code>--no-key</code> server to an untrusted network.</p>"},{"location":"dev/rest-api/authentication/#how-clients-present-credentials","title":"How clients present credentials","text":"<p>Clients authenticate by sending the secret in a single HTTP request header on every call:</p> <pre><code>X-Secret-Key: &lt;your-secret&gt;\n</code></pre> <p>The value must exactly match one of the configured keys (<code>api_secret</code>, or one of the keys under <code>users</code>). There is no login step, no session cookie, and no token exchange for API access. The same static key is sent on each request.</p> curlPython (requests)JavaScript (fetch) <pre><code>curl -H \"X-Secret-Key: your-secret-key-here\" \\\n http://127.0.0.1:8786/api/services\n</code></pre> <pre><code>import requests\n\nBASE = \"http://127.0.0.1:8786\"\nHEADERS = {\"X-Secret-Key\": \"your-secret-key-here\"}\n\nresp = requests.get(f\"{BASE}/api/services\", headers=HEADERS, timeout=30)\nresp.raise_for_status()\nprint(resp.json())\n</code></pre> <pre><code>const resp = await fetch(\"http://127.0.0.1:8786/api/services\", {\n headers: { \"X-Secret-Key\": \"your-secret-key-here\" },\n});\nif (!resp.ok) throw new Error(`Server returned ${resp.status}`);\nconsole.log(await resp.json());\n</code></pre> <p>The reference client sets it for you</p> <p>unshackle's own remote download client (<code>RemoteService</code>) sends <code>X-Secret-Key</code> automatically, reading the key from your <code>remote_services</code> config. It also sends a <code>User-Agent</code> of <code>unshackle/&lt;version&gt;</code>. You only deal with the header directly when writing your own client.</p>"},{"location":"dev/rest-api/authentication/#the-health-check-is-always-open","title":"The health check is always open","text":"<p>One endpoint is exempt from authentication: <code>GET /api/health</code>. It never requires a key, so you can use it for liveness and version probes without embedding a secret in your monitoring:</p> No key needed<pre><code>curl http://127.0.0.1:8786/api/health\n</code></pre> Response<pre><code>{\n \"status\": \"ok\",\n \"version\": \"5.3.0\",\n \"update_check\": {\n \"update_available\": null,\n \"current_version\": \"5.3.0\",\n \"latest_version\": null\n }\n}\n</code></pre> <p>Every other endpoint (including the Swagger UI at <code>/api/docs/</code> on the API-only server) requires a valid key.</p>"},{"location":"dev/rest-api/authentication/#authentication-failures","title":"Authentication failures","text":"<p>When a request is rejected for authentication reasons, the response has an HTTP <code>401 Unauthorized</code> status and a small JSON body.</p> Missing headerWrong key <p>Sending a request with no <code>X-Secret-Key</code> header:</p> <pre><code>{\n \"status\": 401,\n \"message\": \"Secret Key is Empty.\"\n}\n</code></pre> <p>Sending a key that is not in your config:</p> <pre><code>{\n \"status\": 401,\n \"message\": \"Secret Key is Invalid.\"\n}\n</code></pre> <p>Auth errors use a different JSON shape than other errors (developer note)</p> <p>The rest of the API reports errors with a structured body containing <code>error_code</code>, <code>message</code>, <code>timestamp</code>, and other fields (see Errors). The authentication middleware is different: it returns <code>{\"status\": 401, \"message\": \"...\"}</code>, where <code>status</code> is an integer, and there is no <code>error_code</code> or <code>timestamp</code>.</p> <p>A robust client should treat any <code>401</code> as an authentication problem and be prepared to parse both shapes rather than assuming the standard error body is always present.</p>"},{"location":"dev/rest-api/authentication/#building-on-the-key-access-controls","title":"Building on the key: access controls","text":"<p>Once a request is authenticated, several additional controls decide what that specific key is allowed to do.</p>"},{"location":"dev/rest-api/authentication/#per-key-service-allowlists","title":"Per-key service allowlists","text":"<p>You can restrict which services a key may use. Two layers combine:</p> <ul> <li>Global allowlist: <code>serve.services</code>, applied to every key.</li> <li>Per-key allowlist: <code>services</code> inside that key's <code>users</code> entry.</li> </ul> <p>The effective allowlist for a request is:</p> Global set? Per-key set? Result Yes Yes The intersection of the two Yes No The global list No Yes The per-key list No No No restriction, all services allowed Restricting services<pre><code>serve:\n api_secret: \"admin-key\"\n services: [\"EXAMPLE1\", \"EXAMPLE2\", \"EXAMPLE3\"] # global ceiling for all keys\n users:\n limited-key:\n username: limited\n services: [\"EXAMPLE1\"] # this key ends up allowed only EXAMPLE1\n</code></pre> <p>Endpoints that name a service (listing services, searching, listing titles/tracks, downloading, profiles, history, and remote sessions) all filter against this allowlist. A request for a service outside the key's allowlist is rejected as an invalid service. Service tags are matched after normalization, so casing and aliases resolve consistently.</p>"},{"location":"dev/rest-api/authentication/#cdm-overrides-and-per-job-credentials","title":"CDM overrides and per-job credentials","text":"<p>Two download-time capabilities are gated behind server config and, unless enabled, are refused with <code>403 Forbidden</code> even for an authenticated key:</p> Config key Default Controls <code>serve.cdm_overrides</code> off Whether a request may pick a specific CDM device via the <code>cdm</code> field. Set to <code>true</code> to allow any, or to a list/set of device names to allow only those. <code>serve.allow_job_credentials</code> off Whether a request may pass its own <code>credential</code> / <code>credentials</code> login details for a download job. Opting in to per-request CDM and credentials<pre><code>serve:\n api_secret: \"admin-key\"\n cdm_overrides: [\"my_widevine_device\"] # or true to allow any configured device\n allow_job_credentials: true\n</code></pre> <p>When to enable these gates</p> <p>The two gates are fully independent and can be combined. The intended posture is that a locked-down or public-facing deployment leaves both unset (they default off and reject with <code>403</code>) so client requests can never steer the server's CDM or feed it their own logins. Enabling them only makes sense for a trusted single-client deployment, where the caller and the operator are effectively the same party.</p> <p>Client-supplied credentials get isolated token caches</p> <p>When <code>allow_job_credentials</code> is enabled and a download job supplies its own <code>credential</code> / <code>credentials</code>, each distinct credential is given its own isolated token cache on the server. Client-supplied logins are never shared or merged with the server's configured-credential caches, so they cannot cross-contaminate or read the server's own token state, and they don't clobber each other.</p> <p>See Downloads for how these fields are used on the download endpoint.</p>"},{"location":"dev/rest-api/authentication/#session-ip-binding-remote-sessions","title":"Session IP binding (remote sessions)","text":"<p>The remote-download session endpoints (<code>/api/session/*</code>) add an extra check on top of the key. When a session is created, the server records the client's IP address. Any later request for that session must come from the same IP, or it is rejected with <code>403 Forbidden</code>. This means a session is bound both to the key that created it and to the address it was created from.</p>"},{"location":"dev/rest-api/authentication/#transport-security-https","title":"Transport security (HTTPS)","text":"<p>The API server speaks plain HTTP. Because your key is sent on every request, you should not expose it over an unencrypted connection on an untrusted network. To serve over HTTPS, run a reverse proxy in front of unshackle. The <code>serve</code> command can launch Caddy for you:</p> <pre><code>unshackle serve --caddy\n</code></pre> <p>With <code>--caddy</code>, unshackle also starts <code>caddy run</code> using the <code>Caddyfile</code> located next to your unshackle config, letting you terminate TLS and reverse-proxy to the API. Configuring Caddy itself (certificates, domains, upstream) is done in that <code>Caddyfile</code>.</p>"},{"location":"dev/rest-api/authentication/#quick-reference","title":"Quick reference","text":"Item Value Auth header <code>X-Secret-Key</code> Default bind address <code>127.0.0.1:8786</code> Exempt endpoint <code>GET /api/health</code> Failure status <code>401 Unauthorized</code> Missing-header body <code>{\"status\": 401, \"message\": \"Secret Key is Empty.\"}</code> Invalid-key body <code>{\"status\": 401, \"message\": \"Secret Key is Invalid.\"}</code> Disable auth <code>--no-key</code> (all requests allowed) Config location <code>serve.api_secret</code> and <code>serve.users</code> in <code>unshackle.yaml</code>"},{"location":"dev/rest-api/authentication/#developer-notes-how-the-check-is-implemented","title":"Developer notes: how the check is implemented","text":"<p>This section is for people writing or debugging the server, not for API consumers.</p>"},{"location":"dev/rest-api/authentication/#two-middlewares-one-header","title":"Two middlewares, one header","text":"<p>The header and config are identical between modes, but the code that enforces them differs:</p> <ul> <li> <p>API-only server (<code>--api-only</code>, or <code>--remote-only</code> which forces API-only). An <code>api_key_authentication</code> middleware runs on every request. It lets <code>GET /api/health</code> through unconditionally, then reads <code>X-Secret-Key</code>. An empty header returns the \"Secret Key is Empty.\" body; a header that is not a configured user returns \"Secret Key is Invalid.\". In this mode the accepted-keys map contains exactly one entry: your <code>api_secret</code> (labelled <code>api_user</code>, with no devices). With <code>--no-key</code>, this middleware is simply not installed and the users map is empty.</p> </li> <li> <p>Integrated server (default). A <code>serve_authentication</code> middleware wraps pywidevine's authentication (and pyplayready's for <code>/playready*</code> paths), and the REST routes live in the same application, guarded by the same check. Here the accepted-keys map is your full <code>serve</code> config: <code>api_secret</code> (auto-added with access to all loaded devices) plus every entry under <code>users</code>, each with its declared <code>devices</code> / <code>playready_devices</code>.</p> </li> </ul> <p>Because the API-only middleware guards all non-health paths, the Swagger UI at <code>/api/docs/</code> is also behind <code>X-Secret-Key</code> there. In <code>--remote-only</code> mode the Swagger UI is not mounted at all.</p>"},{"location":"dev/rest-api/authentication/#cors-and-the-authorization-header","title":"CORS and the <code>Authorization</code> header","text":"<p>A <code>cors_middleware</code> runs on every response in both modes (and answers <code>OPTIONS</code> preflight requests with an empty response). It emits:</p> <pre><code>Access-Control-Allow-Origin: *\nAccess-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS\nAccess-Control-Allow-Headers: Content-Type, X-Secret-Key, Authorization\nAccess-Control-Max-Age: 3600\n</code></pre> <p>The REST API authenticates with <code>X-Secret-Key</code>; <code>Authorization</code> is advertised because the co-hosted pywidevine / pyplayready CDM endpoints use it. <code>PUT</code> appears in the allowed methods list but no REST route uses it; only <code>GET</code>, <code>POST</code>, and <code>DELETE</code> are wired up.</p>"},{"location":"dev/rest-api/authentication/#where-device-access-is-read","title":"Where device access is read","text":"<p>The map of accepted keys lives at <code>request.app[\"config\"][\"users\"]</code>. For DRM operations, a key's permitted Widevine devices come from its <code>devices</code> list and PlayReady devices from <code>playready_devices</code>; the first configured device is used when a request does not (or may not) override it. A server-wide <code>config.cdm[&lt;service&gt;]</code> mapping, if present, takes precedence over the key's device list when resolving which device to use.</p>"},{"location":"dev/rest-api/endpoints/","title":"REST API Endpoints","text":"<p>This is the full endpoint reference for the unshackle REST API. It covers every route: its method and path, the request body it accepts, the response shape it returns, and the status codes it can produce. Routes are grouped into general, download jobs, server management, and remote-dl sessions.</p> <p>Start the server with <code>unshackle serve</code>. By default it binds to <code>127.0.0.1:8786</code>, and every route lives under the <code>/api/</code> prefix. Authentication, server modes, and the <code>X-Secret-Key</code> header are covered in detail on the Authentication page. Read that first if you have not already. For an end-to-end walkthrough, see the Quickstart.</p> <p>Base URL</p> <p>All examples below assume a base URL of <code>http://127.0.0.1:8786</code>. Replace the host and port to match your own <code>unshackle serve -h &lt;host&gt; -p &lt;port&gt;</code> invocation.</p> <p>Interactive docs</p> <p>A live Swagger UI is mounted at <code>/api/docs/</code> whenever the server is not running in <code>--remote-only</code> mode. Its title is \"Unshackle REST API\" and its version tracks the installed package version. In API-only mode with a key configured, the Swagger UI itself sits behind <code>X-Secret-Key</code>; only <code>/api/health</code> is exempt.</p>"},{"location":"dev/rest-api/endpoints/#conventions","title":"Conventions","text":"<ul> <li>Authentication. Every request except <code>GET /api/health</code> requires the <code>X-Secret-Key</code> header when a key is configured. Starting the server with <code>--no-key</code> disables the check entirely. See Authentication.</li> <li>Content type. Request bodies are JSON (<code>Content-Type: application/json</code>); all success responses are JSON unless a <code>204 No Content</code> is documented.</li> <li>CORS. Every response carries permissive CORS headers, and <code>OPTIONS</code> preflight requests are answered automatically.</li> <li>Compression. JSON responses of 256 bytes or more are gzip-compressed when the client sends <code>Accept-Encoding: gzip</code>.</li> <li>Service allowlist. Service-facing endpoints are filtered by the effective allowlist for your API key (the intersection of the global <code>serve.services</code> list and your per-key list). Services you are not allowed to use are treated as unknown.</li> </ul> <p>Error responses have two shapes</p> <p>Structured application errors (raised inside a handler) return <code>{\"status\": \"error\", \"error_code\": \"...\", \"message\": \"...\", \"timestamp\": \"...\"}</code>. The authentication middleware, however, returns a different shape: <code>{\"status\": 401, \"message\": \"...\"}</code> with an integer <code>status</code> and no <code>error_code</code>. Clients must handle both. The full error model is documented in the Error responses section at the bottom of this page.</p>"},{"location":"dev/rest-api/endpoints/#general-endpoints","title":"General endpoints","text":"<p>These endpoints report server state and enumerate what is available. <code>GET /api/health</code>, <code>GET /api/services</code>, and <code>POST /api/search</code> are also exposed in <code>--remote-only</code> mode.</p>"},{"location":"dev/rest-api/endpoints/#get-apihealth","title":"<code>GET /api/health</code>","text":"<p>Health check. This is the only route exempt from authentication: you can call it without an <code>X-Secret-Key</code> header. It reports the running version and a best-effort update check.</p> RequestResponse <code>200</code> <pre><code>curl http://127.0.0.1:8786/api/health\n</code></pre> <pre><code>{\n \"status\": \"ok\",\n \"version\": \"5.3.0\",\n \"update_check\": {\n \"update_available\": false,\n \"current_version\": \"5.3.0\",\n \"latest_version\": \"5.3.0\"\n }\n}\n</code></pre> <p>If the update check fails (for example, no network), <code>update_available</code> and <code>latest_version</code> are <code>null</code> while <code>current_version</code> still reports the installed version.</p> Status Meaning <code>200</code> Server is healthy."},{"location":"dev/rest-api/endpoints/#get-apiservices","title":"<code>GET /api/services</code>","text":"<p>List the streaming services available on this server, filtered by your allowlist. Each entry describes the service's tag, matching rules, capability flags, and its CLI parameters (useful for building a UI that accepts service-specific options).</p> RequestResponse <code>200</code> <pre><code>curl -H \"X-Secret-Key: $KEY\" http://127.0.0.1:8786/api/services\n</code></pre> <pre><code>{\n \"services\": [\n {\n \"tag\": \"EXAMPLE\",\n \"aliases\": [\"EX\"],\n \"geofence\": [\"US\"],\n \"title_regex\": \"^https?://example\\\\.com/.+\",\n \"url\": \"https://example.com\",\n \"help\": \"EXAMPLE\\nAuthorization: Cookies\\nSecurity: FHD@L3\",\n \"cli_params\": [\n {\"name\": \"title\", \"kind\": \"argument\", \"required\": true},\n {\n \"name\": \"movie\",\n \"kind\": \"option\",\n \"opts\": [\"-m\", \"--movie\"],\n \"is_flag\": true,\n \"default\": false,\n \"help\": \"Title is a movie.\",\n \"type\": \"boolean\",\n \"multiple\": false\n }\n ],\n \"needs_auth\": true,\n \"has_search\": true,\n \"has_drm\": true,\n \"auth_methods\": [\"cookies\"]\n }\n ]\n}\n</code></pre> <p>Field notes:</p> Field Description <code>tag</code> Canonical service tag; use this as the <code>service</code> value on other endpoints. <code>aliases</code> Alternate tags the service also answers to. <code>geofence</code> Region codes the service is geofenced to (may be empty). <code>title_regex</code> URL/ID pattern the service matches, as a string or list of strings (or <code>null</code>). <code>url</code> Service URL, taken from the service's CLI short help. <code>help</code> The service module's docstring. <code>cli_params</code> Array of parameter descriptors. Arguments have <code>{name, kind: \"argument\", required}</code>; options have <code>{name, kind: \"option\", opts, is_flag, default, help, type, multiple}</code> and, for choice options, a <code>choices</code> list. <code>needs_auth</code> Whether the service overrides <code>authenticate()</code>. <code>has_search</code> Whether the service supports <code>POST /api/search</code>. <code>has_drm</code> Whether the service overrides a Widevine or PlayReady license hook. <code>auth_methods</code> Declared or inferred auth methods, e.g. <code>[\"cookies\"]</code>, <code>[\"credentials\"]</code>. Status Meaning <code>200</code> Service list returned. <code>500</code> Unexpected server error (<code>INTERNAL_ERROR</code>)."},{"location":"dev/rest-api/endpoints/#post-apisearch","title":"<code>POST /api/search</code>","text":"<p>Search a service for titles by query string. The service must implement <code>search()</code> (see <code>has_search</code> above).</p> <p>Request body</p> Field Type Required Default Description <code>service</code> string yes - Service tag. <code>query</code> string yes - Search query. <code>profile</code> string no <code>null</code> Credential/cookie profile to use. <code>proxy</code> string no <code>null</code> Proxy URI or country code. <code>no_proxy</code> boolean no <code>false</code> Force-disable all proxy use. RequestResponse <code>200</code> <pre><code>curl -X POST http://127.0.0.1:8786/api/search \\\n -H \"X-Secret-Key: $KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"service\": \"EXAMPLE\", \"query\": \"planet earth\"}'\n</code></pre> <pre><code>{\n \"results\": [\n {\n \"id\": \"12345\",\n \"title\": \"Planet Earth\",\n \"description\": \"A nature documentary series.\",\n \"label\": \"Available\",\n \"url\": \"https://example.com/title/12345\"\n }\n ],\n \"count\": 1\n}\n</code></pre> Status Error code Meaning <code>200</code> - Search completed. <code>400</code> <code>INVALID_PARAMETERS</code> Missing <code>query</code>. <code>400</code> <code>INVALID_SERVICE</code> Unknown or disallowed service. <code>400</code> <code>INVALID_PROXY</code> Proxy could not be resolved. <code>502</code> <code>SERVICE_ERROR</code> Service failed to initialize, or does not support search."},{"location":"dev/rest-api/endpoints/#post-apilist-titles","title":"<code>POST /api/list-titles</code>","text":"<p>Resolve a title ID into its list of titles (episodes, movie, etc.) without downloading anything.</p> <p>Request body</p> Field Type Required Description <code>service</code> string yes Service tag. <code>title_id</code> string yes Title identifier. <code>profile</code> string no Credential/cookie profile. <code>proxy</code> string no Proxy URI or country code. <code>no_proxy</code> boolean no Force-disable proxy. <code>cdm_type</code> string no Preferred CDM type. <p>Service-specific CLI options may also be passed as additional keys.</p> RequestResponse <code>200</code> <pre><code>curl -X POST http://127.0.0.1:8786/api/list-titles \\\n -H \"X-Secret-Key: $KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"service\": \"EXAMPLE\", \"title_id\": \"12345\"}'\n</code></pre> <pre><code>{\n \"titles\": [\n {\n \"type\": \"episode\",\n \"name\": \"Pilot\",\n \"id\": \"ep-1\",\n \"language\": \"en\",\n \"description\": \"The first episode.\",\n \"date\": \"2020-01-01\",\n \"cover_url\": \"https://example.com/cover.jpg\",\n \"year\": 2020,\n \"series_title\": \"Example Show\",\n \"season\": 1,\n \"number\": 1\n }\n ]\n}\n</code></pre> <p>Each serialized title carries <code>type</code> (<code>\"episode\"</code>, <code>\"movie\"</code>, or <code>\"other\"</code>), <code>name</code>, <code>id</code>, <code>language</code>, <code>description</code>, <code>date</code>, and <code>cover_url</code>. Episodes and movies add <code>year</code>; episodes additionally add <code>series_title</code>, <code>season</code>, and <code>number</code>.</p> Status Error code Meaning <code>200</code> - Titles returned. <code>400</code> <code>INVALID_INPUT</code> Missing <code>service</code> or <code>title_id</code>. <code>400</code> <code>INVALID_SERVICE</code> Unknown or disallowed service. <code>401</code> <code>AUTH_FAILED</code> Authentication with the service failed. <code>404</code> <code>NOT_FOUND</code> Title not found. <code>500</code> <code>INTERNAL_ERROR</code> Unexpected error."},{"location":"dev/rest-api/endpoints/#post-apilist-tracks","title":"<code>POST /api/list-tracks</code>","text":"<p>List the video, audio, and subtitle tracks for a title. For series, you can scope to specific episodes.</p> <p>Request body</p> Field Type Required Description <code>service</code> string yes Service tag. <code>title_id</code> string yes Title identifier. <code>wanted</code> string no Episode/season range (e.g. <code>\"S01E01-S01E03\"</code>). <code>season</code> int/string no Season number (combined with <code>episode</code>). <code>episode</code> int/string no Episode number (combined with <code>season</code>). <code>profile</code>, <code>proxy</code>, <code>no_proxy</code>, <code>cdm_type</code> - no As on <code>list-titles</code>. <p>When both <code>season</code> and <code>episode</code> are given, they are combined into a <code>\"{season}x{episode}\"</code> selector.</p> Single title / movie: Response <code>200</code>Multiple episodes: Response <code>200</code> <pre><code>{\n \"title\": { \"type\": \"movie\", \"name\": \"Example Movie\", \"id\": \"12345\", \"year\": 2021 },\n \"video\": [\n {\n \"id\": \"v-1\", \"codec\": \"H265\", \"codec_display\": \"HEVC\",\n \"bitrate\": 8000, \"width\": 3840, \"height\": 2160,\n \"resolution\": \"2160p\", \"fps\": \"24\", \"range\": \"HDR10\",\n \"range_display\": \"HDR10\", \"language\": \"en\", \"drm\": [], \"descriptor\": \"DASH\"\n }\n ],\n \"audio\": [\n {\n \"id\": \"a-1\", \"codec\": \"EC3\", \"codec_display\": \"DD+\",\n \"bitrate\": 640, \"channels\": \"5.1\", \"language\": \"en\",\n \"atmos\": false, \"descriptive\": false, \"drm\": [], \"descriptor\": \"DASH\"\n }\n ],\n \"subtitles\": [\n { \"id\": \"s-1\", \"codec\": \"vtt\", \"language\": \"en\",\n \"forced\": false, \"sdh\": false, \"cc\": false, \"descriptor\": \"DASH\" }\n ]\n}\n</code></pre> <pre><code>{\n \"episodes\": [\n {\n \"title\": { \"type\": \"episode\", \"name\": \"Pilot\", \"id\": \"ep-1\", \"season\": 1, \"number\": 1 },\n \"video\": [ ... ],\n \"audio\": [ ... ],\n \"subtitles\": [ ... ]\n }\n ],\n \"unavailable_episodes\": [\n { \"title\": { \"id\": \"ep-2\" }, \"error\": \"...\" }\n ]\n}\n</code></pre> <p>Tracks are sorted by bitrate, descending. Episodes that fail to resolve are collected into <code>unavailable_episodes</code> rather than failing the whole request. Track objects here do not include a download <code>url</code>; segment URLs are only exposed through the remote-dl session endpoints.</p> <p>The <code>drm</code> array on a track is a list of <code>{type, pssh?, kids?, content_keys?, license_url?}</code> objects.</p> Status Error code Meaning <code>200</code> - Tracks returned. <code>400</code> <code>INVALID_INPUT</code> Missing <code>service</code> or <code>title_id</code>. <code>400</code> <code>INVALID_PARAMETERS</code> Invalid <code>wanted</code> range. <code>400</code> <code>INVALID_SERVICE</code> Unknown or disallowed service. <code>404</code> <code>NO_CONTENT</code> No matching episodes, or all matches failed."},{"location":"dev/rest-api/endpoints/#download-jobs","title":"Download jobs","text":"<p>Downloads are asynchronous. <code>POST /api/download</code> enqueues a job and returns immediately with a <code>job_id</code>; the server runs each job in a background worker subprocess. You then poll the job endpoints for progress and results.</p> <p>Job states</p> <p>A job moves through <code>queued</code> \u2192 <code>downloading</code> \u2192 one of the terminal states <code>completed</code>, <code>failed</code>, or <code>cancelled</code>. Only queued jobs can be prioritized; only terminal jobs can be retried or removed.</p>"},{"location":"dev/rest-api/endpoints/#post-apidownload","title":"<code>POST /api/download</code>","text":"<p>Create a download job. Requires <code>service</code> and <code>title_id</code>; every other field is an optional download parameter with a server-side default. On success this returns <code>202 Accepted</code>, not <code>200</code>.</p> RequestResponse <code>202</code> <pre><code>curl -X POST http://127.0.0.1:8786/api/download \\\n -H \"X-Secret-Key: $KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"service\": \"EXAMPLE\",\n \"title_id\": \"12345\",\n \"quality\": [2160],\n \"vcodec\": \"H265\",\n \"range\": [\"HDR10\"],\n \"wanted\": [\"S01E01\"]\n }'\n</code></pre> <pre><code>{\n \"job_id\": \"b0f7c8e2-4a1d-4e9c-9b7e-2f3a1c0d5e6f\",\n \"status\": \"queued\",\n \"created_time\": \"2026-07-03T12:00:00+00:00\"\n}\n</code></pre> <p>Common parameters (all optional). These mirror the <code>dl</code> command flags:</p> Field Type Default Notes <code>profile</code> string <code>null</code> Credential/cookie profile. <code>quality</code> int[] <code>[]</code> Target resolution(s); best available if empty. <code>vcodec</code> string/string[] <code>null</code> Video codec filter. <code>acodec</code> string/string[] <code>null</code> Audio codec filter. <code>vbitrate</code> / <code>abitrate</code> int <code>null</code> Video / audio bitrate in kbps (positive). <code>vbitrate_range</code> / <code>abitrate_range</code> string <code>null</code> <code>\"MIN-MAX\"</code> bitrate window. <code>range</code> string[] <code>[\"SDR\"]</code> Dynamic range(s). <code>channels</code> number <code>null</code> Audio channel count. <code>no_atmos</code> boolean <code>false</code> Exclude Atmos tracks. <code>wanted</code> string[] <code>[]</code> Episode/season selectors. <code>latest_episode</code> boolean <code>false</code> Only the newest episode. <code>lang</code> / <code>v_lang</code> / <code>a_lang</code> / <code>s_lang</code> string[] <code>[\"orig\"]</code> / <code>[]</code> / <code>[]</code> / <code>[\"all\"]</code> Language filters. <code>require_subs</code> string[] <code>[]</code> Required subtitle languages. <code>forced_subs</code> boolean <code>false</code> Include forced subtitles. <code>exact_lang</code> boolean <code>false</code> Exact language matching. <code>sub_format</code> string <code>null</code> Output subtitle format. <code>video_only</code> / <code>audio_only</code> / <code>subs_only</code> / <code>chapters_only</code> boolean <code>false</code> Track-type restriction (at most one). <code>no_subs</code> / <code>no_audio</code> / <code>no_chapters</code> / <code>no_video</code> boolean <code>false</code> Skip a track type. <code>audio_description</code> boolean <code>false</code> Download audio description. <code>slow</code> boolean/string <code>null</code> Randomized delay between downloads. <code>split_audio</code> boolean <code>null</code> Separate files per audio codec. <code>skip_dl</code> boolean <code>false</code> Only fetch keys, do not download. <code>export</code> boolean <code>false</code> Export manifest/keys/subs to JSON. <code>cdm_only</code> boolean <code>null</code> Force CDM-only (<code>true</code>) or vault-only (<code>false</code>) key retrieval. <code>proxy</code> / <code>no_proxy</code> / <code>no_proxy_download</code> string / bool / bool <code>null</code> / <code>false</code> / <code>false</code> Proxy controls. <code>no_folder</code> / <code>no_source</code> / <code>no_mux</code> boolean <code>false</code> Output/mux controls. <code>workers</code> int <code>null</code> Threads per track. <code>downloads</code> int <code>1</code> Concurrent tracks. <code>worst</code> boolean <code>false</code> Lowest bitrate within quality. <code>best_available</code> boolean <code>false</code> Fall back to best available. <code>repack</code> boolean <code>false</code> Add REPACK tag. <code>tag</code> string <code>null</code> Release group tag. <code>tmdb_id</code> / <code>imdb_id</code> / <code>animeapi_id</code> - <code>null</code> External ID overrides for tagging. <code>enrich</code> boolean <code>false</code> Override title/year from external source. <code>output_dir</code> string <code>null</code> Override output directory. <code>no_cache</code> / <code>reset_cache</code> boolean <code>false</code> Title cache controls. <p>Validation. Invalid values return <code>400 INVALID_PARAMETERS</code>. Notably: <code>vcodec</code> must be one of H264/H265/H.264/H.265/AVC/HEVC/VC1/VC-1/VP8/VP9/AV1; <code>acodec</code> one of AAC/AC3/EC3/EAC3/DD/DD+/AC4/OPUS/FLAC/ALAC/VORBIS/OGG/DTS; <code>range</code> one of SDR/HDR10/HDR10P/DV/HLG/HYBRID (<code>HDR10+</code> is accepted); bitrate/worker/download counts must be positive integers; at most one of the <code>*_only</code> flags may be set; <code>no_subs</code> cannot be combined with <code>subs_only</code>, <code>no_audio</code> with <code>audio_only</code>, or <code>s_lang</code> with <code>require_subs</code>.</p> <p>Gated parameters (developer)</p> <p>A few keys are accepted but only permitted when the server config opts in, otherwise the request is rejected with <code>403 FORBIDDEN</code>:</p> <ul> <li><code>cdm</code> (per-request CDM device name): allowed only if <code>serve.cdm_overrides</code> is <code>true</code> or a list containing that device name.</li> <li><code>credential</code> (<code>\"user:pass\"</code>) and <code>credentials</code> (a map): allowed only if <code>serve.allow_job_credentials</code> is truthy (off by default).</li> </ul> <p>Server-side, effective parameters are merged as defaults \u2192 <code>serve:</code> config overrides \u2192 service-specific defaults \u2192 your request body.</p> Status Error code Meaning <code>202</code> - Job queued. <code>400</code> <code>INVALID_INPUT</code> Missing <code>service</code>/<code>title_id</code> or malformed JSON. <code>400</code> <code>INVALID_PARAMETERS</code> A parameter failed validation. <code>400</code> <code>INVALID_SERVICE</code> Unknown or disallowed service. <code>403</code> <code>FORBIDDEN</code> A gated parameter is not permitted."},{"location":"dev/rest-api/endpoints/#get-apidownloadjobs","title":"<code>GET /api/download/jobs</code>","text":"<p>List download jobs, with optional filtering and sorting.</p> <p>Query parameters</p> Param Values Default Description <code>status</code> <code>queued</code>, <code>downloading</code>, <code>completed</code>, <code>failed</code>, <code>cancelled</code> - Filter by status. <code>service</code> service tag - Filter by service. <code>sort_by</code> <code>created_time</code>, <code>started_time</code>, <code>completed_time</code>, <code>progress</code>, <code>status</code>, <code>service</code> <code>created_time</code> Sort field. <code>sort_order</code> <code>asc</code>, <code>desc</code> <code>desc</code> Sort direction. <code>full</code> <code>true</code>, <code>false</code> <code>false</code> Include full per-job details. RequestResponse <code>200</code> <pre><code>curl -H \"X-Secret-Key: $KEY\" \\\n \"http://127.0.0.1:8786/api/download/jobs?status=downloading&amp;sort_by=progress&amp;sort_order=desc\"\n</code></pre> <pre><code>{\n \"jobs\": [\n {\n \"job_id\": \"b0f7c8e2-...\",\n \"status\": \"downloading\",\n \"created_time\": \"2026-07-03T12:00:00+00:00\",\n \"service\": \"EXAMPLE\",\n \"title_id\": \"12345\",\n \"title\": \"Example Show S01E01\",\n \"progress\": 42.5,\n \"phase\": \"downloading\",\n \"current_title\": \"Episode 1\",\n \"completed_tracks\": 1,\n \"total_tracks\": 3,\n \"active_tracks\": [\"v-1\"],\n \"track_progress\": [{\"label\": \"Video\", \"progress\": 42.5, \"speed\": \"5.2 MB/s\"}],\n \"segments_done\": 120,\n \"segments_total\": 300,\n \"speed\": \"5.2 MB/s\",\n \"skipped_subtitles\": []\n }\n ]\n}\n</code></pre> <p>With <code>full=true</code>, each job additionally includes <code>parameters</code> (with secrets redacted), <code>started_time</code>, <code>completed_time</code>, <code>output_files</code>, <code>error_message</code>, <code>error_details</code>, <code>error_code</code>, <code>error_traceback</code>, and <code>worker_stderr</code>.</p> Status Error code Meaning <code>200</code> - Jobs returned. <code>400</code> <code>INVALID_PARAMETERS</code> Invalid <code>sort_by</code> or <code>sort_order</code>."},{"location":"dev/rest-api/endpoints/#get-apidownloadjobsjob_id","title":"<code>GET /api/download/jobs/{job_id}</code>","text":"<p>Fetch a single job with full details (equivalent to a <code>full=true</code> list entry).</p> Status Error code Meaning <code>200</code> - Job returned. <code>404</code> <code>JOB_NOT_FOUND</code> No such job."},{"location":"dev/rest-api/endpoints/#delete-apidownloadjobsjob_id","title":"<code>DELETE /api/download/jobs/{job_id}</code>","text":"<p>Cancel or remove a job. The behaviour depends on the job's current state:</p> <ul> <li>Terminal job (completed/failed/cancelled): removed from the manager, returning <code>204 No Content</code> with an empty body.</li> <li>Queued or downloading job: cancelled, returning <code>200</code> <code>{\"status\": \"success\", \"message\": \"Job cancelled\"}</code>.</li> </ul> <p>Warning</p> <p>A <code>204</code> response has no body. Do not attempt to parse JSON from it.</p> Status Error code Meaning <code>200</code> - Job cancelled. <code>204</code> - Terminal job removed (empty body). <code>400</code> <code>INVALID_PARAMETERS</code> Job is in a state that cannot be cancelled. <code>404</code> <code>JOB_NOT_FOUND</code> No such job."},{"location":"dev/rest-api/endpoints/#post-apidownloadjobsclear-finished","title":"<code>POST /api/download/jobs/clear-finished</code>","text":"<p>Remove every terminal (completed/failed/cancelled) job from the manager. No request body.</p> Response <code>200</code> <pre><code>{ \"removed\": 3 }\n</code></pre>"},{"location":"dev/rest-api/endpoints/#post-apidownloadjobsjob_idretry","title":"<code>POST /api/download/jobs/{job_id}/retry</code>","text":"<p>Enqueue a new job that reuses a terminal job's service, title, and parameters. The service allowlist and parameter gates are re-checked. Returns <code>202</code> with the new job's ID.</p> <p>Retry reuses the original, unredacted parameters</p> <p>Retry replays the finished job's stored parameters exactly as they were submitted, including any secrets such as <code>credential</code>/<code>credentials</code>, not the redacted <code>parameters</code> view that <code>GET /api/download/jobs</code> and <code>GET /api/history</code> expose. This is deliberate: it lets a retried job reproduce a credentialed download that the redacted job record alone never could. It also means anyone who can retry a job can re-run it with its original credentials, even though those credentials are masked everywhere else in the API.</p> Response <code>202</code> <pre><code>{\n \"job_id\": \"9c1e2f3a-...\",\n \"status\": \"queued\",\n \"created_time\": \"2026-07-03T12:05:00+00:00\"\n}\n</code></pre> Status Error code Meaning <code>202</code> - New job queued. <code>404</code> <code>JOB_NOT_FOUND</code> No such job. <code>409</code> <code>CONFLICT</code> Job is not in a terminal state. <code>400</code> <code>INVALID_SERVICE</code> Service is no longer allowed. <code>403</code> <code>FORBIDDEN</code> A gated parameter is no longer permitted."},{"location":"dev/rest-api/endpoints/#post-apidownloadjobsjob_idpriority","title":"<code>POST /api/download/jobs/{job_id}/priority</code>","text":"<p>Move a queued job to the front of the download queue.</p> Response <code>200</code> <pre><code>{ \"job_id\": \"b0f7c8e2-...\", \"position\": \"front\" }\n</code></pre> Status Error code Meaning <code>200</code> - Job moved to front. <code>404</code> <code>JOB_NOT_FOUND</code> No such job. <code>409</code> <code>CONFLICT</code> Job is not queued."},{"location":"dev/rest-api/endpoints/#server-management","title":"Server management","text":"<p>Endpoints for profiles, effective configuration, download history, environment checks, and maintenance actions.</p>"},{"location":"dev/rest-api/endpoints/#get-apiprofiles","title":"<code>GET /api/profiles</code>","text":"<p>List the named credential profiles configured per service (usable as the <code>profile</code> parameter elsewhere). Only services whose credentials are a mapping of profile name to credential are listed; services with a single unnamed credential are omitted. Filtered by your allowlist.</p> Response <code>200</code> <pre><code>{\n \"profiles\": {\n \"EXAMPLE\": [\"default\", \"premium\"],\n \"OTHER\": [\"us-account\"]\n }\n}\n</code></pre>"},{"location":"dev/rest-api/endpoints/#get-apiconfig","title":"<code>GET /api/config</code>","text":"<p>Return a read-only, redacted view of the effective server configuration, suitable for a settings page in a UI. Secrets are never emitted: keys matching <code>secret</code>, <code>password</code>, <code>token</code>, <code>api_key</code>, or <code>credential</code>, and any userinfo in proxy URLs, are masked.</p> Response <code>200</code> <pre><code>{\n \"config\": {\n \"dl\": { \"...\": \"redacted default dl parameters\" },\n \"serve\": {\n \"max_concurrent_downloads\": 2,\n \"job_retention_hours\": 24,\n \"history_limit\": 100,\n \"services\": null,\n \"remote_only\": false,\n \"cdm_overrides\": null,\n \"allow_job_credentials\": false\n },\n \"directories\": {\n \"downloads\": \"/home/user/Downloads/unshackle\",\n \"temp\": \"/home/user/.unshackle/temp\",\n \"cache\": \"/home/user/.unshackle/cache\"\n },\n \"services\": [\"EXAMPLE\", \"OTHER\"]\n }\n}\n</code></pre>"},{"location":"dev/rest-api/endpoints/#get-apihistory","title":"<code>GET /api/history</code>","text":"<p>Read the persisted history of jobs that reached a terminal state, newest first. History is stored in <code>api_history.jsonl</code> in the cache directory; corrupt lines are skipped and a missing file yields an empty list.</p> <p>Query parameters</p> Param Type Default Description <code>limit</code> int (\u2265 1) <code>100</code> Maximum entries to return. <code>service</code> string - Case-insensitive service filter. Response <code>200</code> <pre><code>{\n \"history\": [\n {\n \"job_id\": \"b0f7c8e2-...\",\n \"service\": \"EXAMPLE\",\n \"title_id\": \"12345\",\n \"title\": \"Example Show S01E01\",\n \"status\": \"completed\",\n \"created_time\": \"2026-07-03T12:00:00+00:00\",\n \"completed_time\": \"2026-07-03T12:08:00+00:00\",\n \"output_files\": [\"/downloads/Example.S01E01.mkv\"],\n \"error_message\": null,\n \"parameters\": { \"...\": \"redacted\" }\n }\n ],\n \"count\": 1\n}\n</code></pre> Status Error code Meaning <code>200</code> - History returned. <code>400</code> <code>INVALID_PARAMETERS</code> Invalid <code>limit</code>."},{"location":"dev/rest-api/endpoints/#delete-apihistoryjob_id","title":"<code>DELETE /api/history/{job_id}</code>","text":"<p>Remove a single persisted history entry. Returns <code>204 No Content</code> (empty body) on success.</p> Status Error code Meaning <code>204</code> - Entry removed (empty body). <code>404</code> <code>NOT_FOUND</code> No such entry (or outside your allowlist)."},{"location":"dev/rest-api/endpoints/#post-apimaintenanceclear-cache-and-post-apimaintenanceclear-temp","title":"<code>POST /api/maintenance/clear-cache</code> and <code>POST /api/maintenance/clear-temp</code>","text":"<p>Delete and recreate the cache or temp directory. Neither takes a request body. Both are blocked with <code>409 CONFLICT</code> if any job is currently <code>downloading</code> (the <code>details</code> include the offending <code>active_jobs</code>).</p> <p>The <code>409</code> guard is about active file I/O, not an arbitrary lock: an in-flight job may still be reading cached title data under the cache directory, and active download workers are writing segment files under temp. Removing either directory mid-download would corrupt those running jobs, so the endpoints refuse until nothing is downloading.</p> <p>clear-cache also wipes download history</p> <p>The persistent history read by <code>GET /api/history</code> lives in <code>api_history.jsonl</code> inside the cache directory. Because clear-cache deletes and recreates that whole directory, calling it also erases your entire download history, not just cached title data. If you want to keep history, do not clear the cache; remove individual entries with <code>DELETE /api/history/{job_id}</code> instead.</p> Response <code>200</code> <pre><code>{ \"cleared\": true, \"freed_bytes\": 1048576 }\n</code></pre> Status Error code Meaning <code>200</code> - Directory cleared. <code>409</code> <code>CONFLICT</code> A download is currently active."},{"location":"dev/rest-api/endpoints/#post-apimaintenancerefresh-services","title":"<code>POST /api/maintenance/refresh-services</code>","text":"<p>git-pull every service repository configured under <code>directories.services</code>. <code>refreshed</code> is <code>true</code> when all repos updated successfully (or none are configured).</p> Response <code>200</code> <pre><code>{\n \"refreshed\": true,\n \"repos\": [\n { \"spec\": \"github.com/example/services\", \"updated\": true, \"changes\": [\"a1b2c3d Update EXAMPLE\"] }\n ]\n}\n</code></pre>"},{"location":"dev/rest-api/endpoints/#get-apienvcheck","title":"<code>GET /api/env/check</code>","text":"<p>Report the install status of the external binaries unshackle depends on (the same set <code>unshackle env check</code> inspects), with best-effort version detection.</p> Response <code>200</code> <pre><code>{\n \"checks\": [\n { \"name\": \"ffmpeg\", \"installed\": true, \"version\": \"6.1.1\", \"required\": true },\n { \"name\": \"ccextractor\", \"installed\": false, \"version\": null, \"required\": false }\n ]\n}\n</code></pre>"},{"location":"dev/rest-api/endpoints/#remote-dl-sessions","title":"Remote-dl sessions","text":"<p>Developer feature</p> <p>The <code>/api/session/*</code> endpoints power unshackle's remote download mode, where a thin local client authenticates once against a remote server, then fetches titles, tracks, and segments and proxies DRM licensing back through it. These endpoints are exposed in <code>--remote-only</code> mode, and they are what the built-in <code>RemoteService</code> client drives. Most end users never call them directly.</p> <p>Sessions are held in memory. They expire after <code>serve.session_ttl</code> (default 300s), except while awaiting interactive authentication input, which uses a 600s window. A session is bound to the IP that created it, so a request from a different IP is rejected with <code>403 FORBIDDEN</code>.</p>"},{"location":"dev/rest-api/endpoints/#session-lifecycle-overview","title":"Session lifecycle overview","text":"<pre><code>POST /api/session/create \u2192 returns session_id, status \"authenticating\"\nGET /api/session/{id}/prompt \u2192 poll until authenticated (submit answers via POST)\nGET /api/session/{id}/titles \u2192 list titles\nPOST /api/session/{id}/tracks \u2192 tracks + chapters (with URLs) for one title\nPOST /api/session/{id}/segments \u2192 resolve segment URLs / DRM / headers per track\nPOST /api/session/{id}/license \u2192 proxy or server-CDM DRM licensing\nDELETE /api/session/{id} \u2192 tear down, harvest updated cache\n</code></pre>"},{"location":"dev/rest-api/endpoints/#post-apisessioncreate","title":"<code>POST /api/session/create</code>","text":"<p>Create a session for a service and title. Authentication runs asynchronously in the background. This call returns immediately with <code>status: \"authenticating\"</code>, and you then poll the prompt endpoint. The body accepts <code>service</code> and <code>title_id</code> (both required) plus a broad set of optional keys (<code>additionalProperties</code> is allowed): <code>credentials</code> (<code>{username, password, extra?}</code>), <code>cookies</code> (base64 of zlib-compressed Netscape cookie file), <code>proxy</code>, <code>no_proxy</code>, <code>profile</code>, <code>cache</code> (map of forwarded cache files), <code>client_region</code>, <code>cdm_type</code>, <code>range_</code>, <code>vcodec</code>, <code>quality</code>, <code>best_available</code>, and any service CLI options.</p> Response <code>200</code> <pre><code>{\n \"session_id\": \"d4e5f6a7-...\",\n \"service\": \"EXAMPLE\",\n \"status\": \"authenticating\"\n}\n</code></pre> Status Error code Meaning <code>200</code> - Session created; authentication in progress. <code>400</code> <code>INVALID_INPUT</code> Missing <code>service</code> or <code>title_id</code>. <code>400</code> <code>INVALID_SERVICE</code> Unknown or disallowed service."},{"location":"dev/rest-api/endpoints/#get-apisessionsession_idprompt","title":"<code>GET /api/session/{session_id}/prompt</code>","text":"<p>Poll for the authentication status and any pending interactive prompt (OTP, PIN, device code). Response variants:</p> AuthenticatingPending inputAuthenticatedFailed <pre><code>{ \"status\": \"authenticating\" }\n</code></pre> <pre><code>{ \"status\": \"pending_input\", \"prompt\": \"Enter the code sent to your email:\" }\n</code></pre> <pre><code>{ \"status\": \"authenticated\" }\n</code></pre> <pre><code>{ \"status\": \"failed\", \"error\": \"Invalid credentials\" }\n</code></pre> Status Error code Meaning <code>200</code> - Status returned. <code>403</code> <code>FORBIDDEN</code> Request IP differs from the session creator. <code>404</code> <code>SESSION_NOT_FOUND</code> No such session."},{"location":"dev/rest-api/endpoints/#post-apisessionsession_idprompt","title":"<code>POST /api/session/{session_id}/prompt</code>","text":"<p>Submit a response to a pending prompt. Body: <code>{ \"response\": \"...\" }</code> (required).</p> Response <code>200</code> <pre><code>{ \"status\": \"accepted\" }\n</code></pre> Status Error code Meaning <code>200</code> - Response accepted. <code>400</code> <code>INVALID_INPUT</code> Missing <code>response</code>, or no prompt is pending. <code>404</code> <code>SESSION_NOT_FOUND</code> No such session."},{"location":"dev/rest-api/endpoints/#get-apisessionsession_idtitles","title":"<code>GET /api/session/{session_id}/titles</code>","text":"<p>Fetch the titles for an authenticated session.</p> Response <code>200</code> <pre><code>{\n \"session_id\": \"d4e5f6a7-...\",\n \"titles\": [ { \"type\": \"episode\", \"name\": \"Pilot\", \"id\": \"ep-1\" } ]\n}\n</code></pre> <p>Requires an authenticated session; <code>404 SESSION_NOT_FOUND</code> otherwise.</p>"},{"location":"dev/rest-api/endpoints/#post-apisessionsession_idtracks","title":"<code>POST /api/session/{session_id}/tracks</code>","text":"<p>Get tracks and chapters for a specific title within the session. Body: <code>{ \"title_id\": \"...\" }</code> (required). Unlike <code>list-tracks</code>, track objects here include download URLs, along with session headers/cookies and manifest data the client needs to download directly.</p> Response <code>200</code> <pre><code>{\n \"title\": { \"type\": \"episode\", \"name\": \"Pilot\", \"id\": \"ep-1\" },\n \"video\": [ { \"id\": \"v-1\", \"url\": \"https://...\", \"drm\": [ ... ] } ],\n \"audio\": [ { \"id\": \"a-1\", \"url\": \"https://...\" } ],\n \"subtitles\": [ { \"id\": \"s-1\", \"url\": \"https://...\" } ],\n \"chapters\": [ { \"timestamp\": \"00:00:00.000\", \"name\": \"Intro\" } ],\n \"attachments\": [ { \"url\": \"https://...\", \"name\": \"font.ttf\", \"mime_type\": \"font/ttf\", \"description\": \"\" } ],\n \"manifests\": [ { \"type\": \"dash\", \"url\": \"https://...\", \"data\": \"&lt;base64 zlib xml&gt;\" } ],\n \"session_headers\": { \"User-Agent\": \"...\" },\n \"session_cookies\": { \"sid\": \"...\" },\n \"server_cdm_type\": \"widevine\"\n}\n</code></pre> Status Error code Meaning <code>200</code> - Tracks returned. <code>400</code> <code>INVALID_INPUT</code> Missing or unknown <code>title_id</code>. <code>404</code> <code>SESSION_NOT_FOUND</code> No such session."},{"location":"dev/rest-api/endpoints/#post-apisessionsession_idsegments","title":"<code>POST /api/session/{session_id}/segments</code>","text":"<p>Resolve the download URL, DRM info, headers, cookies, and raw track data for selected tracks. Body: <code>{ \"track_ids\": [\"v-1\", \"a-1\"] }</code> (required).</p> Response <code>200</code> <pre><code>{\n \"tracks\": {\n \"v-1\": { \"descriptor\": \"DASH\", \"url\": \"https://...\", \"drm\": [ ... ], \"headers\": { ... }, \"cookies\": { ... }, \"data\": { ... } }\n }\n}\n</code></pre> Status Error code Meaning <code>200</code> - Segment info returned. <code>400</code> <code>INVALID_INPUT</code> Missing <code>track_ids</code>. <code>404</code> <code>TRACK_NOT_FOUND</code> An unknown track ID was requested."},{"location":"dev/rest-api/endpoints/#post-apisessionsession_idlicense","title":"<code>POST /api/session/{session_id}/license</code>","text":"<p>Acquire DRM keys. Two modes are supported via the <code>mode</code> field.</p> <p>Proxy mode (<code>mode: \"proxy\"</code>, the default) forwards the client's CDM <code>challenge</code> to the service's license endpoint and returns the raw license bytes:</p> RequestResponse <code>200</code> <pre><code>{ \"track_id\": \"v-1\", \"challenge\": \"&lt;base64 CDM challenge&gt;\", \"drm_type\": \"widevine\" }\n</code></pre> <pre><code>{ \"license\": \"&lt;base64 license bytes&gt;\" }\n</code></pre> <p>Server-CDM mode (<code>mode: \"server_cdm\"</code>) runs the full CDM flow on the server using the device configured for your API key, returning content keys directly. Use <code>track_id</code> for a single track or <code>track_ids</code> for a batch:</p> Single: Response <code>200</code>Batch: Response <code>200</code> <pre><code>{ \"keys\": { \"&lt;kid_hex&gt;\": \"&lt;key_hex&gt;\" } }\n</code></pre> <pre><code>{ \"keys\": { \"v-1\": { \"&lt;kid_hex&gt;\": \"&lt;key_hex&gt;\" } }, \"drm_type\": \"widevine\" }\n</code></pre> Field Description <code>track_id</code> / <code>track_ids</code> Single track, or a batch of tracks. <code>challenge</code> Base64 CDM challenge (proxy mode). <code>pssh</code> Base64 PSSH (server-CDM mode). <code>drm_type</code> <code>widevine</code> (default) or <code>playready</code>. <code>mode</code> <code>proxy</code> (default) or <code>server_cdm</code>. Status Error code Meaning <code>200</code> - License/keys returned. <code>400</code> <code>INVALID_INPUT</code> Missing challenge/PSSH, or no CDM device configured for the key. <code>400</code> <code>INVALID_PARAMETERS</code> Unsupported <code>drm_type</code>. <code>404</code> <code>TRACK_NOT_FOUND</code> Unknown track ID. <code>404</code> <code>NO_CONTENT</code> Server CDM produced no keys. <code>502</code> <code>SERVICE_ERROR</code> The service aborted during licensing."},{"location":"dev/rest-api/endpoints/#get-apisessionsession_id","title":"<code>GET /api/session/{session_id}</code>","text":"<p>Return session metadata and validity.</p> Response <code>200</code> <pre><code>{\n \"session_id\": \"d4e5f6a7-...\",\n \"service\": \"EXAMPLE\",\n \"valid\": true,\n \"expires_in\": 300,\n \"track_count\": 4,\n \"title_count\": 10\n}\n</code></pre> <p><code>404 SESSION_NOT_FOUND</code> if the session does not exist or has expired.</p>"},{"location":"dev/rest-api/endpoints/#delete-apisessionsession_id","title":"<code>DELETE /api/session/{session_id}</code>","text":"<p>Tear down a session. Its input bridge is cancelled, any updated cache files are harvested, and the session plus its cache directory are deleted.</p> Response <code>200</code> <pre><code>{\n \"status\": \"ok\",\n \"cache\": { \"tokens.json\": \"&lt;base64 zlib bytes&gt;\" }\n}\n</code></pre> <p>The <code>cache</code> field is present only if the session produced cache files. <code>404 SESSION_NOT_FOUND</code> if the session does not exist.</p>"},{"location":"dev/rest-api/endpoints/#error-responses","title":"Error responses","text":"<p>Every structured error raised inside a handler is serialized to the same JSON envelope:</p> <pre><code>{\n \"status\": \"error\",\n \"error_code\": \"INVALID_PARAMETERS\",\n \"message\": \"Invalid video codec: XYZ\",\n \"timestamp\": \"2026-07-03T12:00:00+00:00\",\n \"details\": { \"field\": \"vcodec\" },\n \"retryable\": true,\n \"debug_info\": { \"exception_type\": \"APIError\", \"traceback\": \"...\" }\n}\n</code></pre> <ul> <li><code>details</code> appears only when non-empty.</li> <li><code>retryable</code> appears only when the error is retryable (e.g. network errors, rate limiting).</li> <li><code>debug_info</code> appears only when the server was started with <code>--debug-api</code>.</li> </ul> <p>Authentication errors differ</p> <p>Errors raised by the API-key middleware use a distinct shape (<code>{\"status\": 401, \"message\": \"Secret Key is Empty.\"}</code> or <code>{\"status\": 401, \"message\": \"Secret Key is Invalid.\"}</code>) with an integer <code>status</code> and no <code>error_code</code>, <code>timestamp</code>, or <code>details</code>. A malformed JSON body on any POST, by contrast, returns the standard envelope with <code>error_code: \"INVALID_INPUT\"</code>.</p>"},{"location":"dev/rest-api/endpoints/#error-codes-and-default-status","title":"Error codes and default status","text":"Error code HTTP status <code>INVALID_INPUT</code> 400 <code>INVALID_SERVICE</code> 400 <code>INVALID_PROXY</code> 400 <code>INVALID_PARAMETERS</code> 400 <code>AUTH_FAILED</code> 401 <code>FORBIDDEN</code> 403 <code>GEOFENCE</code> 403 <code>NOT_FOUND</code> 404 <code>NO_CONTENT</code> 404 <code>JOB_NOT_FOUND</code> 404 <code>SESSION_NOT_FOUND</code> 404 <code>TRACK_NOT_FOUND</code> 404 <code>CONFLICT</code> 409 <code>RATE_LIMITED</code> 429 <code>INTERNAL_ERROR</code> 500 <code>DOWNLOAD_ERROR</code> 500 <code>WORKER_ERROR</code> 500 <code>SERVICE_ERROR</code> 502 <code>DRM_ERROR</code> 502 <code>NETWORK_ERROR</code> 503 <code>SERVICE_UNAVAILABLE</code> 503 <p>When a generic (uncategorized) exception reaches a handler, unshackle inspects its message and type to pick a code. For example, messages mentioning \"connection\" or \"timeout\" become <code>NETWORK_ERROR</code> (503, retryable), \"rate limit\" or \"429\" become <code>RATE_LIMITED</code> (429, retryable), and anything unrecognized collapses to <code>INTERNAL_ERROR</code> (500).</p>"},{"location":"dev/rest-api/endpoints/#see-also","title":"See also","text":"<ul> <li>REST API overview. What the server is and when to use it.</li> <li>Authentication. Keys, server modes, and the <code>X-Secret-Key</code> header.</li> <li>Quickstart. A first end-to-end request walkthrough.</li> <li>Downloading. The <code>dl</code> flags mirrored by <code>POST /api/download</code>.</li> </ul>"},{"location":"dev/rest-api/errors/","title":"Error Responses","text":"<p>Every endpoint of the unshackle REST API reports failures in a single, predictable shape. Whether a request was rejected because a field was missing, a service refused to authenticate, or the download worker crashed, the server answers with a JSON body that carries a machine-readable error code, a human-readable message, and a matching HTTP status. This page documents that format and catalogues every error code the server can emit.</p> <p>If you are building a client against the API, read this page alongside the endpoint reference. Each endpoint lists the specific codes it raises, and the meanings of those codes are defined here.</p> <p>Where this comes from</p> <p>The error format is defined in <code>unshackle/core/api/errors.py</code>, and the wrapper that turns raised errors into responses lives in <code>unshackle/core/api/routes.py</code>. Nothing on this page is invented; it reflects the actual server behaviour.</p>"},{"location":"dev/rest-api/errors/#the-standard-error-shape","title":"The standard error shape","text":"<p>A structured error is always a JSON object with <code>status</code> set to the literal string <code>\"error\"</code>. The full set of fields:</p> Error response body<pre><code>{\n \"status\": \"error\",\n \"error_code\": \"INVALID_PARAMETERS\",\n \"message\": \"vcodec must be one of: H264, H265, ...\",\n \"timestamp\": \"2026-07-03T12:34:56.789012+00:00\",\n \"details\": { \"field\": \"vcodec\" },\n \"retryable\": true,\n \"debug_info\": {\n \"exception_type\": \"APIError\",\n \"traceback\": \"...\"\n }\n}\n</code></pre> Field Type Always present? Meaning <code>status</code> string Yes Always the literal <code>\"error\"</code>. Lets a client distinguish an error body from a success body at a glance. <code>error_code</code> string Yes A stable, machine-readable code from the catalogue below. Match on this, not on <code>message</code>. <code>message</code> string Yes A human-readable description of what went wrong. Wording may change between versions, so do not parse it. <code>timestamp</code> string Yes ISO 8601 timestamp (UTC) of when the error response was built. <code>details</code> object Only when non-empty Structured, error-specific context (for example the invalid field, a list of available titles, or the set of currently active jobs). <code>retryable</code> boolean Only when <code>true</code> Present and set to <code>true</code> when retrying the same request may succeed later (network blips, rate limiting, transient outages). Absent otherwise. <code>debug_info</code> object Only with <code>--debug-api</code> Technical diagnostics; see Debug information. <p>Match on <code>error_code</code>, branch on HTTP status</p> <p>Treat <code>error_code</code> as the primary signal your code reacts to, and the HTTP status as a coarse fallback for anything you do not recognise. The two are consistent: every code maps to a default status (see the catalogue), and the pairing is stable across releases.</p>"},{"location":"dev/rest-api/errors/#the-details-object","title":"The <code>details</code> object","text":"<p>When present, <code>details</code> carries extra context specific to the error. It is only included when it is non-empty, so a client must treat a missing <code>details</code> as \"no extra information\". Some concrete examples you may encounter:</p> <ul> <li>A validation failure may include the offending field or the list of valid values.</li> <li>A \"title not found\" error on a remote-dl session includes <code>available_titles</code>.</li> <li>A maintenance conflict includes <code>active_jobs</code>, the jobs blocking the operation.</li> <li>Categorised exceptions add a <code>reason</code> tag, such as <code>\"network_connectivity\"</code> or <code>\"geofence_restriction\"</code>.</li> </ul>"},{"location":"dev/rest-api/errors/#the-retryable-hint","title":"The <code>retryable</code> hint","text":"<p>The <code>retryable</code> field appears only when it is <code>true</code>. It is set for conditions the server believes are transient: network errors, rate limiting, and temporary service unavailability. When you see it, backing off and retrying is reasonable; when it is absent, assume the request will keep failing until you change something.</p> <p>A retryable network error</p> <pre><code>{\n \"status\": \"error\",\n \"error_code\": \"NETWORK_ERROR\",\n \"message\": \"Network error occurred: Connection timed out\",\n \"timestamp\": \"2026-07-03T12:00:00+00:00\",\n \"details\": { \"reason\": \"network_connectivity\" },\n \"retryable\": true\n}\n</code></pre>"},{"location":"dev/rest-api/errors/#error-code-catalogue","title":"Error code catalogue","text":"<p>Every code below is a member of the <code>APIErrorCode</code> enumeration. The Status column is the default HTTP status the server returns for that code. A handler can override the status in special cases (for example, a network error is always forced to <code>503</code>), but the defaults hold for the overwhelming majority of responses.</p>"},{"location":"dev/rest-api/errors/#client-errors-4xx","title":"Client errors (4xx)","text":"Code Status Meaning <code>INVALID_INPUT</code> 400 A required field is missing, or the request body could not be parsed. Also used as the generic \"your input was malformed\" code. <code>INVALID_SERVICE</code> 400 The named service is unknown, or is not permitted for your API key. <code>INVALID_PROXY</code> 400 The supplied proxy specification could not be resolved or is malformed. <code>INVALID_PARAMETERS</code> 400 One or more download or query parameters failed validation (bad codec, bitrate, sort field, and so on). <code>AUTH_FAILED</code> 401 Authentication with the streaming service failed (bad credentials or cookies). <code>FORBIDDEN</code> 403 The action is not allowed. Raised by server-side gates (per-key restrictions on CDM or credential overrides) and by session IP binding. <code>GEOFENCE</code> 403 The content is not available in the applicable region. <code>NOT_FOUND</code> 404 A requested resource (title, history entry, and so on) does not exist. <code>NO_CONTENT</code> 404 The request was valid but produced nothing: no matching titles, tracks, episodes, or keys. <code>JOB_NOT_FOUND</code> 404 The referenced download job does not exist. <code>SESSION_NOT_FOUND</code> 404 The remote-dl session does not exist or has expired. <code>TRACK_NOT_FOUND</code> 404 A referenced track ID is not present in the session. <code>CONFLICT</code> 409 The target resource is in a state that disallows the action (retrying a running job, prioritising a non-queued job, clearing cache during an active download). <code>RATE_LIMITED</code> 429 The streaming service is rate-limiting requests. Retryable."},{"location":"dev/rest-api/errors/#server-errors-5xx","title":"Server errors (5xx)","text":"Code Status Meaning <code>INTERNAL_ERROR</code> 500 An unexpected server-side error. This is the fallback for any exception the server could not categorise. <code>DOWNLOAD_ERROR</code> 500 The download process itself failed. <code>WORKER_ERROR</code> 500 The download worker subprocess errored out. <code>SERVICE_ERROR</code> 502 The streaming service's API returned an error, or the service does not support the requested operation. <code>DRM_ERROR</code> 502 DRM or license acquisition failed. Retryable. <code>NETWORK_ERROR</code> 503 A network connectivity problem (connection, timeout, DNS, TLS). Retryable. <code>SERVICE_UNAVAILABLE</code> 503 The service is temporarily unavailable or under maintenance. Retryable. <p>Fallback status</p> <p>If a code is ever emitted without a mapped status, the server falls back to <code>500</code>. In practice every code above has an explicit mapping.</p>"},{"location":"dev/rest-api/errors/#how-errors-are-produced","title":"How errors are produced","text":"<p>Understanding where an error comes from helps interpret it.</p> <p>Explicitly raised errors. Most endpoints raise a structured <code>APIError</code> directly. For example, a missing <code>service</code> field yields <code>INVALID_INPUT</code>, and a disallowed service yields <code>INVALID_SERVICE</code>. These carry a precise code, message, and often a populated <code>details</code> object.</p> <p>Categorised exceptions. When an endpoint calls into a streaming service and an uncategorised exception bubbles up, the server runs it through a classifier that inspects the exception type and message and maps it to the most appropriate code. The classification is keyword-based, checked in order:</p> If the error mentions... It becomes Retryable auth, login, credential, unauthorized, forbidden, token <code>AUTH_FAILED</code> (401) no connection, timeout, network, unreachable, socket, dns, resolve (or <code>ConnectionError</code>, <code>TimeoutError</code>, <code>URLError</code>, <code>SSLError</code>) <code>NETWORK_ERROR</code> (503) yes geofence, region, \"not available in\", territory <code>GEOFENCE</code> (403) no \"not found\", 404, \"does not exist\", \"invalid id\" <code>NOT_FOUND</code> (404) no rate limit, too many requests, 429, throttle <code>RATE_LIMITED</code> (429) yes drm, license, widevine, playready, decrypt <code>DRM_ERROR</code> (502) no \"service unavailable\", 503, maintenance, \"temporarily unavailable\" <code>SERVICE_UNAVAILABLE</code> (503) yes invalid, malformed, validation (or <code>ValueError</code>, <code>ValidationError</code>) <code>INVALID_INPUT</code> (400) no anything else <code>INTERNAL_ERROR</code> (500) no <p>Categorised errors include a <code>reason</code> tag inside <code>details</code> (such as <code>\"network_connectivity\"</code> or <code>\"drm_failure\"</code>) so a client can react without parsing the message text.</p> <p>Invalid JSON bodies. If a <code>POST</code> endpoint receives a body that is not valid JSON, the server returns <code>INVALID_INPUT</code> (400) with the parse error in <code>details.error</code>:</p> Malformed request body<pre><code>{\n \"status\": \"error\",\n \"error_code\": \"INVALID_INPUT\",\n \"message\": \"Invalid JSON request body\",\n \"timestamp\": \"2026-07-03T12:00:00+00:00\",\n \"details\": { \"error\": \"Expecting value: line 1 column 1 (char 0)\" }\n}\n</code></pre>"},{"location":"dev/rest-api/errors/#the-authentication-error-exception","title":"The authentication error exception","text":"<p>There is one place where the response does not follow the standard shape: the API key authentication middleware. When you send a request to a protected endpoint without a valid <code>X-Secret-Key</code> header, the middleware short-circuits with a legacy body that uses an integer <code>status</code> and no <code>error_code</code> or <code>timestamp</code>.</p> Missing keyInvalid key <pre><code>{ \"status\": 401, \"message\": \"Secret Key is Empty.\" }\n</code></pre> <pre><code>{ \"status\": 401, \"message\": \"Secret Key is Invalid.\" }\n</code></pre> <p>Handle both shapes</p> <p>A robust client must expect two error formats: the standard structured error (string <code>status</code> of <code>\"error\"</code>, with <code>error_code</code>), and this authentication error (integer <code>status</code>, no <code>error_code</code>). The <code>GET /api/health</code> endpoint is exempt from authentication, so it never returns the key-error shape.</p>"},{"location":"dev/rest-api/errors/#responses-with-no-body","title":"Responses with no body","text":"<p>Not every failure or completion has a JSON body. Some endpoints answer with <code>204 No Content</code> and an empty body, notably deleting a terminal download job and deleting a history entry.</p> <p>Do not parse <code>204</code> bodies</p> <p>A <code>204</code> response has no body. Clients must check the status code before attempting to decode JSON, or the decode will fail on an empty string.</p>"},{"location":"dev/rest-api/errors/#debug-information","title":"Debug information","text":"<p>By default, error responses never include tracebacks or internal diagnostics. If the server was started with the <code>--debug-api</code> flag, every structured error gains a <code>debug_info</code> object:</p> Error with --debug-api enabled<pre><code>{\n \"status\": \"error\",\n \"error_code\": \"INTERNAL_ERROR\",\n \"message\": \"An unexpected error occurred: ...\",\n \"timestamp\": \"2026-07-03T12:00:00+00:00\",\n \"debug_info\": {\n \"exception_type\": \"KeyError\",\n \"traceback\": \"Traceback (most recent call last): ...\"\n }\n}\n</code></pre> <p>The <code>debug_info</code> object always carries <code>exception_type</code> and, for exception-derived errors, a formatted <code>traceback</code>. Some endpoints add extra diagnostics such as captured worker stderr.</p> <p>Developer use only</p> <p><code>--debug-api</code> exposes internal tracebacks in responses. Enable it only for local debugging, never on a server reachable by untrusted clients.</p>"},{"location":"dev/rest-api/errors/#client-handling-recommendations","title":"Client handling recommendations","text":"<p>For anyone writing a consumer of the API, a durable strategy is:</p> <ol> <li>Read the HTTP status first. It tells you the broad class of outcome and lets you handle the <code>204</code>/no-body and authentication-error cases before touching the body.</li> <li>Branch on <code>error_code</code>. For structured errors, this is the stable identifier to switch on. Do not match on <code>message</code>.</li> <li>Respect <code>retryable</code>. When it is <code>true</code>, back off and retry; the reference client retries <code>429</code>, <code>500</code>, <code>502</code>, <code>503</code>, and <code>504</code> with exponential backoff. When absent, fix the request rather than repeating it.</li> <li>Fall back gracefully. Unrecognised codes should be surfaced using the <code>message</code> plus the HTTP status.</li> </ol> <p>Reference consumer</p> <p>unshackle's own remote-download client treats any status of <code>400</code> or above as fatal: it logs <code>Server error [&lt;error_code&gt;]: &lt;message&gt;</code> and exits. It also wraps requests in a retry adapter (five attempts, backing off on <code>429</code>, <code>500</code>, <code>502</code>, <code>503</code>, and <code>504</code>). This is a reasonable template for your own client's error handling.</p>"},{"location":"dev/rest-api/job-lifecycle/","title":"Download Job Lifecycle","text":"<p>When you submit a download over the REST API, the server does not block the request until the file is written. Instead it creates a job, hands it back to you with an ID, and works through it in the background. Everything you do afterwards (watching progress, cancelling, retrying, reading the result) is done by referring to that job ID.</p> <p>This page explains the states a job moves through, how live progress is reported, how to cancel or retry, and, in clearly marked developer sections, how the worker and manager behind the queue actually run the download.</p> <p>Who this page is for</p> <p>The first half is for anyone driving the API: the states, the fields you can read, and the calls that move a job around. The Under the hood sections near the end describe the internal worker/manager model and are aimed at contributors and people debugging the server. You do not need them to use the API.</p> <p>For the full request and response shape of each endpoint, see Endpoints. For how errors are reported, see Error Responses.</p>"},{"location":"dev/rest-api/job-lifecycle/#the-five-states","title":"The five states","text":"<p>A job is always in exactly one of five states, exposed as the <code>status</code> field:</p> Status Meaning <code>queued</code> Created and waiting for a free worker. No download has started yet. <code>downloading</code> A worker has picked the job up and the download is in progress. <code>completed</code> The download finished successfully; <code>output_files</code> lists the results. <code>failed</code> The download stopped with an error; <code>error_message</code> and <code>error_code</code> explain why. <code>cancelled</code> The job was cancelled before it could finish, from either the queued or downloading state. <p>The last three (<code>completed</code>, <code>failed</code>, and <code>cancelled</code>) are terminal: once a job reaches one of them it never changes state again. Terminal jobs can be removed, retried, or read from history, but they will not resume.</p>"},{"location":"dev/rest-api/job-lifecycle/#how-a-job-moves-between-states","title":"How a job moves between states","text":"<pre><code>stateDiagram-v2\n [*] --&gt; queued: POST /api/download\n queued --&gt; downloading: a worker picks it up\n queued --&gt; cancelled: DELETE (while queued)\n downloading --&gt; completed: download succeeds\n downloading --&gt; failed: download errors\n downloading --&gt; cancelled: DELETE (while downloading)\n completed --&gt; [*]\n failed --&gt; [*]\n cancelled --&gt; [*]\n\n completed --&gt; queued: POST .../retry (as a NEW job)\n failed --&gt; queued: POST .../retry (as a NEW job)\n cancelled --&gt; queued: POST .../retry (as a NEW job)</code></pre> <p>The transitions in prose:</p> <ul> <li><code>queued</code> \u2192 <code>downloading</code> happens automatically. As soon as one of the server's workers is free, it takes the next job off the queue and starts it. You do not trigger this; you only observe it.</li> <li><code>downloading</code> \u2192 <code>completed</code> is the happy path: the download engine wrote all the requested files and reported success.</li> <li><code>downloading</code> \u2192 <code>failed</code> is any error during the download: a service failure, a network problem, a DRM error, and so on. The job records what went wrong.</li> <li><code>queued</code>/<code>downloading</code> \u2192 <code>cancelled</code> happens when you send a <code>DELETE</code> for a job that has not finished (see Cancelling a job).</li> <li>Retry does not move a terminal job back to <code>queued</code>. Instead it creates a brand-new job that reuses the old job's service, title, and parameters. The original job stays in its terminal state (see Retrying a job).</li> </ul> <p>Priority does not change status</p> <p>Moving a job to the front of the queue with the priority endpoint reorders when it will start, but it stays <code>queued</code> until a worker actually picks it up. It is not a state change.</p>"},{"location":"dev/rest-api/job-lifecycle/#creating-a-job","title":"Creating a job","text":"<p>A download is queued with <code>POST /api/download</code>. The request needs at least a <code>service</code> and a <code>title_id</code>, plus any download options you want to set. On success the server replies with <code>202 Accepted</code> and the new job's identity:</p> Queue a download<pre><code>curl -X POST http://127.0.0.1:8786/api/download \\\n -H \"X-Secret-Key: your-api-secret\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"service\": \"EXAMPLE\",\n \"title_id\": \"81234567\",\n \"quality\": [\"1080\"],\n \"range\": [\"HDR10\"]\n }'\n</code></pre> 202 Accepted<pre><code>{\n \"job_id\": \"b1e6c7de-6d0a-4f2f-9d1e-3a2b4c5d6e7f\",\n \"status\": \"queued\",\n \"created_time\": \"2026-07-03T12:00:00.000000\"\n}\n</code></pre> <p>The job starts in <code>queued</code>. Workers auto-start on the first job submitted, so there is nothing else to switch on. Keep the <code>job_id</code>; every later call is addressed to it.</p> <p>The full parameter set</p> <p><code>POST /api/download</code> accepts the same download options as the <code>dl</code> command (quality, codecs, language selection, <code>wanted</code> episode ranges, and many more), with server-side defaults filling in anything you omit. The complete list, their defaults, and validation rules are documented on the Endpoints page.</p>"},{"location":"dev/rest-api/job-lifecycle/#reading-a-jobs-status-and-progress","title":"Reading a job's status and progress","text":"<p>There are two ways to look at jobs.</p> One job in fullAll jobs (summaries) <p><code>GET /api/download/jobs/{job_id}</code> returns the complete detail for a single job, including parameters (with secrets redacted), timing, output files, and error information if it failed.</p> <pre><code>curl http://127.0.0.1:8786/api/download/jobs/b1e6c7de-6d0a-4f2f-9d1e-3a2b4c5d6e7f \\\n -H \"X-Secret-Key: your-api-secret\"\n</code></pre> <p><code>GET /api/download/jobs</code> lists every job the manager currently holds. By default each entry is a summary. Pass <code>full=true</code> to get the same full detail as the single-job endpoint for every job.</p> <pre><code>curl \"http://127.0.0.1:8786/api/download/jobs?status=downloading&amp;sort_by=progress&amp;sort_order=desc\" \\\n -H \"X-Secret-Key: your-api-secret\"\n</code></pre> <p>The list can be filtered by <code>status</code> and <code>service</code>, and ordered with <code>sort_by</code> (<code>created_time</code>, <code>started_time</code>, <code>completed_time</code>, <code>progress</code>, <code>status</code>, or <code>service</code>) and <code>sort_order</code> (<code>asc</code> / <code>desc</code>). See Endpoints for the query-parameter reference.</p>"},{"location":"dev/rest-api/job-lifecycle/#the-progress-fields","title":"The progress fields","text":"<p>While a job is <code>downloading</code>, the following fields update roughly twice a second so a client can poll and render live progress. They are present on both the summary and the full detail:</p> Field Type Meaning <code>progress</code> number <code>0</code> to <code>100</code> Overall percent complete. <code>phase</code> string Human-readable phase, e.g. <code>downloading video 1080p HDR10, audio en 5.1</code>. <code>title</code> string Title being processed. <code>current_title</code> string The specific episode/movie in progress (for a batch). <code>completed_tracks</code> int Number of tracks finished so far. <code>total_tracks</code> int Total tracks selected for the download. <code>active_tracks</code> list of strings Labels of the tracks downloading right now. <code>track_progress</code> list Per-active-track <code>{label, progress, speed}</code> entries. <code>segments_done</code> number Segments downloaded for the track in progress. <code>segments_total</code> number Total segments for the track in progress. <code>speed</code> string Transfer speed of the track in progress, e.g. <code>4.20 MB/s</code>. <code>skipped_subtitles</code> list Subtitles that were skipped as non-fatal failures (when <code>skip_subtitle_errors</code> is set). <p>The full detail adds <code>started_time</code>, <code>completed_time</code>, <code>output_files</code>, the redacted <code>parameters</code>, and, for failed jobs, <code>error_message</code>, <code>error_details</code>, <code>error_code</code>, <code>error_traceback</code>, and <code>worker_stderr</code>.</p> <p>A typical polling loop</p> <pre><code>JOB=b1e6c7de-6d0a-4f2f-9d1e-3a2b4c5d6e7f\nwhile true; do\n curl -s \"http://127.0.0.1:8786/api/download/jobs/$JOB\" \\\n -H \"X-Secret-Key: your-api-secret\" \\\n | python -c 'import sys,json; d=json.load(sys.stdin); print(d[\"status\"], d[\"progress\"], d.get(\"phase\"))'\n sleep 1\ndone\n</code></pre> <p>What the percentage means</p> <p><code>progress</code> climbs from <code>0</code> toward <code>90</code> while tracks download, then the final stretch to <code>100</code> covers post-download work such as decryption cleanup, repackaging, and muxing. A job that has finished downloading but is still muxing can sit near <code>90</code> for a moment before completing. On success the manager sets it to exactly <code>100</code>.</p> <p>For a batch, <code>progress</code> is per-episode, not whole-batch</p> <p>A multi-episode request (a <code>wanted</code> range) is a single job that processes its episodes sequentially. As each new episode begins, <code>progress</code> and the track counts (<code>completed_tracks</code> / <code>total_tracks</code>) reset to zero and count up again for that episode alone. The top-level bar therefore tracks the current episode, not the batch as a whole. To derive true overall completion, compare the growing <code>output_files</code> array against <code>parameters.wanted</code> rather than trusting <code>progress</code>.</p>"},{"location":"dev/rest-api/job-lifecycle/#terminal-states-in-detail","title":"Terminal states in detail","text":""},{"location":"dev/rest-api/job-lifecycle/#completed","title":"Completed","text":"<p>A <code>completed</code> job has its <code>output_files</code> populated with the paths of the muxed results, and <code>progress</code> is <code>100</code>. This is the state you are waiting for.</p>"},{"location":"dev/rest-api/job-lifecycle/#failed","title":"Failed","text":"<p>A <code>failed</code> job carries the error. <code>error_message</code> is the short human message, <code>error_code</code> is one of the API's structured error codes (for example <code>NETWORK_ERROR</code>, <code>DRM_ERROR</code>, <code>AUTH_FAILED</code>, or <code>DOWNLOAD_ERROR</code>), and <code>error_details</code> gives more context. When the server was started with <code>--debug-api</code>, <code>error_traceback</code> and <code>worker_stderr</code> are also filled in for diagnosis.</p> <p>Secrets are scrubbed from error text</p> <p>A service can echo a credential or a proxy URL into its output. The server masks any known secret values out of <code>error_message</code>, <code>error_details</code>, <code>error_traceback</code>, and <code>worker_stderr</code> before returning them, so it is safe to log these fields.</p> <p>The error-code catalogue and how each maps to an HTTP status is on the Error Responses page.</p>"},{"location":"dev/rest-api/job-lifecycle/#cancelled","title":"Cancelled","text":"<p>A <code>cancelled</code> job was stopped on request before finishing. It may have partial output, but it is not considered complete. See below.</p>"},{"location":"dev/rest-api/job-lifecycle/#cancelling-a-job","title":"Cancelling a job","text":"<p>Send <code>DELETE /api/download/jobs/{job_id}</code>. The behaviour depends on the job's current state, and this is important because the response differs:</p> Job state when you DELETE What happens Response <code>queued</code> or <code>downloading</code> The job is cancelled. A running download's worker process is terminated. <code>200</code> with <code>{\"status\": \"success\", \"message\": \"Job cancelled\"}</code> <code>completed</code>, <code>failed</code>, or <code>cancelled</code> (terminal) The job is removed from the manager entirely. <code>204 No Content</code>, empty body Not found - <code>404</code> with error code <code>JOB_NOT_FOUND</code> <p>In other words, <code>DELETE</code> on a live job cancels it, while <code>DELETE</code> on an already finished job deletes it from the list. This dual meaning is deliberate: one verb both stops in-flight work and tidies up afterwards.</p> <p>Do not parse the body of a 204</p> <p>Removing a terminal job returns <code>204 No Content</code> with an empty body. A client must not try to decode JSON from it; check the status code first.</p> Cancel a running job<pre><code>curl -X DELETE http://127.0.0.1:8786/api/download/jobs/b1e6c7de-6d0a-4f2f-9d1e-3a2b4c5d6e7f \\\n -H \"X-Secret-Key: your-api-secret\"\n</code></pre> <p>To remove all terminal jobs at once, use <code>POST /api/download/jobs/clear-finished</code>, which returns <code>{\"removed\": &lt;count&gt;}</code>.</p>"},{"location":"dev/rest-api/job-lifecycle/#retrying-a-job","title":"Retrying a job","text":"<p><code>POST /api/download/jobs/{job_id}/retry</code> re-runs a finished job by creating a new job with the same service, title, and parameters. The original job is untouched and stays in its terminal state; the response gives you the new job's ID with <code>202</code>.</p> <ul> <li>Only terminal jobs can be retried. Retrying a <code>queued</code> or <code>downloading</code> job returns <code>409</code> with error code <code>CONFLICT</code>.</li> <li>A missing job returns <code>404</code> (<code>JOB_NOT_FOUND</code>).</li> <li>The service allowlist and any download gates are re-checked for the new job, exactly as they were for the original submission, so a retry can be rejected with <code>INVALID_SERVICE</code> or <code>FORBIDDEN</code> if permissions changed.</li> </ul> 202 Accepted, a fresh job<pre><code>{\n \"job_id\": \"c2f7d8ef-7e1b-5a3a-ae2f-4b3c5d6e7f80\",\n \"status\": \"queued\",\n \"created_time\": \"2026-07-03T12:30:00.000000\"\n}\n</code></pre>"},{"location":"dev/rest-api/job-lifecycle/#prioritising-a-job","title":"Prioritising a job","text":"<p><code>POST /api/download/jobs/{job_id}/priority</code> moves a queued job to the front of the line, so it will be the next one a free worker picks up.</p> <ul> <li>The job must be <code>queued</code>. Prioritising a job in any other state returns <code>409</code> (<code>CONFLICT</code>); a missing job returns <code>404</code>.</li> <li>On success the response is <code>{\"job_id\": \"&lt;id&gt;\", \"position\": \"front\"}</code>.</li> </ul> <p>This only reorders the queue; the job's status stays <code>queued</code> until a worker starts it.</p>"},{"location":"dev/rest-api/job-lifecycle/#history-and-retention","title":"History and retention","text":"<p>Every job that reaches a terminal state is also written once to a persistent history log, so it survives even after the job is removed from the live list.</p> <ul> <li>Read it with <code>GET /api/history</code> (newest first; supports <code>limit</code> and <code>service</code> filters).</li> <li>Delete a single entry with <code>DELETE /api/history/{job_id}</code> (returns <code>204</code>).</li> </ul> <p>The live in-memory jobs are separate from this on-disk history. A background cleanup task periodically drops old terminal jobs from the live list based on a retention period; the history file keeps them for later reference. See Endpoints for the history response shape.</p> <p>Why the history file lives under the cache directory</p> <p><code>api_history.jsonl</code> is placed under the cache directory on purpose, so it stays out of the config/data tree. It is disposable runtime state, not user configuration or curated data, which is exactly why clearing the cache is a safe operation against it.</p>"},{"location":"dev/rest-api/job-lifecycle/#under-the-hood-the-workermanager-model","title":"Under the hood: the worker/manager model","text":"<p>Developer section</p> <p>Everything below describes server internals. It is useful for contributors and for anyone debugging the server, but it is not needed to use the API.</p>"},{"location":"dev/rest-api/job-lifecycle/#the-manager-and-its-queue","title":"The manager and its queue","text":"<p>A single process-wide download queue manager owns all jobs. It holds them in memory keyed by ID, backs the wait list with a FIFO queue, and keeps a separate priority deque for jobs that have been bumped to the front. On the first job, it starts a fixed pool of worker tasks plus one cleanup task; starting is idempotent, so later jobs reuse the same pool.</p> <ul> <li>Concurrency is capped by <code>max_concurrent_downloads</code> (default 2). That many jobs can be in <code>downloading</code> at once; the rest wait in <code>queued</code>.</li> <li>Retention is governed by <code>job_retention_hours</code> (default 24). An hourly cleanup task removes terminal jobs whose completion time (or, if never started, creation time) is older than the retention window.</li> </ul> <p>Two concurrency knobs that are easy to conflate</p> <p><code>max_concurrent_downloads</code> caps how many separate download jobs run at once. The separate <code>serve.downloads</code> setting controls how many tracks download in parallel within a single job. They are independent, and raising one does not affect the other.</p> <p>Concurrency and retention config keys</p> <p>The manager reads these as top-level config attributes (<code>config.max_concurrent_downloads</code> and <code>config.download_job_retention_hours</code>). Those keys are not part of the standard config schema, so in practice the built-in defaults of 2 and 24 apply. The live values are surfaced by <code>GET /api/config</code>. The related <code>serve.history_limit</code> (default 100) instead controls how many entries the on-disk history file keeps.</p> <p>Each worker loop drains the priority deque first, then the FIFO queue. A job that was promoted has its stale FIFO copy skipped so it does not run twice. When a worker takes a job it flips it to <code>downloading</code>, stamps <code>started_time</code>, runs it, and on finish stamps <code>completed_time</code> and records history.</p>"},{"location":"dev/rest-api/job-lifecycle/#each-job-runs-in-its-own-subprocess","title":"Each job runs in its own subprocess","text":"<p>The manager does not run the download in the server's event loop or even in the server process. For each job it spawns a separate Python subprocess:</p> <pre><code>python -m unshackle.core.api.download_worker &lt;payload.json&gt; &lt;result.json&gt; &lt;progress.json&gt;\n</code></pre> <p>Three temporary files bridge the parent and the worker:</p> <ul> <li><code>payload.json</code>: written by the manager before launch; contains the job ID, service, title ID, and merged parameters.</li> <li><code>progress.json</code>: written continuously by the worker as the download proceeds.</li> <li><code>result.json</code>: written by the worker at the end.</li> </ul> <p>Running each download out-of-process isolates the server from crashes, memory growth, and blocking work inside the download engine, and makes hard cancellation (killing the process) reliable.</p> <p>The worker's exit codes are <code>0</code> for success, <code>1</code> for a download error, and <code>2</code> for bad arguments. Its <code>result.json</code> is either <code>{\"status\": \"success\", \"output_files\": [...]}</code> or <code>{\"status\": \"error\", \"message\", \"error_details\", \"error_code\", \"traceback\"}</code>. If the process exits non-zero, or the result is missing or not a success, the parent marks the job <code>failed</code> and adopts the worker's <code>error_code</code> (or derives one by categorising the exception).</p>"},{"location":"dev/rest-api/job-lifecycle/#how-progress-reaches-the-api","title":"How progress reaches the API","text":"<p>While the worker runs, the manager polls <code>progress.json</code> every 0.5 s and copies the fields it finds onto the live <code>DownloadJob</code>. That is what the <code>GET</code> endpoints return.</p> <p>Inside the worker, progress is aggregated across all selected tracks. Each track's completion fraction is weighted by its bitrate, so video and audio dominate the bar and subtitles barely move it (subtitles get a small fixed weight). Track fractions are kept monotonic: the percentage only ever climbs. The download portion is scaled to fill <code>0</code> to <code>90</code>; the remaining <code>90</code> to <code>100</code> is driven by the download engine as it repackages and muxes. A track counts as done when it reaches a terminal state such as <code>Downloaded</code>, <code>Decrypted</code>, or a skipped subtitle.</p>"},{"location":"dev/rest-api/job-lifecycle/#how-cancellation-actually-works","title":"How cancellation actually works","text":"<p>Each job carries a cancellation event. When you <code>DELETE</code> a live job:</p> <ul> <li>If it is <code>queued</code>, it flips straight to <code>cancelled</code>, its history is recorded immediately (it never reaches a worker), and the worker loop skips it if it later pops it off the queue.</li> <li>If it is <code>downloading</code>, the manager sets the cancellation event and flips the job to <code>cancelled</code>. The polling loop notices the event, <code>terminate()</code>s the worker subprocess (escalating to <code>kill()</code> if it does not exit within 5 seconds), and raises a cancellation so the task unwinds. The subprocess model is what makes this a clean, immediate stop rather than a cooperative one.</li> </ul>"},{"location":"dev/rest-api/job-lifecycle/#secret-handling-in-serialized-jobs","title":"Secret handling in serialized jobs","text":"<p>Job parameters may carry secrets: a raw <code>user:pass</code> credential, or a proxy URL with embedded userinfo. Whenever the manager serializes a job (for an API response or the history file), it masks the sensitive keys (<code>credential</code>, <code>credentials</code>, <code>password</code>, <code>token</code>, <code>api_key</code>) and strips userinfo from proxy URLs. Free-text fields that a service might have leaked a secret into (<code>error_message</code>, <code>error_details</code>, <code>error_traceback</code>, <code>worker_stderr</code>, and worker stdout/stderr in the logs) are scrubbed of the job's known secret values, longest-match first, before they are ever returned or logged.</p>"},{"location":"dev/rest-api/job-lifecycle/#see-also","title":"See also","text":"<ul> <li>Endpoints: the full request/response reference for every job endpoint.</li> <li>Error Responses: the error envelope, codes, and HTTP statuses a failed job reports.</li> <li>Authentication: the <code>X-Secret-Key</code> header and per-key service allowlists that gate job creation and retry.</li> <li>Downloading: the equivalent options on the <code>dl</code> command line.</li> </ul>"},{"location":"dev/rest-api/quickstart/","title":"REST API Quick Start","text":"<p>Unshackle ships with a built-in REST API that exposes the same download engine you drive from the command line. It is served by the <code>unshackle serve</code> command and lets you queue downloads, poll their progress, browse services, and manage history over HTTP instead of the terminal.</p> <p>The full loop runs end to end: start the server, authenticate, submit a download job, and poll it to completion, using real <code>curl</code> commands built directly from the API routes.</p> <p>Who this page is for</p> <p>This is a developer guide. It assumes you are comfortable with HTTP, JSON, and a tool like <code>curl</code>. If you just want to download something, the command line is simpler. The REST API is meant for building tools, UIs, and automation on top of unshackle.</p>"},{"location":"dev/rest-api/quickstart/#before-you-begin","title":"Before you begin","text":"<p>You need a working unshackle install with services and CDM devices already configured, exactly as you would for a normal command-line download. If <code>unshackle dl</code> works for you, the API will too, since it runs the identical download pipeline.</p> Installed as a toolFrom a clone <pre><code>uv tool install git+https://github.com/unshackle-dl/unshackle.git\nunshackle --help\n</code></pre> <pre><code>uv run unshackle --help\n</code></pre>"},{"location":"dev/rest-api/quickstart/#step-1-configure-an-api-secret","title":"Step 1: Configure an API secret","text":"<p>Every request (except the health check) is authenticated with a secret key sent in the <code>X-Secret-Key</code> header. The server reads this key from the <code>serve</code> section of your <code>unshackle.yaml</code> config.</p> <p>At minimum you must set <code>api_secret</code>:</p> unshackle.yaml<pre><code>serve:\n api_secret: \"choose-a-long-random-secret\"\n</code></pre> <p>If you want the API to be able to license and download DRM-protected content, you also need to grant CDM devices to the key. Configure that under <code>serve.users</code>, keyed by the secret:</p> unshackle.yaml<pre><code>serve:\n api_secret: \"choose-a-long-random-secret\"\n users:\n choose-a-long-random-secret:\n devices: [\"your_widevine_device\"] # Widevine .wvd stems\n playready_devices: [\"your_playready_device\"] # PlayReady .prd stems\n username: api_user\n</code></pre> <p>The secret must exist</p> <p>If <code>api_secret</code> is not set and you do not pass <code>--no-key</code>, <code>unshackle serve</code> refuses to start and raises an error. Treat the secret like a password. Anyone who has it can queue downloads on your machine.</p> <p>Disabling auth for local testing</p> <p>Passing <code>--no-key</code> to <code>serve</code> turns authentication off entirely: every request is allowed and the <code>X-Secret-Key</code> header is ignored. This is convenient for a throwaway local test, but never expose a <code>--no-key</code> server to a network you do not fully trust.</p>"},{"location":"dev/rest-api/quickstart/#step-2-start-the-server","title":"Step 2: Start the server","text":"<p>Start the REST API with the <code>serve</code> command:</p> <pre><code>unshackle serve --api-only\n</code></pre> <p>By default the server binds to <code>127.0.0.1:8786</code>. The <code>--api-only</code> flag serves just the REST API and omits the Widevine/PlayReady CDM HTTP endpoints; drop it if you also want to expose those.</p> <p>Common options:</p> Option Default Effect <code>-h, --host</code> <code>127.0.0.1</code> Address to bind to <code>-p, --port</code> <code>8786</code> Port to bind to <code>--api-only</code> off Serve only the REST API, no CDM endpoints <code>--no-key</code> off Disable API-key authentication (allow all requests) <code>--debug-api</code> off Include tracebacks and stderr in error responses <code>--debug</code> off Enable DEBUG-level logging <code>--remote-only</code> off Expose only the remote-session subset of routes <code>--caddy</code> off Also launch Caddy as a reverse proxy (for HTTPS) <p>Once it is up you will see the API mounted under <code>/api/</code> and, unless you started in remote-only mode, an interactive Swagger UI:</p> <pre><code>REST API endpoints available at http://127.0.0.1:8786/api/\nSwagger UI available at http://127.0.0.1:8786/api/docs/\n</code></pre> <p>Swagger UI is also behind auth</p> <p>In <code>--api-only</code> mode (without <code>--no-key</code>), the Swagger UI at <code>/api/docs/</code> requires the <code>X-Secret-Key</code> header just like every other route. Only <code>/api/health</code> is exempt from authentication.</p> <p>For the rest of this page we will assume the server is reachable at <code>http://127.0.0.1:8786</code> and store the secret in a shell variable:</p> <pre><code>export SECRET=\"choose-a-long-random-secret\"\nexport BASE=\"http://127.0.0.1:8786\"\n</code></pre>"},{"location":"dev/rest-api/quickstart/#step-3-confirm-the-server-is-alive","title":"Step 3: Confirm the server is alive","text":"<p>The health endpoint is the one route that never requires a key. Use it to confirm the server is running and to read its version:</p> <pre><code>curl \"$BASE/api/health\"\n</code></pre> 200 OK<pre><code>{\n \"status\": \"ok\",\n \"version\": \"5.3.0\",\n \"update_check\": {\n \"update_available\": false,\n \"current_version\": \"5.3.0\",\n \"latest_version\": \"5.3.0\"\n }\n}\n</code></pre> <p>The <code>update_check</code> block is best effort. If unshackle cannot reach the update source, <code>update_available</code> and <code>latest_version</code> come back as <code>null</code> rather than failing the request.</p>"},{"location":"dev/rest-api/quickstart/#step-4-authenticate-a-real-request","title":"Step 4: Authenticate a real request","text":"<p>Every other endpoint needs the <code>X-Secret-Key</code> header. A quick way to prove your key works is to list the services the server can see:</p> <pre><code>curl \"$BASE/api/services\" \\\n -H \"X-Secret-Key: $SECRET\"\n</code></pre> 200 OK (truncated)<pre><code>{\n \"services\": [\n {\n \"tag\": \"EXAMPLE\",\n \"aliases\": [\"EX\"],\n \"geofence\": [],\n \"title_regex\": null,\n \"url\": \"https://example.com\",\n \"help\": \"EXAMPLE service documentation...\",\n \"needs_auth\": true,\n \"has_search\": true,\n \"has_drm\": true,\n \"auth_methods\": [\"cookies\", \"credentials\"],\n \"cli_params\": []\n }\n ]\n}\n</code></pre> <p>If the key is missing or wrong, you get a <code>401</code> with a plain body:</p> 401 Unauthorized<pre><code>{ \"status\": 401, \"message\": \"Secret Key is Invalid.\" }\n</code></pre> <p>Two error shapes exist</p> <p>The authentication middleware returns the short <code>{\"status\": 401, \"message\": \"...\"}</code> shape shown above. Every other error the API produces uses the richer structured shape (<code>error_code</code>, <code>timestamp</code>, <code>details</code>, ...) described in Error handling. A robust client should handle both.</p> <p>The <code>tag</code> value for the service you want is the identifier you pass as <code>service</code> in the calls below.</p>"},{"location":"dev/rest-api/quickstart/#step-5-submit-a-download-job","title":"Step 5: Submit a download job","text":"<p>Downloads are asynchronous. You <code>POST</code> a job to <code>/api/download</code>, the server immediately hands back a <code>job_id</code>, and the actual download runs in the background so your request never blocks.</p> <p>The only required fields are <code>service</code> and <code>title_id</code>. Everything else mirrors the flags of the <code>dl</code> command and has a sensible default, so a minimal job looks like this:</p> <pre><code>curl -X POST \"$BASE/api/download\" \\\n -H \"X-Secret-Key: $SECRET\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"service\": \"EXAMPLE\",\n \"title_id\": \"12345\"\n }'\n</code></pre> <p>A more realistic job pins the quality and codecs and asks for specific episodes:</p> <pre><code>curl -X POST \"$BASE/api/download\" \\\n -H \"X-Secret-Key: $SECRET\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"service\": \"EXAMPLE\",\n \"title_id\": \"12345\",\n \"quality\": [1080],\n \"vcodec\": \"H265\",\n \"range\": [\"SDR\"],\n \"wanted\": [\"S01E01\", \"S01E02\"]\n }'\n</code></pre> <p>On success the server responds with <code>202 Accepted</code> and the identifier you will poll:</p> 202 Accepted<pre><code>{\n \"job_id\": \"3f9c1e0a-8d2b-4e6f-9a1c-77b0f2a1c4d5\",\n \"status\": \"queued\",\n \"created_time\": \"2026-07-03T12:00:00.000000+00:00\"\n}\n</code></pre> <p>Capture the <code>job_id</code> for the next step:</p> <pre><code>JOB=$(curl -s -X POST \"$BASE/api/download\" \\\n -H \"X-Secret-Key: $SECRET\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"service\":\"EXAMPLE\",\"title_id\":\"12345\",\"quality\":[1080]}' \\\n | python -c \"import sys, json; print(json.load(sys.stdin)['job_id'])\")\n</code></pre>"},{"location":"dev/rest-api/quickstart/#frequently-used-download-fields","title":"Frequently used download fields","text":"<p>The request body accepts the full download parameter set. A few of the most useful:</p> Field Default Meaning <code>service</code> - Service tag (required) <code>title_id</code> - Title identifier (required) <code>profile</code> <code>null</code> Named credential/cookie profile to use <code>quality</code> <code>[]</code> Resolution(s), e.g. <code>[1080]</code>; empty means best available <code>vcodec</code> <code>null</code> Video codec, e.g. <code>\"H265\"</code> <code>acodec</code> <code>null</code> Audio codec, e.g. <code>\"EC3\"</code> <code>range</code> <code>[\"SDR\"]</code> Dynamic range: <code>SDR</code>, <code>HDR10</code>, <code>HDR10+</code>, <code>DV</code>, <code>HLG</code>, <code>HYBRID</code> <code>wanted</code> <code>[]</code> Episodes to fetch, e.g. <code>[\"S01E01\"]</code>; empty means all <code>lang</code> <code>[\"orig\"]</code> Video/audio language(s) <code>s_lang</code> <code>[\"all\"]</code> Subtitle language(s) <code>downloads</code> <code>1</code> Number of tracks to download concurrently <code>proxy</code> <code>null</code> Proxy URI or country code <p>Validation is strict: invalid codecs, subtitle formats, dynamic-range names, non-positive counts, or mutually exclusive flags (for example both <code>video_only</code> and <code>audio_only</code>) come back as <code>400</code> with error code <code>INVALID_PARAMETERS</code>. See the full reference on the download reference page for every accepted field.</p> <p>Gated fields</p> <p>Passing a per-request CDM (<code>cdm</code>) or inline credentials (<code>credential</code> / <code>credentials</code>) is refused with <code>403 FORBIDDEN</code> unless the server operator has explicitly opted in via <code>serve.cdm_overrides</code> and <code>serve.allow_job_credentials</code>. Both are off by default.</p>"},{"location":"dev/rest-api/quickstart/#step-6-poll-the-job-to-completion","title":"Step 6: Poll the job to completion","text":"<p>A job moves through these states:</p> <pre><code>queued \u2192 downloading \u2192 completed | failed | cancelled\n</code></pre> <p>The last three are terminal. Poll the job detail endpoint until you reach one of them. This endpoint always returns the full job record:</p> <pre><code>curl \"$BASE/api/download/jobs/$JOB\" \\\n -H \"X-Secret-Key: $SECRET\"\n</code></pre> <p>While the download is running you will see <code>status: \"downloading\"</code> and a <code>progress</code> value climbing from <code>0</code> toward <code>100</code>:</p> 200 OK (in progress)<pre><code>{\n \"job_id\": \"3f9c1e0a-8d2b-4e6f-9a1c-77b0f2a1c4d5\",\n \"status\": \"downloading\",\n \"progress\": 42.7,\n \"phase\": \"downloading\",\n \"service\": \"EXAMPLE\",\n \"title_id\": \"12345\",\n \"title\": \"Example Show S01E01\",\n \"current_title\": \"Example Show S01E01\",\n \"completed_tracks\": 1,\n \"total_tracks\": 3,\n \"segments_done\": 512,\n \"segments_total\": 1200,\n \"speed\": \"8.4 MiB/s\",\n \"created_time\": \"2026-07-03T12:00:00.000000+00:00\",\n \"started_time\": \"2026-07-03T12:00:03.000000+00:00\"\n}\n</code></pre> <p>When it finishes you will see <code>status: \"completed\"</code> and the produced files under <code>output_files</code>:</p> 200 OK (completed)<pre><code>{\n \"job_id\": \"3f9c1e0a-8d2b-4e6f-9a1c-77b0f2a1c4d5\",\n \"status\": \"completed\",\n \"progress\": 100.0,\n \"output_files\": [\"/path/to/downloads/Example Show S01E01.mkv\"],\n \"completed_time\": \"2026-07-03T12:04:31.000000+00:00\"\n}\n</code></pre> <p>A simple polling loop in shell:</p> poll.sh<pre><code>while true; do\n STATUS=$(curl -s \"$BASE/api/download/jobs/$JOB\" \\\n -H \"X-Secret-Key: $SECRET\" \\\n | python -c \"import sys, json; print(json.load(sys.stdin)['status'])\")\n echo \"job status: $STATUS\"\n case \"$STATUS\" in\n completed|failed|cancelled) break ;;\n esac\n sleep 3\ndone\n</code></pre> <p>Polling cadence</p> <p>A few seconds between polls is plenty. The server writes progress updates roughly twice a second internally, but there is no push/streaming channel; you read the current snapshot each time you ask.</p> <p>If a job ends in <code>failed</code>, the full record includes <code>error_message</code>, <code>error_code</code>, and (when the server was started with <code>--debug-api</code>) <code>error_traceback</code> and <code>worker_stderr</code> to help you diagnose it. Sensitive values in these fields are scrubbed before they are returned.</p>"},{"location":"dev/rest-api/quickstart/#step-7-clean-up","title":"Step 7: Clean up","text":"<p>Once you have collected the output you can remove the finished job. <code>DELETE</code> on a job has two behaviors depending on its state:</p> <pre><code>curl -X DELETE \"$BASE/api/download/jobs/$JOB\" \\\n -H \"X-Secret-Key: $SECRET\"\n</code></pre> <ul> <li>If the job is terminal (completed/failed/cancelled) it is removed from the manager and you get <code>204 No Content</code> with an empty body.</li> <li>If the job is still queued or downloading it is cancelled instead, and you get <code>200</code> with <code>{\"status\": \"success\", \"message\": \"Job cancelled\"}</code>.</li> </ul> <p>Do not parse JSON on 204</p> <p>A <code>204</code> response has no body. This applies to terminal-job removal here and to deleting history entries; check the status code before attempting to decode JSON.</p> <p>To clear every finished job at once instead of one at a time:</p> <pre><code>curl -X POST \"$BASE/api/download/jobs/clear-finished\" \\\n -H \"X-Secret-Key: $SECRET\"\n</code></pre> 200 OK<pre><code>{ \"removed\": 3 }\n</code></pre>"},{"location":"dev/rest-api/quickstart/#managing-the-queue","title":"Managing the queue","text":"<p>A handful of endpoints round out job control. All require the <code>X-Secret-Key</code> header.</p> Method Path Purpose <code>GET</code> <code>/api/download/jobs</code> List all jobs, with optional filtering and sorting <code>GET</code> <code>/api/download/jobs/{job_id}</code> Full detail for one job <code>DELETE</code> <code>/api/download/jobs/{job_id}</code> Cancel a running job, or remove a terminal one <code>POST</code> <code>/api/download/jobs/{job_id}/retry</code> Re-queue a new job from a terminal one <code>POST</code> <code>/api/download/jobs/{job_id}/priority</code> Move a queued job to the front of the queue <code>POST</code> <code>/api/download/jobs/clear-finished</code> Remove all terminal jobs <p>Listing supports query parameters for filtering by <code>status</code> or <code>service</code>, sorting via <code>sort_by</code> (<code>created_time</code>, <code>started_time</code>, <code>completed_time</code>, <code>progress</code>, <code>status</code>, <code>service</code>) and <code>sort_order</code> (<code>asc</code> / <code>desc</code>), and requesting full per-job detail with <code>full=true</code>:</p> <pre><code>curl \"$BASE/api/download/jobs?status=downloading&amp;sort_by=progress&amp;sort_order=desc\" \\\n -H \"X-Secret-Key: $SECRET\"\n</code></pre> 200 OK<pre><code>{\n \"jobs\": [\n {\n \"job_id\": \"3f9c1e0a-8d2b-4e6f-9a1c-77b0f2a1c4d5\",\n \"status\": \"downloading\",\n \"service\": \"EXAMPLE\",\n \"title_id\": \"12345\",\n \"title\": \"Example Show S01E01\",\n \"progress\": 42.7,\n \"phase\": \"downloading\",\n \"completed_tracks\": 1,\n \"total_tracks\": 3\n }\n ]\n}\n</code></pre> <p>Retrying reuses the original job's service, title, and parameters to enqueue a brand new job (returning <code>202</code> with a fresh <code>job_id</code>); it only works on terminal jobs and returns <code>409 CONFLICT</code> otherwise. Prioritizing only works on jobs still in the <code>queued</code> state.</p>"},{"location":"dev/rest-api/quickstart/#beyond-a-single-download","title":"Beyond a single download","text":"<p>The download loop above is the core of the API, but the same server exposes more:</p> <ul> <li>Discovery: <code>POST /api/search</code> finds titles by query, and <code>POST /api/list-titles</code> / <code>POST /api/list-tracks</code> inspect what a title offers before you commit to downloading it. See list titles and tracks.</li> <li>History: <code>GET /api/history</code> reads a persisted log of jobs that reached a terminal state (newest first), and <code>DELETE /api/history/{job_id}</code> removes a single entry. See history.</li> <li>Introspection: <code>GET /api/profiles</code> lists configured credential profiles per service, <code>GET /api/config</code> returns a redacted view of the effective server config, and <code>GET /api/env/check</code> reports which external binaries are installed.</li> <li>Maintenance: <code>POST /api/maintenance/clear-cache</code>, <code>.../clear-temp</code>, and <code>.../refresh-services</code> perform housekeeping (the cache/temp clears are blocked with <code>409</code> while a download is active).</li> <li>Remote sessions: the <code>/api/session/*</code> endpoints drive the thin-client \"remote download\" flow, where the server authenticates and licenses on behalf of a local client. See remote sessions.</li> </ul> <p>The interactive Swagger UI at <code>/api/docs/</code> documents every route and lets you try them in the browser (send your <code>X-Secret-Key</code> there too).</p>"},{"location":"dev/rest-api/quickstart/#error-handling","title":"Error handling","text":"<p>Apart from the auth middleware's short form, every error the API returns uses a single structured envelope:</p> <pre><code>{\n \"status\": \"error\",\n \"error_code\": \"INVALID_PARAMETERS\",\n \"message\": \"Human-readable description\",\n \"timestamp\": \"2026-07-03T12:00:00Z\",\n \"details\": { }\n}\n</code></pre> <p><code>details</code> appears only when there is something to add, <code>retryable: true</code> appears only for transient failures, and a <code>debug_info</code> block (exception type and traceback) is included only when the server runs with <code>--debug-api</code>.</p> <p>The <code>error_code</code> maps to an HTTP status. The ones you will meet most often:</p> Error code HTTP Typical cause <code>INVALID_INPUT</code> 400 Malformed JSON body or missing required field <code>INVALID_SERVICE</code> 400 Unknown or disallowed service tag <code>INVALID_PARAMETERS</code> 400 A download field failed validation <code>AUTH_FAILED</code> 401 Service login/credential failure <code>FORBIDDEN</code> 403 A gated field was used without server opt-in <code>NOT_FOUND</code> 404 Title or resource does not exist <code>JOB_NOT_FOUND</code> 404 No job with that <code>job_id</code> <code>CONFLICT</code> 409 Illegal state transition (e.g. retry a running job) <code>RATE_LIMITED</code> 429 Upstream throttling (retryable) <code>INTERNAL_ERROR</code> 500 Unexpected server-side failure <code>SERVICE_ERROR</code> 502 The service raised an error <code>NETWORK_ERROR</code> 503 Connection/timeout reaching the service (retryable) <p>Retry politely</p> <p>Codes marked retryable (<code>NETWORK_ERROR</code>, <code>RATE_LIMITED</code>, <code>SERVICE_UNAVAILABLE</code>) reflect transient conditions. Back off and retry rather than hammering the server.</p>"},{"location":"dev/rest-api/remote-sessions/","title":"Remote Service Sessions","text":"<p>A remote service session lets one machine do the hard, service-specific work (authenticating to a streaming service, listing titles, resolving tracks and manifests, and, optionally, DRM licensing) while another machine runs the actual download, decryption, and muxing locally.</p> <p>This is the mechanism behind unshackle's client/server \"remote download\" workflow. A thin local client (<code>RemoteService</code>) talks to an unshackle <code>serve</code> instance over HTTP. The server keeps an authenticated service instance alive between requests so the client can authenticate once and then make many follow-up calls against the same session.</p> <p>Why you'd use this</p> <ul> <li>The server has service accounts, cookies, or a CDM you don't want to copy to every machine.</li> <li>You want to run downloads on a fast/local machine but keep credentials and licensing centralized.</li> <li>A service is region-locked to where the server lives, and the client isn't.</li> </ul>"},{"location":"dev/rest-api/remote-sessions/#the-big-picture","title":"The big picture","text":"<pre><code>\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 HTTP (X-Secret-Key) \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502 Local machine (client) \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25b6 \u2502 unshackle serve \u2502\n\u2502 \u2502 \u2502 \u2502\n\u2502 unshackle dl --server \u2502 POST /api/session/create \u2502 authenticated Service \u2502\n\u2502 \u2502 GET /api/session/{id}/titles \u2502 instance, kept alive in \u2502\n\u2502 \u2022 track selection \u2502 POST /api/session/{id}/tracks \u2502 an in-memory session \u2502\n\u2502 \u2022 download / decrypt \u2502 POST /api/session/{id}/segments \u2502 store (TTL-based) \u2502\n\u2502 \u2022 mux \u2502 POST /api/session/{id}/license \u2502 \u2502\n\u2502 \u2502 DELETE /api/session/{id} \u2502 \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n</code></pre> <p>The client implements the same interface <code>dl</code> expects from a normal service, but every service-facing method proxies to the server. Everything after track selection (downloading segments, decrypting, and muxing) runs locally.</p> <p>Migration: <code>remote_dl</code> is gone</p> <p>The <code>RemoteService</code> adapter lives inside the ordinary <code>dl</code> command and replaces the old standalone <code>remote_dl</code> command. If you have prior scripts or docs that invoke <code>remote_dl</code>, use <code>dl</code> with a configured remote server instead. The functionality now rides on <code>dl</code> via <code>RemoteService</code>.</p> <p>For the auth-facing endpoints, header format, and error shapes referenced below, see Authentication and the endpoint reference in the REST API index.</p>"},{"location":"dev/rest-api/remote-sessions/#configuring-a-remote-server-client-side","title":"Configuring a remote server (client side)","text":"<p>On the client, add a <code>remote_services</code> block to your <code>unshackle.yaml</code>. Each entry names a server and provides its URL and API key.</p> unshackle.yaml (client)<pre><code>remote_services:\n my_server:\n url: \"https://my-box.example:8786\"\n api_key: \"your-api-key\"\n # Optional: let the server's CDM do the licensing instead of a local CDM\n server_cdm: false\n # Optional: per-service config overrides applied locally (title_map, cdm, etc.)\n services:\n EXAMPLE:\n title_map:\n \"0ABCDEF\": \"The Show (Renamed Locally)\"\n</code></pre> Key Required Meaning <code>url</code> yes Base URL of the <code>unshackle serve</code> instance (no trailing slash needed) <code>api_key</code> no Sent as the <code>X-Secret-Key</code> header on every request <code>server_cdm</code> no When <code>true</code>, DRM keys are resolved by the server's CDM rather than a local device (default <code>false</code>) <code>services</code> no Per-service local config overrides, keyed by service tag <p>Port default</p> <p>The <code>unshackle serve</code> default port is <code>8786</code> (not <code>8080</code>). Use the port your server actually binds. Some older example snippets show <code>8080</code>, which is not the default.</p>"},{"location":"dev/rest-api/remote-sessions/#selecting-a-server","title":"Selecting a server","text":"<p>If exactly one server is configured, unshackle uses it implicitly:</p> <pre><code>unshackle dl EXAMPLE 0ABCDEF\n</code></pre> <p>If more than one server is configured, you must pick one with <code>--server</code>:</p> <pre><code>unshackle dl --server my_server EXAMPLE 0ABCDEF\n</code></pre> <p>With no <code>remote_services</code> configured at all, unshackle raises a clear error telling you to add the block shown above.</p>"},{"location":"dev/rest-api/remote-sessions/#what-happens-during-a-download","title":"What happens during a download","text":"<p>From your point of view the command looks like an ordinary download. Under the hood the client walks a session through its lifecycle.</p> 1. Create + authenticate2. Interactive prompts (if needed)3. Titles + tracks4. Licensing5. Download + close <p>The client calls <code>POST /api/session/create</code>, forwarding whatever it can so the server doesn't have to prompt:</p> <ul> <li>Local credentials for the service/profile (<code>{username, password, extra?}</code>)</li> <li>Local cookies, compressed and base64-encoded</li> <li>A resolved proxy, or, if you didn't set one, your detected client region so the server can auto-proxy to match</li> <li>Track-selection hints (<code>range_</code>, <code>vcodec</code>, <code>quality</code>, <code>best_available</code>) so the server fetches the right manifests</li> <li>Your local per-service cache files (e.g. refreshed tokens)</li> </ul> <p>The server responds immediately with a session ID and a status. Authentication runs in the background on the server.</p> <p>Some services need a one-time code, PIN, or device confirmation. When the server's auth flow asks for input, the session enters <code>pending_input</code>. The client polls, displays the prompt to you locally, collects your answer, and sends it back. The server's auth thread resumes with your response.</p> <pre><code>Enter the 6-digit code sent to your email: 483920\n</code></pre> <p>Once authenticated, the client fetches the title list, then the tracks for the chosen title. The tracks come back with playback URLs, and DASH/ISM manifests are shipped as compressed XML so the client can re-parse them locally for downloading. Any <code>session_headers</code> / <code>session_cookies</code> the server used are merged into the client's local HTTP session.</p> <p>For DRM content the client either proxies its CDM challenge through the server, or, if <code>server_cdm: true</code>, asks the server to run the full CDM flow and return the content keys directly. See Server-side vs. proxied CDM below.</p> <p>The client downloads, decrypts, and muxes locally. On completion it deletes the session. If the server has updated cache files (e.g. a refreshed token), they're returned on delete and saved locally so the next session can skip interactive auth.</p> <p>Renaming remote titles locally</p> <p>You can rename titles for a remote service you don't have installed locally by adding a <code>title_map</code> under that service in your client <code>remote_services.&lt;name&gt;.services</code> config. The server sends raw titles; your local map wins.</p> <p>This is deliberate: the server does no <code>title_map</code> remapping of its own and sends titles exactly as the service returns them. All remapping happens on the client, applied to the titles the server sends back. It keeps the final output name fully under the client's control and lets you rename titles even for services you have no local install of.</p>"},{"location":"dev/rest-api/remote-sessions/#server-side-vs-proxied-cdm","title":"Server-side vs. proxied CDM","text":"<p>There are two ways DRM keys get resolved, chosen by the client's <code>server_cdm</code> flag.</p> Proxied CDM (default)Server-side CDM (server_cdm: true) <p>Your local CDM builds the license challenge. The client sends that challenge to <code>POST /api/session/{id}/license</code>, the server forwards it to the service, and the raw license bytes come back for your local CDM to parse.</p> <ul> <li>Keeps your CDM local; the server just relays the license request.</li> <li>Used when <code>server_cdm</code> is <code>false</code> (the default).</li> </ul> <p>The server's CDM does everything. The client sends track IDs (or a PSSH), the server checks its key vaults, loads the device configured for your API key, runs the CDM flow, and returns <code>KID:KEY</code> pairs directly. No CDM is needed on the client.</p> <ul> <li>Enable with <code>server_cdm: true</code> in the server entry.</li> <li>The server tells the client which DRM type it actually used (<code>widevine</code> or <code>playready</code>).</li> </ul>"},{"location":"dev/rest-api/remote-sessions/#session-lifecycle-and-expiry","title":"Session lifecycle and expiry","text":"<p>Sessions live in an in-memory store on the server and expire on a timer. You generally never touch this directly, but it explains behavior you might observe.</p> Behavior Value Notes Idle session TTL 300s (5 min) default Refreshed on every request to the session Max concurrent sessions 100 default Oldest (least recently used) is evicted when full Auth/input timeout 600s (10 min) Sessions still authenticating or awaiting a prompt use this longer window instead of the TTL Cleanup sweep every 60s Expired sessions are removed and their input prompts cancelled <p>Auth is never rushed</p> <p>A session that is still <code>authenticating</code> or waiting on <code>pending_input</code> is not subject to the short 300s TTL; it gets the full 600s auth window. This gives you time to enter an interactive code without the session vanishing mid-prompt.</p> <p>The TTL and max-session limits are read from server config:</p> unshackle.yaml (server)<pre><code>serve:\n session_ttl: 300 # seconds a session may sit idle\n max_sessions: 100 # cap on concurrent sessions\n</code></pre>"},{"location":"dev/rest-api/remote-sessions/#security-properties-worth-knowing","title":"Security properties worth knowing","text":"<ul> <li>API key required. Every session request carries <code>X-Secret-Key</code>; requests without a valid key are rejected (health check aside). See Authentication.</li> <li>IP binding. A session records the creator's IP at create time. If a later request for the same session comes from a different IP, the server returns <code>403 FORBIDDEN</code>. Sessions are not portable between hosts.</li> <li>Namespaced, isolated cache. Each session gets its own cache directory, namespaced by a hash of the API key and the session ID, so sessions can't read each other's cached tokens. The directory is deleted when the session ends.</li> <li>Secrets are scrubbed from logs. Session IDs, service tags, and other user values are sanitized before logging.</li> </ul>"},{"location":"dev/rest-api/remote-sessions/#developer-reference","title":"Developer reference","text":"<p>This section is for developers</p> <p>The material below documents the server-side implementation and the HTTP contract. End users configuring a client can stop at the sections above.</p>"},{"location":"dev/rest-api/remote-sessions/#session-endpoints","title":"Session endpoints","text":"<p>All routes are exposed even in <code>--remote-only</code> server mode. Paths use the <code>session_id</code> returned by create.</p> <p>Why <code>--remote-only</code> exists</p> <p><code>--remote-only</code> narrows the server to just the health, services, search, and session subset (and emits CORS headers) precisely so it is safe to sit behind Cloudflare or serve cross-origin browser clients. That trimmed surface, rather than the full <code>--api-only</code> mode, is what makes a CORS/Cloudflare-fronted deployment practical: reach for it when the server is public-facing or accessed from a browser origin, not when you simply want the local HTTP API.</p> Method Path Purpose <code>POST</code> <code>/api/session/create</code> Build + authenticate a service instance; returns a session ID immediately <code>GET</code> <code>/api/session/{id}/titles</code> Fetch and cache the title list <code>POST</code> <code>/api/session/{id}/tracks</code> Resolve tracks, manifests, chapters, headers/cookies for a title <code>POST</code> <code>/api/session/{id}/segments</code> Resolve per-segment/track download descriptors <code>POST</code> <code>/api/session/{id}/license</code> DRM licensing (proxy or server CDM) <code>GET</code> <code>/api/session/{id}/prompt</code> Poll interactive auth status / pending prompt <code>POST</code> <code>/api/session/{id}/prompt</code> Submit an answer to a pending prompt <code>GET</code> <code>/api/session/{id}</code> Session info (validity, TTL, counts) <code>DELETE</code> <code>/api/session/{id}</code> Close the session, return updated cache, clean up"},{"location":"dev/rest-api/remote-sessions/#create-request-and-response","title":"Create: request and response","text":"<p><code>POST /api/session/create</code> requires <code>service</code> and <code>title_id</code>. It also accepts <code>credentials</code>, <code>cookies</code> (base64 of zlib-compressed Netscape cookie file), <code>proxy</code>, <code>no_proxy</code>, <code>profile</code>, <code>cache</code> (a map of <code>filename \u2192 base64(zlib(bytes))</code>), <code>client_region</code>, <code>cdm_type</code>, and the track-selection hints <code>range_</code>, <code>vcodec</code>, <code>quality</code>, <code>best_available</code>, plus arbitrary service CLI options (<code>additionalProperties: true</code>).</p> <p>The response returns before authentication finishes:</p> <pre><code>{ \"session_id\": \"...uuid4...\", \"service\": \"EXAMPLE\", \"status\": \"authenticating\" }\n</code></pre> <p>Authentication runs on a background thread (<code>asyncio.to_thread(authenticate, ...)</code>). The session starts in <code>AUTHENTICATING</code>; the client must poll the prompt endpoint until it reaches <code>authenticated</code> (or <code>failed</code>).</p>"},{"location":"dev/rest-api/remote-sessions/#interactive-auth-the-inputbridge","title":"Interactive auth: the <code>InputBridge</code>","text":"<p>When the service calls its input function during <code>authenticate()</code> on the server thread, an <code>InputBridge</code> pauses that thread and exposes the prompt to the HTTP layer.</p> <ul> <li><code>AuthStatus</code> values: <code>authenticating</code>, <code>pending_input</code>, <code>authenticated</code>, <code>failed</code>.</li> <li><code>InputBridge.request_input(prompt, timeout=600)</code> blocks the sync auth thread on a <code>threading.Event</code> until <code>submit_response()</code> or <code>cancel()</code> fires.</li> <li>A timeout raises <code>TimeoutError</code> and marks the session <code>FAILED</code>.</li> <li><code>AUTH_INPUT_TIMEOUT = 600.0</code> seconds. This is also the TTL granted to <code>AUTHENTICATING</code> / <code>PENDING_INPUT</code> sessions in the store.</li> </ul> <p><code>GET /api/session/{id}/prompt</code> returns one of:</p> <pre><code>{ \"status\": \"authenticated\" }\n{ \"status\": \"authenticating\" }\n{ \"status\": \"pending_input\", \"prompt\": \"Enter code: \" }\n{ \"status\": \"failed\", \"error\": \"...message...\" }\n</code></pre> <p>A missing session returns <code>404 SESSION_NOT_FOUND</code>; an IP mismatch returns <code>403 FORBIDDEN</code>. <code>POST /api/session/{id}/prompt</code> takes <code>{ \"response\": \"...\" }</code> and returns <code>{ \"status\": \"accepted\" }</code>; posting with no pending prompt is an <code>INVALID_INPUT</code> error.</p>"},{"location":"dev/rest-api/remote-sessions/#sessionstore-internals","title":"<code>SessionStore</code> internals","text":"<p>Source: <code>unshackle/core/api/session_store.py</code>. A singleton obtained via <code>get_session_store()</code>.</p> <ul> <li>Config-driven limits. <code>serve.session_ttl</code> (default <code>300</code>) and <code>serve.max_sessions</code> (default <code>100</code>) are read as properties, so config changes take effect without recreating the store.</li> <li><code>create()</code> evicts the least-recently-accessed session when at capacity, then stores a new <code>SessionEntry</code> (defaulting <code>auth_status</code> to <code>AUTHENTICATED</code>; the create handler overrides it to <code>AUTHENTICATING</code>).</li> <li><code>get()</code> refreshes <code>last_accessed</code> via <code>touch()</code>. It returns <code>None</code> (and deletes the entry) if an authenticated session has been idle longer than the TTL. Sessions in <code>AUTHENTICATING</code> / <code>PENDING_INPUT</code> are exempt from TTL expiry.</li> <li><code>cleanup_expired()</code> runs every 60s: authenticated sessions expire at <code>ttl</code>, in-flight-auth sessions expire at <code>AUTH_INPUT_TIMEOUT</code>. Removing a session cancels its <code>InputBridge</code> and deletes its cache directory (pruning empty parent dirs up to, but not including, the cache root).</li> <li><code>cancel_all_bridges()</code> is called on server shutdown to unblock any waiting auth threads.</li> </ul> <p><code>SessionEntry</code> fields:</p> Field Description <code>session_id</code> UUID4 string <code>service_tag</code> Normalized service tag <code>service_instance</code> The authenticated service object kept alive between calls <code>titles</code> / <code>title_map</code> Result of <code>get_titles()</code> and a <code>title_id \u2192 Title</code> map <code>tracks</code> / <code>tracks_by_title</code> / <code>chapters_by_title</code> Cached resolved tracks and chapters <code>creator_ip</code> IP recorded at create time for IP-binding checks <code>cache_tag</code> Per-session cache directory tag <code>input_bridge</code> <code>InputBridge</code> for interactive auth, if any <code>auth_status</code> / <code>auth_error</code> Current <code>AuthStatus</code> and last error message <code>created_at</code> / <code>last_accessed</code> Timestamps; <code>last_accessed</code> drives TTL and LRU eviction"},{"location":"dev/rest-api/remote-sessions/#per-session-cache-namespacing","title":"Per-session cache namespacing","text":"<p>The create handler builds a <code>Cacher</code> namespaced as:</p> <pre><code>_sessions/&lt;pbkdf2_hmac(sha256, X-Secret-Key, \"unshackle-session-ns\", 100000)[:12]&gt;/&lt;session_id&gt;/&lt;service&gt;\n</code></pre> <p>Forwarded <code>cache</code> files are written into that directory before authentication. On <code>DELETE</code>, the handler harvests updated cache files (compressing each with zlib and base64-encoding, excluding <code>titles_*</code> files) and returns them under a <code>cache</code> key so the client can persist refreshed tokens:</p> <pre><code>{ \"status\": \"ok\", \"cache\": { \"tokens\": \"...base64(zlib(bytes))...\" } }\n</code></pre>"},{"location":"dev/rest-api/remote-sessions/#session-info-response","title":"Session info response","text":"<p><code>GET /api/session/{id}</code>:</p> <pre><code>{\n \"session_id\": \"...\",\n \"service\": \"EXAMPLE\",\n \"valid\": true,\n \"expires_in\": 300,\n \"track_count\": 12,\n \"title_count\": 40\n}\n</code></pre> <p><code>expires_in</code> is the configured TTL, not time remaining</p> <p>The <code>expires_in</code> value reports the store's configured <code>session_ttl</code>, not the seconds left before this specific session expires.</p>"},{"location":"dev/rest-api/remote-sessions/#reference-client-remoteservice","title":"Reference client: <code>RemoteService</code>","text":"<p>Source: <code>unshackle/core/remote_service.py</code>. This is the canonical consumer of the session API and a good template for any client.</p> <ul> <li><code>RemoteClient._request</code> sets <code>X-Secret-Key</code> and <code>User-Agent: unshackle/&lt;version&gt;</code>, uses a 120s timeout for <code>POST</code> and 30s for <code>GET</code>/<code>DELETE</code>, and treats any <code>status_code &gt;= 400</code> as fatal: it logs <code>Server error [&lt;error_code&gt;]: &lt;message&gt;</code> and raises <code>SystemExit(1)</code>.</li> <li>Retries. The download-side HTTP session mounts an adapter with <code>Retry(total=5, backoff_factor=0.2, status_forcelist=[429, 500, 502, 503, 504])</code>.</li> <li>Flow. <code>authenticate()</code> \u2192 <code>create</code> (+ poll <code>prompt</code> every 2s up to a 600s deadline, answering <code>pending_input</code> prompts) \u2192 <code>get_titles()</code> \u2192 <code>get_tracks()</code> (merging returned <code>session_headers</code>/<code>session_cookies</code>, re-parsing <code>manifests</code>) \u2192 license via proxy or <code>server_cdm</code> \u2192 <code>close()</code> (<code>DELETE</code>, saving any returned <code>cache</code>).</li> <li>Server resolution. <code>resolve_server()</code> reads <code>config.remote_services.&lt;name&gt;</code> into <code>{url, api_key, services, server_cdm}</code>, injecting the <code>server_cdm</code> flag into the services map as <code>_server_cdm</code>.</li> </ul>"},{"location":"dev/rest-api/remote-sessions/#troubleshooting","title":"Troubleshooting","text":"<p>\\\"Could not connect to remote server ... Is it running?\\\"</p> <p>The client couldn't reach the URL. Confirm <code>unshackle serve</code> is running on the server, the <code>url</code>/port in <code>remote_services</code> are correct (default port <code>8786</code>), and any firewall or reverse proxy allows the connection.</p> <p><code>403 FORBIDDEN</code> mid-download</p> <p>The request came from a different IP than the one that created the session. Sessions are IP-bound. Don't move between networks (or NAT egress IPs) during a remote download.</p> <p>Auth times out or the prompt never resolves</p> <p>Interactive auth allows up to 600s. If you miss that window the session is marked <code>failed</code> and cleaned up; just re-run the download. If the server never prompts you, check that credentials/cookies forwarded from the client are valid for the service.</p> <p>\\\"Multiple remote services configured. Use --server ...\\\"</p> <p>You have more than one entry under <code>remote_services</code>. Pass <code>--server &lt;name&gt;</code> to pick one.</p>"},{"location":"getting-started/configuration-file/","title":"The Configuration File","text":"<p>Almost everything about how unshackle behaves is controlled by a single YAML file named <code>unshackle.yaml</code>: where it saves downloads, which CDM it uses, your credentials, proxies, filename templates, and more. This page covers where that file lives, how unshackle finds it, the shape of its contents, the directory layout unshackle builds around it, and how to edit values from the command line.</p> <p>Where the exhaustive key list lives</p> <p>This page is an overview. For the complete, key-by-key breakdown of every setting, its type, and its default, see the Configuration Reference.</p>"},{"location":"getting-started/configuration-file/#the-config-filename","title":"The config filename","text":"<p>The main configuration file is always named <code>unshackle.yaml</code>. It is a plain YAML file. You can open and edit it in any text editor, or manage individual values with the <code>unshackle cfg</code> command.</p> <p>If you have never created one, that is fine: unshackle runs entirely on built-in defaults when no config file exists. The file only needs to contain the keys you want to change from their defaults.</p>"},{"location":"getting-started/configuration-file/#where-the-config-file-lives","title":"Where the config file lives","text":"<p>When unshackle starts, it searches a fixed list of locations and uses the first one that exists. In order of priority:</p> # Location Typical path 1 The unshackle package folder <code>.../site-packages/unshackle/unshackle.yaml</code> 2 The parent of the package folder <code>.../site-packages/unshackle.yaml</code> 3 Your OS user-config directory see the table below <p>The third location, your per-user config directory, is the recommended place for most installations, because it lives outside the package and survives reinstalls and upgrades. Its exact path depends on your operating system:</p> LinuxWindowsmacOS <pre><code>~/.config/unshackle/unshackle.yaml\n</code></pre> <pre><code>%LOCALAPPDATA%\\unshackle\\unshackle.yaml\n</code></pre> <pre><code>~/Library/Application Support/unshackle/unshackle.yaml\n</code></pre> <p>Not sure which file is being used?</p> <p>Run <code>unshackle env info</code>. It prints the path the config was loaded from (or tells you none was found), along with every directory unshackle is currently using.</p> <p>The config is read exactly once, when unshackle starts. If you edit the file, the change takes effect on the next command you run.</p>"},{"location":"getting-started/configuration-file/#top-level-structure","title":"Top-level structure","text":"<p><code>unshackle.yaml</code> is a flat map of top-level keys. Each key configures one area of the program. You only include the keys you want to change; everything else falls back to its default.</p> <p>Here is a small, realistic example that sets a download location, a release tag, a default CDM, and one service's credentials:</p> unshackle.yaml<pre><code># Where finished downloads are written\ndirectories:\n downloads: ~/Videos/unshackle\n\n# Release group tag appended to filenames\ntag: MYGRP\n\n# Default Widevine/PlayReady device to use, with per-service overrides\ncdm:\n default: my_device_l3\n EXAMPLE: my_device_l1\n\n# Per-service login details (service tag -&gt; \"username:password\")\ncredentials:\n EXAMPLE: my_email@example.com:hunter2\n\n# Default HTTP headers merged into every request\nheaders:\n Accept-Language: en-US,en;q=0.9\n</code></pre> <p>The top-level keys group loosely into these areas:</p> Area Example keys Downloading &amp; DRM <code>dl</code>, <code>cdm</code>, <code>remote_cdm</code>, <code>decryption</code> Networking <code>network</code>, <code>headers</code> Credentials &amp; cookies <code>credentials</code>, <code>firefox_cookies</code> Tracks &amp; muxing <code>subtitle</code>, <code>audio</code>, <code>muxing</code>, <code>language_tags</code> Key vaults <code>key_vaults</code>, <code>vault_timeout</code> Proxies &amp; remote <code>proxy_providers</code>, <code>remote_services</code>, <code>serve</code>, <code>services</code> Naming &amp; tagging <code>tag</code>, <code>output_template</code>, <code>chapter_fallback_name</code> External API keys <code>tmdb_api_key</code>, <code>simkl_client_id</code>, <code>ipinfo_api_key</code> Behavior &amp; logging <code>update_checks</code>, <code>redact_paths</code>, <code>debug</code>, <code>unicode_filenames</code> Paths <code>directories</code>, <code>filenames</code> <p>For the full list with types and defaults, see the Configuration Reference.</p> <p>Unknown keys are silently ignored</p> <p>unshackle does not validate your config against a schema. If you misspell a key, it is simply skipped and the default is used. You will not get an error. Double-check key names (and their nesting) if a setting does not seem to apply.</p>"},{"location":"getting-started/configuration-file/#setting-download-defaults-dl","title":"Setting download defaults (<code>dl:</code>)","text":"<p>If you always pass the same <code>dl</code> flags (a language, a resolution, a codec), put them under a <code>dl:</code> key once and unshackle applies them to every download. Any flag from Downloading works here; the key is the flag's long name with dashes turned into underscores (<code>--best-available</code> \u2192 <code>best_available</code>).</p> unshackle.yaml<pre><code>dl:\n lang: [en] # -l en\n quality: [1080] # -q 1080\n vcodec: [H265] # -v H265\n sub_format: srt # convert subtitles to SRT\n downloads: 2 # two tracks at once\n</code></pre> <p>You can still override any of these on the command line for a one-off; an explicit flag always beats the config default. You can also scope defaults to a single service by nesting a <code>dl:</code> block under it:</p> Per-service defaults<pre><code>dl:\n lang: [en] # default for everything\nservices:\n EXAMPLE:\n dl:\n lang: [en, ja] # Example downloads English + Japanese\n</code></pre> <p>A few keys are named after the flag's internal name</p> <p>Most keys are obvious, but set these exact ones: <code>range</code> (<code>-r</code>), <code>list</code> (<code>--list</code>), <code>tmdb_id</code> (<code>--tmdb</code>), <code>imdb_id</code> (<code>--imdb</code>), <code>no_atmos</code> (<code>--noatmos</code>), and <code>output_dir</code> (<code>-o</code>). The Configuration Reference has the full list and every available key.</p>"},{"location":"getting-started/configuration-file/#the-directory-layout","title":"The directory layout","text":"<p>The <code>directories</code> key controls where unshackle reads and writes its various files. Each directory has a sensible default, and you can override most of them by giving a new path. Paths support <code>~</code> for your home directory.</p> unshackle.yaml<pre><code>directories:\n downloads: ~/Videos/unshackle\n temp: /mnt/fast/unshackle-temp\n cache: ~/.cache/unshackle\n</code></pre> <p>The directories unshackle uses:</p> Name Purpose Overridable <code>downloads</code> Default output folder for finished downloads Yes <code>temp</code> Temporary working files during a download Yes <code>cache</code> Cache store (title cache, update checks, service caches) Yes <code>cookies</code> Per-service cookie files Yes <code>logs</code> Log files Yes <code>exports</code> Export JSONs Yes <code>wvds</code> Widevine devices (<code>.wvd</code> files) Yes <code>prds</code> PlayReady devices (<code>.prd</code> files) Yes <code>dcsl</code> DCSL data Yes <code>services</code> Search paths for service code (see below) Yes <code>commands</code> CLI command modules Yes <code>vaults</code> Vault modules Yes <code>fonts</code> Bundled fonts Yes <p>Some directories cannot be moved</p> <p>A handful of internal locations are protected: the package root, the core directory, the user-config directory, and the data base. If you list them under <code>directories</code>, unshackle silently ignores the override. This is intentional; those paths are tied to where the package is installed.</p>"},{"location":"getting-started/configuration-file/#the-services-directory-is-special","title":"The <code>services</code> directory is special","text":"<p>Unlike the other entries, <code>services</code> is a list, and each entry can be either a local folder or a remote repository. This lets you mix your own local service code with services pulled from Git:</p> unshackle.yaml<pre><code>directories:\n services:\n - unshackle-dl/services # a GitHub owner/repo shorthand\n - https://github.com/me/my-services.git\n - ~/code/local-services # a local folder\n</code></pre> <p>Entries are searched in the order listed, and the first source to define a given service tag wins, so put local folders last if you want them to act as fallbacks rather than overrides. Remote repositories are cloned and periodically updated for you. See Services for the full details on how service discovery and repositories work.</p>"},{"location":"getting-started/configuration-file/#the-filenames-key","title":"The <code>filenames</code> key","text":"<p>Alongside <code>directories</code>, the <code>filenames</code> key lets you override the templates unshackle uses when naming its own working and log files (for example the log filename or the temporary chapters file). Most users never need to touch this. The available names and their default templates are listed in the Configuration Reference.</p>"},{"location":"getting-started/configuration-file/#editing-the-config-with-unshackle-cfg","title":"Editing the config with <code>unshackle cfg</code>","text":"<p>You do not have to edit <code>unshackle.yaml</code> by hand. The <code>unshackle cfg</code> command reads and writes individual values for you, creating the config file (and its parent directory) if it does not exist yet.</p> <p>Read a single value by passing its key. Nested keys use dot notation:</p> <pre><code>$ unshackle cfg tag\n$ unshackle cfg cdm.default\n</code></pre> <p>Set a value by passing a key and a value:</p> <pre><code>$ unshackle cfg tag MYGRP\n$ unshackle cfg cdm.default my_device_l3\n</code></pre> <p>Values are parsed as Python literals where possible, so numbers, booleans, and lists work naturally, while bare text is treated as a string:</p> <pre><code>$ unshackle cfg update_checks false\n$ unshackle cfg vault_timeout 30\n</code></pre> <p>Remove a value with <code>--unset</code>:</p> <pre><code>$ unshackle cfg cdm.default --unset\n</code></pre> <p>List everything currently set with <code>--list</code>:</p> <pre><code>$ unshackle cfg --list\n</code></pre> <p>When it writes, <code>unshackle cfg</code> targets the config file that was loaded. If none exists yet, it creates <code>unshackle.yaml</code> in your OS user-config directory.</p> <p>Editing with <code>cfg</code> strips comments</p> <p>Because <code>unshackle cfg</code> rewrites the whole file when it saves, any comments in <code>unshackle.yaml</code> are removed by a write. If you keep important notes as comments, edit the file by hand instead, or keep those notes elsewhere.</p>"},{"location":"getting-started/configuration-file/#next-steps","title":"Next steps","text":"<ul> <li>Browse the Configuration Reference for every key and default.</li> <li>Set up your first download in Downloading.</li> <li>Learn how services are discovered and updated in Services.</li> </ul>"},{"location":"getting-started/installation/","title":"Installation","text":"<p>unshackle is a modular archival tool for movies, TV, and music. It ships as a single Python package named <code>unshackle</code> that installs one console command, also called <code>unshackle</code>. This page covers installing that command, the Python version it needs, and the external command-line tools it expects to find on your <code>PATH</code>.</p> <p>What you get</p> <p>Installing the package registers a single entry point, the <code>unshackle</code> command. It covers everything: downloading, key-vault management, device provisioning, the REST server, and the helper utilities.</p>"},{"location":"getting-started/installation/#requirements-at-a-glance","title":"Requirements at a glance","text":"Requirement Recommended version Needed for Python 3.11 to 3.14 Running unshackle itself uv \u2265 0.5 Installing and running unshackle FFmpeg \u2265 6.0 Media processing and analysis MKVToolNix \u2265 80 MKV muxing and metadata editing shaka-packager 2.6.1 DRM decryption Bento4 \u2265 1.6.0-639 Alternate DRM decryption (<code>mp4decrypt</code>) dovi_tool \u2265 2.1 Dolby Vision handling SubtitleEdit \u2265 5.0 Subtitle conversion (optional) <p>The sections below explain each of these and how to confirm your setup is complete.</p>"},{"location":"getting-started/installation/#python-version-support","title":"Python version support","text":"<p>unshackle requires Python 3.11 or newer, up to and including 3.14 (<code>requires-python = \"&gt;=3.11,&lt;3.15\"</code>). Anything older than 3.11 or 3.15 and later is unsupported and the installer will refuse to build the environment.</p> <p>You do not usually need to install a matching Python interpreter by hand, since <code>uv</code> can download and manage one for you. If you are working inside an existing virtual environment, make sure it is on a supported version.</p>"},{"location":"getting-started/installation/#installing-with-uv","title":"Installing with uv","text":"<p>The recommended way to install unshackle is as a <code>uv</code> tool. This creates an isolated environment for the package and puts the <code>unshackle</code> command on your <code>PATH</code> without touching your system Python.</p> Install as a uv tool<pre><code>uv tool install git+https://github.com/unshackle-dl/unshackle.git\n</code></pre> <p>Once it finishes, the <code>unshackle</code> command is available globally:</p> <pre><code>unshackle --help\n</code></pre> <p>Upgrading and removing</p> <p>Because it is installed from a git URL, re-run the same <code>uv tool install</code> command (uv will update in place) to pull a newer build, and use <code>uv tool uninstall unshackle</code> to remove it.</p>"},{"location":"getting-started/installation/#running-from-a-clone","title":"Running from a clone","text":"<p>If you would rather work from a checkout of the repository (for example to try an in-development branch or to keep local service code alongside unshackle), use <code>uv run</code> inside the clone. This keeps the project's virtual environment active for the duration of the command, so you do not have to activate it yourself.</p> Run from a git clone<pre><code>git clone https://github.com/unshackle-dl/unshackle.git\ncd unshackle\nuv run unshackle --help\n</code></pre> <p>Every command shown elsewhere in these docs works the same way from a clone, just prefix it with <code>uv run</code>:</p> <pre><code>uv run unshackle env check\n</code></pre> <p>Developer note</p> <p>Contributors will also want the development and test dependency groups. The project defines <code>dev</code> (linters, type checkers) and <code>test</code> (pytest and friends) groups in <code>pyproject.toml</code>; install them with <code>uv sync --group dev --group test</code> inside the clone. End users can ignore these entirely.</p>"},{"location":"getting-started/installation/#external-tools-on-your-path","title":"External tools on your PATH","text":"<p>unshackle shells out to a number of external command-line programs for media processing and DRM work. It looks for each one first in a <code>binaries/</code> folder next to the installed package, and then falls back to your system <code>PATH</code>, so installing these tools system-wide (or dropping them into that folder) both work.</p>"},{"location":"getting-started/installation/#required-tools","title":"Required tools","text":"<p>These must be present for core downloading, decryption, and muxing to work:</p> Tool Binary looked up Why it is needed FFmpeg <code>ffmpeg</code> Media processing: remuxing, conversion, stream handling FFprobe <code>ffprobe</code> Media analysis: inspecting tracks and container details MKVToolNix <code>mkvmerge</code> Muxing downloaded tracks into a final MKV mkvpropedit <code>mkvpropedit</code> Editing MKV metadata after muxing shaka-packager <code>shaka-packager</code> / <code>packager</code> Decrypting DRM-protected content (the default decryptor) <p>shaka-packager is the default decryptor</p> <p>unshackle decrypts with shaka-packager unless you explicitly configure a different decryptor. If it is missing, protected downloads will fail at the decryption step. See the configuration reference for the <code>decryption</code> key if you want to switch to <code>mp4decrypt</code>.</p>"},{"location":"getting-started/installation/#recommended-and-optional-tools","title":"Recommended and optional tools","text":"<p>These extend unshackle's capabilities. Install the ones relevant to what you download. For example, <code>dovi_tool</code> only matters if you handle Dolby Vision.</p> Tool Binary looked up Why it is needed Bento4 (<code>mp4decrypt</code>) <code>mp4decrypt</code> Alternative DRM decryptor to shaka-packager dovi_tool <code>dovi_tool</code> Dolby Vision metadata handling HDR10Plus_tool <code>hdr10plus_tool</code> HDR10+ metadata handling SubtitleEdit <code>seconv</code>, <code>SubtitleEdit</code> Subtitle conversion (the <code>SeConv</code> CLI from 5.x) CCExtractor <code>ccextractor</code> Extracting closed captions FFplay <code>ffplay</code> Simple preview player MPV <code>mpv</code> Advanced preview player (used by <code>util crop</code>/<code>util range</code> previews) HolaProxy <code>hola-proxy</code> Hola proxy provider support Caddy <code>caddy</code> Optional reverse proxy for <code>unshackle serve --caddy</code> Docker <code>docker</code> Gluetun VPN proxy support Git <code>git</code> Fetching and updating remote service repositories <p>SubtitleEdit specifics</p> <p>unshackle looks for <code>seconv</code> first, the batch CLI shipped with SubtitleEdit 5.x, before falling back to a <code>SubtitleEdit</code> (4.x) binary. The 5.0 GUI has no batch mode, so the <code>SeConv</code> CLI is what you want for automated subtitle conversion.</p>"},{"location":"getting-started/installation/#verifying-your-installation","title":"Verifying your installation","text":"<p>After installing, confirm the command runs and that unshackle can see the tools it depends on.</p>"},{"location":"getting-started/installation/#confirm-the-command-is-available","title":"Confirm the command is available","text":"<pre><code>unshackle --help\n</code></pre> <p>This prints the banner and the list of available commands (<code>dl</code>, <code>env</code>, <code>kv</code>, <code>serve</code>, <code>wvd</code>, <code>prd</code>, <code>search</code>, <code>util</code>, <code>cfg</code>, <code>import</code>). If your shell reports that <code>unshackle</code> is not found, the <code>uv tool</code> bin directory is probably not on your <code>PATH</code>. Run <code>uv tool update-shell</code> and open a new terminal.</p>"},{"location":"getting-started/installation/#check-external-dependencies","title":"Check external dependencies","text":"<p>The <code>env check</code> subcommand inspects your environment and reports which tools it found:</p> <pre><code>unshackle env check\n</code></pre> OutputFrom a clone <p>It prints a table grouped by category (Core, DRM, HDR, Subtitle, Player, Network) with a status column: a green check for tools that resolved and a red cross for those it could not find, plus a summary line such as <code>All required tools installed \u2713</code> or <code>Missing required: &lt;names&gt;</code>.</p> <pre><code>uv run unshackle env check\n</code></pre> <p>If a required tool shows as missing, install it and put it on your <code>PATH</code> (or in the package's <code>binaries/</code> folder), then re-run the check.</p>"},{"location":"getting-started/installation/#inspect-environment-paths","title":"Inspect environment paths","text":"<p>To see where unshackle will read its configuration from and where it stores downloads, caches, cookies, and devices, use:</p> <pre><code>unshackle env info\n</code></pre> <p>If no configuration file exists yet, this command lists the locations unshackle searches for one, so you know where to create it. See the configuration guide for the details of that file.</p>"},{"location":"getting-started/installation/#next-steps","title":"Next steps","text":"<ul> <li>Set up your configuration file (<code>unshackle.yaml</code>).</li> <li>Start downloading content once your tools check out.</li> </ul>"},{"location":"getting-started/quickstart/","title":"Quick Start","text":"<p>This page takes you from a fresh install to your first downloaded file. You will create the one piece of configuration unshackle insists on, add a streaming service and a CDM so it can actually fetch and decrypt media, run a basic <code>unshackle dl</code> command, and learn where the finished file lands.</p> <p>Before you start</p> <p>This guide assumes unshackle is already installed and on your <code>PATH</code>. If <code>unshackle --help</code> does not print a help screen, work through Installation first.</p>"},{"location":"getting-started/quickstart/#1-check-your-environment","title":"1. Check your environment","text":"<p>unshackle drives several external tools (FFmpeg, MKVToolNix, shaka-packager, and others) to decrypt, repack, and mux media. Confirm they are visible before you download anything:</p> <pre><code>unshackle env check\n</code></pre> <p>This prints a dependency table. The required tools (FFmpeg, FFprobe, MKVToolNix, mkvpropedit, and shaka-packager) must show a green check. Optional tools such as <code>dovi_tool</code> (Dolby Vision) and CCExtractor (closed captions) only matter for the features that use them.</p> <p>Tip</p> <p>The summary line at the bottom reports <code>installed/total</code> and lists anything required that is still missing, so you know exactly what to install next.</p>"},{"location":"getting-started/quickstart/#2-create-a-minimal-config","title":"2. Create a minimal config","text":"<p>unshackle reads a single YAML file named <code>unshackle.yaml</code>. To see where it looks for that file, and where it would accept one if you have not made it yet, run:</p> <pre><code>unshackle env info\n</code></pre> <p>If no config exists, this prints the candidate locations. In search order they are:</p> <ol> <li><code>unshackle.yaml</code> inside the unshackle package folder.</li> <li><code>unshackle.yaml</code> in that folder's parent.</li> <li><code>unshackle.yaml</code> in your OS user-config directory (<code>~/.config/unshackle/</code> on Linux, <code>%LOCALAPPDATA%\\unshackle\\</code> on Windows, <code>~/Library/Application Support/unshackle/</code> on macOS).</li> </ol> <p>The first file that exists wins. Create <code>unshackle.yaml</code> in one of those locations.</p>"},{"location":"getting-started/quickstart/#the-one-key-you-must-set","title":"The one key you must set","text":"<p>unshackle refuses to start a download unless it knows how to name the output file. That means <code>output_template</code> is the one setting a first run genuinely requires. Everything else has a sensible default. A minimal, working config looks like this:</p> unshackle.yaml<pre><code>output_template:\n movies: \"{title} ({year}) {quality} {source}\"\n series: \"{title} S{season}E{episode} {episode_name} {quality} {source}\"\n</code></pre> <p>Each <code>{variable}</code> is filled in from the title and the tracks you downloaded. The full set of valid variables, including <code>resolution</code>, <code>video</code>, <code>audio</code>, <code>hdr</code>, <code>edition</code>, <code>tag</code>, and more, is documented in Configuration.</p> <p>Spaces or dots?</p> <p>unshackle auto-detects your naming style from the template: if the separators between variables are mostly spaces, it uses spaces; if they are mostly dots, it produces scene-style <code>Title.S01E01.1080p</code> names. Write the template in the style you want the filenames to look.</p> <p>Editing config from the CLI strips comments</p> <p>You can read and set keys with <code>unshackle cfg</code> (for example <code>unshackle cfg tag MYGROUP</code> or <code>unshackle cfg --list</code>), but writing a value rewrites the file and removes any comments it contained. If you keep notes in your config, edit the file by hand instead.</p>"},{"location":"getting-started/quickstart/#3-add-a-service","title":"3. Add a service","text":"<p>The service tag you pass to <code>dl</code> (like <code>EXAMPLE</code>) maps to a service module, a small plugin that knows how to talk to one streaming platform. unshackle ships without any bundled services, so you add the one(s) you want.</p> <p>Services live under the <code>directories.services</code> path (run <code>unshackle env info</code> to see where that is). unshackle discovers them by looking for <code>*/__init__.py</code>: the folder name becomes the service tag, and the folder must contain a class with that exact same name.</p> Local folderGit repository <p>Drop a service folder into your services directory. A service tagged <code>EXAMPLE</code> lives at:</p> <pre><code>&lt;services&gt;/EXAMPLE/__init__.py # defines a class named EXAMPLE\n</code></pre> <p>Once the folder is in place, the tag <code>EXAMPLE</code> is immediately available to <code>dl</code>, <code>search</code>, and the other service-aware commands.</p> <p><code>directories.services</code> may also list git repositories. unshackle clones them on first use and keeps them up to date:</p> unshackle.yaml<pre><code>directories:\n services:\n - owner/unshackle-services # a GitHub owner/repo shorthand\n - /path/to/local/services # local folders still work too\n</code></pre> <p>Force a refresh of every configured service repo at any time with:</p> <pre><code>unshackle util refresh-services\n</code></pre> <p>Where to get services</p> <p>Service modules are kept separate from the core project. Ask in the community Discord for where to find the service you need. The core repository deliberately does not host them.</p>"},{"location":"getting-started/quickstart/#4-add-a-cdm-for-drm","title":"4. Add a CDM for DRM","text":"<p>Most streaming content is encrypted. To fetch decryption keys, unshackle needs a CDM, a Widevine device (<code>.wvd</code>) or a PlayReady device (<code>.prd</code>). Register a Widevine device you already have with:</p> <pre><code>unshackle wvd add /path/to/device.wvd\n</code></pre> <p>This validates the file and moves it into your WVDs directory. Then point services at it in your config. The <code>cdm</code> map is keyed by service tag, with a <code>default</code> that covers everything else:</p> unshackle.yaml<pre><code>cdm:\n default: my_device # the .wvd file's name, without the extension\n EXAMPLE: my_other_device # override for a specific service\n</code></pre> <p>PlayReady works the same way with <code>.prd</code> files created and managed by the <code>prd</code> command. If a title is DRM-free, no CDM is needed.</p> <p>Tip</p> <p>Run <code>unshackle wvd parse my_device</code> to inspect a device's security level and contents, and <code>unshackle env info</code> to confirm where WVDs and PRDs are stored.</p>"},{"location":"getting-started/quickstart/#5-provide-authentication","title":"5. Provide authentication","text":"<p>Services that require a login read either cookies or credentials.</p> <ul> <li> <p>Cookies: export the service's cookies to a Netscape-format text file and place it in your cookies directory. unshackle looks for, in order: <code>cookies/{SERVICE}.txt</code>, then <code>cookies/{SERVICE}/{profile}.txt</code>, then <code>cookies/{SERVICE}/default.txt</code>. So a file at <code>cookies/EXAMPLE.txt</code> is picked up automatically for the <code>EXAMPLE</code> service.</p> </li> <li> <p>Credentials: store a username and password per service in your config:</p> unshackle.yaml<pre><code>credentials:\n EXAMPLE: \"email@example.com:your-password\"\n</code></pre> </li> </ul> <p>Use the <code>-p/--profile</code> flag to switch between multiple accounts for the same service. Whether a given service needs cookies, credentials, or nothing at all depends on the service module.</p>"},{"location":"getting-started/quickstart/#6-find-a-title-optional","title":"6. Find a title (optional)","text":"<p>If you have a URL or ID already, skip this. Otherwise, search the service for a title and note the <code>id</code> it prints, since that is what you feed to <code>dl</code>:</p> <pre><code>unshackle search EXAMPLE \"My Show\"\n</code></pre> <p>You can also list what a service exposes for a given title without downloading:</p> <pre><code>unshackle dl --list-titles EXAMPLE 81234567 # show seasons/episodes\nunshackle dl --list EXAMPLE 81234567 # show available tracks\n</code></pre>"},{"location":"getting-started/quickstart/#7-run-your-first-download","title":"7. Run your first download","text":"<p>A download always has three parts:</p> <pre><code>unshackle dl &lt;FLAGS&gt; &lt;SERVICE-TAG&gt; &lt;TITLE&gt;\n</code></pre> <ul> <li><code>dl</code> carries every quality, language, track, and output flag.</li> <li><code>&lt;SERVICE-TAG&gt;</code> picks which service to talk to (e.g. <code>EXAMPLE</code>).</li> <li><code>&lt;TITLE&gt;</code> is the URL, ID, or slug the service understands.</li> </ul> <p>A good first command asks for 1080p with English audio and subtitles:</p> Your first download<pre><code>unshackle dl -q 1080 -l en EXAMPLE 81234567\n</code></pre> <p>unshackle will fetch the title, select the tracks matching your flags, acquire keys through your CDM (and any key vaults), then decrypt, mux, and tag the result.</p>"},{"location":"getting-started/quickstart/#handy-first-flags","title":"Handy first flags","text":"Flag Meaning <code>-q</code>, <code>--quality</code> Target resolution(s), e.g. <code>-q 1080</code> or <code>-q 1080,720</code>. Defaults to best available. <code>-l</code>, <code>--lang</code> Language(s) for video and audio, e.g. <code>-l en</code> or <code>-l orig,en</code>. <code>orig</code> = the title's original language. <code>-sl</code>, <code>--s-lang</code> Subtitle language(s); defaults to <code>all</code>. <code>-v</code>, <code>--vcodec</code> Video codec, e.g. <code>-v H.265</code>. Defaults to any. <code>-r</code>, <code>--range</code> Dynamic range, e.g. <code>-r HDR10</code> or <code>-r DV</code>. Defaults to <code>SDR</code>. <code>-w</code>, <code>--wanted</code> Which episodes, e.g. <code>-w S01</code> or <code>-w S01E01-S01E03</code>. <code>-o</code>, <code>--output</code> Override the output directory for this run. <code>--list</code> List the tracks that would be downloaded, then stop. <p>A few realistic variations</p> <pre><code># A whole first season in the best available quality\nunshackle dl -w S01 EXAMPLE 81234567\n\n# 2160p HDR10 with the original-language audio plus English subtitles\nunshackle dl -q 2160 -r HDR10 -l orig -sl en EXAMPLE 81234567\n\n# Just the newest episode of an ongoing show\nunshackle dl --latest-episode EXAMPLE 81234567\n</code></pre> <p>See Downloading for the complete flag reference, including codec, bitrate, channel-layout, and track-type selection.</p>"},{"location":"getting-started/quickstart/#8-where-the-output-lands","title":"8. Where the output lands","text":"<p>By default, finished files are written to the <code>downloads</code> directory (<code>unshackle env info</code> shows its exact path; the built-in default is a <code>downloads</code> folder alongside the project). Override it per run with <code>-o</code>:</p> <pre><code>unshackle dl -q 1080 -o /mnt/media/incoming EXAMPLE 81234567\n</code></pre> <ul> <li>Movies are written as a single <code>.mkv</code> file named from your <code>movies</code> template.</li> <li>TV episodes are grouped into a per-show / per-season folder (from your <code>series</code> template) unless you pass <code>--no-folder</code>.</li> <li>The filename is built from your <code>output_template</code>, and IMDb/TMDB IDs are added to the file's metadata tags when available.</li> </ul> <p>To change the default output location permanently, set it in your config:</p> unshackle.yaml<pre><code>directories:\n downloads: /mnt/media/incoming\n</code></pre>"},{"location":"getting-started/quickstart/#where-to-go-next","title":"Where to go next","text":"<ul> <li>Downloading. The full <code>dl</code> command: quality, codecs, languages, track selection, hybrid Dolby Vision, and output control.</li> <li>Configuration. Every <code>unshackle.yaml</code> key, plus directories, key vaults, proxies, and naming templates.</li> <li>REST API. Run the <code>serve</code> server to drive downloads over HTTP.</li> </ul> <p>You are never far from help</p> <p><code>unshackle --help</code>, <code>unshackle dl --help</code>, and <code>unshackle &lt;command&gt; --help</code> list every option with its default. When in doubt, add <code>--list</code> to a <code>dl</code> command to preview what it would do before it downloads anything.</p>"},{"location":"guide/cli-reference/","title":"CLI Reference","text":"<p>A complete reference for every <code>unshackle</code> command, subcommand, and flag. Commands are grouped by purpose:</p> <ul> <li><code>dl</code>: the download pipeline (the command you use most).</li> <li><code>search</code>: find titles on a service.</li> <li><code>import</code>: rebuild a download from an export file.</li> <li><code>cfg</code>, <code>env</code>: manage configuration and the environment.</li> <li><code>kv</code>: Key Vault operations.</li> <li><code>wvd</code>, <code>prd</code>: Widevine / PlayReady device management.</li> <li><code>serve</code>: run the local CDM + REST API server.</li> <li><code>util</code>: helper media utilities.</li> </ul> <p>Getting help on any command</p> <p>Every command accepts <code>-h</code>, <code>--help</code>, or <code>-?</code>. For example <code>unshackle dl --help</code> or <code>unshackle wvd new --help</code>. Service-specific arguments for <code>dl</code> and <code>search</code> (such as a title ID or search query) are defined by each service, so check <code>unshackle dl SERVICE --help</code> for those.</p>"},{"location":"guide/cli-reference/#root-command","title":"Root command","text":"<pre><code>unshackle [OPTIONS] COMMAND [ARGS]...\n</code></pre> <p>unshackle: Modular Movie, TV, and Music Archival Software.</p> <p>Every invocation prints a banner and, when <code>update_checks</code> is enabled in your config, checks for a newer release.</p> Option Description <code>-v</code>, <code>--version</code> Print version information and exit. <code>-d</code>, <code>--debug</code> Enable <code>DEBUG</code>-level logs and JSON debug logging. Silences noisy HTTP libraries unless <code>debug_requests</code> is set in config. <code>-h</code>, <code>--help</code>, <code>-?</code> Show help and exit. <p>Commands are auto-discovered, so third-party command modules dropped into the commands directory appear automatically.</p>"},{"location":"guide/cli-reference/#dl","title":"<code>dl</code>","text":"<p>The download command. It is itself a group whose subcommands are the installed streaming services, so an invocation always has three layers:</p> <pre><code>unshackle dl [OPTIONS] SERVICE [SERVICE ARGS...]\n</code></pre> <ul> <li><code>OPTIONS</code>: every flag below, parsed at the <code>dl</code> level.</li> <li><code>SERVICE</code>: a service tag (e.g. <code>EXAMPLE1</code>, <code>EXAMPLE2</code>). Tags are case-insensitive and honour each service's aliases (<code>example+</code>, <code>EXAMPLE2</code>, etc. all resolve to the same tag).</li> <li><code>SERVICE ARGS</code>: the title, URL, or ID, plus any service-specific options. These belong to the service, not to <code>dl</code>.</li> </ul> <p>Typical downloads</p> <pre><code># Best available 1080p SDR of a title\nunshackle dl -q 1080 EXAMPLE 81234567\n\n# 4K HDR10, English audio + subs, from a URL\nunshackle dl -q 2160 -r HDR10 -l en EXAMPLE \"https://www.example.com/...\"\n\n# A season range, HEVC video, EC3 audio\nunshackle dl -w S01-S03 -v H.265 -a EC3 SERVICE TITLE-ID\n</code></pre> <p>Config-driven defaults</p> <p>Any <code>dl</code> flag can be given a default under the <code>dl:</code> section of <code>unshackle.yaml</code>, and per-service under <code>services.&lt;TAG&gt;.dl</code>. Explicit command-line values (and environment values) always win over both; service defaults only fill in options you did not set. See the configuration file guide.</p>"},{"location":"guide/cli-reference/#quality-codec-bitrate-range","title":"Quality, codec, bitrate &amp; range","text":"Flag Default Description <code>-p</code>, <code>--profile</code> - Profile for credentials and cookies. <code>-q</code>, <code>--quality</code> best Resolution(s), comma-separated, e.g. <code>1080,720</code>. <code>-q 1080</code> also matches anamorphic tracks by 16:9 canvas. <code>-v</code>, <code>--vcodec</code> any Video codec(s). Accepts names or values: <code>AVC</code>/<code>H.264</code>, <code>HEVC</code>/<code>H.265</code>, <code>VC1</code>, <code>VP8</code>, <code>VP9</code>, <code>AV1</code>. <code>-a</code>, <code>--acodec</code> any Audio codec(s), comma-separated. Accepts <code>AAC</code>, <code>AC3</code>/<code>DD</code>, <code>EC3</code>/<code>DD+</code>/<code>eac3</code>/<code>ddp</code>, <code>AC4</code>, <code>OPUS</code>, <code>OGG</code>/<code>vorbis</code>, <code>DTS</code>, <code>ALAC</code>, <code>FLAC</code>. <code>-vb</code>, <code>--vbitrate</code> highest Exact video bitrate in kbps. <code>-ab</code>, <code>--abitrate</code> highest Exact audio bitrate in kbps. <code>-vb-range</code>, <code>--vbitrate-range</code> - Video bitrate range in kbps, e.g. <code>6000-7000</code>; picks highest within. Mutually exclusive with <code>--vbitrate</code>. <code>-ab-range</code>, <code>--abitrate-range</code> - Audio bitrate range in kbps, e.g. <code>128-256</code>. Mutually exclusive with <code>--abitrate</code>. <code>-r</code>, <code>--range</code> <code>SDR</code> Colour range(s): <code>SDR</code>, <code>HLG</code>, <code>HDR10</code>, <code>HDR10P</code> (HDR10+), <code>DV</code>, <code>HYBRID</code>. <code>-c</code>, <code>--channels</code> - Audio channels; matches sub-layouts (5.1 \u2248 6.0). <code>-naa</code>, <code>--noatmos</code> off Exclude Dolby Atmos audio tracks. <code>--worst</code> off Pick the lowest bitrate within the requested quality. Requires <code>-q</code>. <code>--best-available</code> off Continue with the best available if a requested resolution/language is absent, instead of failing. <code>-rvb</code>, <code>--real-video-bitrate</code> off Probe real media size for true video bitrates, overriding the manifest. <code>-rab</code>, <code>--real-audio-bitrate</code> off Same for audio (slower). <p><code>HYBRID</code> range</p> <p><code>-r HYBRID</code> fetches both HDR10/HDR10+ and Dolby Vision and merges them with <code>dovi_tool</code>. It requires the <code>dovi_tool</code> binary on your <code>PATH</code>.</p>"},{"location":"guide/cli-reference/#language-subtitles","title":"Language &amp; subtitles","text":"Flag Default Description <code>-l</code>, <code>--lang</code> <code>orig</code> Language(s) for both video and audio. <code>orig</code> = the title's original language; e.g. <code>orig,en</code>. <code>-vl</code>, <code>--v-lang</code> - Video-only language (overrides <code>-l</code> for video). <code>-al</code>, <code>--a-lang</code> - Audio-only language (overrides <code>-l</code> for audio). <code>-sl</code>, <code>--s-lang</code> <code>all</code> Subtitle language(s). <code>--require-subs</code> - Required subtitle langs; keeps all subs only if these exist. Cannot combine with <code>--s-lang</code>. <code>-fs</code>, <code>--forced-subs</code> off Include forced subtitle tracks. <code>--exact-lang</code> off Exact matching only: <code>-l es-419</code> matches <code>es-419</code>, not <code>es-ES</code>. <code>--sub-format</code> - Output subtitle format (<code>SRT</code>/<code>srt</code>, <code>VTT</code>/<code>webvtt</code>, <code>ASS</code>/<code>ssa</code>, <code>TTML</code>, <code>SMI</code>, ...), or <code>original</code> to keep the source format. <p>The special language tokens <code>orig</code>, <code>all</code>, and <code>best</code> are honoured everywhere a language is expected.</p>"},{"location":"guide/cli-reference/#title-episode-selection","title":"Title &amp; episode selection","text":"Flag Description <code>-w</code>, <code>--wanted</code> Wanted episodes, e.g. <code>S01-S05,S07</code>, <code>S01E01-S02E03</code>. Supports exclusions with a leading <code>-</code> (e.g. <code>-S03</code>). <code>--select-titles</code> Interactively select titles (series only). Cannot combine with <code>-w</code>. <code>--latest-episode</code> Download only the single most recent episode. <code>--list-titles</code> List titles only; do not download."},{"location":"guide/cli-reference/#track-type-inclusion-exclusion","title":"Track-type inclusion / exclusion","text":"<p>Keep only certain track types, or skip certain track types. Attachments are always kept.</p> Include-only Skip <code>-V</code>, <code>--video-only</code> <code>-nv</code>, <code>--no-video</code> <code>-A</code>, <code>--audio-only</code> <code>-na</code>, <code>--no-audio</code> <code>-S</code>, <code>--subs-only</code> <code>-ns</code>, <code>--no-subs</code> <code>-C</code>, <code>--chapters-only</code> <code>-nc</code>, <code>--no-chapters</code> Flag Description <code>-ad</code>, <code>--audio-description</code> Include descriptive (audio-description) tracks. <code>--skip-subtitle-errors</code> Skip a failed subtitle instead of aborting the title. Video/audio failures remain fatal."},{"location":"guide/cli-reference/#output-muxing-files","title":"Output, muxing &amp; files","text":"Flag Description <code>--split-audio</code> Write a separate output file per audio codec instead of merging. Defaults to config <code>muxing.merge_audio</code>. <code>--merge-video</code> Mux all selected video tracks into one file. Defaults to config <code>muxing.merge_video</code>. <code>-o</code>, <code>--output</code> Override the output directory for this run. <code>--no-folder</code> Disable folder creation for TV shows. <code>--no-source</code> Remove the source tag from the filename/path. <code>--no-mux</code> Do not mux; keep individual track files. <code>--tag</code> Group tag override. <code>--repack</code> Add a <code>REPACK</code> tag to the filename."},{"location":"guide/cli-reference/#metadata-tagging","title":"Metadata &amp; tagging","text":"Flag Description <code>--tmdb</code> TMDB ID (integer). <code>--imdb</code> IMDb ID, e.g. <code>tt1375666</code>. <code>--animeapi</code> AnimeAPI ID, e.g. <code>mal:12345</code> or <code>anilist:98765</code> (defaults to MAL). Back-fills TMDB/IMDb. <code>--enrich</code> Override show title/year from the external source. Requires one of <code>--tmdb</code>, <code>--imdb</code>, or <code>--animeapi</code>."},{"location":"guide/cli-reference/#drm-keys-decryption","title":"DRM, keys &amp; decryption","text":"Flag Description <code>--cdm-only</code> / <code>--vaults-only</code> Use only the CDM, or only Key Vaults, for key acquisition. <code>--skip-dl</code> Skip the download but still retrieve keys. <code>--export</code> Export track info and keys to a JSON file in the exports directory."},{"location":"guide/cli-reference/#network-proxy","title":"Network &amp; proxy","text":"Flag Description <code>--proxy</code> Proxy URI, a 2-letter country code resolved from configured providers, or <code>provider:region</code> (e.g. <code>nordvpn:ca</code>, <code>gluetun:us</code>, <code>protonvpn:de:berlin</code>). <code>--no-proxy</code> Force-disable all proxy use. <code>--no-proxy-download</code> Bypass the proxy for segment downloads only (manifest, licence, and auth stay proxied). <code>--remote</code> Use a remote unshackle server. <code>--server</code> Name a remote server from the <code>remote_services</code> config."},{"location":"guide/cli-reference/#concurrency-caching-listing","title":"Concurrency, caching &amp; listing","text":"Flag Default Description <code>--workers</code> downloader default Per-track download threads. <code>--downloads</code> <code>1</code> Number of tracks downloaded concurrently. <code>--no-cache</code> off Bypass the title cache. <code>--reset-cache</code> off Clear the title cache. <code>--list</code> off List available/would-be-downloaded tracks; do not download. <code>--slow</code> - Inter-title delay. Bare <code>--slow</code> = 60-120s; <code>--slow 20-40</code> = custom range (minimum 20s). <p>Some flags cannot be combined</p> <p><code>--require-subs</code> and <code>--s-lang</code>; <code>--select-titles</code> and <code>--wanted</code>; <code>--worst</code> requires <code>--quality</code>; <code>--vbitrate</code> and <code>--vbitrate-range</code> (and the audio equivalents) are mutually exclusive.</p>"},{"location":"guide/cli-reference/#search","title":"<code>search</code>","text":"<p>Search a service for titles. Like <code>dl</code>, <code>search</code> is a group whose subcommands are the installed services, and it reuses <code>dl</code>'s authentication, cookie, and proxy machinery.</p> <pre><code>unshackle search [OPTIONS] SERVICE [QUERY...]\n</code></pre> <p>The query syntax is defined per service. Results are printed as a tree of titles with their service IDs. Feed an ID straight into <code>dl</code>.</p> Option Description <code>-p</code>, <code>--profile</code> Profile for credentials and cookies. <code>--proxy</code> Proxy URI, 2-letter country code, or <code>provider:region</code>. <code>--no-proxy</code> Force-disable all proxy use. <p>Example</p> <pre><code>unshackle search EXAMPLE \"My Show\"\nunshackle search -p myprofile EXAMPLE \"Another Show\"\nunshackle search --proxy nordvpn:ca SERVICE \"query\"\n</code></pre>"},{"location":"guide/cli-reference/#import","title":"<code>import</code>","text":"<p>Reconstruct a download (download \u2192 decrypt \u2192 mux) from an <code>--export</code> JSON file without re-contacting the service. It re-fetches the manifest, injects the stored keys, and then runs the normal <code>dl</code> pipeline. The service tag is read from the export file, not passed by you.</p> <pre><code>unshackle import EXPORT_FILE [DL_ARGS...]\n</code></pre> <p>Any <code>dl</code> options placed after the file are forwarded verbatim, so you can override quality, range, proxy, and so on.</p> <p>Example</p> <pre><code>unshackle import export.json\nunshackle import export.json -r HDR10 --proxy US\n</code></pre> <p>The export file must be a valid v2 export (created by a current build of unshackle via <code>dl --export</code>) and must contain a <code>service</code> tag.</p>"},{"location":"guide/cli-reference/#cfg","title":"<code>cfg</code>","text":"<p>Read, set, delete, or list configuration values in <code>unshackle.yaml</code> without hand-editing YAML.</p> <pre><code>unshackle cfg [KEY] [VALUE] [OPTIONS]\n</code></pre> Argument / Option Description <code>KEY</code> Dotted path into the config, e.g. <code>tag</code>, <code>serve.api_secret</code>, <code>directories.downloads</code>. <code>VALUE</code> Value to set. Parsed as a Python literal when possible, so <code>true</code>, <code>123</code>, <code>['a','b']</code>, and <code>{'k':1}</code> become real types; bare words stay strings. <code>--unset</code> Remove the configuration value. <code>--list</code> List all set configuration values. <p>Comments are stripped</p> <p>Writing a value through <code>cfg</code> rewrites the YAML file and removes all comments from it. If your config relies on comments, edit it by hand instead. Setting a value and using <code>--unset</code> together is an error.</p> <p>Example</p> <pre><code>unshackle cfg --list # print entire config\nunshackle cfg serve.api_secret # read a nested key\nunshackle cfg tag MYGROUP # set a string\nunshackle cfg update_checks false # literal \u2192 boolean False\nunshackle cfg directories.downloads /mnt/dl # set a nested path\nunshackle cfg tag --unset # remove a key\n</code></pre>"},{"location":"guide/cli-reference/#env","title":"<code>env</code>","text":"<p>Inspect and manage the project environment.</p> <pre><code>unshackle env COMMAND [ARGS]...\n</code></pre>"},{"location":"guide/cli-reference/#env-check","title":"<code>env check</code>","text":"<pre><code>unshackle env check\n</code></pre> <p>Prints a dependency table (Category / Tool / Status / Required / Purpose) showing which external tools resolve on your <code>PATH</code>, and a summary of how many required tools are installed.</p> Category Tools Core FFmpeg*, FFprobe*, MKVToolNix*, mkvpropedit* DRM shaka-packager*, mp4decrypt, ML-Worker HDR dovi_tool, HDR10Plus_tool Subtitle SubtitleEdit, CCExtractor Player FFplay, MPV Network HolaProxy, Caddy, Docker, git <p>* required; all others are optional.</p>"},{"location":"guide/cli-reference/#env-info","title":"<code>env info</code>","text":"<pre><code>unshackle env info\n</code></pre> <p>Shows where the config was loaded from (or lists the candidate config locations if none was found) and prints a table of every configured directory (downloads, temp, cache, cookies, logs, exports, WVDs, PRDs, services, and more).</p>"},{"location":"guide/cli-reference/#env-clear","title":"<code>env clear</code>","text":"<p>Clear an environment directory. The directory is emptied and recreated, and the number of files and bytes freed is reported.</p> Command Description <code>unshackle env clear cache [SERVICE]</code> Clear the cache directory, or just one service's cache subdirectory. <code>unshackle env clear temp</code> Clear the temp directory. <p>Example</p> <pre><code>unshackle env check\nunshackle env info\nunshackle env clear cache\nunshackle env clear cache EXAMPLE # one service only\nunshackle env clear temp\n</code></pre>"},{"location":"guide/cli-reference/#kv","title":"<code>kv</code>","text":"<p>Manage Key Vaults. Vaults are configured under <code>key_vaults</code> in <code>unshackle.yaml</code>, each with a <code>name</code>, a <code>type</code> (<code>sqlite</code>, <code>mysql</code>, <code>http</code>, <code>api</code>), and type-specific options. Service tags are normalised automatically.</p> <pre><code>unshackle kv COMMAND [ARGS]...\n</code></pre>"},{"location":"guide/cli-reference/#kv-copy-to_vault-from_vault","title":"<code>kv copy TO_VAULT FROM_VAULT...</code>","text":"<p>Copy keys from one or more source vaults into a destination vault. Rows with matching KIDs are skipped unless the existing row has no key; existing data is never altered or deleted.</p> Option Description <code>-s</code>, <code>--service</code> Only copy data for a specific service. <code>-l</code>, <code>--local-only</code> Only copy data for services installed locally. Mutually exclusive with <code>--service</code>."},{"location":"guide/cli-reference/#kv-sync-vault","title":"<code>kv sync VAULT...</code>","text":"<p>Ensure two or more vaults hold the same set of keys, essentially a chained bidirectional copy. Requires more than one vault. Accepts the same <code>--service</code> / <code>--local-only</code> options as <code>copy</code>.</p>"},{"location":"guide/cli-reference/#kv-add-file-service-vault","title":"<code>kv add FILE SERVICE VAULT...</code>","text":"<p>Add content keys to one or more vaults for a service. <code>FILE</code> contains one <code>KID:KEY</code> pair per line (32 hex : 32 hex, UTF-8). Lines that don't match are skipped.</p>"},{"location":"guide/cli-reference/#kv-search-kid","title":"<code>kv search KID</code>","text":"<p>Search configured vaults for a KID (32 hex characters, no dashes) and report any matching key.</p> Option Description <code>-s</code>, <code>--service</code> Limit the search to a specific service tag. <code>-v</code>, <code>--vault</code> Limit the search to a specific configured vault by name. <p>Note</p> <p>Remote vaults cannot be enumerated without a service, so pass <code>--service</code> when searching them.</p>"},{"location":"guide/cli-reference/#kv-prepare-vault","title":"<code>kv prepare VAULT...</code>","text":"<p>Create service tables on vaults that use tables, for every installed service, where they don't already exist.</p> <p>Example</p> <pre><code>unshackle kv copy main backup1 backup2\nunshackle kv copy main backup -s EXAMPLE\nunshackle kv sync main mysql_vault\nunshackle kv add keys.txt EXAMPLE main backup\nunshackle kv search 0123456789abcdef0123456789abcdef -s EXAMPLE -v main\nunshackle kv prepare main mysql_vault\n</code></pre>"},{"location":"guide/cli-reference/#wvd","title":"<code>wvd</code>","text":"<p>Manage Widevine Device (<code>.wvd</code>) files. Devices live in the configured WVDs directory.</p> <pre><code>unshackle wvd COMMAND [ARGS]...\n</code></pre> Command Description <code>wvd add PATHS...</code> Validate and move one or more <code>.wvd</code> files into the WVDs directory. <code>wvd delete NAMES...</code> Delete <code>.wvd</code> files by name (without extension). Prompts for confirmation. <code>wvd parse PATH</code> Parse a <code>.wvd</code> and print its System ID, security level, type, flags, and client info. Relative paths resolve against the WVDs directory. <code>wvd dump WVD_PATHS... OUT_DIR</code> Extract a device's contents (metadata, private key, client ID, VMP) into <code>OUT_DIR/&lt;name&gt;/</code>. With no paths, dumps every WVD in the WVDs directory. <code>wvd new NAME PRIVATE_KEY CLIENT_ID [FILE_HASHES]</code> Create a new <code>.wvd</code> from a PEM private key and a <code>ClientIdentification</code> blob, optionally with a VMP (<code>FileHashes</code>) blob. <p><code>wvd new</code> options:</p> Option Default Description <code>-t</code>, <code>--type</code> <code>Android</code> Device type. <code>-l</code>, <code>--level</code> <code>1</code> Security level (1-3). <code>-o</code>, <code>--output</code> WVDs dir Output directory. <p>Example</p> <pre><code>unshackle wvd add device.wvd\nunshackle wvd parse nexus_6p_1234_l1\nunshackle wvd dump device.wvd ./out_dir\nunshackle wvd new \"Nexus 6P\" private_key.pem client_id.bin vmp.bin -t ANDROID -l 3\n</code></pre>"},{"location":"guide/cli-reference/#prd","title":"<code>prd</code>","text":"<p>Manage PlayReady Device (<code>.prd</code>) files. Devices live in the configured PRDs directory. Built on <code>pyplayready</code>.</p> <pre><code>unshackle prd COMMAND [ARGS]...\n</code></pre>"},{"location":"guide/cli-reference/#prd-new-paths","title":"<code>prd new PATHS...</code>","text":"<p>Create a new <code>.prd</code>. Provide either a single folder containing <code>zgpriv.dat</code> (group key) and <code>bgroupcert.dat</code> (group certificate), or two file paths (group key, then group certificate).</p> Option Description <code>-e</code>, <code>--encryption_key</code> Optional device ECC private encryption key (generated if omitted). <code>-s</code>, <code>--signing_key</code> Optional device ECC private signing key (generated if omitted). <code>-o</code>, <code>--output</code> Output directory or <code>.prd</code> file path. <p><code>prd new</code> will not overwrite an existing file.</p>"},{"location":"guide/cli-reference/#prd-reprovision-prd_path","title":"<code>prd reprovision PRD_PATH</code>","text":"<p>Reprovision an existing device by replacing its leaf certificate and keys. The device must support reprovisioning (version 3 or higher). Accepts the same <code>-e</code> / <code>-s</code> / <code>-o</code> options; defaults to overwriting the device in place.</p>"},{"location":"guide/cli-reference/#prd-test-device","title":"<code>prd test DEVICE</code>","text":"<p>Test a device against the Microsoft PlayReady demo server and print the returned keys.</p> Option Default Description <code>-c</code>, <code>--ckt</code> <code>aesctr</code> Content key encryption type: <code>aesctr</code> or <code>aescbc</code>. <code>-sl</code>, <code>--security-level</code> <code>2000</code> Minimum security level: <code>150</code>, <code>2000</code>, or <code>3000</code>. <p>Example</p> <pre><code>unshackle prd new ./device_folder/\nunshackle prd new zgpriv.dat bgroupcert.dat -o /out/dir\nunshackle prd reprovision mydevice.prd\nunshackle prd test mydevice.prd -sl 3000 -c aescbc\n</code></pre>"},{"location":"guide/cli-reference/#serve","title":"<code>serve</code>","text":"<p>Serve your local Widevine/PlayReady devices and the REST API for remote access. Built on <code>aiohttp</code>.</p> <pre><code>unshackle serve [OPTIONS]\n</code></pre> Option Default Description <code>-h</code>, <code>--host</code> <code>127.0.0.1</code> Host to serve from. <code>-p</code>, <code>--port</code> <code>8786</code> Port to serve from. <code>--caddy</code> off Also serve through Caddy (requires the <code>caddy</code> binary and a <code>Caddyfile</code>). <code>--api-only</code> off Serve only the REST API, not the CDM endpoints. Incompatible with <code>--no-widevine</code>/<code>--no-playready</code>. <code>--no-widevine</code> off Disable the Widevine CDM endpoints. <code>--no-playready</code> off Disable the PlayReady CDM endpoints. <code>--no-key</code> off Disable API-key authentication (allows all requests). <code>--debug-api</code> off Include tracebacks/stderr in API error responses. <code>--debug</code> off Enable debug logging for API operations. <code>--remote-only</code> off Expose only the remote service session endpoints (health, services, search, session). Implies <code>--api-only</code>. <p>WVD files in the WVDs directory and PRD files in the PRDs directory are auto-loaded. The REST API lives under <code>http://&lt;host&gt;:&lt;port&gt;/api/</code>, with Swagger UI at <code>/api/docs/</code> and a health check at <code>/api/health</code> (exempt from auth).</p> <p>Configure <code>api_secret</code> first</p> <p>Unless you pass <code>--no-key</code>, <code>serve.api_secret</code> must be set in your config. Requests authenticate with the <code>X-Secret-Key</code> header. Running with <code>--no-key</code> disables authentication entirely and should only be used on a trusted, private network.</p> unshackle.yaml<pre><code>serve:\n api_secret: \"your-api-secret\"\n users:\n your-secret-key:\n devices: [\"device_name\"] # Widevine devices\n playready_devices: [\"device_name\"] # PlayReady devices\n username: user\n</code></pre> <p>Example</p> <pre><code>unshackle serve\nunshackle serve -h 0.0.0.0 -p 8080\nunshackle serve --api-only\nunshackle serve --remote-only\nunshackle serve --caddy\n</code></pre>"},{"location":"guide/cli-reference/#util","title":"<code>util</code>","text":"<p>Various helper media utilities. When a command is given a directory, it processes every <code>.mkv</code>/<code>.mp4</code> inside it in natural (S01E01 before S01E10) order.</p> <pre><code>unshackle util COMMAND [ARGS]...\n</code></pre>"},{"location":"guide/cli-reference/#util-refresh-services","title":"<code>util refresh-services</code>","text":"<pre><code>unshackle util refresh-services\n</code></pre> <p>Force a refresh (git pull / hard reset) of all service repos configured under <code>directories.services</code>.</p>"},{"location":"guide/cli-reference/#util-crop-path-aspect","title":"<code>util crop PATH ASPECT</code>","text":"<p>Losslessly crop H.264/H.265 video at the bitstream level. <code>ASPECT</code> is a <code>W:H</code> target such as <code>2.39:1</code>.</p> Option Default Description <code>--letter</code> / <code>--pillar</code> <code>--letter</code> Crop top/bottom (<code>--letter</code>) or the sides (<code>--pillar</code>). <code>-o</code>, <code>--offset</code> <code>0</code> Fine-tune the computed crop area if not perfectly centred. <code>-p</code>, <code>--preview</code> off Preview the crop in MPV (or FFplay) instead of writing a file."},{"location":"guide/cli-reference/#util-range-path","title":"<code>util range PATH</code>","text":"<p>Losslessly set the video range flag to full or limited at the bitstream level.</p> Option Default Description <code>--full</code> / <code>--limited</code> - Full (0-255) or limited (16-235) range. <code>-p</code>, <code>--preview</code> off Preview instead of writing a file."},{"location":"guide/cli-reference/#util-test-path","title":"<code>util test PATH</code>","text":"<p>Decode an entire video with FFmpeg and report any corruptions or errors. All streams are tested by default; subtitles cannot be tested.</p> Option Default Description <code>-m</code>, <code>--map</code> <code>0</code> Test specific streams via FFmpeg's <code>-map</code>, e.g. <code>0:v:0</code> or <code>0:a</code>. <p>Example</p> <pre><code>unshackle util refresh-services\nunshackle util crop video.mkv 2.39:1\nunshackle util crop ./season/ 16:9 --pillar -o 10\nunshackle util range video.mkv --full\nunshackle util test video.mkv -m 0:v:0\n</code></pre>"},{"location":"guide/cli-reference/#see-also","title":"See also","text":"<ul> <li>Installation: install unshackle and its dependencies.</li> <li>Quickstart: your first download.</li> <li>Configuration file: set defaults for any <code>dl</code> flag and configure vaults, proxies, and directories.</li> </ul>"},{"location":"guide/downloading/","title":"Downloading","text":"<p><code>unshackle dl</code> is the main download command: it fetches a title's manifest from a streaming service, selects exactly the tracks you asked for, acquires and applies decryption keys, and muxes everything into a finished Matroska file. The flags below cover quality and codec selection, language and subtitle handling, episode ranges, and the download flow itself, with examples throughout.</p> <p>Where the full flag list lives</p> <p>This page covers the flags you will use most and explains how they interact. It is not an exhaustive enumeration. For the complete, always-current list of every option and its exact wording, run <code>unshackle dl --help</code>. Every flag shown here can also be given a default in your configuration file. See Configuration file.</p>"},{"location":"guide/downloading/#command-shape","title":"Command shape","text":"<p>A download is always three layers: the root CLI, the <code>dl</code> command (which is where all the flags below are parsed), and a service tag subcommand that carries the title argument.</p> <pre><code>unshackle dl [OPTIONS] SERVICE [SERVICE ARGUMENTS]\n</code></pre> <ul> <li><code>unshackle</code>: the root command.</li> <li><code>dl</code>: the download command. All of the options on this page are parsed here, so they go before the service tag.</li> <li><code>SERVICE</code>: a service tag such as <code>EXAMPLE1</code>, <code>EXAMPLE2</code>, <code>EXAMPLE3</code>. Service tags are case-insensitive and honour each service's aliases (for example <code>example+</code> resolves to its real tag).</li> <li><code>SERVICE ARGUMENTS</code>: usually a title ID or URL. This positional argument belongs to the service, not to <code>dl</code>, so it comes after the tag.</li> </ul> A minimal download<pre><code>unshackle dl EXAMPLE 81234567\n</code></pre> Flags belong to dl, the title belongs to the service<pre><code>unshackle dl -q 1080 -v H.265 -r HDR10 --lang en EXAMPLE 'https://www.example.com/...'\n</code></pre> <p>See what a service accepts</p> <p>Because the positional argument is defined by each service, run <code>unshackle dl SERVICE --help</code> (e.g. <code>unshackle dl EXAMPLE --help</code>) to see that service's own argument and any service-specific options.</p>"},{"location":"guide/downloading/#the-download-flow","title":"The download flow","text":"<p>When you run a download, <code>dl</code> moves through the pipeline below. Understanding the order helps explain why, for example, <code>--list</code> stops early and why keys are fetched even with <code>--skip-dl</code>.</p> <ol> <li>Setup: load the DRM CDM, key vaults, proxy providers, cookies, and credentials.</li> <li>Authenticate: sign in to the service with your profile's cookies/credentials.</li> <li>Fetch titles: retrieve the movie, episode list, or album (cached unless <code>--no-cache</code>/<code>--reset-cache</code>).</li> <li>Filter titles: apply <code>--wanted</code>, <code>--latest-episode</code>, or <code>--select-titles</code>.</li> <li>Get tracks: parse the manifest into video, audio, subtitle, and chapter tracks.</li> <li>Select tracks: narrow each type down using your quality, codec, range, language, and bitrate flags.</li> <li>Download: pull segments for the selected tracks (concurrently per <code>--downloads</code>).</li> <li>License &amp; decrypt: acquire content keys (vault \u2192 CDM), decrypt each track.</li> <li>Post-process: extract closed captions, convert subtitles, repack, mux with <code>mkvmerge</code>, and move the finished file to your downloads directory.</li> </ol> <p><code>--list</code> and <code>--list-titles</code> stop after selection/filtering and print what would be downloaded. <code>--skip-dl</code> runs the license step but skips the actual segment download.</p>"},{"location":"guide/downloading/#choosing-quality","title":"Choosing quality","text":""},{"location":"guide/downloading/#resolution","title":"Resolution","text":"<p><code>-q</code> / <code>--quality</code> takes one or more target resolutions (heights) as a comma-separated list. Without it, unshackle picks the best available resolution.</p> Single resolution<pre><code>unshackle dl -q 1080 EXAMPLE 81234567\n</code></pre> Multiple resolutions in one run<pre><code>unshackle dl -q 2160,1080,720 EXAMPLE 81234567\n</code></pre> <p>16:9 canvas matching</p> <p>Resolution matching is by track height first. If no track has an exact matching height, unshackle falls back to a 16:9-canvas match, so <code>-q 1080</code> will also match an anamorphic <code>1920\u00d7804</code> track (computed as <code>int(width \u00d7 9 / 16)</code>).</p>"},{"location":"guide/downloading/#best-available-and-worst","title":"Best-available and worst","text":"<p>By default a missing requested resolution is an error. Two flags change that:</p> Flag Behaviour <code>--best-available</code> If the requested resolution(s) aren't present, continue with the best that is available instead of failing. Also softens missing video/audio/subtitle languages and hybrid fallbacks. <code>--worst</code> Within the specified quality, pick the lowest bitrate rendition. Requires <code>-q/--quality</code>. Never fail on a missing resolution<pre><code>unshackle dl -q 2160 --best-available EXAMPLE 0ABC123\n</code></pre>"},{"location":"guide/downloading/#video-codec-and-color-range","title":"Video codec and color range","text":""},{"location":"guide/downloading/#codec","title":"Codec","text":"<p><code>-v</code> / <code>--vcodec</code> selects one or more video codecs; the default is any codec. It accepts either enum names or their values, comma-separated.</p> Name Value <code>AVC</code> <code>H.264</code> <code>HEVC</code> <code>H.265</code> <code>VC1</code> <code>VC-1</code> <code>VP8</code> <code>VP8</code> <code>VP9</code> <code>VP9</code> <code>AV1</code> <code>AV1</code> Either spelling works<pre><code>unshackle dl -v HEVC EXAMPLE 81234567\nunshackle dl -v H.265 EXAMPLE 81234567\nunshackle dl -v hevc,avc EXAMPLE 81234567\n</code></pre>"},{"location":"guide/downloading/#color-range","title":"Color range","text":"<p><code>-r</code> / <code>--range</code> selects one or more color ranges; the default is <code>SDR</code>.</p> Range Meaning <code>SDR</code> Standard dynamic range (default) <code>HLG</code> Hybrid Log-Gamma <code>HDR10</code> HDR10 <code>HDR10P</code> HDR10+ <code>DV</code> Dolby Vision <code>HYBRID</code> Fetch both an HDR10/HDR10+ base and a DV track, then merge them Grab HDR10 and Dolby Vision in one run<pre><code>unshackle dl -q 2160 -r HDR10,DV EXAMPLE '...'\n</code></pre> <p>HYBRID requires dovi_tool</p> <p><code>-r HYBRID</code> produces a single hybrid stream by injecting the Dolby Vision RPU metadata onto an HDR10/HDR10+ base layer using dovi_tool. It requires the <code>dovi_tool</code> binary on your PATH and needs both an HDR10(+) and a DV track to be available, otherwise the title fails (unless <code>--best-available</code> lets it fall back). When HDR10+ is present it is preferred over HDR10 as the base layer.</p> <p>To keep an HDR10+ deliverable alongside the hybrid, request both ranges: <code>-r HYBRID,HDR10P</code>. <code>-r HYBRID</code> on its own muxes only the merged hybrid.</p>"},{"location":"guide/downloading/#bitrate-selection","title":"Bitrate selection","text":"<p>By default unshackle keeps the highest-bitrate rendition for each selected resolution/codec/range/language combination. You can constrain this.</p> Flag Purpose <code>-vb</code> / <code>--vbitrate</code> Exact video bitrate in kbps. <code>-ab</code> / <code>--abitrate</code> Exact audio bitrate in kbps. <code>-vb-range</code> / <code>--vbitrate-range</code> Video bitrate range in kbps, e.g. <code>6000-7000</code>; picks the highest within it. <code>-ab-range</code> / <code>--abitrate-range</code> Audio bitrate range in kbps, e.g. <code>128-256</code>. <p>Exact vs range are mutually exclusive</p> <p><code>--vbitrate</code> cannot be combined with <code>--vbitrate-range</code>, and likewise for the audio pair. Pick one form.</p>"},{"location":"guide/downloading/#real-bitrate-probing","title":"Real bitrate probing","text":"<p>Manifest-declared bitrates are sometimes rounded or wrong. Services often advertise a peak or nominal bandwidth that is far from the stream's real average. This matters because a track's bitrate drives the track listing, the sort order, and the <code>--vbitrate</code>/<code>--vbitrate-range</code> selection above. A bogus declared value therefore makes unshackle pick the wrong track. These flags remove that risk by probing the actual media size to compute a true bitrate for the top renditions, overriding the manifest value:</p> <ul> <li><code>-rvb</code> / <code>--real-video-bitrate</code>: probe real video bitrates (per codec/range).</li> <li><code>-rab</code> / <code>--real-audio-bitrate</code>: probe real audio bitrates (per codec/channels/ language). Slower than the video variant because there are more renditions to probe.</li> </ul> <p>Reading the probed numbers</p> <p>A single-file track (DASH <code>SegmentBase</code>/<code>BaseURL</code>) is measured exactly. A multi-segment track (most HLS) is a sampled estimate, normally within a few percent of the true value. For MPEG-TS HLS the probed figure also reads a few percent above the demuxed elementary stream, because the segment bytes include container overhead. That is the real delivered size, not an over-report or a bug.</p> <p>Why not every rendition is probed</p> <p>Probing does not touch every rendition. Only the top rendition of each quality tier is probed in parallel (video grouped by codec+range, audio by codec+channels+language), and the pass then reaches downward only as far as it must to keep the ranking correct. This keeps probing fast even when a service exposes dozens of renditions. Tracks whose duration can't be determined fall back to <code>ffprobe</code>, and a probe failure is non-fatal: the manifest value is simply left in place.</p>"},{"location":"guide/downloading/#audio-codec-channels-and-atmos","title":"Audio codec, channels, and Atmos","text":""},{"location":"guide/downloading/#codec_1","title":"Codec","text":"<p><code>-a</code> / <code>--acodec</code> selects one or more audio codecs (comma-separated); the default is any.</p> Name Value Codec <code>AAC</code> <code>AAC</code> Advanced Audio Coding <code>AC3</code> <code>DD</code> Dolby Digital <code>EC3</code> <code>DD+</code> Dolby Digital Plus <code>AC4</code> <code>AC-4</code> Dolby AC-4 <code>OPUS</code> <code>OPUS</code> Opus <code>OGG</code> <code>VORB</code> Vorbis <code>DTS</code> <code>DTS</code> DTS <code>ALAC</code> <code>ALAC</code> Apple Lossless <code>FLAC</code> <code>FLAC</code> FLAC <p>Names, values, and a few aliases are accepted: <code>eac3</code> and <code>ddp</code> both resolve to <code>EC3</code>, and <code>vorbis</code> resolves to <code>OGG</code>.</p> Prefer Dolby Digital Plus, fall back to AAC<pre><code>unshackle dl -a EC3,AAC EXAMPLE 81234567\n</code></pre>"},{"location":"guide/downloading/#channels-and-atmos","title":"Channels and Atmos","text":"<ul> <li><code>-c</code> / <code>--channels</code>: desired channel layout, e.g. <code>5.1</code> or <code>2.0</code>. Matching is by ceiling, so <code>5.1</code> implicitly matches a <code>6.0</code>-reported layout.</li> <li><code>-naa</code> / <code>--noatmos</code>: exclude Dolby Atmos audio tracks from selection.</li> </ul> 5.1 audio, no Atmos<pre><code>unshackle dl -c 5.1 --noatmos EXAMPLE 0ABC123\n</code></pre>"},{"location":"guide/downloading/#languages","title":"Languages","text":""},{"location":"guide/downloading/#video-and-audio-language","title":"Video and audio language","text":"<p><code>-l</code> / <code>--lang</code> sets the wanted language(s) for both video and audio. The default is <code>orig</code>, the title's original language.</p> Original language plus English<pre><code>unshackle dl -l orig,en EXAMPLE 81234567\n</code></pre> <p>The special token <code>orig</code> is resolved to the title's actual original language everywhere it is used. You can override each stream type independently:</p> <ul> <li><code>-vl</code> / <code>--v-lang</code>: language for video only (overrides <code>-l</code> for video). Useful when the burned-in video language differs from the audio you want.</li> <li><code>-al</code> / <code>--a-lang</code>: language for audio only (overrides <code>-l</code> for audio).</li> </ul> English audio over the original video<pre><code>unshackle dl -al en EXAMPLE 81234567\n</code></pre>"},{"location":"guide/downloading/#exact-vs-fuzzy-matching","title":"Exact vs fuzzy matching","text":"<p>By default language matching is fuzzy: <code>-l en</code> also accepts <code>en-US</code>, <code>en-GB</code>, etc. (up to a small distance). Pass <code>--exact-lang</code> to require an exact match: with it, <code>-l es-419</code> matches only <code>es-419</code>, not <code>es-ES</code>.</p> <p>The <code>all</code> and <code>best</code> tokens</p> <p>For audio, the tokens <code>all</code> and <code>best</code> bypass the usual one-track-per-language pick and instead select the best track for each language present. For subtitles, <code>all</code> keeps every subtitle language.</p>"},{"location":"guide/downloading/#subtitles","title":"Subtitles","text":""},{"location":"guide/downloading/#selecting-subtitle-languages","title":"Selecting subtitle languages","text":"<p><code>-sl</code> / <code>--s-lang</code> sets the wanted subtitle language(s). The default is <code>all</code>, meaning every available subtitle language is downloaded.</p> Only English and Spanish subtitles<pre><code>unshackle dl -sl en,es EXAMPLE 81234567\n</code></pre>"},{"location":"guide/downloading/#requiring-subtitles","title":"Requiring subtitles","text":"<p><code>--require-subs</code> takes a list of languages that must exist. If they all exist, all subtitles are downloaded; if any is missing, the title fails. This is useful for gating a download on the presence of a specific subtitle track.</p> <p>Cannot combine with <code>--s-lang</code></p> <p><code>--require-subs</code> and <code>--s-lang</code> are mutually exclusive. Use one or the other.</p>"},{"location":"guide/downloading/#forced-subtitles-and-output-format","title":"Forced subtitles and output format","text":"<ul> <li><code>-fs</code> / <code>--forced-subs</code>: include forced subtitle tracks (signs/foreign dialogue). Without this flag, forced subs are dropped from selection.</li> <li><code>--sub-format</code>: set the output subtitle format, converting only when necessary. Accepts codec names/values and common aliases (<code>srt</code>, <code>vtt</code>, <code>ass</code>, <code>ssa</code>, <code>ttml</code>, etc.), or the literal <code>original</code> to keep the source format.</li> </ul> Value Format <code>SRT</code> / <code>srt</code> SubRip <code>VTT</code> / <code>vtt</code> WebVTT <code>ASS</code> / <code>ass</code> Advanced SubStation Alpha <code>SSA</code> / <code>ssa</code> SubStation Alpha <code>TTML</code> / <code>ttml</code> Timed Text Markup <code>original</code> Keep the source format, no conversion Convert subtitles to SRT<pre><code>unshackle dl --sub-format srt EXAMPLE 81234567\n</code></pre> <p>SDH stripping happens by default</p> <p>When a subtitle track is marked SDH (for the deaf/hard-of-hearing) and there is no plain same-language subtitle, unshackle produces a stripped, non-SDH variant automatically. This behaviour is governed by the <code>subtitle.strip_sdh</code> config option (default on).</p>"},{"location":"guide/downloading/#selecting-episodes","title":"Selecting episodes","text":"<p>For series, several flags control which episodes are downloaded. By default, all episodes are downloaded.</p>"},{"location":"guide/downloading/#wanted-ranges","title":"Wanted ranges","text":"<p><code>-w</code> / <code>--wanted</code> accepts flexible season/episode ranges, comma-separated. Prefix a token with <code>-</code> to exclude it.</p> Whole seasonsSpecific episodesExclusions <pre><code>unshackle dl -w S01 EXAMPLE 81234567\nunshackle dl -w S01-S03 EXAMPLE 81234567\nunshackle dl -w S01,S03,S05 EXAMPLE 81234567\n</code></pre> <pre><code>unshackle dl -w S01E01 EXAMPLE 81234567\nunshackle dl -w S01E01-S01E05 EXAMPLE 81234567\nunshackle dl -w S01E01-S02E03 EXAMPLE 81234567\n</code></pre> <pre><code># Seasons 1 through 5, but not season 3\nunshackle dl -w S01-S05,-S03 EXAMPLE 81234567\n</code></pre>"},{"location":"guide/downloading/#other-selection-flags","title":"Other selection flags","text":"Flag Behaviour <code>--select-titles</code> Interactively pick episodes from a list (Series only). Cannot combine with <code>-w</code>. <code>--latest-episode</code> Download only the single most recent episode. <code>--list-titles</code> List the titles that would be downloaded, then stop. Grab just the newest episode<pre><code>unshackle dl --latest-episode EXAMPLE 81234567\n</code></pre>"},{"location":"guide/downloading/#including-and-excluding-track-types","title":"Including and excluding track types","text":"<p>You can restrict a download to certain track categories, either positively (only these) or negatively (everything but these).</p> <p>Only these types (<code>*-only</code> flags):</p> <ul> <li><code>-V</code> / <code>--video-only</code></li> <li><code>-A</code> / <code>--audio-only</code></li> <li><code>-S</code> / <code>--subs-only</code></li> <li><code>-C</code> / <code>--chapters-only</code></li> </ul> <p>Skip these types (<code>no-*</code> flags):</p> <ul> <li><code>-nv</code> / <code>--no-video</code></li> <li><code>-na</code> / <code>--no-audio</code></li> <li><code>-ns</code> / <code>--no-subs</code></li> <li><code>-nc</code> / <code>--no-chapters</code></li> </ul> <p>Additional track-type flags:</p> <ul> <li><code>-ad</code> / <code>--audio-description</code>: include descriptive (audio-description) tracks, which are dropped by default.</li> <li><code>--skip-subtitle-errors</code>: if a subtitle fails to download, skip it and continue rather than aborting the whole title. Video and audio failures remain fatal.</li> </ul> Subtitles only<pre><code>unshackle dl -S -sl en EXAMPLE 81234567\n</code></pre> Everything except chapters<pre><code>unshackle dl -nc EXAMPLE 81234567\n</code></pre> <p>Note</p> <p>You can combine an <code>*-only</code> flag with <code>no-*</code> flags to fine-tune: <code>*-only</code> chooses the starting set of categories, then <code>no-*</code> subtracts from it. Attachments (e.g. fonts) are always kept.</p>"},{"location":"guide/downloading/#listing-and-dry-runs","title":"Listing and dry runs","text":"<p>Before committing to a long download, inspect what unshackle would do:</p> Flag Effect <code>--list</code> List the available tracks and which would be selected, then stop. No download. <code>--list-titles</code> List the titles (episodes) that would be downloaded, then stop. <code>--skip-dl</code> Skip downloading but still acquire the decryption keys. See the track selection without downloading<pre><code>unshackle dl -q 1080 -v H.265 -r HDR10 --list EXAMPLE 81234567\n</code></pre>"},{"location":"guide/downloading/#output-and-muxing","title":"Output and muxing","text":""},{"location":"guide/downloading/#output-location-and-folders","title":"Output location and folders","text":"<ul> <li><code>-o</code> / <code>--output</code>: override the output directory for this run (otherwise the configured downloads directory is used).</li> <li><code>--no-folder</code>: do not create a per-show folder for TV downloads.</li> <li><code>--no-source</code>: remove the service source tag from the filename and path.</li> </ul> Send this download somewhere specific<pre><code>unshackle dl -o ~/Videos/incoming EXAMPLE 81234567\n</code></pre>"},{"location":"guide/downloading/#muxing-behaviour","title":"Muxing behaviour","text":"<p>By default, tracks are muxed into a single Matroska (<code>.mkv</code>) file with <code>mkvmerge</code>. These flags change how the output is assembled:</p> Flag Behaviour Default source <code>--no-mux</code> Do not mux; keep the individual track files. - <code>--split-audio</code> Write a separate output file per audio codec instead of merging all audio. config <code>muxing.merge_audio</code> (on) <code>--merge-video</code> Mux all selected video tracks into one file. config <code>muxing.merge_video</code> (off)"},{"location":"guide/downloading/#naming-tags","title":"Naming tags","text":"<ul> <li><code>--tag</code>: set the release group tag (overrides the configured tag).</li> <li><code>--repack</code>: add a <code>REPACK</code> tag to the output filename.</li> </ul> Custom group tag and a REPACK label<pre><code>unshackle dl --tag MYGRP --repack EXAMPLE 81234567\n</code></pre>"},{"location":"guide/downloading/#proxies","title":"Proxies","text":"<p><code>--proxy</code> accepts a full proxy URI, a 2-letter country code (resolved through your configured proxy providers), or a <code>provider:region</code> form.</p> Proxy forms<pre><code>unshackle dl --proxy us EXAMPLE 81234567\nunshackle dl --proxy nordvpn:ca EXAMPLE 81234567\nunshackle dl --proxy 'http://user:pass@host:8080' EXAMPLE 81234567\n</code></pre> <p>Two related flags:</p> <ul> <li><code>--no-proxy</code>: force-disable all proxy use for this run.</li> <li><code>--no-proxy-download</code>: bypass the proxy for segment downloads only. The manifest, license, and authentication requests still go through the proxy. This is useful when the proxy is only needed to satisfy geo-checks, not to move the bulk of the data.</li> </ul>"},{"location":"guide/downloading/#performance-and-caching","title":"Performance and caching","text":"Flag Purpose <code>--workers N</code> Threads used per track for segment downloads. Default depends on the downloader. <code>--downloads N</code> Number of tracks downloaded concurrently. Default <code>1</code>. <code>--slow [MIN-MAX]</code> Add a delay between titles to look more like a real device. <code>--slow</code> alone means 60-120s; <code>--slow 20-40</code> sets a custom range. Minimum 20s. <code>--no-cache</code> Bypass the title cache for this download. <code>--reset-cache</code> Clear the title cache before fetching. Two tracks at a time, eight threads each<pre><code>unshackle dl --downloads 2 --workers 8 EXAMPLE 81234567\n</code></pre> Space out a season download<pre><code>unshackle dl -w S01 --slow 30-60 EXAMPLE 81234567\n</code></pre>"},{"location":"guide/downloading/#keys-vaults-and-export","title":"Keys, vaults, and export","text":"<p>By default, unshackle checks your key vaults first and only asks a CDM to license a key when the vault misses. You can force one side or the other:</p> <ul> <li><code>--cdm-only</code>: only use the CDM (skip vaults).</li> <li><code>--vaults-only</code>: only use key vaults (never license via the CDM); a missing key fails.</li> </ul> Fetch keys only, no download<pre><code>unshackle dl --skip-dl EXAMPLE 81234567\n</code></pre> <p><code>--export</code> writes a JSON file, into the configured exports directory, containing track info and the acquired content keys for each title. This is the format consumed by <code>unshackle import</code> to reconstruct a download later.</p> Export track info and keys<pre><code>unshackle dl --skip-dl --export EXAMPLE 81234567\n</code></pre> <p>Region is recorded only with a proxy</p> <p>When <code>--proxy</code> is used, the export records the region so an import can reproduce the correct geofence. Without a proxy, no region is stored.</p>"},{"location":"guide/downloading/#metadata-and-tagging","title":"Metadata and tagging","text":"<p>unshackle looks up metadata automatically, but you can override the identifiers used for tagging and naming:</p> Flag Example Purpose <code>--tmdb</code> <code>--tmdb 27205</code> Use this TMDB ID instead of automatic lookup. <code>--imdb</code> <code>--imdb tt1375666</code> Use this IMDb ID. <code>--animeapi</code> <code>--animeapi mal:12345</code> Resolve via AnimeAPI (<code>mal:</code>/<code>anilist:</code> prefix; defaults to MAL). <code>--enrich</code> - Override the show title and year from an external source. Requires one of <code>--tmdb</code>, <code>--imdb</code>, or <code>--animeapi</code>. Force the right IMDb match and enrich the title<pre><code>unshackle dl --imdb tt1375666 --enrich EXAMPLE 81234567\n</code></pre>"},{"location":"guide/downloading/#configuration-defaults","title":"Configuration defaults","text":"<p>Every flag on this page can be set as a default in your configuration file so you don't have to type it each time, and defaults can be scoped per service. See Configuration file for the <code>dl:</code> block and per-service overrides.</p> <p>Explicit flags always win</p> <p>A value you pass on the command line (or via an environment variable) always takes precedence over both the global <code>dl:</code> defaults and any per-service <code>dl:</code> overrides. Config only fills in options you didn't set explicitly.</p>"},{"location":"guide/downloading/#quick-reference","title":"Quick reference","text":"<p>A condensed lookup of the most-used options. Run <code>unshackle dl --help</code> for the complete, authoritative list.</p> Flag Short Meaning <code>--quality</code> <code>-q</code> Target resolution(s), e.g. <code>1080,720</code>. <code>--vcodec</code> <code>-v</code> Video codec(s). <code>--acodec</code> <code>-a</code> Audio codec(s). <code>--range</code> <code>-r</code> Color range(s); default <code>SDR</code>. <code>--channels</code> <code>-c</code> Audio channel layout. <code>--noatmos</code> <code>-naa</code> Exclude Atmos audio. <code>--lang</code> <code>-l</code> Video + audio language(s); default <code>orig</code>. <code>--a-lang</code> <code>-al</code> Audio-only language override. <code>--v-lang</code> <code>-vl</code> Video-only language override. <code>--s-lang</code> <code>-sl</code> Subtitle language(s); default <code>all</code>. <code>--forced-subs</code> <code>-fs</code> Include forced subtitles. <code>--sub-format</code> Output subtitle format. <code>--wanted</code> <code>-w</code> Episode/season range. <code>--select-titles</code> Interactively pick episodes. <code>--latest-episode</code> Only the newest episode. <code>--video-only</code> / <code>--audio-only</code> / <code>--subs-only</code> <code>-V</code> / <code>-A</code> / <code>-S</code> Restrict track types. <code>--no-video</code> / <code>--no-audio</code> / <code>--no-subs</code> / <code>--no-chapters</code> <code>-nv</code> / <code>-na</code> / <code>-ns</code> / <code>-nc</code> Skip track types. <code>--worst</code> Lowest bitrate within <code>-q</code>. <code>--best-available</code> Degrade gracefully instead of failing. <code>--output</code> <code>-o</code> Output directory for this run. <code>--split-audio</code> / <code>--merge-video</code> / <code>--no-mux</code> Muxing behaviour. <code>--proxy</code> / <code>--no-proxy</code> / <code>--no-proxy-download</code> Proxy control. <code>--workers</code> / <code>--downloads</code> / <code>--slow</code> Concurrency and pacing. <code>--list</code> / <code>--list-titles</code> / <code>--skip-dl</code> Dry runs. <code>--cdm-only</code> / <code>--vaults-only</code> Key source control. <code>--export</code> Export track info and keys to JSON. <code>--tmdb</code> / <code>--imdb</code> / <code>--animeapi</code> / <code>--enrich</code> Metadata overrides."},{"location":"guide/drm-and-cdm/","title":"DRM &amp; CDM Setup","text":"<p>Most commercial streaming content is protected by a Digital Rights Management (DRM) system. To download and play it back, unshackle needs to obtain the content keys for the encrypted tracks and then decrypt them. This page explains the DRM systems unshackle supports, how to provide a device so it can talk to a license server, the difference between local and remote CDMs, and how to choose a decryption backend.</p> <p>Who this page is for</p> <p>This is a practical configuration guide for end users of the unshackle CLI. A few sections are marked Developer. They describe internal behaviour that is useful when writing a service, but you do not need them to download protected content.</p>"},{"location":"guide/drm-and-cdm/#key-concepts","title":"Key concepts","text":"<p>Before configuring anything, it helps to know the vocabulary. unshackle draws a firm line between two things:</p> <ul> <li>A CDM (Content Decryption Module) is the trusted \"black box\" that turns a license challenge into content keys. It is backed by a device, a file containing the cryptographic identity of a real client (a phone, a browser, etc.).</li> <li>A DRM system is the wrapper around a CDM that parses the protection metadata, drives the challenge \u2192 license \u2192 keys handshake, and finally invokes an external tool to physically decrypt the downloaded file.</li> </ul> <p>A handful of other terms show up throughout:</p> Term Meaning PSSH Protection System Specific Header. The per-system init data extracted from the file's init segment or the manifest. KID Key ID: a 16-byte UUID identifying which key a track needs. CEK Content Encryption Key: the actual AES key, mapped from its KID. Challenge The license request the CDM produces, sent to the service's license server. License The server's response, which the CDM parses to recover the content keys. <p>For a Widevine or PlayReady title, the flow is: unshackle reads the PSSH and KIDs from the track, asks the CDM for a license challenge, sends that challenge to the service's license server, hands the response back to the CDM to extract the keys, and then decrypts the file with those keys.</p>"},{"location":"guide/drm-and-cdm/#supported-drm-systems","title":"Supported DRM systems","text":"<p>unshackle implements five DRM systems. Only the first two need a device file and a license-server handshake; the rest are special cases.</p> System Device file License flow Decryption Widevine (Google) <code>.wvd</code> CDM challenge \u2192 license server \u2192 CDM parses \u2192 keys shaka-packager / mp4decrypt PlayReady (Microsoft) <code>.prd</code> CDM challenge (WRM header) \u2192 license server \u2192 CDM parses \u2192 keys shaka-packager / mp4decrypt ClearKey (CENC), W3C EME <code>org.w3.clearkey</code> none JSON <code>{\"kids\":[...],\"type\":\"temporary\"}</code> \u2192 license server returns a JWK Set. No CDM. shaka-packager / mp4decrypt ClearKey (HLS), AES-128 <code>EXT-X-KEY</code> none Key fetched directly from a URI or <code>data:</code> URL. No CDM, no challenge. in-process AES-CBC MonaLisa (proprietary, WASM) <code>.mld</code> Ticket from the service API; keys extracted locally via WASM. No license server. ML-Worker binary + AES-ECB, per segment <p>Two different ClearKeys</p> <p>\"ClearKey (HLS)\" and \"ClearKey (CENC)\" are entirely different systems that happen to share a name. The HLS variant is the AES-128 key referenced by an <code>EXT-X-KEY</code> tag and is decrypted in-process. The CENC variant is the W3C EME <code>org.w3.clearkey</code> scheme, delivers keys as a JWK Set, and is decrypted through shaka-packager or mp4decrypt just like Widevine. Neither involves a device file.</p>"},{"location":"guide/drm-and-cdm/#widevine-vs-playready","title":"Widevine vs PlayReady","text":"<p>These are the two \"real\" DRMs, and in unshackle they behave almost identically: the same PSSH/KID handling, the same decryption backends, and the same key-caching flow. The differences that matter to you are:</p> <ul> <li>Device file: Widevine uses a <code>.wvd</code>; PlayReady uses a <code>.prd</code>.</li> <li>Availability: some services offer only one system, some offer both. When a manifest carries both, unshackle picks the appropriate CDM for each track (see Widevine and PlayReady on the same title).</li> </ul> <p>To download a Widevine-protected title you need a <code>.wvd</code> device; for PlayReady you need a <code>.prd</code> device. You can hold both, and unshackle automatically selects the appropriate one for each track.</p> <p>Obtaining device files</p> <p>A <code>.wvd</code> or <code>.prd</code> encodes the private keys of a real client device. unshackle does not ship with one and cannot generate the underlying secret material for you. You must supply your own. The <code>wvd</code> and <code>prd</code> commands below manage and provision device files once you have the raw key material.</p>"},{"location":"guide/drm-and-cdm/#providing-a-device-with-the-wvd-and-prd-commands","title":"Providing a device with the <code>wvd</code> and <code>prd</code> commands","text":"<p>Device files live in dedicated directories, by default:</p> Kind Default directory Widevine <code>.wvd</code> <code>data/WVDs</code> PlayReady <code>.prd</code> <code>data/PRDs</code> <p>You can move these with the <code>directories</code> section of your <code>unshackle.yaml</code>:</p> unshackle.yaml<pre><code>directories:\n wvds: /home/george/unshackle-data/WVDs\n prds: /home/george/unshackle-data/PRDs\n</code></pre>"},{"location":"guide/drm-and-cdm/#widevine-devices-the-wvd-command","title":"Widevine devices: the <code>wvd</code> command","text":"<p>The <code>wvd</code> command group manages <code>.wvd</code> files.</p> Add an existing deviceInspect a deviceCreate from raw materialDelete / dump <pre><code>$ unshackle wvd add ./nexus_6p.wvd\n</code></pre> <p>The file is validated and moved into the WVDs directory. You can add several at once by passing multiple paths.</p> <pre><code>$ unshackle wvd parse nexus_6p\n</code></pre> <p>Prints the System ID, Security Level, Type, Flags, and whether a Private Key, Client ID, and VMP are present. A bare name (no extension) is resolved inside the WVDs directory; a path with an extension is used as-is.</p> <pre><code>$ unshackle wvd new \"Nexus 6P\" ./private_key.pem ./client_id.bin ./vmp.bin -t ANDROID -l 3\n</code></pre> <p>Builds a <code>.wvd</code> from a PEM private key, a Client ID blob, and an optional FileHashes (VMP) blob. <code>-t/--type</code> is the device type (default <code>Android</code>) and <code>-l/--level</code> is the security level 1 to 3 (default <code>1</code>). The VMP argument is optional.</p> <pre><code>$ unshackle wvd delete nexus_6p\n$ unshackle wvd dump nexus_6p ./out\n</code></pre> <p><code>delete</code> removes a device (with a confirmation prompt). <code>dump</code> extracts a device's contents (metadata, private key, Client ID, VMP) into a folder.</p> <p>v1 WVD files must be migrated</p> <p>If loading a device fails with a message about a \"v1 WVD file\", it was made with an older format. Migrate it with pywidevine before use:</p> <pre><code>$ pywidevine migrate --help\n</code></pre>"},{"location":"guide/drm-and-cdm/#playready-devices-the-prd-command","title":"PlayReady devices: the <code>prd</code> command","text":"<p>The <code>prd</code> command group creates and maintains <code>.prd</code> files.</p> Create a new deviceReprovisionTest against Microsoft's demo server <pre><code>$ unshackle prd new ./zgpriv.dat ./bgroupcert.dat\n</code></pre> <p>Provision a new device from a group key and group certificate. You can instead point at a single folder that contains <code>zgpriv.dat</code> and <code>bgroupcert.dat</code>:</p> <pre><code>$ unshackle prd new ./device_folder/\n</code></pre> <p>A fresh leaf certificate is generated and the device is written to the PRDs directory (or to <code>-o/--output</code>). Use <code>-e/--encryption_key</code> and <code>-s/--signing_key</code> to supply your own ECC keys instead of generating them.</p> <pre><code>$ unshackle prd reprovision ./data/PRDs/mydevice.prd\n</code></pre> <p>Regenerates the leaf certificate and encryption/signing keys of an existing device in place. The device must support reprovisioning (a group key must be present, i.e. a version 3 or higher device).</p> <pre><code>$ unshackle prd test ./data/PRDs/mydevice.prd -sl 2000 -c aesctr\n</code></pre> <p>Runs a full challenge/license/keys cycle against Microsoft's public PlayReady test server and prints the returned keys, confirming the device works. <code>-sl/--security-level</code> accepts <code>150</code>, <code>2000</code>, or <code>3000</code> (default <code>2000</code>); <code>-c/--ckt</code> accepts <code>aesctr</code> or <code>aescbc</code>.</p>"},{"location":"guide/drm-and-cdm/#selecting-which-device-to-use-the-cdm-config","title":"Selecting which device to use: the <code>cdm</code> config","text":"<p>Having a device on disk is not enough; you must tell unshackle which device to use for which service. That is the job of the <code>cdm</code> section, which maps a service tag to a device name (the file's name without extension). A <code>default</code> entry acts as the fallback:</p> unshackle.yaml<pre><code>cdm:\n default: nexus_6p_26830_l3\n EXAMPLE1: chromecdm_l3\n EXAMPLE2: sm_g935f_l1\n</code></pre> <p>Lookups are case-insensitive.</p> <p>The device name is the file name</p> <p>A device named <code>chromecdm_l3</code> in the config resolves to <code>chromecdm_l3.wvd</code> in the WVDs directory (or <code>chromecdm_l3.prd</code> in the PRDs directory). It may also be the <code>name</code> of a remote CDM defined in <code>remote_cdm</code>. See Remote CDMs below.</p>"},{"location":"guide/drm-and-cdm/#advanced-selection-by-quality-drm-or-profile","title":"Advanced selection: by quality, DRM, or profile","text":"<p>Instead of a plain name, a <code>cdm</code> entry can be a nested mapping, letting unshackle pick a different device based on the track quality, the DRM system, or the active service profile.</p> By qualityBy DRM systemBy profile <p>Keys are matched against the video height. You can use exact heights or comparisons (<code>&gt;=1080</code>, <code>&gt;720</code>, <code>&lt;=576</code>, <code>&lt;480</code>). More specific matches win.</p> <pre><code>cdm:\n SOMESERVICE:\n \"&gt;=1080\": sm_g935f_l1\n default: chromecdm_l3\n</code></pre> <p>Keys <code>widevine</code> and <code>playready</code> select a device per system. unshackle applies these automatically, using the <code>widevine</code> device for Widevine tracks and the <code>playready</code> device for PlayReady tracks.</p> <pre><code>cdm:\n SOMESERVICE:\n widevine: sm_g935f_l1\n playready: mydevice_sl3\n</code></pre> <p>Keys are matched against the active profile, with a <code>default</code> fallback.</p> <pre><code>cdm:\n SOMESERVICE:\n premium: sm_g935f_l1\n default: chromecdm_l3\n</code></pre>"},{"location":"guide/drm-and-cdm/#local-vs-remote-cdms","title":"Local vs remote CDMs","text":"<p>A CDM can run in two places:</p> <ul> <li>A local CDM loads a <code>.wvd</code> or <code>.prd</code> device from your machine and performs the challenge/license/keys handshake locally. This is what the <code>cdm</code> mapping above resolves to by default.</li> <li>A remote CDM delegates the CDM operations to an HTTP API. Your device (and its secrets) live on the remote server; unshackle sends it PSSH/challenge data and receives keys back. This is useful for sharing a high-security-level device, using a hosted key service, or keeping device secrets off your download machine.</li> </ul> <p>The device name in your <code>cdm</code> mapping resolves to a remote CDM whenever it matches the <code>name</code> of an entry in the <code>remote_cdm</code> list. Otherwise it falls back to a local <code>.prd</code>/<code>.wvd</code> file of that name.</p>"},{"location":"guide/drm-and-cdm/#remote-cdms","title":"Remote CDMs","text":"<p>Remote CDMs are declared as a list under <code>remote_cdm</code>. Each entry has a <code>name</code> (which you then reference from the <code>cdm</code> mapping) and a shape that depends on its <code>type</code>. There are four kinds.</p>"},{"location":"guide/drm-and-cdm/#widevine-remote-cdm-pywidevine-serve","title":"Widevine remote CDM (pywidevine serve)","text":"<p>With no <code>type</code> field and a non-PlayReady device type, the entry is treated as a standard pywidevine \"serve\" endpoint:</p> unshackle.yaml<pre><code>remote_cdm:\n - name: my_wv_remote\n device_type: ANDROID\n system_id: 26830\n security_level: 3\n host: https://cdm.example.com\n secret: your-api-secret\n device_name: sm_g935f_l1\n\ncdm:\n default: my_wv_remote\n</code></pre> <p><code>security_level</code> defaults to <code>3000</code> if omitted. Field names are read case-insensitively, so <code>Device Type</code>/<code>device_type</code>, <code>System ID</code>/<code>system_id</code>, etc. are all accepted.</p>"},{"location":"guide/drm-and-cdm/#playready-remote-cdm","title":"PlayReady remote CDM","text":"<p>If the device type is <code>PLAYREADY</code>, the entry is routed to the pyplayready remote CDM:</p> unshackle.yaml<pre><code>remote_cdm:\n - name: my_pr_remote\n device_type: PLAYREADY\n security_level: 3000\n host: https://cdm.example.com\n secret: your-api-secret\n device_name: mydevice_sl3\n</code></pre> <p>The <code>host</code> must end in <code>/playready</code></p> <p>For a PlayReady remote CDM the <code>host</code> URL has to include the trailing <code>/playready</code> path segment (e.g. <code>https://cdm.example.com/playready</code>). pyplayready's <code>RemoteCdm</code> treats <code>host</code> as a base and appends its own endpoint paths on top of it, so a host without the suffix points the requests at the wrong location. The symptom is <code>404</code> responses from the server rather than an obvious configuration error.</p>"},{"location":"guide/drm-and-cdm/#decrypt-labs-hosted-keyxtractor-api","title":"Decrypt Labs (hosted KeyXtractor API)","text":"<p>Set <code>type: decrypt_labs</code> to use Decrypt Labs' hosted KeyXtractor service, which includes an intelligent key-caching layer:</p> unshackle.yaml<pre><code>remote_cdm:\n - name: decryptlabs\n type: decrypt_labs\n device_name: L1 # ChromeCDM, L1, L2 (Widevine) or SL2, SL3 (PlayReady)\n # host: https://keyxtractor.decryptlabs.com # optional, this is the default\n # secret: ... # optional if decrypt_labs_api_key is set globally\n\ndecrypt_labs_api_key: your-decrypt-labs-key\n</code></pre> <p>The API key is sent as the <code>decrypt-labs-api-key</code> header. If you omit <code>secret</code> on the entry, unshackle falls back to the global <code>decrypt_labs_api_key</code> value; if neither is present it raises an error. The <code>host</code> defaults to <code>https://keyxtractor.decryptlabs.com</code>. PlayReady devices (<code>SL2</code>/<code>SL3</code>) default to security level <code>2000</code>/<code>3000</code> respectively; Widevine devices default to <code>system_id: 26830</code>, <code>security_level: 3</code>.</p>"},{"location":"guide/drm-and-cdm/#custom-api-custom_api","title":"Custom API (<code>custom_api</code>)","text":"<p>For an arbitrary CDM HTTP API, <code>type: custom_api</code> provides a fully configurable client that adapts to almost any request/response shape through YAML alone. A minimal example:</p> unshackle.yaml<pre><code>remote_cdm:\n - name: my_custom\n type: custom_api\n device:\n name: ChromeCDM\n type: CHROME # CHROME, ANDROID, or PLAYREADY\n system_id: 26830\n security_level: 3\n auth:\n type: bearer # header, bearer, or basic\n key: your-token\n endpoints:\n get_request:\n path: /get-challenge\n method: POST\n decrypt_response:\n path: /get-keys\n method: POST\n timeout: 30\n</code></pre> <p>The <code>custom_api</code> type supports much more: request/response field remapping, transforms (base64/hex/JSON encoding, <code>kid:key</code> parsing), conditional parameters, success/error detection, and vault-backed caching. Its full schema is aimed at developers integrating a bespoke key server; see the developer note below.</p> <p>Developer: full <code>custom_api</code> schema</p> <p>A <code>custom_api</code> entry accepts these sub-objects: <code>device</code> (<code>name</code>, <code>type</code>, <code>system_id</code>, <code>security_level</code>); <code>auth</code> (<code>type</code> of <code>header</code>/<code>bearer</code>/<code>basic</code> with the matching credential fields, plus <code>custom_headers</code>); <code>endpoints</code> (<code>get_request</code> and <code>decrypt_response</code>, each <code>{path, method, timeout}</code>); per-endpoint <code>request_mapping</code> (<code>param_names</code>, <code>static_params</code>, <code>conditional_params</code>, <code>transforms</code>, <code>nested_params</code>, <code>exclude_params</code>) and <code>response_mapping</code> (<code>fields</code>, <code>transforms</code>, <code>response_types</code>, <code>success_conditions</code>, <code>error_fields</code>, <code>key_fields</code>); <code>caching</code> (<code>enabled</code>, <code>use_vaults</code>, <code>check_cached_first</code>); and <code>legacy</code>/<code>timeout</code>. PlayReady mode is inferred when <code>device.type == PLAYREADY</code> or the device name is <code>SL2</code>/<code>SL3</code>.</p>"},{"location":"guide/drm-and-cdm/#decryption-backends","title":"Decryption backends","text":"<p>Once the content keys are known, the encrypted file (for Widevine, PlayReady, and ClearKey-CENC) is decrypted by one of two external tools:</p> <ul> <li>shaka-packager is the default.</li> <li>mp4decrypt is part of the Bento4 tools.</li> </ul> <p>Both must be discoverable in unshackle's bundled <code>binaries/</code> directory or on your <code>PATH</code>. If the selected tool's binary is missing at decrypt time, unshackle raises an \"executable not found but is required\" error. See dependencies for installation.</p> <p>You choose the backend with the <code>decryption</code> key. It can be a single value applied globally, or a per-service mapping:</p> Global defaultPer service unshackle.yaml<pre><code>decryption: shaka\n</code></pre> unshackle.yaml<pre><code>decryption:\n default: shaka\n SOMESERVICE: mp4decrypt\n</code></pre> <p>How the value is interpreted</p> <p>The default is <code>shaka</code>. Only the exact value <code>mp4decrypt</code> selects mp4decrypt; anything else (including <code>shaka</code>) selects shaka-packager. Per-service lookups are case-insensitive, with the <code>default</code>/<code>DEFAULT</code> entry used as the fallback.</p> <p>The two backends produce equivalent output for standard CENC content. shaka-packager is generally preferred; switch a specific service to <code>mp4decrypt</code> if you hit a track that shaka-packager cannot handle.</p> <p>ClearKey (HLS) does not use these tools</p> <p>HLS AES-128 ClearKey content is decrypted in-process using AES-CBC and ignores the <code>decryption</code> setting entirely. There is nothing to configure.</p>"},{"location":"guide/drm-and-cdm/#clearkey","title":"ClearKey","text":""},{"location":"guide/drm-and-cdm/#clearkey-over-hls-aes-128","title":"ClearKey over HLS (AES-128)","text":"<p>When an HLS playlist references a key with an <code>EXT-X-KEY</code> tag, unshackle fetches the key directly (from the given URI or an inline <code>data:</code> URL) and decrypts each segment in-process with AES-CBC. There is no device, no CDM, and no license challenge, so there is nothing to set up. Such tracks are handled automatically during download.</p>"},{"location":"guide/drm-and-cdm/#clearkey-over-cenc-w3c-eme-orgw3clearkey","title":"ClearKey over CENC (W3C EME <code>org.w3.clearkey</code>)","text":"<p>The CENC ClearKey scheme is a proper license flow, but the \"license server\" simply returns the keys as a JWK Set rather than a DRM-wrapped blob. unshackle builds a W3C EME request of the form:</p> <pre><code>{\"kids\": [\"&lt;base64url-kid&gt;\", ...], \"type\": \"temporary\"}\n</code></pre> <p>It sends this to the manifest's license URL (or to whatever a service's ClearKey license hook returns) and reads the JSON Web Key set back. No device file is needed. The decrypted content still goes through shaka-packager or mp4decrypt like any other CENC track, so the <code>decryption</code> setting applies.</p>"},{"location":"guide/drm-and-cdm/#widevine-and-playready-on-the-same-title","title":"Widevine and PlayReady on the same title","text":"<p>A single manifest can advertise both Widevine and PlayReady. unshackle picks the CDM per track: if a track needs a system that your loaded CDM does not provide, it transparently switches to the appropriate device for that track using your <code>cdm</code> mapping. If it cannot find a matching device, it fails with a clear message such as:</p> <pre><code>Title needs a Widevine CDM but SOMESERVICE is configured with PlayReady.\n</code></pre> <p>Use the <code>cdm</code> mapping's DRM-based selection to configure a device for each system; unshackle selects the right one per track automatically.</p>"},{"location":"guide/drm-and-cdm/#keys-vaults-and-caching","title":"Keys, vaults, and caching","text":"<p>Fetching a license is comparatively slow and, for some services, rate-limited. unshackle therefore resolves each key ID in this order before ever contacting a license server:</p> <ol> <li>Keys already known for the current DRM object.</li> <li>An in-process license-key cache (for the running session).</li> <li>Your configured key vaults.</li> <li>Only if still missing, a live license request.</li> </ol> <p>After a successful license request, the recovered keys are written back to all configured vaults so future downloads can skip the license server. Two flags let you control this trade-off on the <code>dl</code> command:</p> Flag Effect <code>--vaults-only</code> Never send a license request; use only cached/vault keys. Fails if a key is missing. <code>--cdm-only</code> Ignore vaults for sourcing keys and always perform a fresh license request. <p>See key vaults for how to configure vault backends.</p>"},{"location":"guide/drm-and-cdm/#debugging-drm-issues","title":"Debugging DRM issues","text":"<p>A few configuration toggles help when a title will not decrypt:</p> Config key Default Effect <code>debug</code> <code>false</code> Global debug output. <code>debug_keys</code> <code>false</code> Log decryption keys. <code>debug_requests</code> <code>false</code> Log HTTP requests. unshackle.yaml<pre><code>debug_keys: true\ndebug_requests: true\n</code></pre> <p>Keys and paths in logs</p> <p>When key logging is enabled, content keys (KID:key pairs) are written to the logs. Treat those logs as sensitive. The unrelated <code>redact_paths</code> option (default <code>true</code>) masks local directory paths in log output.</p>"},{"location":"guide/drm-and-cdm/#see-also","title":"See also","text":"<ul> <li>Downloading: the <code>dl</code> command and its DRM-related flags.</li> <li>Key vaults: caching content keys across downloads.</li> <li>Configuration: the full <code>unshackle.yaml</code> reference.</li> <li>Dependencies: installing shaka-packager and mp4decrypt.</li> </ul>"},{"location":"guide/output-and-naming/","title":"Output &amp; Naming","text":"<p>This page explains where unshackle writes finished downloads and how it names them. You control naming with output templates (the filename) and folder templates (the directory the file lands in), using a set of <code>{variable}</code> placeholders that unshackle fills in from the media it just downloaded. It also covers muxing options, release-group tagging, Unicode filenames, and how to relocate unshackle's working directories.</p> <p>If you have not configured <code>unshackle.yaml</code> yet, read Configuration File first. Everything below lives in that file.</p>"},{"location":"guide/output-and-naming/#how-an-output-path-is-assembled","title":"How an output path is assembled","text":"<p>When a download finishes muxing, unshackle builds the final path from three pieces:</p> <pre><code>&lt;output directory&gt; / &lt;folder template&gt; / &lt;filename template&gt;&lt;extension&gt;\n</code></pre> <ul> <li>Output directory: <code>directories.downloads</code> from your config, or whatever you pass to <code>-o/--output</code> on the command line for a single run.</li> <li>Folder template: an optional per-title subfolder. TV episodes and music tracks are always placed in a folder; movies only get one if you define a <code>movies</code> folder template, or a single-string <code>folder</code> template that applies to all title kinds (see Folder templates).</li> <li>Filename template: the <code>output_template</code> for the title kind (movie, series, or song).</li> <li>Extension: chosen by the muxer: <code>.mkv</code> for video, <code>.mka</code> for audio-only, <code>.mks</code> for subtitle-only.</li> </ul> <p>A typical episode path</p> <p><pre><code>/home/user/Downloads/\n \u2514\u2500 Show Name S01 1080p EXAMPLE WEB-DL DDP5.1 H.264/\n \u2514\u2500 Show.Name.S01E01.Pilot.1080p.EXAMPLE.WEB-DL.DDP5.1.H.264-TAG.mkv\n</code></pre> The folder name comes from the <code>series</code> folder template and the file from the <code>series</code> output template.</p> <p>Two command-line flags change this layout for a single run:</p> Flag Effect <code>-o</code>, <code>--output</code> Use this directory instead of <code>directories.downloads</code>. <code>--no-folder</code> Skip the per-title subfolder; write the file directly into the output directory. <code>--no-source</code> Omit the service source tag from both the filename and folder (the <code>{source}</code> variable resolves to empty)."},{"location":"guide/output-and-naming/#output-templates","title":"Output templates","text":"<p>Filename templates live under the <code>output_template</code> key, keyed by title kind. Each value is a format string built from <code>{variable}</code> placeholders.</p> unshackle.yaml<pre><code>output_template:\n movies: \"{title}.{year}.{quality}.{source}.WEB-DL.{audio_full}.{video}-{tag}\"\n series: \"{title}.{season_episode}.{episode_name?}.{quality}.{source}.WEB-DL.{audio_full}.{video}-{tag}\"\n songs: \"{track_number}. {title}\"\n</code></pre> <p>The recognized kinds are:</p> Kind Applies to Default when unset <code>movies</code> Movies (required for movie downloads to be named, no built-in default) <code>series</code> TV episodes (required for episode downloads to be named) <code>songs</code> Music tracks <code>\"{track_number}. {title}\"</code> <code>albums</code> Album folders only (see below) - <p>Note</p> <p><code>movies</code> and <code>series</code> have no hardcoded filename fallback. If you download those title types, define their templates. <code>songs</code> falls back to <code>\"{track_number}. {title}\"</code> when omitted.</p>"},{"location":"guide/output-and-naming/#required-vs-optional-variables","title":"Required vs. optional variables","text":"<ul> <li><code>{variable}</code>: required. If it is missing from the download's context, formatting raises an error. (Note that most variables are always present in context but resolve to an empty string when not applicable, so being \"present but empty\" is different from \"missing\".)</li> <li><code>{variable?}</code>: optional. A trailing <code>?</code> marks the variable conditional. When it resolves to empty, unshackle removes the placeholder and one adjacent separator (<code>.</code>, <code>-</code>, or space), so the surrounding text collapses cleanly.</li> </ul> <p>Use <code>?</code> for anything that isn't always there</p> <p>Episode names, editions, tags, HDR labels and audio extras aren't present on every title. Mark them optional so you never get doubled dots or dangling separators:</p> <p><pre><code>series: \"{title}.{season_episode}.{episode_name?}.{quality}.{hdr?}.{source}-{tag?}\"\n</code></pre> For an episode with no on-screen name, <code>{episode_name?}</code> and its adjacent dot simply disappear.</p>"},{"location":"guide/output-and-naming/#separator-style-dots-vs-spaces","title":"Separator style (dots vs. spaces)","text":"<p>unshackle looks at the characters you place between variables to decide the filename's separator style. If spaces outnumber dots in your template, it sanitizes with spaces; otherwise it uses dots (the scene-style default). This is also applied to the auto-generated date separators for daily/dated content.</p> Scene style (dots)Readable style (spaces) <p><pre><code>output_template:\n movies: \"{title}.{year}.{quality}.{source}.WEB-DL.{audio_full}.{video}-{tag}\"\n</code></pre> <pre><code>The.Movie.2024.1080p.EXAMPLE.WEB-DL.DDP5.1.H.264-TAG.mkv\n</code></pre></p> <p><pre><code>output_template:\n movies: \"{title} ({year}) {quality} {source} WEB-DL {audio_full} {video}\"\n</code></pre> <pre><code>The Movie (2024) 1080p EXAMPLE WEB-DL DDP5.1 H.264.mkv\n</code></pre></p>"},{"location":"guide/output-and-naming/#template-variables","title":"Template variables","text":"<p>Every variable below is valid in both output and folder templates. Values are derived from the downloaded media (via MediaInfo), from the title metadata, or from your config. Variables that don't apply to a given title resolve to an empty string.</p>"},{"location":"guide/output-and-naming/#common-video","title":"Common / video","text":"Variable Meaning Example <code>title</code> Title name (movie/show/song name; <code>$</code> is rendered as <code>S</code>) <code>The Show</code> <code>year</code> Release year <code>2024</code> <code>source</code> Service tag / class name (empty with <code>--no-source</code>) <code>EXAMPLE</code> <code>quality</code> Resolution with scan suffix <code>1080p</code>, <code>2160p</code>, <code>576i</code> <code>resolution</code> Resolution number only <code>1080</code> <code>video</code> Video codec <code>H.264</code>, <code>H.265</code> <code>hdr</code> Dynamic-range label <code>HDR</code>, <code>HDR10P</code>, <code>DV</code>, <code>DV.HDR10</code>, <code>HLG</code> <code>hfr</code> High frame rate marker (frame rate &gt; 30) <code>HFR</code> <code>edition</code> Edition label from the track, if any <code>Directors Cut</code> <code>tag</code> Release-group tag (from <code>config.tag</code> or <code>--tag</code>) <code>TAG</code> <code>repack</code> <code>REPACK</code> when the <code>--repack</code> flag is used <code>REPACK</code> <code>lang_tag</code> Result of your <code>language_tags</code> rules, if configured <code>MULTi</code> <p>How <code>language_tags</code> rules match</p> <p>Rules are tried in order, but language comparison is fuzzy: a rule condition of <code>en</code> matches <code>en-US</code>, <code>en-GB</code>, and any other <code>en-*</code> variant. Within a single rule, all conditions must match (AND logic) for it to apply. The first rule that fully matches wins; if none match, <code>{lang_tag?}</code> is removed from the filename cleanly.</p>"},{"location":"guide/output-and-naming/#episode-specific","title":"Episode-specific","text":"Variable Meaning Example <code>season</code> Zero-padded season (<code>S%02d</code>) <code>S01</code> <code>episode</code> Zero-padded episode (<code>E%02d</code>) <code>E05</code> <code>season_episode</code> Combined <code>S01E05</code> <code>episode_name</code> Episode title <code>Pilot</code> <code>date</code> ISO air date for daily/dated content <code>2024-06-01</code> <p>Daily &amp; sports content</p> <p>When an episode has an air date, unshackle switches to date-based naming automatically: <code>season</code> and <code>season_episode</code> become the formatted air date, <code>episode</code> and <code>year</code> are cleared, and <code>{date}</code> holds the ISO date. The date's internal separator (dots or spaces) follows your <code>series</code> template style.</p>"},{"location":"guide/output-and-naming/#audio","title":"Audio","text":"Variable Meaning Example <code>audio</code> Audio codec <code>DDP</code>, <code>DD</code>, <code>AAC</code> <code>audio_channels</code> Channel layout <code>5.1</code>, <code>2.0</code> <code>audio_full</code> Codec + channels combined <code>DDP5.1</code> <code>atmos</code> <code>Atmos</code> when any track carries JOC <code>Atmos</code> <code>dual</code> <code>DUAL</code> for exactly two distinct audio languages <code>DUAL</code> <code>multi</code> <code>MULTi</code> for more than two audio languages <code>MULTi</code>"},{"location":"guide/output-and-naming/#music-specific","title":"Music-specific","text":"Variable Meaning <code>track_number</code> Zero-padded track number <code>artist</code> / <code>album_artist</code> Artist / album artist (falls back to artist) <code>album</code> Album name <code>disc</code> Disc number (only shown when greater than 1) <code>track_total</code> / <code>disc_total</code> Totals <code>release_type</code> <code>album</code>, <code>single</code>, <code>ep</code>, etc. <code>genre</code> Genre <code>explicit</code> <code>Explicit</code> when flagged <code>isrc</code> / <code>upc</code> / <code>label</code> ISRC, UPC and record label <p>Unknown variables are ignored, not errors</p> <p>If you use a variable that isn't in the list above, unshackle emits a warning at startup but continues. Double-check spelling. A typo'd <code>{quailty}</code> will simply be left in the filename literally or dropped, not filled in.</p>"},{"location":"guide/output-and-naming/#folder-templates","title":"Folder templates","text":"<p>Folder templates are nested under a special <code>folder</code> key inside <code>output_template</code>. This key is handled separately from the filename kinds. You can give it a single string (used for all title kinds) or a per-kind map.</p> Single folder templatePer-kind folder templates unshackle.yaml<pre><code>output_template:\n movies: \"{title}.{year}.{quality}.{source}-{tag}\"\n series: \"{title}.{season_episode}.{quality}.{source}-{tag}\"\n folder: \"{title}.{year}\"\n</code></pre> unshackle.yaml<pre><code>output_template:\n movies: \"{title}.{year}.{quality}.{source}-{tag}\"\n series: \"{title}.{season_episode}.{quality}.{source}-{tag}\"\n folder:\n movies: \"{title} ({year})\"\n series: \"{title} ({year})/Season {season}\"\n albums: \"{artist} - {album} ({year})\"\n</code></pre> <p>The per-kind folder keys are <code>movies</code>, <code>series</code>, <code>songs</code>, and <code>albums</code>. Any other key produces a startup warning. Path separators (<code>/</code> or <code>\\</code>) are allowed in folder templates. Each segment is formatted independently, so you can build nested directory structures like <code>Show/Season 01</code>.</p> <p>Fallback behavior:</p> <ul> <li>A per-kind folder template wins if present; otherwise the single <code>folder</code> string is used; otherwise unshackle falls back to a built-in default.</li> <li>Built-in defaults when no folder template is set: movies get no folder at all unless a <code>movies</code> folder template (or a single-string <code>folder</code> template) exists; series fall back to a folder derived from the <code>series</code> output template (stripping <code>{episode}</code>, <code>{episode_name}</code>, and collapsing <code>{season_episode}</code> down to <code>{season}</code>); music albums fall back to <code>{artist} - {album} ({year})</code>.</li> </ul> <p>Movies are flat by default</p> <p>Episodes and songs are always foldered. Movies are written directly into the output directory unless you define a <code>movies</code> folder template (or a single-string <code>folder</code> template, which folders every kind). Set one if you want each movie in its own directory.</p>"},{"location":"guide/output-and-naming/#muxing-options","title":"Muxing options","text":"<p>Muxing (combining video, audio, subtitle, chapter and attachment tracks into a single Matroska file with <code>mkvmerge</code>) is configured under the <code>muxing</code> key.</p> unshackle.yaml<pre><code>muxing:\n set_title: true\n merge_video: false\n merge_audio: true\n default_language:\n audio: en\n subtitle: en\n</code></pre> Key Type Default Effect <code>set_title</code> bool <code>true</code> Write the title name into the MKV container title with <code>--title</code>. Set to <code>false</code> to omit it. <code>merge_video</code> bool <code>false</code> Group video tracks that share the same resolution, range, and codec into one file so only language varies inside it. <code>merge_audio</code> bool <code>true</code> Merge audio tracks of the same kind so multiple languages sit in one file. <code>default_language</code> map (unset) Preferred language per track type (<code>video</code> / <code>audio</code> / <code>subtitle</code>). A track in the preferred language is flagged as the default track. <p>When no preferred language is matched, unshackle applies sensible defaults: the video default falls back to the title language / original-language track / first track; the audio default is the original-language track; and the subtitle default is a forced track matching the first audio's language.</p> <p><code>default_language</code> only sets the default-track flag</p> <p><code>default_language</code> controls which track carries the MKV <code>--default-track</code> flag. Nothing else. It does not change track selection (that stays with <code>-l</code>/<code>--alang</code> and friends), and it does not touch which track is marked as original: <code>--original-flag</code> still tags the true original-audio track. That is the point: you can make your player default to, say, Polish audio on an English-original title without altering the original marker. When the configured language isn't present in the manifest, each track type falls back to its normal default rule described above.</p> <p><code>merge_video</code> collapses only the language dimension</p> <p><code>merge_video</code> groups video tracks by <code>(resolution, range, codec)</code> and merges them so that only language differs within a single file, with no re-encode and no concatenation. Different resolutions, ranges (SDR / HDR10 / HDR10+ / DV / HYBRID), and codecs (H.264 / H.265) always land in separate files. So <code>-r HYBRID,DV,HDR10,SDR --merge-video</code> produces one file per range (never a single fused file), whereas English + French video of identical resolution, range, and codec yields one file containing both video tracks. <code>merge_audio</code> works the same way for audio languages.</p> <p>A few muxing behaviors are automatic and not configurable:</p> <ul> <li><code>--no-date</code> is always passed for privacy (no timestamps embedded).</li> <li>Descriptive audio gets the visually-impaired flag; SDH subtitles get the hearing-impaired flag; forced subtitles get the forced flag.</li> <li>Chapters are written from the title's chapter list (see Chapters below).</li> </ul> <p>The <code>--no-mux</code> flag skips muxing entirely and writes the individual track files, each with a track-type suffix, into the same output/folder structure.</p>"},{"location":"guide/output-and-naming/#tags-group-naming","title":"Tags &amp; group naming","text":"<p>The release-group tag is the <code>-TAG</code> portion at the end of scene-style names, produced by the <code>{tag}</code> variable.</p> unshackle.yaml<pre><code>tag: \"MYGROUP\"\ntag_group_name: true\ntag_imdb_tmdb: true\n</code></pre> Key Type Default Effect <code>tag</code> str <code>\"\"</code> The release-group tag used for <code>{tag}</code>. <code>tag_group_name</code> bool <code>true</code> Write the group name (<code>config.tag</code>) into the MKV <code>Group</code> metadata tag. <code>tag_imdb_tmdb</code> bool <code>true</code> Look up and embed IMDb / TMDB / TVDB external-ID tags in the MKV metadata (uses <code>tmdb_api_key</code> / <code>simkl_client_id</code> when available). <p>You can override the tag per run without editing config:</p> <pre><code>unshackle dl --tag OTHERGROUP EXAMPLE \"...\"\n</code></pre> <p>The <code>--repack</code> flag adds the <code>REPACK</code> marker (surfaced through the <code>{repack}</code> variable) to the filename for that run:</p> <pre><code>unshackle dl --repack EXAMPLE \"...\"\n</code></pre> <p>Empty tags collapse cleanly</p> <p>If <code>config.tag</code> is empty and your template ends with <code>-{tag?}</code>, the trailing <code>-</code> and the placeholder are both removed. Use the optional form <code>{tag?}</code> if you sometimes download without a tag set.</p>"},{"location":"guide/output-and-naming/#unicode-filenames","title":"Unicode filenames","text":"<p>By default unshackle transliterates non-ASCII characters (Korean, Japanese, Chinese, accented Latin, etc.) into ASCII equivalents, which is safest for older tools, DDL, and P2P sharing. Set <code>unicode_filenames</code> to keep the native characters.</p> unshackle.yaml<pre><code>unicode_filenames: true\n</code></pre> Value Result <code>false</code> (default) <code>\uae30\uc0dd\ucda9</code> \u2192 transliterated ASCII; accents stripped. <code>true</code> Native characters preserved in filenames and folders. <p>Regardless of this setting, a set of filesystem-unsafe and structural characters is always removed or replaced during sanitization (for example <code>/</code> and <code>;</code> become <code>&amp;</code>, and characters like <code>\\ * ! ? , ' \" &lt; &gt; | $ # ~</code> are stripped). This is why you should never put path-unsafe characters directly in a template. unshackle warns about templates containing <code>&lt; &gt; : \" / \\ | ? *</code> at startup (folder templates are checked per path segment, so <code>/</code> is allowed there as a directory separator).</p>"},{"location":"guide/output-and-naming/#directory-filename-configuration","title":"Directory &amp; filename configuration","text":"<p>The <code>directories</code> key relocates unshackle's working folders. Only the folders listed here can be moved; core package paths are protected and silently ignored if you try to override them.</p> unshackle.yaml<pre><code>directories:\n downloads: \"~/Media/unshackle\"\n temp: \"/mnt/fast/unshackle-temp\"\n cache: \"~/.cache/unshackle\"\n cookies: \"~/.config/unshackle/cookies\"\n logs: \"~/.config/unshackle/logs\"\n</code></pre> Name Purpose <code>downloads</code> Default output directory for finished files. <code>temp</code> Working directory for in-progress downloads, muxing, and intermediate files. <code>cache</code> Title/HTTP cache and update-check state. <code>cookies</code> Per-service cookie files. <code>logs</code> Log files. <code>exports</code> Export JSONs. <code>services</code>, <code>vaults</code>, <code>fonts</code>, <code>commands</code> Search paths for services, key-vault backends, bundled fonts, and CLI commands. <code>wvds</code>, <code>prds</code>, <code>dcsl</code> Widevine devices, PlayReady devices, and DCSL data. <p>Paths support <code>~</code> expansion. The names <code>app_dirs</code>, <code>core_dir</code>, <code>namespace_dir</code>, <code>user_configs</code>, and <code>data</code> are protected and cannot be changed.</p>"},{"location":"guide/output-and-naming/#filename-patterns","title":"Filename patterns","text":"<p>The <code>filenames</code> key overrides the naming patterns for a handful of internal files. These are not your media output names. They are logs, temp files, and per-service configs.</p> unshackle.yaml<pre><code>filenames:\n log: \"unshackle_{name}_{time}.log\"\n chapters: \"Chapters_{title}_{random}.txt\"\n subtitle: \"Subtitle_{id}_{language}.srt\"\n</code></pre> Name Default Where <code>log</code> <code>unshackle_{name}_{time}.log</code> <code>directories.logs</code> <code>debug_log</code> <code>unshackle_debug_{service}_{time}.jsonl</code> <code>directories.logs</code> <code>config</code> <code>config.yaml</code> per-service directory <code>root_config</code> <code>unshackle.yaml</code> main config filename <code>chapters</code> <code>Chapters_{title}_{random}.txt</code> <code>directories.temp</code> <code>subtitle</code> <code>Subtitle_{id}_{language}.srt</code> <code>directories.temp</code>"},{"location":"guide/output-and-naming/#chapters-naming","title":"Chapters naming","text":"<p>When a title has chapters, they are written to an OGM chapters file (<code>filenames.chapters</code>) and passed to the muxer. Unnamed chapters use the <code>chapter_fallback_name</code> template:</p> unshackle.yaml<pre><code>chapter_fallback_name: \"Chapter {i:02}\"\n</code></pre> <p>The fallback supports two placeholders: <code>{i}</code> (chapter number, starting at 1) and <code>{j}</code> (which increments only for unnamed chapters). Standard format directives like <code>{i:02}</code> are allowed.</p>"},{"location":"guide/output-and-naming/#removed-migrated-options","title":"Removed &amp; migrated options","text":"<p><code>scene_naming</code> was removed</p> <p>The old <code>scene_naming</code> option no longer exists. If it is present in your config, unshackle exits immediately with an error asking you to configure <code>output_template</code> instead. Migrate any scene-naming setup to the templates described on this page.</p>"},{"location":"guide/output-and-naming/#worked-examples","title":"Worked examples","text":"MoviesTV seriesMusic <p><pre><code>output_template:\n movies: \"{title}.{year}.{edition?}.{quality}.{source}.WEB-DL.{audio_full}.{atmos?}.{video}.{hdr?}-{tag?}\"\n folder:\n movies: \"{title} ({year})\"\n</code></pre> <pre><code>The Movie (2024)/\n \u2514\u2500 The.Movie.2024.1080p.EXAMPLE.WEB-DL.DDP5.1.Atmos.H.265.HDR-TAG.mkv\n</code></pre></p> <p><pre><code>output_template:\n series: \"{title}.{season_episode}.{episode_name?}.{quality}.{source}.WEB-DL.{audio_full}.{video}-{tag}\"\n folder:\n series: \"{title} ({year})/Season {season}\"\n</code></pre> <pre><code>The Show (2023)/Season S02/\n \u2514\u2500 The.Show.S02E04.The.Reckoning.2160p.EXAMPLE.WEB-DL.DDP5.1.H.265-TAG.mkv\n</code></pre></p> <p><pre><code>output_template:\n songs: \"{track_number}. {title}\"\n folder:\n albums: \"{album_artist} - {album} ({year})\"\n</code></pre> <pre><code>The Artist - The Album (2024)/\n \u2514\u2500 01. Opening Track.mka\n</code></pre></p>"},{"location":"guide/output-and-naming/#see-also","title":"See also","text":"<ul> <li>Configuration File: the full <code>unshackle.yaml</code> structure.</li> <li>Downloading: the <code>dl</code> command and per-run flags like <code>-o</code>, <code>--no-folder</code>, <code>--tag</code>, and <code>--repack</code>.</li> </ul>"},{"location":"guide/proxies-and-vpn/","title":"Proxies &amp; VPN","text":"<p>Most streaming services are geo-restricted, region-priced, or simply refuse to hand over a manifest from the \"wrong\" country. unshackle routes its traffic through a proxy so the service sees the location you choose instead of your own. You can point it at a single proxy URL, or configure one of several proxy providers (commercial VPNs and self-hosted tunnels), then ask for a country by its two-letter code and let unshackle pick a working server for you.</p> <p>The <code>--proxy</code> flag controls proxying, and a query is resolved to a real proxy URL by the providers unshackle supports: basic static proxies, Gluetun (documented in the most detail, since it is the most flexible), ExpressVPN, NordVPN, Proton VPN, Hola, Surfshark, and Windscribe.</p> <p>Where proxies are configured</p> <p>All provider configuration lives under the top-level <code>proxy_providers:</code> key in your <code>unshackle.yaml</code>. Each provider has its own sub-key, and the keys inside it map directly onto that provider's settings. See the Configuration file page for where the file lives and how it is loaded.</p>"},{"location":"guide/proxies-and-vpn/#the-proxy-flag","title":"The <code>--proxy</code> flag","text":"<p>Proxying is controlled at download time by three options on the <code>dl</code> command:</p> Option Effect <code>--proxy</code> The proxy to use. Either an explicit URI, or a query that unshackle resolves against your configured providers. <code>--no-proxy</code> Force all proxy use off. No providers are initialised and no proxy query is resolved. <code>--no-proxy-download</code> Use the proxy for the manifest, licence, and authentication, but bypass it for the segment downloads themselves. Explicit proxy URI<pre><code>unshackle dl --proxy http://user:pass@1.2.3.4:8080 EXAMPLE 81234567\n</code></pre> Resolve a US server from your configured providers<pre><code>unshackle dl --proxy us EXAMPLE 81234567\n</code></pre> Target a specific provider<pre><code>unshackle dl --proxy nordvpn:us EXAMPLE 81234567\n</code></pre> <p>Set a default proxy in config</p> <p>Like every <code>dl</code> flag, <code>--proxy</code> can be given a default in your configuration so you do not have to pass it on every command. See Downloading for how <code>dl</code> options and config defaults interact.</p>"},{"location":"guide/proxies-and-vpn/#-no-proxy-download","title":"<code>--no-proxy-download</code>","text":"<p>Segment downloads are usually the largest share of traffic, and a residential-grade VPN proxy is often the slowest link in the chain. <code>--no-proxy-download</code> lets you keep the proxy where it matters (passing the geo-check for the manifest and the licence) while pulling the actual audio and video segments over your normal connection for full speed.</p> Proxy the manifest and licence, download segments direct<pre><code>unshackle dl --proxy gb --no-proxy-download EXAMPLE 10a1234\n</code></pre> <p>When this is unsafe</p> <p>Some services tie segment delivery (CDN tokens, per-segment geo-checks) to the same region as the manifest. On those services, bypassing the proxy for downloads will cause segment fetches to fail or return the wrong region. If downloads break with <code>--no-proxy-download</code>, remove it.</p>"},{"location":"guide/proxies-and-vpn/#how-proxy-resolution-works","title":"How proxy resolution works","text":"<p>The value you pass to <code>--proxy</code> is interpreted in one of three ways. unshackle checks them in order.</p> <pre><code>flowchart TD\n A[\"--proxy value\"] --&gt; B{\"Looks like a URI?&lt;br/&gt;http:// https:// socks\"}\n B -- yes --&gt; C[\"Use it verbatim\"]\n B -- no --&gt; D{\"Has a provider prefix?&lt;br/&gt;provider:query\"}\n D -- yes --&gt; E[\"Ask that one provider&lt;br/&gt;for the query\"]\n D -- no --&gt; F[\"Ask every provider in order,&lt;br/&gt;first match wins\"]</code></pre> <ol> <li>An explicit URI. Anything shaped like <code>http://...</code>, <code>https://...</code>, or a <code>socks...</code> URI is used exactly as given. unshackle logs <code>Using explicit Proxy: ...</code> and does no lookup.</li> <li>A provider-prefixed query: <code>provider:query</code>, for example <code>nordvpn:us</code> or <code>gluetun:windscribe:us</code>. unshackle finds the provider whose name matches the prefix (case-insensitive) and asks only that provider to resolve the remainder. If no such provider is loaded, or it returns no proxy, the download errors.</li> <li>A bare query: a region like <code>us</code>, <code>gb</code>, <code>us:seattle</code>, or <code>us1234</code>. unshackle asks each loaded provider in order and uses the first proxy any of them returns.</li> </ol> <p>The query is matched against a region grammar (a two-letter country code, optionally followed by a server number and/or a <code>:city</code> or <code>-city</code> part), lowercased, and then handed to the provider. The exact forms each provider accepts are documented in its section below.</p>"},{"location":"guide/proxies-and-vpn/#provider-load-order","title":"Provider load order","text":"<p>When you run a download without <code>--no-proxy</code>, unshackle instantiates every configured provider once, in this fixed order, and that same order is used for bare-query resolution:</p> <p>Basic \u2192 ExpressVPN \u2192 NordVPN \u2192 Proton VPN \u2192 Surfshark \u2192 Windscribe \u2192 Gluetun \u2192 Hola</p> <p>So if you have both Basic and NordVPN configured and run <code>--proxy us</code>, a <code>us</code> entry in your Basic config wins because Basic is tried first. To skip ahead to a specific provider, prefix the query (<code>--proxy nordvpn:us</code>).</p> <p>Auto-loading providers</p> <p>Most providers only load when you configure them under <code>proxy_providers:</code>. Three are special: ExpressVPN and Proton VPN also load automatically once their cached session file exists on disk (even with no YAML), and Hola loads automatically whenever the <code>hola-proxy</code> binary is found on your <code>PATH</code>.</p>"},{"location":"guide/proxies-and-vpn/#connection-feedback","title":"Connection feedback","text":"<p>After a provider resolves a query, unshackle prints a line so you can confirm where you came out:</p> <ul> <li>Gluetun reports the verified exit IP, country, and city of the container.</li> <li>ExpressVPN and Proton VPN print a location summary such as <code>(USA - New York, #3 of 5): .214</code>.</li> <li>Other providers log the resolved proxy URL.</li> </ul>"},{"location":"guide/proxies-and-vpn/#basic-static-proxies","title":"Basic (static proxies)","text":"<p>The <code>Basic</code> provider is pure static configuration, with no accounts and no network calls. You list proxy URLs per country code, and unshackle serves them back when you query that country. This is the right choice when you already have proxy endpoints (from a proxy seller, your own servers, or a corporate gateway).</p> <p>Under each two-letter country code you can put either a single proxy string or a list of them:</p> unshackle.yaml<pre><code>proxy_providers:\n basic:\n us: http://user:pass@1.2.3.4:8080\n de:\n - http://a.example:8080\n - socks5://b.example:1080\n</code></pre> <p>Query forms:</p> Query Meaning <code>us</code> A proxy for the US. If several are listed, one is chosen at random. <code>us2</code> The 2<sup>nd</sup> entry in the US list (1-based). <ul> <li>If a country has a single proxy string, that proxy is always returned.</li> <li>If it has a list and you give a plain country code, one is picked at random; append an index (<code>de1</code>, <code>de2</code>) to pin a specific entry.</li> <li>Each URL is normalised (a missing scheme defaults to <code>http</code>) and validated, so a malformed URI is rejected up front rather than failing mid-download.</li> </ul> <pre><code>unshackle dl --proxy de2 EXAMPLE 81234567\n</code></pre>"},{"location":"guide/proxies-and-vpn/#gluetun","title":"Gluetun","text":"<p>Gluetun is unshackle's most flexible proxy backend, and the one to reach for if you want one configuration to cover many VPN providers. Instead of returning a remote proxy URL, Gluetun launches a local Docker container running the <code>qmcgaw/gluetun</code> image. That container establishes a WireGuard or OpenVPN tunnel to your chosen VPN provider and exposes a plain HTTP proxy on <code>localhost</code>, which unshackle then routes traffic through. When the download finishes, the container is torn down automatically.</p> <p>This means you get access to the 50+ VPN providers that Gluetun supports, using your own VPN subscription, through a single uniform interface, with no per-provider integration in unshackle itself.</p> <p>Docker is required</p> <p>Gluetun needs a working Docker installation on your <code>PATH</code>. If Docker is not found, the provider fails to load with an error linking to the install docs. The container also needs the <code>NET_ADMIN</code> capability and access to <code>/dev/net/tun</code> to bring up the tunnel. unshackle requests both automatically.</p>"},{"location":"guide/proxies-and-vpn/#query-format","title":"Query format","text":"<p>Gluetun uses a nested selector: the provider prefix picks Gluetun, and the rest names the VPN provider and the region.</p> <pre><code>gluetun:&lt;vpn-provider&gt;:&lt;region&gt;\n</code></pre> A Windscribe US exit via Gluetun<pre><code>unshackle dl --proxy gluetun:windscribe:us EXAMPLE 81234567\n</code></pre> A NordVPN Germany exit via Gluetun<pre><code>unshackle dl --proxy gluetun:nordvpn:de EXAMPLE 81234567\n</code></pre> <p>After unshackle strips the leading <code>gluetun:</code>, the provider receives exactly <code>provider:region</code> (two colon-separated parts; anything else is an error). The <code>&lt;vpn-provider&gt;</code> must be one you have configured under <code>gluetun.providers</code>, and friendly names are normalised to Gluetun's identifiers (for example <code>pia</code> and <code>privateinternetaccess</code> both map to <code>private internet access</code>).</p>"},{"location":"guide/proxies-and-vpn/#configuration","title":"Configuration","text":"<p>Each VPN provider you want to use gets an entry under <code>providers:</code>, carrying its VPN type, credentials, and how your region aliases map onto Gluetun's server selectors.</p> unshackle.yaml<pre><code>proxy_providers:\n gluetun:\n providers:\n windscribe:\n vpn_type: wireguard\n credentials:\n private_key: YOUR_WIREGUARD_PRIVATE_KEY\n addresses: YOUR_WIREGUARD_ADDRESS\n preshared_key: YOUR_PRESHARED_KEY\n server_countries:\n us: US\n uk: GB\n server_cities: {}\n server_hostnames: {}\n extra_env: {}\n nordvpn:\n vpn_type: wireguard\n credentials:\n private_key: YOUR_WIREGUARD_PRIVATE_KEY\n server_countries:\n us: US\n de: DE\n\n # Global settings (all optional)\n base_port: 8888\n auto_cleanup: true\n container_prefix: unshackle-gluetun\n auth_user: null\n auth_password: null\n verify_ip: true\n</code></pre> <p>Per-provider keys:</p> Key Purpose <code>vpn_type</code> <code>wireguard</code> (default) or <code>openvpn</code>. <code>credentials</code> The secrets for the tunnel; see the credential rules below. <code>server_countries</code> Maps your region alias (e.g. <code>us</code>) to Gluetun's country value (e.g. <code>US</code>). <code>server_cities</code> Optional. Maps an alias to a Gluetun city. <code>server_hostnames</code> Optional. Maps an alias directly to a specific server hostname. <code>extra_env</code> Optional. Raw environment variables merged into the container last, for any Gluetun setting not covered above. <p>Credential rules by VPN type:</p> WireGuardOpenVPN <ul> <li><code>private_key</code> is always required.</li> <li><code>surfshark</code>, <code>mullvad</code>, and <code>ivpn</code> also require <code>addresses</code>.</li> <li><code>windscribe</code> additionally requires both <code>addresses</code> and <code>preshared_key</code> (<code>preshared_key</code> may be an empty string, but the key must be present).</li> <li>NordVPN and Proton VPN need only <code>private_key</code>.</li> </ul> <ul> <li>Requires <code>username</code> and <code>password</code>.</li> </ul> <p>Which <code>vpn_type</code> should I pick?</p> <p>WireGuard is the default because it can be faster, but it needs the fiddlier credential setup above (private keys, and for some providers <code>addresses</code> and a preshared key). OpenVPN is the simplest to configure (just a username and password) at the cost of some speed. If you are getting started or hitting credential trouble, OpenVPN is the path of least resistance; switch to WireGuard when you want the extra throughput.</p> <p>Global keys:</p> Key Default Purpose <code>base_port</code> <code>8888</code> The first local port to expose proxies on. Additional containers take the next free ports. <code>auto_cleanup</code> <code>true</code> Remove containers on exit. If <code>false</code>, containers are only stopped, not deleted. <code>container_prefix</code> <code>unshackle-gluetun</code> Prefix for Docker container names. <code>auth_user</code> / <code>auth_password</code> <code>null</code> Optional HTTP-proxy credentials. If set, the local proxy requires auth and the credentials are embedded in the proxy URL. <code>verify_ip</code> <code>true</code> After connecting, verify the container's real exit IP and region."},{"location":"guide/proxies-and-vpn/#region-selection","title":"Region selection","text":"<p>For a given query region, Gluetun resolves the server like this:</p> <ol> <li>An explicit entry in <code>server_hostnames</code>, <code>server_cities</code>, or <code>server_countries</code> for that alias always wins.</li> <li>A <code>us1239</code>-style query (country code + number) with no explicit mapping is turned into a provider-specific server hostname (for example <code>us1239.nordvpn.com</code> for NordVPN, <code>us-1239.prod.surfshark.com</code> for Surfshark).</li> <li>A bare two-letter code is expanded to the full country name Gluetun expects.</li> </ol> <p>A few providers (Windscribe, VyprVPN, VPN Secure) select by region rather than country, and Windscribe region names are translated automatically. For instance <code>us</code> becomes <code>US East</code> and <code>uk</code>/<code>gb</code> become <code>United Kingdom</code>.</p>"},{"location":"guide/proxies-and-vpn/#container-lifecycle","title":"Container lifecycle","text":"<p>Understanding what Gluetun does behind the scenes helps when something goes wrong:</p> <ol> <li>Image check. <code>qmcgaw/gluetun:latest</code> is pulled if it is not already present.</li> <li>Reuse. If a container for this exact <code>provider:region</code> is already running (from a concurrent unshackle session), it is adopted instead of starting a new one. Stopped or dead containers with the same name are pruned first.</li> </ol> <p>Expect a slow first request, then instant reuse</p> <p>Bringing up a fresh tunnel takes roughly 10 to 30 seconds for the first request to a given <code>provider:region</code>. This is the VPN handshake and readiness wait, not a hang. Every subsequent request that reuses that same container is effectively instant. A slow first run is normal.</p> <ol> <li>Port allocation. A free local port is chosen starting from <code>base_port</code>.</li> <li>Start. The container is launched bound to <code>127.0.0.1:{port}</code>. Credentials are passed through a temporary, <code>0600</code>-permission env-file (never as <code>-e</code> flags), which is overwritten and deleted immediately after.</li> <li>Readiness wait. unshackle polls the container logs (up to 60 seconds) until both the HTTP proxy is listening and the VPN reports a completed connection. Fatal errors like <code>authentication failed</code> or <code>invalid credentials</code> abort early, and recent logs are attached to the error to help you diagnose it.</li> <li>IP verification. When <code>verify_ip</code> is on, unshackle queries the container's exit IP and checks the country matches what you asked for, raising a region mismatch error if it does not.</li> <li>Proxy handed back. You get <code>http://localhost:{port}</code> (or with auth credentials if configured).</li> </ol> <p>Cleanup and Ctrl+C</p> <p>Containers are cleaned up via an <code>atexit</code> handler on normal exit. Gluetun deliberately does not install its own signal handlers, so <code>Ctrl+C</code> continues to work as you expect. If a run is killed hard (e.g. <code>kill -9</code>) a container can be left behind; with <code>auto_cleanup: true</code> the next run adopting that name will still work, or you can remove it manually with <code>docker rm -f</code>.</p>"},{"location":"guide/proxies-and-vpn/#troubleshooting","title":"Troubleshooting","text":"<p>Common Gluetun issues</p> <ul> <li><code>RuntimeError</code> about Docker not found. Install Docker and confirm <code>docker</code> is on your <code>PATH</code>.</li> <li><code>invalid credentials</code> / <code>authentication failed</code> in the readiness wait. Your WireGuard/OpenVPN credentials are wrong or in the wrong fields. Double-check <code>private_key</code>, <code>addresses</code>, and (for Windscribe) <code>preshared_key</code>.</li> <li>Region mismatch error. The VPN connected but exited in a different country than requested. Check your <code>server_countries</code> mapping, or set <code>verify_ip: false</code> if you are intentionally using a nearby region.</li> <li>Timeout after 60 seconds. The tunnel never came up. Inspect the container logs (<code>docker logs &lt;container&gt;</code>) for the underlying VPN error.</li> </ul>"},{"location":"guide/proxies-and-vpn/#expressvpn","title":"ExpressVPN","text":"<p>ExpressVPN mirrors the ExpressVPN Android TV app: it signs in through Express's OAuth 2.0 device-login flow, obtains proxy-capable locations from Express's API, and returns an authenticated HTTPS proxy. The device login runs once; after that the cached refresh token keeps the session alive headlessly.</p> <p>Enable it and run a download interactively once:</p> unshackle.yaml<pre><code>proxy_providers:\n expressvpn:\n enable: true\n</code></pre> <p>With <code>enable: true</code> and an interactive terminal, unshackle prints a code and a URL to enter it at. Once approved, the tokens are cached and reused automatically, so later runs need no terminal. ExpressVPN also auto-loads once its token cache exists, so you can drop <code>enable</code> after the first login, but you can keep a YAML block to pin regions or servers:</p> unshackle.yaml (optional)<pre><code>proxy_providers:\n expressvpn:\n region_map:\n us: ny-02 # prefer New York, server 02 for the US\n gb: # empty = smart random location\n server_map:\n myserver: usny-newyork-2\n</code></pre> <p>Default file location:</p> File Default path Token cache <code>{cache}/vpn/expressvpn_tokens.json</code> <p>Where <code>{cache}</code> is your configured cache directory.</p> <p>Query forms:</p> Query Meaning <code>us</code> A smart, random US location. <code>us-ny</code> US, New York. <code>us-ny-2</code> / <code>us-ny2</code> US, New York, the 2<sup>nd</sup> server. <code>usny-newyork-2</code> A full location slug. <code>hostname.expressprovider.com</code> A direct endpoint hostname. <p>The resolved proxy is an HTTPS proxy on port <code>443</code>. On success, unshackle prints a location summary such as <code>(USA - New York, #3 of 5): .214</code>.</p> <p>Cache safety</p> <p>ExpressVPN's token cache is written with <code>0600</code> permissions so the refresh token is never briefly world-readable.</p>"},{"location":"guide/proxies-and-vpn/#nordvpn","title":"NordVPN","text":"<p>NordVPN uses your Service Credentials, not your normal NordVPN login. Generate them from the NordVPN dashboard under manual setup; they are a long random username/password pair, not your email and password.</p> unshackle.yaml<pre><code>proxy_providers:\n nordvpn:\n username: YOUR_SERVICE_USERNAME\n password: YOUR_SERVICE_PASSWORD\n server_map: # optional: pin specific server IDs\n us: 1234\n us:seattle: 5678\n</code></pre> <p>Required keys: <code>username</code>, <code>password</code>. unshackle validates them up front: the combined username and password must be exactly 48 alphanumeric characters (case-insensitive), and the username must not contain an <code>@</code>. If validation fails, you have almost certainly used your login credentials instead of your service credentials.</p> <p><code>server_map</code> is optional and maps a region (or <code>code:city</code>) to a pinned NordVPN server ID. Its main use is tuning: for a given streaming service one specific server often performs noticeably better than NordVPN's recommended pick, so hard-coding that server for a day or two is a handy workaround until it degrades and you swap in another.</p> <p>Use <code>gb</code>, not <code>uk</code>, for the United Kingdom</p> <p>Query the UK as <code>gb</code>. unshackle uses the Alpha-2 country code <code>gb</code> deliberately to stay consistent with its other regional/country-code systems and avoid the language-vs- country-code confusion that <code>uk</code> invites.</p> <p>Query forms:</p> Query Meaning <code>us</code> A recommended US server. <code>us1234</code> The specific server <code>us1234</code>. <code>us:seattle</code> A recommended server in Seattle. <code>228</code> A NordVPN numeric country ID. <p>The returned proxy is HTTPS on port 89 (NordVPN disabled its plain-HTTP proxies on port 80 in 2021).</p> <pre><code>unshackle dl --proxy nordvpn:us:seattle EXAMPLE 81234567\n</code></pre>"},{"location":"guide/proxies-and-vpn/#proton-vpn","title":"Proton VPN","text":"<p>Proton VPN supports two authentication methods, and unshackle can work with either. Note that free Proton accounts work but are limited to Proton's free-tier exit countries.</p> TV login (recommended)Exported cookies <p>A self-sustaining, refreshable session obtained through Proton's TV device-login flow. This is the only method that can refresh itself headlessly, so it keeps working without re-exporting anything. Enable it and run a download interactively once:</p> unshackle.yaml<pre><code>proxy_providers:\n protonvpn:\n enable: true\n</code></pre> <p>With <code>enable: true</code> and an interactive terminal, unshackle prints a code and asks you to enter it at account.proton.me/vpn/tv/code. Once approved, the session is cached and reused automatically.</p> <p>Export your <code>account.proton.me</code> session cookies (the <code>AUTH-&lt;UID&gt;</code> cookie) to the Proton cookie file. This method is access-only: it cannot refresh, so you must re-export when it expires.</p> <p>The <code>AUTH-&lt;UID&gt;</code> cookie is HttpOnly</p> <p>This is the single most common cause of a failed Proton cookie import: the required <code>AUTH-&lt;UID&gt;</code> cookie is HttpOnly, and many one-click cookie-export extensions silently skip HttpOnly cookies by default. If your import \"doesn't work,\" use an exporter that explicitly includes HttpOnly cookies.</p> <p>Why this session can't refresh, and lapses after ~24h</p> <p>Proton rotates browser refresh tokens and ties them to the live browser, so a headless refresh is impossible. unshackle therefore deliberately uses only the cookie's short-lived access token and never attempts a refresh, which is why the session lapses at Proton's ~24h TTL and must be re-exported. This is exactly why TV login is preferred for set-and-forget use.</p> <p>Default file locations:</p> File Default path Cookies <code>{cookies}/vpn/protonvpn.txt</code> Session cache <code>{cache}/vpn/protonvpn.json</code> <p>Proton VPN auto-loads if its cookie file exists. Like ExpressVPN, its cached session is written with <code>0600</code> permissions.</p> <p>Cache vs cookie precedence</p> <p>If both a TV-login cache and a cookie file exist, the cache is preferred unless the cookie file is newer. Cookies are read fresh every run and never written back to the cache. So to deliberately force use of the cookie session, just re-save (re-export) the cookie file so its modification time is newer than the cache.</p> <p>Query forms (after the <code>protonvpn:</code> prefix):</p> Query Meaning <code>us</code> A random US server (paid tiers preferred over free). <code>us12</code> Proton US server #12. <code>us:ny</code> A server in New York. <p>The returned proxy is HTTPS on port 4443 (or port 443 for Secure Core servers). Secure Core and Tor servers are excluded from selection because they are too slow for a plain proxy. On success, unshackle prints a summary such as <code>(Name - City): server-host</code>.</p> <p>Proton server numbers aren't sequential</p> <p>When pinning a server with <code>protonvpn:deNN</code>, don't guess a low number. A country may expose non-contiguous IDs like <code>#203</code>, <code>#813</code>, and so on. Copy the number from a previous run's log line (e.g. <code>DE#203</code>) instead.</p>"},{"location":"guide/proxies-and-vpn/#hola","title":"Hola","text":"<p>Hola requires no configuration at all. It uses the <code>hola-proxy</code> binary, and auto-loads whenever that binary is found on your <code>PATH</code>. If you query Hola but the binary is missing, the provider raises an error telling you to install it.</p> Install hola-proxy, then just query a country<pre><code>unshackle dl --proxy hola:us EXAMPLE 81234567\n</code></pre> <p>Query forms: a two-letter country code (e.g. <code>us</code>, <code>gb</code>). unshackle asks <code>hola-proxy</code> for available proxies in that country and picks one at random, returning an HTTP proxy.</p> <p>Temporary bans</p> <p>Hola's free tier can rate-limit or temporarily ban you if queried too aggressively. If you see a temporary ban detected error, wait before retrying. Hola currently uses only datacenter proxies.</p>"},{"location":"guide/proxies-and-vpn/#surfshark","title":"Surfshark","text":"<p>Surfshark, like NordVPN, uses Service Credentials rather than your login. Generate them from the Surfshark manual-setup page.</p> unshackle.yaml<pre><code>proxy_providers:\n surfsharkvpn:\n username: YOUR_SERVICE_USERNAME\n password: YOUR_SERVICE_PASSWORD\n server_map: # optional\n us: 1234\n</code></pre> <p>Required keys: <code>username</code>, <code>password</code>, validated with the same 48-character rule as NordVPN (combined username+password must be 48 alphanumeric characters, case-insensitive, no <code>@</code>). <code>server_map</code> optionally pins server IDs per region.</p> <p>Query forms:</p> Query Meaning <code>us</code> A random US server. <code>us-bos</code> A specific server. <code>us:seattle</code> A random server in Seattle. <p>The returned proxy is HTTPS on port 443.</p>"},{"location":"guide/proxies-and-vpn/#windscribe","title":"Windscribe","text":"<p>Windscribe uses Service Credentials from its OpenVPN config page. Only the presence of a username and password is checked (there is no 48-character rule).</p> unshackle.yaml<pre><code>proxy_providers:\n windscribevpn:\n username: YOUR_SERVICE_USERNAME\n password: YOUR_SERVICE_PASSWORD\n server_map: # optional: alias -&gt; hostname\n us: us-east.totallyacdn.com\n us:seattle: us-seattle.totallyacdn.com\n</code></pre> <p>Required keys: <code>username</code>, <code>password</code>. <code>server_map</code> optionally maps a region (or <code>region:city</code>) directly to a hostname.</p> <p>Query forms:</p> Query Meaning <code>us</code> A random US server. <code>us150</code> / <code>sg007</code> A specific numbered server. <code>us:seattle</code> A random server in Seattle. <p>The returned proxy is HTTPS on port 443.</p> <p>Windscribe is not loaded by the REST API resolver</p> <p>The standalone Windscribe provider (and Gluetun) are loaded by the <code>dl</code> command, but not by the proxy resolver used by the REST API and remote-download client. If you drive downloads through the API and need Windscribe or Gluetun exits, resolve the proxy on the CLI side or use a different provider for API jobs. See the developer note below.</p>"},{"location":"guide/proxies-and-vpn/#developer-notes","title":"Developer notes","text":"<p>Two resolution paths (developers)</p> <p>unshackle has two proxy-resolution code paths that are intentionally not identical:</p> <ul> <li><code>unshackle/commands/dl.py</code> inlines its own logic and loads all eight providers, including Windscribe and Gluetun.</li> <li><code>unshackle/core/proxies/resolve.py::initialize_proxy_providers()</code> is the shared resolver used by the REST API handlers and the remote-service client. It omits Windscribe and Gluetun.</li> </ul> <p>Both paths accept the same query grammar (a direct URI, a <code>provider:query</code>, or a bare country query tried against providers in order), but the set of available providers differs. Keep this in mind when adding a provider: wiring it into <code>dl.py</code> does not make it available over the API, and vice versa.</p> <p>Implementing a new provider (developers)</p> <p>Every provider subclasses <code>unshackle.core.proxies.proxy.Proxy</code> and implements three methods:</p> <ul> <li><code>__init__(self, **kwargs)</code> receives its <code>proxy_providers</code> sub-dict splatted as keyword arguments, so YAML keys map 1:1 to constructor parameters. Do authentication and catalog pre-fetching here.</li> <li><code>__repr__(self)</code> is a human summary, conventionally <code>\"{n} Countries ({m} Servers)\"</code>.</li> <li><code>get_proxy(self, query)</code> returns a Requests-compatible proxy URI, or <code>None</code> only when the query was valid but no proxy exists. Raise on genuine errors or bad queries.</li> </ul> <p>Optionally expose <code>get_connection_info(query)</code> (as Gluetun does) or <code>last_connection_display()</code> (as ExpressVPN and Proton VPN do) to have <code>dl</code> print a friendly connection line instead of the raw proxy URL.</p>"},{"location":"guide/proxies-and-vpn/#see-also","title":"See also","text":"<ul> <li>Downloading: the full <code>dl</code> command guide, including where proxy flags sit in the download flow.</li> <li>Configuration file: the <code>unshackle.yaml</code> reference, including directories for cookies and cache used by the cookie-based providers.</li> <li>Configuration reference: the developer-facing configuration API, including the <code>proxy_providers</code> structure.</li> </ul>"},{"location":"guide/subtitles/","title":"Subtitles","text":"<p>Subtitles are first-class tracks in unshackle. When you download a title, subtitle tracks are parsed from the manifest alongside video and audio, downloaded, cleaned up, optionally converted to the format you want, and then either muxed into the final Matroska file or written out as sidecar files next to it. The sections below cover the supported formats, how tracks are normalized after download, how to select and filter subtitles, and every subtitle-related configuration option.</p> <p>Most of this is controlled with a handful of <code>dl</code> flags and a small <code>subtitle</code> block in your configuration file. See Downloading for how subtitle flags fit into a full download command.</p>"},{"location":"guide/subtitles/#supported-formats","title":"Supported formats","text":"<p>unshackle understands the following subtitle codecs. The Format column is the value shown in track listings; the Extension column is the file extension used on disk.</p> Codec (internal name) Format Extension Notes <code>SubRip</code> SRT <code>srt</code> SubRip, the most widely compatible plain-text format <code>SubStationAlpha</code> SSA <code>ssa</code> SubStation Alpha (styled) <code>SubStationAlphav4</code> ASS <code>ass</code> Advanced SubStation Alpha (styled) <code>TimedTextMarkupLang</code> TTML <code>ttml</code> Timed Text Markup Language (IMSC/DFXP) <code>WebVTT</code> VTT <code>vtt</code> WebVTT <code>SAMI</code> SMI <code>smi</code> Synchronized Accessible Media Interchange <code>MicroDVD</code> SUB <code>sub</code> MicroDVD <code>MPL2</code> MPL2 <code>mpl2</code> MPL2 <code>TMP</code> TMP <code>tmp</code> TMP <code>fTTML</code> STPP <code>stpp</code> MPEG-DASH box-encapsulated TTML (IMSC1) <code>fVTT</code> WVTT <code>wvtt</code> MPEG-DASH box-encapsulated WebVTT <p>The two boxed formats convert automatically</p> <p><code>fTTML</code> (STPP) and <code>fVTT</code> (WVTT) are the fragmented, MP4-box-encapsulated forms that DASH and HLS deliver. You never keep these as-is: right after download they are unwrapped into their plain counterparts (<code>fTTML</code> becomes TTML and <code>fVTT</code> becomes WebVTT), so you always end up with an editable text subtitle. Note that this is a one-way, source-only relationship: you can convert from these boxed formats, but no backend can produce them as an output target, so they can never be a conversion destination.</p>"},{"location":"guide/subtitles/#what-happens-to-a-subtitle-after-download","title":"What happens to a subtitle after download","text":"<p>A subtitle download does more than save a file. Once the bytes are on disk, unshackle runs format-appropriate clean-up to produce a single, valid file:</p> <ul> <li>Encoding: non-boxed subtitles are forced to UTF-8, and stray <code>&amp;lrm;</code> / <code>&amp;rlm;</code> bidirectional entities are unescaped.</li> <li>Segment merging: when a WebVTT or boxed subtitle arrives as many DASH/HLS segments, the segments are stitched back into one continuous document with correct timing.</li> <li>WebVTT sanitization: merged WebVTT runs through a repair pipeline that clamps negative timestamps to <code>00:00:00.000</code>, removes stray cue identifiers (like <code>Q0</code>, <code>Q1</code>) that confuse downstream parsers, and merges multi-line cues that a service split into separate overlapping cues. By default the original styling and layout are preserved (see <code>preserve_formatting</code>).</li> <li>TTML for muxing: Matroska cannot carry TTML. If you do not request a specific output format, any plain TTML track is automatically converted to WebVTT before muxing (the closest lossless equivalent). Boxed <code>fTTML</code> is likewise unwrapped to TTML first.</li> </ul> <p>You normally do not need to think about any of this. It just produces a clean file.</p>"},{"location":"guide/subtitles/#selecting-and-filtering-subtitles","title":"Selecting and filtering subtitles","text":"<p>Subtitle selection happens through <code>dl</code> flags. The most important is language selection.</p> Flag Purpose <code>-sl</code>, <code>--s-lang</code> Language(s) wanted for subtitles. Defaults to <code>all</code>. <code>--require-subs</code> Require these languages to exist; if present, download all subtitles. Cannot be combined with <code>--s-lang</code>. <code>-fs</code>, <code>--forced-subs</code> Include forced subtitle tracks (excluded by default). <code>--exact-lang</code> Exact language matching, with no regional variants. <code>-S</code>, <code>--subs-only</code> Download only subtitle tracks. <code>-ns</code>, <code>--no-subs</code> Do not download subtitle tracks at all. <code>--sub-format</code> Output subtitle format / conversion target (see conversion). <code>--skip-subtitle-errors</code> Skip a subtitle that fails to download instead of aborting the whole title."},{"location":"guide/subtitles/#choosing-languages","title":"Choosing languages","text":"<p>By default (<code>--s-lang all</code>) unshackle keeps every subtitle language the service offers. To narrow it down, pass a comma-separated list of language tags:</p> English and Spanish subtitles only<pre><code>unshackle dl --s-lang en,es EXAMPLE 81234567\n</code></pre> <p>Language matching is fuzzy by default: <code>en</code> will match <code>en-US</code>, <code>en-GB</code>, and similar variants. If a requested language is missing but others were found, unshackle continues with whatever remains and tells you which languages it dropped.</p> <p>For strict matching, where <code>es-419</code> matches only <code>es-419</code> and never <code>es-ES</code>, add <code>--exact-lang</code>:</p> Only Latin-American Spanish, no other Spanish variants<pre><code>unshackle dl --s-lang es-419 --exact-lang EXAMPLE 'https://www.example.com/...'\n</code></pre>"},{"location":"guide/subtitles/#requiring-languages-before-downloading","title":"Requiring languages before downloading","text":"<p><code>--require-subs</code> is a gate rather than a filter. It downloads all available subtitles, but only if every language you list is present; if any is missing the title errors out. This is useful for batch jobs where a title without your must-have language should fail loudly rather than silently produce a partial result.</p> Fail unless both English and French subs exist, then grab everything<pre><code>unshackle dl --require-subs en,fr EXAMPLE B0ABCDEFGH\n</code></pre> <p><code>--require-subs</code> and <code>--s-lang</code> are mutually exclusive</p> <p>Because <code>--require-subs</code> forces downloading of all subtitle languages, it cannot be combined with <code>--s-lang</code>. Choose one or the other.</p>"},{"location":"guide/subtitles/#forced-subtitles","title":"Forced subtitles","text":"<p>Forced tracks carry only the important on-screen signs and foreign-dialogue lines meant to display even when you are watching in your own language. They are excluded by default. Add <code>-fs</code> / <code>--forced-subs</code> to include them:</p> Include forced tracks alongside full subtitles<pre><code>unshackle dl --s-lang en --forced-subs EXAMPLE 81234567\n</code></pre>"},{"location":"guide/subtitles/#track-types-forced-sdh-and-cc","title":"Track types: forced, SDH, and CC","text":"<p>Every subtitle track carries flags describing what kind of captions it holds. These flags drive selection, sort order, output filenames, and the Matroska track flags.</p> <ul> <li>Forced: only signs and foreign dialogue; meant to play when the audio language matches. Off by default; enable with <code>--forced-subs</code>.</li> <li>SDH (Subtitles for the Deaf and Hard-of-Hearing; also called HOH): a full transcript that includes both dialogue and non-speech sound cues.</li> <li>CC (Closed Captions): captions originating from an EIA-608/708 broadcast stream, often uppercase with <code>&gt;&gt;&gt;</code> speaker markers and sound cues.</li> </ul> <p>SDH and CC are treated together for sorting and stripping</p> <p>Within a language, unshackle orders subtitles from fewest to most captions: Forced \u2192 Normal \u2192 SDH/CC. For the purposes of hearing-impaired handling, SDH and CC tracks are grouped as the \"most captions\" variant.</p> <p>A single track cannot be both CC and SDH, and a forced track cannot also be flagged CC or SDH. These combinations are rejected as invalid.</p>"},{"location":"guide/subtitles/#closed-captions-embedded-in-video","title":"Closed captions embedded in video","text":"<p>Some services do not ship subtitles as separate tracks but instead embed EIA-608/708 captions inside the video stream. After a video track is downloaded and decrypted, unshackle probes it for these captions and, when found, extracts them into a SubRip (<code>SRT</code>) subtitle flagged as CC. This runs automatically unless you disabled subtitles (<code>--no-subs</code>) or video (<code>--no-video</code> / <code>--video-only</code> semantics), and it requires the CCExtractor tool on your <code>PATH</code>.</p>"},{"location":"guide/subtitles/#automatic-sdh-stripping","title":"Automatic SDH stripping","text":"<p>When a language has an SDH track but no plain (non-SDH, non-forced) track, unshackle can generate a clean non-SDH version for you by stripping the hearing-impaired cues: sound effects, speaker labels, music notes, and similar. This is on by default and controlled by the <code>strip_sdh</code> config key.</p> <p>The check is deliberately loose: if a close-enough plain track already exists (for example an <code>en-GB</code> non-SDH track when the SDH track is <code>en-US</code>), no stripped copy is created. When a stripped copy is created, the original SDH track is kept as well, so you end up with both.</p> <p>The stripping engine itself is chosen by the <code>sdh_method</code> config key. The default (<code>auto</code>) prefers the <code>subby</code> cleaner for SRT, falls back to SubtitleEdit when it is installed, and otherwise uses the built-in <code>filter-subs</code> approach.</p> <p>Why <code>convert_before_strip</code> exists</p> <p><code>subby</code>'s SDH stripper only operates on SRT. Handed any other codec it returns silently without stripping anything, not an error but a no-op that leaves the SDH cues in place. This is the whole reason for <code>convert_before_strip</code>: non-SubtitleEdit engines need the subtitle converted to SRT first, or the hearing-impaired cues survive the strip untouched.</p>"},{"location":"guide/subtitles/#converting-subtitle-formats","title":"Converting subtitle formats","text":"<p>By default unshackle keeps each subtitle in its downloaded format (only auto-converting TTML to WebVTT for muxing, as noted above). To force a specific output format, use <code>--sub-format</code>:</p> Convert every subtitle to SRT<pre><code>unshackle dl --s-lang en,es --sub-format srt EXAMPLE 81234567\n</code></pre> <p><code>--sub-format</code> accepts the common format names and aliases, including <code>srt</code>, <code>vtt</code>, <code>ssa</code>, <code>ass</code>, and <code>ttml</code>. Pass <code>original</code> to explicitly keep the source format and skip all conversion:</p> Keep whatever the service delivered<pre><code>unshackle dl --sub-format original EXAMPLE 'https://www.example.com/...'\n</code></pre> <p>Conversion only runs when the source format differs from the target, so <code>--sub-format srt</code> on a track that is already SRT is a no-op.</p> <p>Down-converting styled subtitles is lossy</p> <p>Converting styled SSA/ASS subtitles to SRT throws away positioning, colours, and italics. unshackle never does this automatically. It only happens when you explicitly ask for it via <code>--sub-format</code>. If you want to preserve styling, convert to a format that supports it (or keep <code>original</code>).</p> <p>Note that this automatic protection guards only the default muxed track: there the conversion is skipped and the styled original is kept. It does not cover sidecars. A <code>sidecar_format: srt</code> will still lossily flatten styled subtitles, dropping positioning, colours, and styling, and a per-download <code>--sub-format srt</code> forces the muxed track to convert as well. To keep raw styled sidecars, set <code>sidecar_format: original</code>.</p>"},{"location":"guide/subtitles/#how-the-conversion-backend-is-chosen","title":"How the conversion backend is chosen","text":"<p>Under the hood unshackle picks the highest-fidelity converter that supports the source\u2192target pair. Which converter runs depends on the <code>conversion_method</code> config key (default <code>auto</code>) and the formats involved:</p> Backend Best at Requires <code>subtitleedit</code> Highest fidelity; preserves positioning and italics SubtitleEdit installed <code>subby</code> Native SRT output with clean-up - <code>pysubs2</code> Best fidelity for styled SSA/ASS - (pure Python, always available) <code>pycaption</code> Last-resort fallback; flattens styling - <p>With <code>conversion_method: auto</code>, unshackle ranks these automatically per conversion. Setting it to a specific value pins that backend as the first choice, falling back to others only if the pin cannot handle the pair.</p>"},{"location":"guide/subtitles/#what-each-backend-actually-preserves","title":"What each backend actually preserves","text":"<p>The table below comes from round-tripping a subtitle that carries italics, bold, underline, positioning, and colour through every backend. Each cell lists the styling that survives; <code>\u2014</code> means the backend cannot handle that pair.</p> Conversion <code>subtitleedit</code> <code>pysubs2</code> <code>subby</code> <code>pycaption</code> WebVTT \u2192 SRT italic, bold, underline, position italic, underline italic, position (strips all) WebVTT \u2192 ASS italic, bold, underline, position italic, bold, underline \u2014 \u2014 WebVTT \u2192 TTML italic, bold, underline, position italic, bold, underline position (strips all) ASS/SSA \u2192 SRT all (+ colour) italic, underline \u2014 \u2014 ASS/SSA \u2192 TTML position only italic, bold, underline \u2014 \u2014 ASS/SSA \u2192 VTT position only italic, underline \u2014 \u2014 <p>Reading the table:</p> <ul> <li>Keep the original: leaving <code>--sub-format</code> unset (or set to <code>original</code>) never round-trips the file, so every style survives. Only convert when your player cannot read the source format.</li> <li><code>subtitleedit</code> (SubtitleEdit / <code>seconv</code>): the best choice for anything \u2192 SRT. It is the only backend that carries colour, and it embeds <code>{\\an8}</code> tags to preserve positioning. When writing TTML or WebVTT from ASS it flattens inline styling to plain text and keeps only positioning, so avoid it there.</li> <li><code>pysubs2</code>: keeps inline italic/underline on every pair, and bold except when writing SRT or WebVTT. It never carries positioning or colour. SSA/ASS is its native model, which makes it the best pick for SSA\u2194ASS.</li> <li><code>subby</code>: reads only WebVTT/fVTT/SAMI (never ASS) and is tuned for \u2192 SRT, where it uniquely converts WebVTT cue settings into <code>{\\an8}</code> positioning. Its <code>CommonIssuesFixer</code> may also drop near-duplicate cues.</li> <li><code>pycaption</code>: strips all styling; last-resort fallback only.</li> </ul> <p>What <code>auto</code> picks</p> <p><code>auto</code> prefers <code>subtitleedit</code> first when it is installed, then falls back to <code>subby</code> for \u2192 SRT and <code>pysubs2</code> otherwise. The one exception comes from the table above: for ASS/SSA \u2192 TTML or WebVTT it picks <code>pysubs2</code> even when SubtitleEdit is installed, since SubtitleEdit flattens inline styling on those pairs. Most installs do not ship SubtitleEdit, so in practice <code>auto</code> means <code>subby</code> (\u2192 SRT) or <code>pysubs2</code>. Install SubtitleEdit / <code>seconv</code> if you need colour or the highest \u2192 SRT fidelity.</p> <p>Config wins over a service's preference</p> <p>A service may set a <code>preferred_conversion_method</code> on its own tracks (for example when it ships subtitles that a particular backend handles best). An explicit <code>conversion_method</code> in <code>unshackle.yaml</code> always overrides that per-track preference, so your config takes precedence. This only matters when a service ships a non-default preference; leave <code>conversion_method</code> at <code>auto</code> to let the service's hint stand.</p>"},{"location":"guide/subtitles/#muxed-vs-sidecar-output","title":"Muxed vs. sidecar output","text":"<p>By default subtitles are muxed into the final <code>.mkv</code>. You can instead (or additionally) write them as separate sidecar files next to the video, controlled by the <code>output_mode</code> config key:</p> mux (default)sidecarboth unshackle.yaml<pre><code>subtitle:\n output_mode: mux\n</code></pre> <p>Subtitles are embedded in the Matroska file. Nothing is written separately.</p> unshackle.yaml<pre><code>subtitle:\n output_mode: sidecar\n sidecar_format: srt\n</code></pre> <p>Subtitles are written as standalone files and not muxed into the video (when there is a video or audio track to sit beside).</p> unshackle.yaml<pre><code>subtitle:\n output_mode: both\n sidecar_format: srt\n</code></pre> <p>Subtitles are muxed into the video and written as sidecar files.</p> <p>Sidecar files are named after the output file with the language and flags encoded in the name, so players and media managers can match them automatically:</p> <pre><code>Show.S01E01.1080p.WEB.en.srt\nShow.S01E01.1080p.WEB.en.forced.srt\nShow.S01E01.1080p.WEB.en.sdh.srt\n</code></pre> <p>The pattern is <code>{base}.{language}[.forced][.sdh].{extension}</code>. The sidecar file format is set by <code>sidecar_format</code>; use a format name like <code>srt</code> or <code>vtt</code>, or <code>original</code> to keep each subtitle in its downloaded format.</p>"},{"location":"guide/subtitles/#fonts-for-styled-subtitles","title":"Fonts for styled subtitles","text":"<p>Styled SSA/ASS subtitles reference specific fonts by name. When unshackle muxes such a subtitle it scans it for the fonts it uses and attaches the matching font files to the Matroska output so the styling renders correctly on playback. If a referenced font is not available locally, unshackle logs the missing font names and suggests installing the relevant font packages.</p>"},{"location":"guide/subtitles/#subtitle-configuration","title":"Subtitle configuration","text":"<p>All of the behaviour above can be defaulted in the <code>subtitle</code> block of your configuration file:</p> unshackle.yaml<pre><code>subtitle:\n strip_sdh: true\n preserve_formatting: true\n conversion_method: auto\n sdh_method: auto\n convert_before_strip: true\n output_mode: mux\n sidecar_format: srt\n</code></pre> Key Default Values Purpose <code>strip_sdh</code> <code>true</code> <code>true</code> / <code>false</code> Auto-generate a stripped non-SDH copy when a language has only an SDH track. <code>preserve_formatting</code> <code>true</code> <code>true</code> / <code>false</code> Keep original WebVTT styling and layout during sanitization. When <code>false</code>, WebVTT is re-encoded more aggressively (merging identical cues, dropping empty ones). <code>conversion_method</code> <code>auto</code> <code>auto</code>, <code>subby</code>, <code>pysubs2</code>, <code>subtitleedit</code>, <code>pycaption</code> Which conversion backend to prefer. <code>auto</code> ranks them per conversion. <code>sdh_method</code> <code>auto</code> <code>auto</code>, <code>subby</code>, <code>subtitleedit</code>, <code>filter-subs</code> Engine used to strip hearing-impaired cues. <code>convert_before_strip</code> <code>true</code> <code>true</code> / <code>false</code> Convert a subtitle to SRT before stripping SDH (for non-SubtitleEdit engines). <code>output_mode</code> <code>mux</code> <code>mux</code>, <code>sidecar</code>, <code>both</code> Whether subtitles are embedded, written as sidecars, or both. <code>sidecar_format</code> <code>srt</code> a format name (e.g. <code>srt</code>, <code>vtt</code>) or <code>original</code> Format used for sidecar files. <p>SubtitleEdit is optional but recommended</p> <p>Several high-fidelity paths (the best-quality conversions and the SubtitleEdit SDH stripper) only activate when the SubtitleEdit CLI is installed and on your <code>PATH</code>. See Installation for how to add it. Without it, unshackle falls back to its built-in Python backends.</p>"},{"location":"guide/subtitles/#developer-reference","title":"Developer reference","text":"<p>Audience</p> <p>This section is for people extending unshackle or writing services. Everyday users can stop here.</p> <p>The subtitle model lives in <code>unshackle.core.tracks.Subtitle</code>. A few internals worth knowing when working with subtitle tracks in code:</p> <ul> <li>Flags and validation: <code>Subtitle(codec=..., cc=..., sdh=..., forced=...)</code>. A track cannot be both <code>cc</code> and <code>sdh</code>, and <code>forced</code> cannot be combined with either; both raise <code>ValueError</code> at construction.</li> <li><code>convert(codec, *, forced=False)</code>: converts the downloaded file in place through the backend chain in <code>subtitle_convert.run_conversion</code>. <code>forced=True</code> (what <code>--sub-format</code> sets) is the only way lossy styled down-converts such as ASS\u2192SRT are permitted. Raises <code>NotImplementedError</code> if no backend supports the pair and <code>RuntimeError</code> if all attempts fail.</li> <li><code>strip_hearing_impaired()</code>: removes SDH cues using the engine selected by <code>config.subtitle[\"sdh_method\"]</code>.</li> <li><code>reverse_rtl()</code>: fixes right-to-left sentence-ending positioning via SubtitleEdit (requires the binary).</li> <li><code>parse(data, codec)</code>: the central parser, returning a <code>pycaption.CaptionSet</code>; it handles the boxed DASH formats, SAMI, and the WebVTT repair helpers.</li> <li><code>extract_fonts(text)</code>: returns the set of font names referenced by an ASS/SSA subtitle, used to decide which fonts to attach at mux time.</li> </ul> <p>The conversion backends (<code>SubtitleEditBackend</code>, <code>SubbyBackend</code>, <code>Pysubs2Backend</code>, <code>PycaptionBackend</code>) each implement a small protocol (<code>is_available()</code>, <code>can_convert()</code>, <code>rank()</code>, <code>convert()</code>) and are tried in rank order, lowest rank first. See the Tracks API reference for the full model.</p>"},{"location":"guide/troubleshooting/","title":"Troubleshooting &amp; Debugging","text":"<p>When a download fails, a service misbehaves, or a key won't resolve, unshackle gives you three tools to find out why:</p> <ul> <li>Debug logging: verbose <code>DEBUG</code>-level console output plus a structured, machine-readable log file.</li> <li><code>unshackle env</code>: verify that the external tools unshackle depends on are installed, and see exactly which directories and config file are in use.</li> <li>Targeted toggles: <code>debug_keys</code> and <code>debug_requests</code> for the two areas (DRM keys and raw HTTP traffic) that are deliberately quiet by default.</li> </ul> <p>The sections below cover how to enable each of them, how to read what they produce, and which diagnostic fits which failure mode.</p>"},{"location":"guide/troubleshooting/#turning-on-debug-logging","title":"Turning on debug logging","text":"<p>There are two independent ways to enable debug logging, and they do slightly different things.</p> The <code>-d</code> / <code>--debug</code> flagThe <code>debug</code> config key <p>The root-level flag turns on verbose logging for a single invocation:</p> <pre><code>unshackle -d dl SERVICE TITLE_ID\n</code></pre> <p>It must come before the subcommand, because it is an option on the root <code>unshackle</code> command, not on <code>dl</code>.</p> <p><code>-d</code> does three things:</p> <ol> <li>Sets the console log level to <code>DEBUG</code>, so every module logs its full detail.</li> <li>Enables the structured JSON debug log file (see below).</li> <li>Adds source-path annotations to console log lines (which file and line each message came from).</li> </ol> <p>To make debug logging the default for every run without typing <code>-d</code> each time, set it in your <code>unshackle.yaml</code>:</p> <pre><code>debug: true\n</code></pre> <p>or via the <code>cfg</code> command:</p> <pre><code>unshackle cfg debug true\n</code></pre> <p><code>debug: true</code> is not identical to <code>-d</code></p> <p>The <code>debug</code> config key enables the JSON debug log file, but it does not raise the console to <code>DEBUG</code> level and does not add source-path annotations. Those only happen when you pass the <code>-d</code> flag. Use the flag when you want to watch the verbose output live; use the config key when you just want the log file written every time. Passing <code>-d</code> is the most complete option, and you can combine both.</p> <p>Debug logging can be noisy and revealing</p> <p>Debug output is verbose and includes request metadata, service internals, and stack traces. Secrets, URLs, and local paths are automatically redacted (see Redaction), but you should still glance over a log before sharing it publicly.</p>"},{"location":"guide/troubleshooting/#the-structured-json-debug-log","title":"The structured JSON debug log","text":"<p>Beyond the console output, unshackle writes a structured log in JSON Lines format: one complete JSON object per line. This file is designed to be filtered, searched, and analysed with standard tooling (<code>jq</code>, <code>grep</code>, a text editor), and it is safe to attach to a bug report because it is redacted.</p>"},{"location":"guide/troubleshooting/#where-it-is-written","title":"Where it is written","text":"<p>The debug log is created during a <code>dl</code> run (and by <code>import</code>, which wraps <code>dl</code>). The path is:</p> <pre><code>&lt;logs directory&gt;/unshackle_debug_&lt;service&gt;_&lt;timestamp&gt;.jsonl\n</code></pre> <p>For example, <code>unshackle_debug_EXAMPLE_20260703-142530.jsonl</code>. The <code>&lt;service&gt;</code> tag and the timestamp mean each download gets its own file, so runs never overwrite each other.</p> <p>Find your logs directory</p> <p>The logs directory defaults to a <code>logs</code> folder inside the package data directory, but it can be relocated with the <code>directories.logs</code> config key. To see the exact resolved path on your machine, run <code>unshackle env info</code> and read the Directories table.</p>"},{"location":"guide/troubleshooting/#what-a-log-entry-looks-like","title":"What a log entry looks like","text":"<p>Every line is a self-contained JSON object. The first line of a session records the environment:</p> <pre><code>{\"timestamp\":\"2026-07-03T14:25:30.123456+00:00\",\"session_id\":\"a1b2c3d4\",\"level\":\"INFO\",\"operation\":\"session_start\",\"message\":\"Debug logging session started\",\"context\":{\"unshackle_version\":\"5.3.0\",\"python_version\":\"3.12.4 ...\",\"platform\":\"Linux-6.18.5-x86_64\",\"platform_system\":\"Linux\",\"platform_release\":\"6.18.5\"}}\n</code></pre> <p>Subsequent lines describe operations: service calls, DRM licence requests, vault lookups, downloader progress, and errors. Common fields include:</p> Field Meaning <code>timestamp</code> UTC ISO-8601 time of the entry. <code>session_id</code> Short random ID shared by every entry in one run, handy for correlating lines. <code>level</code> <code>DEBUG</code>, <code>INFO</code>, <code>WARNING</code>, or <code>ERROR</code>. <code>operation</code> The action being logged, e.g. <code>service_call</code>, <code>download_init</code>, <code>drm_get_widevine_license</code>, <code>vault_get_key</code>, <code>session_end</code>. <code>message</code> Human-readable description (redacted). <code>service</code> Service tag the entry belongs to, when applicable. <code>context</code> Arbitrary structured detail for the operation. <code>request</code> / <code>response</code> HTTP method/URL and response metadata for network operations. <code>duration_ms</code> How long a timed operation took. <code>success</code> Whether the operation succeeded. <code>error</code> On failures: the exception <code>type</code>, <code>message</code>, and a full <code>traceback</code> array (all redacted)."},{"location":"guide/troubleshooting/#reading-and-filtering-the-log","title":"Reading and filtering the log","text":"<p>Because each line is independent JSON, <code>jq</code> is the natural tool:</p> <pre><code># Show only error-level entries\njq 'select(.level == \"ERROR\")' unshackle_debug_EXAMPLE_20260703-142530.jsonl\n\n# List every operation and whether it succeeded\njq -c '{operation, success}' unshackle_debug_EXAMPLE_20260703-142530.jsonl\n\n# Pull the traceback out of the first error\njq -r 'select(.error) | .error.traceback[]' unshackle_debug_EXAMPLE_20260703-142530.jsonl\n\n# Show only DRM / licensing operations\njq 'select(.operation | startswith(\"drm_\"))' unshackle_debug_EXAMPLE_20260703-142530.jsonl\n</code></pre> <p>The session's binary-tool versions (Shaka Packager, mp4decrypt, mkvmerge, FFmpeg, FFprobe) are logged near the start of a <code>dl</code> run, which is often the fastest way to confirm a muxing or decryption failure is really a wrong-version problem.</p>"},{"location":"guide/troubleshooting/#debugging-drm-keys-with-debug_keys","title":"Debugging DRM keys with <code>debug_keys</code>","text":"<p>By default, content-decryption keys are redacted in the JSON debug log. Any field that looks like a key is written as <code>[REDACTED]</code>. This keeps logs shareable. When you are specifically debugging a key-retrieval or decryption problem and need to see the actual KID/KEY values that were fetched, enable <code>debug_keys</code>:</p> <pre><code>debug_keys: true\n</code></pre> <pre><code>unshackle cfg debug_keys true\n</code></pre> <p>With <code>debug_keys: true</code>, the debug log stops masking key fields, so you can confirm which keys came back from a licence server or vault and compare them against what decryption expected.</p> <p>Keys are sensitive, turn this back off</p> <p><code>debug_keys</code> writes real decryption keys into the log file in cleartext. Only enable it while actively diagnosing a key issue, never share a log produced with it on, and set it back to <code>false</code> when you're done. Note that <code>debug_keys</code> only affects the JSON debug log file. It does not change what the console prints.</p> <p>Fields that are always redacted regardless of <code>debug_keys</code> (anything whose name contains <code>password</code>, <code>token</code>, <code>secret</code>, <code>auth</code>, or <code>cookie</code>) stay masked, so credentials never leak even in a keys-on log.</p>"},{"location":"guide/troubleshooting/#debugging-http-traffic-with-debug_requests","title":"Debugging HTTP traffic with <code>debug_requests</code>","text":"<p>When you pass <code>-d</code>, unshackle raises its own modules to <code>DEBUG</code> but deliberately silences the noisy low-level HTTP libraries (<code>urllib3</code>, <code>requests</code>, <code>rnet</code>, <code>httpx</code>, <code>httpcore</code>, <code>hpack</code>, <code>h2</code>) back down to <code>WARNING</code>. Without this, a single download would bury the useful output under thousands of connection-pool and HTTP/2 frame messages.</p> <p>If you need that low-level traffic (for example when a request is failing at the TLS or connection layer and you need to see the underlying library's own logs), enable <code>debug_requests</code>:</p> <pre><code>debug_requests: true\n</code></pre> <pre><code>unshackle cfg debug_requests true\n</code></pre> <p>With <code>debug_requests: true</code>, those libraries are left at <code>DEBUG</code> level when you run with <code>-d</code>, so their request/response chatter appears in the console.</p> <p><code>debug_requests</code> needs <code>-d</code> to have any effect</p> <p>The <code>debug_requests</code> toggle only decides whether the HTTP libraries are silenced when the <code>-d</code> flag is active. If you are not running with <code>-d</code> (verbose console logging), it changes nothing. Combine them: <code>unshackle -d dl ...</code> with <code>debug_requests: true</code> in config.</p>"},{"location":"guide/troubleshooting/#what-gets-redacted","title":"What gets redacted","text":"<p>unshackle redacts logged strings so that debug output is safe to share. Three passes are applied to every logged message, error, and structured value:</p> <ul> <li>Secrets: passwords, tokens, API secrets, auth values, and cookies are replaced with <code>[REDACTED]</code>.</li> <li>URLs: every <code>http(s)</code> URL is collapsed to <code>redacted</code> (keeping only the file extension, so a manifest still shows as <code>redacted.mpd</code> and a segment as <code>redacted.m4s</code>). This hides content, CDN, manifest, and licence-server locations while preserving the type of resource.</li> <li>Local paths: install-root, virtualenv, and home-directory prefixes are replaced with tokens, so your username and machine layout don't appear in logs.</li> </ul> <p>Path redaction is controlled by the <code>redact_paths</code> config key, which is on by default:</p> <pre><code>redact_paths: true # default - mask local base directories in logged paths\n</code></pre> <p>Set <code>redact_paths: false</code> if you are debugging a path problem locally and want to see full, unmasked paths in the console and logs. Secret and URL redaction in the JSON debug log are always applied and are not affected by this toggle.</p>"},{"location":"guide/troubleshooting/#checking-your-environment","title":"Checking your environment","text":"<p>Many \"download failed\" problems are really missing external tools or a config file that isn't where you think it is. The <code>unshackle env</code> command group answers both questions before you dig into logs.</p>"},{"location":"guide/troubleshooting/#env-check","title":"<code>env check</code>","text":"<p><code>unshackle env check</code> verifies every external binary unshackle can use and prints a table of what's installed:</p> <pre><code>unshackle env check\n</code></pre> <p>It reports each tool's status (<code>\u2713</code> installed / <code>\u2717</code> missing), whether it is required or optional, and what it's for. A summary line tells you the installed-vs-total count and, if anything mandatory is absent, exactly which required tools are missing.</p> <p>The required tools (unshackle will not get far without them) are:</p> Tool Purpose FFmpeg Media processing FFprobe Media analysis MKVToolNix (<code>mkvmerge</code>) MKV muxing mkvpropedit MKV metadata Shaka Packager DRM decryption <p>Optional tools unlock extra capabilities. For example, <code>mp4decrypt</code> (alternative decryptor), <code>dovi_tool</code> / <code>HDR10Plus_tool</code> (Dolby Vision / HDR10+), <code>SubtitleEdit</code> / <code>CCExtractor</code> (subtitle conversion and CC extraction), <code>MPV</code> / <code>FFplay</code> (playback preview), and <code>git</code> (service repositories) or <code>docker</code> (Gluetun VPN, see Proxies &amp; VPN).</p> <p>First thing to run when something breaks</p> <p>If a decryption step errors, a mux fails, or a Dolby Vision title won't process, run <code>unshackle env check</code> first. A red <code>\u2717</code> next to the relevant tool is the answer far more often than a bug in unshackle.</p>"},{"location":"guide/troubleshooting/#env-info","title":"<code>env info</code>","text":"<p><code>unshackle env info</code> shows where unshackle is reading configuration from and where every working directory lives:</p> <pre><code>unshackle env info\n</code></pre> <ul> <li>If a config file was found, it prints the path it was loaded from. If none was found, it lists every location it would accept one (see Config file discovery below), so you can create the file in the right place.</li> <li>It then prints a Directories table for every configured path: <code>downloads</code>, <code>temp</code>, <code>cache</code>, <code>cookies</code>, <code>logs</code>, <code>exports</code>, <code>wvds</code>, <code>prds</code>, the <code>services</code> search paths, and more.</li> </ul> <p>This is the authoritative way to answer \"where are my logs / downloads / cookies actually going?\" The defaults are relative to the installed package, and any <code>directories:</code> overrides in your config are reflected here.</p>"},{"location":"guide/troubleshooting/#env-clear","title":"<code>env clear</code>","text":"<p>Stale cache or leftover temp files can cause confusing behaviour (an old cached title list, a half-written temp file). <code>env clear</code> wipes those directories safely:</p> <pre><code>unshackle env clear cache # clear the whole cache directory\nunshackle env clear cache EXAMPLE # clear just one service's cache subdirectory\nunshackle env clear temp # clear the temp working directory\n</code></pre> <p>Each command reports how many files it removed and how much space it freed, then recreates the empty directory.</p> <p>Cache-related weirdness</p> <p>If a service keeps returning stale titles or metadata even after the source changed, clear that service's cache with <code>unshackle env clear cache &lt;SERVICE&gt;</code>. See Vaults for the separate, persistent key-vault store, which <code>env clear</code> does not touch.</p>"},{"location":"guide/troubleshooting/#common-failure-modes-and-how-to-inspect-them","title":"Common failure modes and how to inspect them","text":"<p>A required tool is missing</p> <p>Symptom: decryption, muxing, or analysis fails early, sometimes with a \"binary not found\" style error.</p> <p>Inspect: run <code>unshackle env check</code> and look for a red <code>\u2717</code> on a required row. Install the missing tool and re-run.</p> <p>Decryption produces garbage or fails</p> <p>Symptom: the download completes but the file won't play, or the decrypt step errors.</p> <p>Inspect: enable <code>debug_keys</code> and run with <code>-d</code>, then check the JSON debug log's <code>drm_*</code> and <code>vault_*</code> operations to confirm which keys were fetched and from where. Also confirm Shaka Packager (or <code>mp4decrypt</code>) shows a sane version in the <code>download_init</code> binary-versions entry. See DRM &amp; CDM.</p> <p>A network request fails at the connection or TLS layer</p> <p>Symptom: timeouts, connection resets, or handshake errors that unshackle's own logs don't fully explain.</p> <p>Inspect: set <code>debug_requests: true</code> and run with <code>-d</code> to surface the underlying <code>urllib3</code> / <code>rnet</code> / <code>httpx</code> logs. In the JSON debug log, filter for <code>service_call</code> operations to see which request failed. If a proxy is involved, cross-check Proxies &amp; VPN.</p> <p>The wrong titles/metadata keep coming back</p> <p>Symptom: a service returns outdated titles even after the source changed.</p> <p>Inspect: the title cache is likely serving stale data. Clear it with <code>unshackle env clear cache &lt;SERVICE&gt;</code>, or bypass it for one run using the <code>dl</code> no-cache / reset-cache options (see Downloading and the CLI Reference).</p> <p>A config value doesn't seem to apply</p> <p>Symptom: a setting you edited has no effect.</p> <p>Inspect: run <code>unshackle env info</code> to confirm which config file is actually loaded, and <code>unshackle cfg --list</code> to dump the effective values. It's common to edit a config file in a location unshackle isn't reading from. See below.</p>"},{"location":"guide/troubleshooting/#why-is-my-config-not-being-picked-up","title":"Why is my config not being picked up?","text":"<p>unshackle loads the first <code>unshackle.yaml</code> it finds, in this order:</p> <ol> <li><code>unshackle.yaml</code> inside the package's namespace directory.</li> <li><code>unshackle.yaml</code> in the parent of that directory.</li> <li><code>unshackle.yaml</code> in your OS user-config directory: on Linux <code>~/.config/unshackle/unshackle.yaml</code>, on Windows <code>%LOCALAPPDATA%\\unshackle\\unshackle.yaml</code>, on macOS <code>~/Library/Application Support/unshackle/unshackle.yaml</code>.</li> </ol> <p>If you have config in more than one of these, an earlier one wins and your edits to a later file are silently ignored. <code>unshackle env info</code> prints the path that was actually loaded (or, if none exists, lists all three candidate locations so you can create the file correctly). See Configuration for editing values with the <code>cfg</code> command.</p> <p>Developer note: structured logging in code</p> <p>Service and command code emits entries through the shared <code>log_event(...)</code> helper (and the <code>timed_operation(...)</code> context manager for timing a block) from <code>unshackle.core.utilities</code>. These are no-ops when debug logging is disabled, so they are always safe to leave in place. When adding a new feature, call <code>log_event(\"my_feature_event\", message=\"...\", context={...})</code> rather than reimplementing the \"is the logger enabled?\" guard. The redaction and JSON-serialisation are handled for you, and any field whose name looks like a key/secret/token is redacted automatically (keys only appear when the run has <code>debug_keys</code> enabled).</p>"},{"location":"guide/troubleshooting/#logging-conventions-when-adding-entries","title":"Logging conventions when adding entries","text":"<p>The debug log is tuned for developers troubleshooting pipeline flow (maximum signal, minimum noise), not for end users. A few conventions keep it that way. They are not enforced by the <code>log_event</code> signature, so they are easy to miss and worth stating explicitly.</p> <p>Log levels are a flow skeleton, not just severity</p> <p>Treat <code>level</code> as structure, not decoration. Emit exactly one <code>INFO</code> milestone per pipeline stage so that <code>jq 'select(.level==\"INFO\")'</code> reads back the whole end-to-end flow of a run. Everything internal goes to <code>DEBUG</code>; failures go to <code>ERROR</code>. Keeping <code>INFO</code> sparse is the whole point. It is the line a developer skims first to see where a run got to before it broke.</p> <pre><code># Read the pipeline's high-level flow, one line per stage\njq 'select(.level == \"INFO\")' unshackle_debug_EXAMPLE_20260703-142530.jsonl\n</code></pre> <p>No raw dumps</p> <p>Never log a full <code>Tracks</code> object, an MPD/manifest body, or a response payload. Log only counts, ids, sizes, and <code>safe_display_url(url)</code>. This keeps the log low-noise and prevents leaking content or manifest data into the file before redaction even runs. Redaction is a backstop, not a licence to dump raw objects.</p> <p>Operation names: <code>&lt;area&gt;_&lt;event&gt;</code>, no registry</p> <p>Operation names are plain lowercase strings following an <code>&lt;area&gt;_&lt;event&gt;</code> convention: <code>manifest_dash_parse</code>, <code>drm_decrypt</code>, <code>vault_get_key</code>, <code>tool_run</code>. They are written inline at each call site on purpose: there is no central registry or enum, and you should not go hunting for one or create one. The absence is a deliberate design choice, not an omission.</p> <p>Message reads alone; data lives in fields</p> <p>Give every entry a single-sentence <code>message</code> that stands on its own, and put all structured data (<code>context</code>, counts, ids, <code>duration_ms</code>) in fields rather than baking it into the prose. This separation is what lets the log be both human-scannable and machine-filterable; a message like <code>\"Parsed DASH manifest\"</code> with <code>context={\"video\": 4, \"audio\": 2}</code> beats <code>\"Parsed manifest with 4 video and 2 audio tracks\"</code>.</p> <p>Let tool runs log themselves</p> <p>For external-tool calls (FFmpeg, mkvmerge, <code>dovi_tool</code>, and friends), route through <code>run_step</code> / <code>ffprobe</code>, which auto-emit a <code>tool_run</code> entry capturing the binary's version, return code, and duration consistently. Only fall back to calling <code>log_tool_run</code> manually for a direct <code>subprocess.run</code> you genuinely can't route through <code>run_step</code>. Auto-logging is the preferred path precisely because it captures those fields the same way every time.</p>"},{"location":"guide/vaults/","title":"Key Vaults","text":"<p>A key vault is a store of DRM content keys that unshackle remembers between downloads. Once a title's keys have been recovered, unshackle saves them to your configured vaults. The next time you download something that reuses those same keys, unshackle finds them in a vault instead of performing another license exchange. The download starts faster and puts less load on the service.</p> <p>Vaults are entirely optional, but if you download regularly they are one of the biggest quality-of-life improvements you can configure.</p> <p>Vaults save license calls even on the very first download</p> <p>The benefit is not limited to repeat downloads. Within a single run, a service often issues the same Key ID and content key for both the video and audio tracks, and for several resolutions or bitrates of the same title. Once unshackle has recovered a key it writes it to your vaults immediately, so the moment the next track presents a KID it has already seen, the key is served from the vault instead of triggering another license exchange. A single fetched key can therefore satisfy many tracks in one run.</p>"},{"location":"guide/vaults/#what-a-vault-stores","title":"What a vault stores","text":"<p>Every key is stored as a KID \u2192 KEY pair, grouped by service:</p> <ul> <li>KID (Key ID): a 16-byte identifier for a specific encrypted stream, stored as 32 lowercase hex characters with no dashes.</li> <li>KEY: the 16-byte content key that decrypts that stream, also 32 hex characters.</li> <li>Service: the canonical service tag (for example <code>EXAMPLE</code>, not <code>ExampleService</code>) that namespaces the key. Each service gets its own logical table.</li> </ul> <p>Why keys are matched by KID</p> <p>Vaults match keys by KID, never by PSSH/CENC header. A KID does not change unless the underlying video file itself changes, whereas the PSSH box can vary between requests for the very same content. That makes the KID a far more reliable match key.</p> <p>Null keys are ignored everywhere</p> <p>A key made entirely of zeroes (<code>00000000000000000000000000000000</code>) is treated as \"no key\". Vault lookups skip it, and every backend raises an error if you try to add one. This prevents a placeholder key from masking a real one.</p>"},{"location":"guide/vaults/#how-lookups-and-caching-work","title":"How lookups and caching work","text":"<p>When unshackle needs a key during a download it asks your vaults in the order they are listed in your config. It returns the first non-null key it finds and stops searching. If a vault raises a permission error or is unreachable, that vault is skipped and the search continues with the next one.</p> <p>When new keys are recovered from a license, unshackle pushes them to all configured vaults, so every vault gradually converges on the same set of keys. Two rules apply to pushing:</p> <ul> <li>Keys that already exist in a vault are skipped (existing data is never overwritten or deleted).</li> <li>A vault marked <code>no_push: true</code> receives lookups but is never written to. This is useful for read-only or shared upstream vaults you do not own.</li> </ul> <p>A good two-vault setup</p> <p>A common arrangement is a fast local SQLite vault plus a shared remote vault (MySQL, HTTP, or API). The local vault answers instantly and works offline; the remote vault lets you share keys across machines or with a group.</p>"},{"location":"guide/vaults/#configuring-vaults","title":"Configuring vaults","text":"<p>Vaults are declared under the <code>key_vaults</code> list in your unshackle config file. Each entry is a mapping with two required fields, <code>type</code> (which backend to use) and <code>name</code> (a label you choose), plus whatever settings that backend needs.</p> unshackle.yaml<pre><code>key_vaults:\n - type: SQLite\n name: local\n path: ~/.local/share/unshackle/vaults/local.db\n - type: MySQL\n name: shared\n host: vault.example.com\n database: unshackle\n username: reader\n password: \"s3cret\"\n</code></pre> <p>The <code>type</code> value is matched to a vault backend by name. The four backends that ship with unshackle are <code>SQLite</code>, <code>MySQL</code>, <code>HTTP</code>, and <code>API</code>, described below.</p> <p>SQLite vaults are loaded critically</p> <p>During a download, a SQLite vault that fails to load will abort the run. The assumption is that a local database you configured should always be available. <code>MySQL</code>, <code>HTTP</code>, and <code>API</code> vaults are loaded leniently: if one fails to load it is logged and skipped, and the download continues with the remaining vaults.</p>"},{"location":"guide/vaults/#vault_timeout","title":"<code>vault_timeout</code>","text":"<p>Network-backed vaults (<code>HTTP</code> and <code>API</code>) accept an optional per-vault <code>timeout</code> in seconds. If you omit it, unshackle injects the global default:</p> unshackle.yaml<pre><code>vault_timeout: 10.0 # default, in seconds\n</code></pre> <p>A <code>timeout</code> set inline on an individual vault always wins over this global value. The <code>SQLite</code> and <code>MySQL</code> backends do not take a <code>timeout</code> field.</p>"},{"location":"guide/vaults/#sqlite-backend","title":"SQLite backend","text":"<p>A locally-accessed SQLite database file. This is the simplest and fastest option and needs no server.</p> unshackle.yaml<pre><code>key_vaults:\n - type: SQLite\n name: local\n path: ~/.local/share/unshackle/vaults/local.db\n</code></pre> Field Required Description <code>type</code> yes Must be <code>SQLite</code>. <code>name</code> yes A label for this vault. <code>path</code> yes Path to the database file. <code>~</code> is expanded. The file (and its tables) are created automatically on first use. <code>no_push</code> no If <code>true</code>, keys are read but never written. Defaults to <code>false</code>. <p>Each service gets its own table (named after the service tag), created on demand with <code>kid</code> and <code>key_</code> columns. Connections use WAL journaling with a 30-second busy timeout, so the same database file can be used safely from multiple threads.</p> <p>Moving the .db file silently forks your vault</p> <p>Because the file is created on demand, if you relocate an existing <code>.db</code> without updating <code>path</code> to match, unshackle will simply create a fresh empty database at the old location, leaving you with two divergent vaults and no error to warn you. Always update the config path whenever you move the file.</p> <p>Keep a local SQLite vault even when you share a MySQL one</p> <p>The SQLite vault is best thought of as an offline-only backup should anything ever happen to a shared <code>MySQL</code> vault. Each member of a group should keep their own local SQLite vault alongside the shared database, so no one loses their keys if the shared vault goes down or away.</p>"},{"location":"guide/vaults/#mysql-backend","title":"MySQL backend","text":"<p>A remotely-accessed MySQL/MariaDB database, ideal for sharing keys across several machines. It connects via <code>pymysql</code>. MariaDB is recommended over MySQL where you have the choice.</p> <p>The vault connects directly to the database server</p> <p>A <code>MySQL</code> vault (like <code>SQLite</code>) speaks the database wire protocol directly to the host or IP you configure. It cannot sit behind a PHP API or any other application layer. A common real-world snag: many hosting providers firewall their MySQL server to their own internal network, so a database on shared hosting is frequently unreachable from the outside world even when your credentials are perfectly correct. If connections time out, confirm the server accepts remote connections from your address before suspecting the config.</p> unshackle.yaml<pre><code>key_vaults:\n - type: MySQL\n name: shared\n host: vault.example.com\n database: unshackle\n username: unshackle\n password: \"your-password\"\n port: 3306\n</code></pre> Field Required Description <code>type</code> yes Must be <code>MySQL</code>. <code>name</code> yes A label for this vault. <code>host</code> yes Database server hostname or IP. <code>database</code> yes Database (schema) name. <code>username</code> yes Login user. <code>no_push</code> no If <code>true</code>, keys are read but never written. <p>Any additional fields you provide (such as <code>password</code>, <code>port</code>, or <code>ssl</code>) are passed straight through to <code>pymysql.connect</code>, so you can use the full range of its connection options.</p> <p>Account security is on you, not on unshackle</p> <p>unshackle enforces none of this. It is operational policy for a database that may be shared with a group. Never connect with the <code>root</code> account, not even for yourself. Give every account a password, and never let two users share a username/password. Restrict each account's access to only the <code>unshackle</code> database, and grant normal users just <code>SELECT</code> and <code>INSERT</code>. Reserve the <code>CREATE</code> grant for a single trusted user who bootstraps the service tables (see <code>kv prepare</code>); everyone else can insert new keys but should not be creating tables.</p> <p>Grants determine what the vault can do</p> <p>On connection the backend reads its own <code>SHOW GRANTS</code>. It requires at least <code>SELECT</code> to load at all (a missing <code>SELECT</code> grant makes the vault fail to load). Writing keys additionally needs <code>INSERT</code>, and creating a new service table needs <code>CREATE</code>. A read-only account still works fine as a lookup source. It simply cannot push new keys. Because <code>MySQL</code> is loaded leniently during downloads, a permission problem will not abort the run.</p>"},{"location":"guide/vaults/#http-backend","title":"HTTP backend","text":"<p>A flexible HTTP vault that speaks one of three wire protocols, selected with <code>api_mode</code>. Use this to integrate with a community or self-hosted vault service.</p> <code>api_mode</code> Transport Authentication Notes <code>query</code> (default) <code>GET</code> with query parameters <code>username</code> + <code>password</code> Full read and write. <code>json</code> <code>POST</code> with a JSON payload <code>password</code> used as a token Read and write per key; cannot bulk-enumerate keys. <code>decrypt_labs</code> <code>POST</code> in DecryptLabs format <code>api_key</code> sent as a header Read-only. <code>no_push</code> is forced on. query modejson modedecrypt_labs mode unshackle.yaml<pre><code>key_vaults:\n - type: HTTP\n name: community\n host: https://vault.example.com/api\n api_mode: query\n username: myuser\n password: \"your-password\"\n</code></pre> <p><code>username</code> is required in query mode. Both the username and password are sent as query parameters on each request.</p> unshackle.yaml<pre><code>key_vaults:\n - type: HTTP\n name: jsonvault\n host: https://vault.example.com/rpc\n api_mode: json\n password: \"your-api-token\"\n</code></pre> <p>Requests are <code>POST</code>ed as <code>{\"method\": ..., \"params\": ..., \"token\": ...}</code> using methods like <code>GetKey</code>, <code>InsertKey</code>, and <code>GetServices</code>. This mode cannot list all keys in bulk, so a <code>kv copy</code> from a json vault relies on the remote server's own duplicate handling.</p> unshackle.yaml<pre><code>key_vaults:\n - type: HTTP\n name: decrypt_labs\n host: https://api.decryptlabs.example/\n api_mode: decrypt_labs\n api_key: \"your-decrypt-labs-key\"\n</code></pre> <p>A read-only lookup source. The key is sent in a <code>decrypt-labs-api-key</code> header and the vault refuses all writes.</p> Field Required Description <code>type</code> yes Must be <code>HTTP</code>. <code>name</code> yes A label for this vault. <code>host</code> yes Base URL of the vault API. <code>api_mode</code> no <code>query</code> (default), <code>json</code>, or <code>decrypt_labs</code>. <code>username</code> for <code>query</code> Required in query mode; ignored otherwise. <code>password</code> one of these Password (query mode) or token (json mode). <code>api_key</code> one of these Alternative to <code>password</code>; used for <code>decrypt_labs</code>. If both are given, <code>api_key</code> wins. <code>no_push</code> no Read-only when <code>true</code> (always <code>true</code> for <code>decrypt_labs</code>). <code>timeout</code> no Request timeout in seconds; defaults to <code>vault_timeout</code>. <p>You must supply either <code>password</code> or <code>api_key</code>, or the vault will fail to load.</p>"},{"location":"guide/vaults/#api-backend","title":"API backend","text":"<p>A simple RESTful HTTP vault with a fixed, well-defined protocol. Authentication is a bearer token.</p> unshackle.yaml<pre><code>key_vaults:\n - type: API\n name: myapi\n uri: https://vault.example.com/api\n token: \"your-bearer-token\"\n</code></pre> Field Required Description <code>type</code> yes Must be <code>API</code>. <code>name</code> yes A label for this vault. <code>uri</code> yes Base URI of the vault API (a trailing slash is trimmed). <code>token</code> yes Bearer token, sent as <code>Authorization: Bearer &lt;token&gt;</code>. <code>no_push</code> no If <code>true</code>, keys are read but never written. <code>timeout</code> no Request timeout in seconds; defaults to <code>vault_timeout</code>. <p>The backend talks to endpoints under <code>uri</code> (for example <code>GET {uri}/{service}/{kid}</code> to look up a single key) and interprets a numeric <code>code</code> field in each JSON response to detect errors such as an invalid token, rate limiting, or an invalid service tag.</p> <p>This is unshackle's own protocol, not a generic vault client</p> <p>The <code>API</code> backend expects unshackle's specific HTTP request and response shape. An API or HTTP key-vault endpoint built for a different project or service will generally not be compatible. You cannot simply point this at an arbitrary third-party vault API and expect it to work. To bridge another service, put an adapter in front of it that speaks this format, or use the <code>HTTP</code> backend if one of its wire protocols matches. When pushing many keys at once it batches requests and automatically shrinks the batch size if the server rejects an over-large request.</p> <p>DecryptLabs shortcut</p> <p>An <code>API</code> vault whose <code>name</code> contains <code>decrypt_labs</code> will have its <code>token</code> filled in automatically from a global <code>decrypt_labs_api_key</code> in your config if you leave <code>token</code> unset. This lets you keep the key in one place.</p>"},{"location":"guide/vaults/#managing-vaults-with-unshackle-kv","title":"Managing vaults with <code>unshackle kv</code>","text":"<p>The <code>kv</code> command group manages the contents of your configured vaults. Every subcommand refers to vaults by the <code>name</code> you gave them in <code>key_vaults</code>; an unknown name is an error.</p> <pre><code>$ unshackle kv --help\n</code></pre>"},{"location":"guide/vaults/#kv-add-import-keys-from-a-file","title":"<code>kv add</code>: import keys from a file","text":"<p>Add <code>KID:KEY</code> pairs to one or more vaults for a given service. The file must contain one pair per line as <code>HEX:HEX</code> (32 hex characters each); lines that do not match are ignored.</p> <pre><code>$ unshackle kv add keys.txt EXAMPLE local shared\n</code></pre> keys.txt<pre><code>9a04f07998404286ab92e65be0885f95:b1c2d3e4f5a6978012345678deadbeef\n0e7cc1a4e2f9411db0f24a3fbb8f8b21:00112233445566778899aabbccddeeff\n</code></pre> <p>The service argument (<code>EXAMPLE</code> above) is normalized to its canonical tag automatically. Keys that already exist in a vault are reported as skipped.</p>"},{"location":"guide/vaults/#kv-search-find-a-key-by-kid","title":"<code>kv search</code>: find a key by KID","text":"<p>Search your vaults for a KID and print any matching key.</p> <pre><code>$ unshackle kv search 9a04f07998404286ab92e65be0885f95\n</code></pre> <p>The KID must be 32 hex characters (dashes are stripped for you). By default every configured vault and every service table is scanned; narrow the search with options:</p> Option Description <code>-s</code>, <code>--service</code> Limit the search to a single service tag. <code>-v</code>, <code>--vault</code> Limit the search to one configured vault by name. <p>Note</p> <p>Remote vaults that cannot enumerate their service tables (for example an <code>HTTP</code> vault in <code>json</code> or <code>decrypt_labs</code> mode) can only be searched when you also pass <code>--service</code>. Without it, they are skipped.</p>"},{"location":"guide/vaults/#kv-copy-copy-keys-between-vaults","title":"<code>kv copy</code>: copy keys between vaults","text":"<p>Copy every key from one or more source vaults into a single destination vault. Existing rows are never altered; only genuinely new KIDs are added, and null keys are skipped.</p> <pre><code>$ unshackle kv copy shared local\n</code></pre> <p>The first argument is the destination; the rest are sources. You can supply several sources at once:</p> <pre><code>$ unshackle kv copy local shared community\n</code></pre> Option Description <code>-s</code>, <code>--service</code> Only copy the given service. <code>-l</code>, <code>--local-only</code> Only copy services you have installed locally, skipping tables for unknown services. <p><code>--service</code> and <code>--local-only</code> are mutually exclusive.</p>"},{"location":"guide/vaults/#kv-sync-mirror-vaults-both-ways","title":"<code>kv sync</code>: mirror vaults both ways","text":"<p>Ensure two or more vaults each end up with every key the others have. This is effectively a two-way <code>copy</code> between each pair, so afterwards all listed vaults hold the same set of keys.</p> <pre><code>$ unshackle kv sync local shared\n</code></pre> <p>It accepts the same <code>--service</code> and <code>--local-only</code> options as <code>copy</code>, and requires at least two vaults.</p>"},{"location":"guide/vaults/#kv-prepare-pre-create-service-tables","title":"<code>kv prepare</code>: pre-create service tables","text":"<p>Create the per-service tables on table-based vaults (<code>SQLite</code>, <code>MySQL</code>) ahead of time, for every service you have installed. Vaults that do not use tables (the network-backed <code>HTTP</code> and <code>API</code> backends) are skipped.</p> <pre><code>$ unshackle kv prepare shared\n</code></pre> <p>This is mainly useful with a <code>MySQL</code> vault where you want the tables created once by an account that has the <code>CREATE</code> grant.</p>"},{"location":"guide/vaults/#see-also","title":"See also","text":"<ul> <li>Downloading: how keys are recovered and used during a download.</li> </ul>"},{"location":"reference/configuration/","title":"Configuration Reference","text":"<p>This page is the exhaustive, authoritative reference for every key you can set in <code>unshackle.yaml</code>. For each key you will find its name, expected type, default value, and what it does. Keys are grouped by area so you can jump straight to the part of unshackle you are configuring.</p> <p>If you are new to the config file (where it lives, how unshackle discovers it, and how to edit it), start with The Configuration File. This page assumes you already know the basics and want precise details.</p> <p>How defaults work</p> <p>Every key is optional. If you omit a key, unshackle uses the built-in default listed here. There is no schema validation: unknown keys are silently ignored (they never become settings), and the file is parsed with <code>yaml.safe_load</code>. An empty or missing file means all defaults apply.</p> <p>Two keys behave specially on load</p> <ul> <li><code>curl_impersonate</code> is a deprecated alias of <code>network</code> and emits a <code>DeprecationWarning</code>.</li> <li><code>scene_naming</code> has been removed. If it is present at all, unshackle exits immediately with an error telling you to use <code>output_template</code> instead.</li> </ul> <p>See Deprecated &amp; removed keys at the end of this page.</p>"},{"location":"reference/configuration/#quick-index","title":"Quick index","text":"Area Keys Directories <code>directories</code>, <code>filenames</code> Services &amp; authentication <code>services</code>, <code>credentials</code>, <code>firefox_cookies</code>, <code>remote_services</code>, <code>serve</code> Download &amp; processing <code>dl</code>, <code>subtitle</code>, <code>audio</code>, <code>muxing</code>, <code>language_tags</code> Output &amp; naming <code>output_template</code>, <code>tag</code>, <code>tag_group_name</code>, <code>tag_imdb_tmdb</code>, <code>chapter_fallback_name</code>, <code>unicode_filenames</code> DRM &amp; CDM <code>cdm</code>, <code>remote_cdm</code>, <code>decryption</code> Network &amp; proxy <code>network</code>, <code>headers</code>, <code>proxy_providers</code> Key vaults <code>key_vaults</code>, <code>vault_timeout</code> External API keys <code>imdb_api_enabled</code>, <code>omdb_api_key</code>, <code>tmdb_api_key</code>, <code>simkl_client_id</code>, <code>decrypt_labs_api_key</code>, <code>ipinfo_api_key</code> Caching &amp; updates <code>title_cache_enabled</code>, <code>title_cache_time</code>, <code>title_cache_max_retention</code>, <code>update_checks</code>, <code>update_check_interval</code> Logging, privacy &amp; debug <code>redact_paths</code>, <code>debug</code>, <code>debug_keys</code>, <code>debug_requests</code>, <code>set_terminal_bg</code> Deprecated &amp; removed <code>curl_impersonate</code>, <code>downloader</code>, <code>scene_naming</code>"},{"location":"reference/configuration/#directories","title":"Directories","text":"<p>The <code>directories</code> key is a dict mapping directory names to filesystem paths. Only the names listed below are honoured; a handful are protected and cannot be moved (attempts to override them are silently skipped). All defaults are computed relative to the installed package, and every user-settable path is passed through <code>Path(...).expanduser()</code>, so <code>~</code> works.</p> unshackle.yaml<pre><code>directories:\n downloads: ~/Media/unshackle\n temp: /mnt/fast-scratch/unshackle-temp\n wvds: ~/.unshackle/WVDs\n prds: ~/.unshackle/PRDs\n</code></pre> Key Type Default Overridable Purpose <code>downloads</code> path <code>&lt;repo&gt;/downloads</code> \u2705 Default output directory for finished files. <code>temp</code> path <code>&lt;repo&gt;/temp</code> \u2705 Temporary working files during download/decrypt/mux. <code>cache</code> path <code>&lt;data&gt;/cache</code> \u2705 Generic cache, title cache, and the update-check store. <code>cookies</code> path <code>&lt;data&gt;/cookies</code> \u2705 Per-service cookie files (and VPN cookie/token files). <code>logs</code> path <code>&lt;data&gt;/logs</code> \u2705 Log files. <code>exports</code> path <code>&lt;data&gt;/exports</code> \u2705 Export JSON files. <code>wvds</code> path <code>&lt;data&gt;/WVDs</code> \u2705 Widevine device files (<code>.wvd</code>). <code>prds</code> path <code>&lt;data&gt;/PRDs</code> \u2705 PlayReady device files (<code>.prd</code>). <code>dcsl</code> path <code>&lt;data&gt;/DCSL</code> \u2705 DCSL data. <code>commands</code> path <code>unshackle/commands</code> \u2705 CLI command modules. <code>services</code> list | path <code>[unshackle/services]</code> \u2705 Service search paths and/or remote repo specs (see below). <code>vaults</code> path <code>unshackle/vaults</code> \u2705 Vault backend modules. <code>fonts</code> path <code>unshackle/fonts</code> \u2705 Bundled fonts. <code>user_configs</code> path <code>unshackle/</code> \u274c protected Where <code>unshackle.yaml</code> lives. <code>data</code> path <code>unshackle/</code> \u274c protected Base for the data subdirectories above. <code>core_dir</code> path <code>unshackle/core</code> \u274c protected Package core. <code>namespace_dir</code> path <code>unshackle/</code> \u274c protected Package root. <code>app_dirs</code> - <code>AppDirs(\"unshackle\", False)</code> \u274c protected Internal AppDirs instance. <p>The <code>services</code> directory is special</p> <p><code>services</code> may be a list, and each entry can be either a local directory or a repository spec: a git URL (<code>https://...</code>, <code>ssh://...</code>, <code>git@...</code>, or anything ending in <code>.git</code>) or <code>owner/repo</code> shorthand. Repo specs are cloned and updated automatically; plain paths are used as-is. List order is priority: the first source to define a service tag wins, so put your own local service directories last to make them fallbacks.</p> <pre><code>directories:\n services:\n - unshackle-dl/community-services # cloned from GitHub\n - https://example.com/private.git@stable\n - ~/my-services # local, lowest priority\n</code></pre> <p>How git-backed service repos are handled</p> <p>unshackle's use of git is read-only on the remote: it only ever performs a shallow <code>clone</code>, <code>fetch</code>, <code>pull</code>, and a local <code>reset</code>; nothing is ever pushed. Private repos are authenticated through your existing git credential helper, and unshackle stores no tokens of its own. Clones live under <code>&lt;first-local-services-dir&gt;/_repos/&lt;repo-name&gt;/</code> (or the bundled <code>unshackle/services</code>), and nothing is written to the cache directory. After the first clone unshackle re-pulls at most once every 24 h, so it does not touch the network on every run.</p> <p>The two refresh paths diverge on purpose</p> <p>The automatic 24 h-TTL refresh that happens during a normal <code>dl</code>/<code>search</code> run will deliberately refuse to refresh and exit (naming the offending clone) if that clone has uncommitted changes to tracked files or unpushed local commits, so a background pull can never clobber work in progress. Untracked files (new service folders, <code>__pycache__</code>) never block it. The manual <code>unshackle util refresh-services</code> command does the opposite: it hard-resets the clone to upstream, discarding any local edits. Reach for the manual command only when you actually want to throw local changes away.</p> <p>Read-only installs and reinstalls</p> <p>If the services directory lives inside the installed package, a reinstall can delete the <code>_repos</code> clones. They are simply re-cloned on next use. On read-only installs you must point <code>services</code> at a writable path, or cloning will fail.</p>"},{"location":"reference/configuration/#filenames","title":"Filenames","text":"<p>The <code>filenames</code> key is a dict of templated file/name patterns. Each value is used verbatim (no path processing). Braced fields like <code>{time}</code> and <code>{service}</code> are filled in at runtime.</p> Key Type Default Notes <code>log</code> str <code>\"unshackle_{name}_{time}.log\"</code> Written under <code>directories.logs</code>. <code>debug_log</code> str <code>\"unshackle_debug_{service}_{time}.jsonl\"</code> Structured debug log, under <code>directories.logs</code>. <code>config</code> str <code>\"config.yaml\"</code> Per-service config file, under that service's directory. <code>root_config</code> str <code>\"unshackle.yaml\"</code> The main config filename itself. <code>chapters</code> str <code>\"Chapters_{title}_{random}.txt\"</code> Under <code>directories.temp</code>. <code>subtitle</code> str <code>\"Subtitle_{id}_{language}.srt\"</code> Under <code>directories.temp</code>."},{"location":"reference/configuration/#services-auth","title":"Services &amp; authentication","text":""},{"location":"reference/configuration/#services","title":"<code>services</code>","text":"<ul> <li>Type: <code>dict</code> keyed by service tag \u00a0\u00b7\u00a0 Default: <code>{}</code></li> </ul> <p>Per-service configuration, keyed by the canonical service tag (for example <code>EXAMPLE1</code>, <code>EXAMPLE2</code>, <code>EXAMPLE3</code>). unshackle reads several well-known sub-keys out of each service's block:</p> <ul> <li><code>proxy_map</code>: a dict mapping <code>\"provider:query\"</code> or <code>\"query\"</code> to a proxy value, used to auto-select a proxy for that service.</li> <li><code>title_map</code>: an exact-match rename map applied to fetched titles (source name \u2192 desired name), so a service that names a title differently from your library still matches.</li> </ul> <p>Individual services may read any additional keys they define. The whole block is handed to the service as <code>self.config</code>.</p> <p>Why put secrets here and not in the service's own <code>config.yaml</code>?</p> <p>A service ships a per-service <code>config.yaml</code> inside its own folder, and that file is typically shared/committed and not meant to be edited by you. So anything user- or device-specific (API keys, account IDs, device attributes) belongs in this <code>services</code> block of <code>unshackle.yaml</code> instead, where it is merged over the service's <code>config.yaml</code> at load time. That is why the two config locations exist: one for shared service defaults, one for your private overrides.</p> <pre><code>services:\n EXAMPLE1:\n proxy_map:\n default: us\n title_map:\n \"My Show: The Movie\": \"My Show Presents The Movie\"\n</code></pre>"},{"location":"reference/configuration/#credentials","title":"<code>credentials</code>","text":"<ul> <li>Type: <code>dict</code> keyed by service tag \u00a0\u00b7\u00a0 Default: <code>{}</code></li> </ul> <p>Per-service login credentials. Each value is a <code>username:password[:extra]</code> string (a list or dict form is also accepted where a service supports it). These are parsed into <code>Credential</code> objects; the credential's SHA-1 is also used as an account hash for cache keys.</p> <pre><code>credentials:\n EXAMPLE2: user@example.com:hunter2\n EXAMPLE1:\n - primary@example.com:pw1\n - secondary@example.com:pw2\n</code></pre> <p>Cookies vs credentials</p> <p>Cookies are stored as files under <code>directories.cookies</code>, not in this key. A service's <code>authenticate()</code> accepts cookies, credentials, or both.</p>"},{"location":"reference/configuration/#firefox_cookies","title":"<code>firefox_cookies</code>","text":"<ul> <li>Type: <code>dict</code> \u00a0\u00b7\u00a0 Default: <code>{}</code></li> </ul> <p>Settings for extracting cookies directly from a local Firefox profile. A service block is expected to provide <code>hosts</code> (a list of cookie hostnames; entries shorter than 3 characters are ignored to prevent dumping the whole cookie store) and an optional <code>local_storage</code> boolean to also pull matching local-storage entries. Extraction is read-only.</p> <p>Firefox does not need to be closed</p> <p>The extractor copies both <code>cookies.sqlite</code> and its WAL file into a <code>0700</code> temp directory; the WAL copy exists to capture writes Firefox has not yet flushed to the main DB, so the copy is current even against a running browser. The only real constraint is that Firefox must not hold an exclusive write lock at the exact instant of the copy. The live profile is otherwise left untouched.</p> <p>When you actually need <code>local_storage: true</code></p> <p>Enable it only for services that keep their auth tokens in the browser's localStorage (<code>webappsstore.sqlite</code>) rather than in HTTP cookies. If a service authenticates with plain cookies, leaving it off is correct.</p> <p>Extraction fails silently to file cookies</p> <p>If extraction yields no cookies or fails for any reason, unshackle silently falls back to the normal file-based cookie path (<code>cookies/&lt;SERVICE&gt;.txt</code> or <code>cookies/&lt;SERVICE&gt;/&lt;profile&gt;.txt</code>). This is a safety net, but it also means that if you expected Firefox cookies and file cookies are being used instead, extraction quietly failed. Check that first when troubleshooting.</p>"},{"location":"reference/configuration/#remote_services","title":"<code>remote_services</code>","text":"<ul> <li>Type: <code>dict</code> \u00a0\u00b7\u00a0 Default: <code>{}</code></li> </ul> <p>Definitions of remote unshackle service servers, used by the <code>--remote</code> mode. Each entry carries a <code>services</code> sub-dict of remote service tags, which unshackle turns into synthetic CLI commands that run against the remote server.</p>"},{"location":"reference/configuration/#serve","title":"<code>serve</code>","text":"<ul> <li>Type: <code>dict</code> \u00a0\u00b7\u00a0 Default: <code>{}</code></li> </ul> <p>Configuration for the <code>serve</code> command (the built-in REST API server). The full server guide is the REST API section; these are the config keys.</p> Sub-key Type Default Description <code>api_secret</code> str (unset) Master secret accepted in the <code>X-Secret-Key</code> header. <code>users</code> dict <code>{}</code> Per-user API keys and their allowlists (see below). <code>services</code> list (unset) Global service allowlist. Omit to allow all. <code>remote_only</code> bool <code>false</code> Run without a local <code>output_template</code> (CORS/Cloudflare-friendly). <code>session_ttl</code> int (s) <code>300</code> Lifetime of an interactive auth session. <code>max_sessions</code> int <code>100</code> Maximum concurrent sessions. <code>history_limit</code> int <code>100</code> How many finished jobs to retain in history. <code>compression_level</code> int <code>1</code> gzip level for responses. <code>cdm_overrides</code> dict (unset) Allowed per-request CDM overrides. <code>allow_job_credentials</code> bool <code>false</code> Permit clients to supply credentials per job. <code>devices</code> list (auto) Widevine devices offered; auto-filled from <code>directories.wvds</code>. <code>playready_devices</code> list (auto) PlayReady devices; auto-filled from <code>directories.prds</code>. <code>country</code> / <code>locations</code> str / dict (unset) Advertised region metadata. <p>Each entry under <code>users</code> is keyed by that user's API key and may set its own <code>services</code>, <code>devices</code>, and <code>playready_devices</code> allowlists, narrowing the global ones.</p> <pre><code>serve:\n api_secret: change-me\n remote_only: true\n services: [EXAMPLE1, EXAMPLE2]\n # server-wide download defaults (same keys as the `dl:` block)\n downloads: 3\n best_available: true\n users:\n a1b2c3d4: # this user's API key\n services: [EXAMPLE1] # may only use EXAMPLE1\n</code></pre> <p>Declaring <code>dl</code> defaults under <code>serve</code></p> <p>You can set any <code>dl</code> flag key (<code>downloads</code>, <code>workers</code>, <code>best_available</code>, and so on) directly inside <code>serve</code>. The point is to raise concurrency and behaviour defaults server-wide (every request the server handles picks them up) without having to change each client call individually.</p>"},{"location":"reference/configuration/#download-processing","title":"Download &amp; processing","text":""},{"location":"reference/configuration/#dl","title":"<code>dl</code>","text":"<ul> <li>Type: <code>dict</code> \u00a0\u00b7\u00a0 Default: <code>{}</code></li> </ul> <p>Persistent defaults for the <code>dl</code> command. This block is used as Click's <code>default_map</code>, so any <code>dl</code> flag can be given a default here and it applies to every download without you typing it. See Downloading and the CLI Reference for what each flag does.</p> <p>Key naming. A key is the flag's long name with dashes replaced by underscores (<code>--best-available</code> \u2192 <code>best_available</code>, <code>--sub-format</code> \u2192 <code>sub_format</code>). A few keys are named after the flag's internal destination rather than its visible name; set these exact keys:</p> Flag Config key <code>-r</code> / <code>--range</code> <code>range</code> <code>--list</code> <code>list</code> <code>--tmdb</code> <code>tmdb_id</code> <code>--imdb</code> <code>imdb_id</code> <code>--animeapi</code> <code>animeapi_id</code> <code>-naa</code> / <code>--noatmos</code> <code>no_atmos</code> <code>-o</code> / <code>--output</code> <code>output_dir</code> <code>--cdm-only</code> / <code>--vaults-only</code> <code>cdm_only</code> <p>Precedence (highest first): an explicit CLI flag or environment variable \u2192 a per-service <code>services.&lt;TAG&gt;.dl</code> override \u2192 this global <code>dl:</code> block \u2192 the built-in default. In other words, config only fills in options you did not set on the command line.</p> <p>Common keys (a useful subset; every <code>dl</code> flag works):</p> Key Type Default Sets <code>lang</code> list <code>[\"orig\"]</code> Video/audio language(s); <code>orig</code> = original language. <code>a_lang</code> / <code>v_lang</code> list <code>[]</code> Audio- / video-only language override. <code>s_lang</code> list <code>[\"all\"]</code> Subtitle language(s). <code>quality</code> list <code>[]</code> (best) Resolution(s), e.g. <code>[1080]</code>. <code>vcodec</code> list <code>[]</code> (any) Video codec(s), e.g. <code>[H265]</code>. <code>acodec</code> list <code>[]</code> (any) Audio codec(s), e.g. <code>[EC3]</code>. <code>range</code> list <code>[\"SDR\"]</code> Colour range(s): <code>SDR</code>, <code>HDR10</code>, <code>HDR10+</code>, <code>DV</code>. <code>channels</code> float (unset) Audio channels, e.g. <code>6</code> for 5.1. <code>sub_format</code> str (unset) Convert subtitles to this format (<code>srt</code>, <code>vtt</code>, <code>original</code>, ...). <code>forced_subs</code> bool <code>false</code> Include forced subtitle tracks. <code>no_subs</code> / <code>no_audio</code> / <code>no_chapters</code> bool <code>false</code> Skip that track type. <code>downloads</code> int <code>1</code> Tracks downloaded concurrently. <code>workers</code> int (downloader default) Threads per track. <code>slow</code> str (unset) Inter-title delay, e.g. <code>\"20-40\"</code>. <code>best_available</code> bool <code>false</code> Fall back to best quality if the request is unavailable. <code>proxy</code> str (unset) Default proxy URI or 2-letter country. <code>no_folder</code> bool <code>false</code> Do not create a per-title folder. Global download defaults<pre><code>dl:\n lang: [en]\n quality: [1080]\n range: [HDR10]\n vcodec: [H265]\n sub_format: srt\n downloads: 2\n</code></pre> <p>Per-service overrides</p> <p>Nest a <code>dl</code> block under a service in <code>services</code> to override these defaults for just that service. It uses the same keys and wins over the global <code>dl:</code> block (but still loses to an explicit CLI flag).</p> <pre><code>dl:\n lang: [en] # global default\nservices:\n EXAMPLE1:\n dl:\n lang: [en, ja] # EXAMPLE1 downloads both; everything else stays English\n range: [DV]\n</code></pre> <p><code>serve</code> uses these same keys</p> <p>The <code>serve</code> block accepts the same <code>dl</code> option keys at its top level to set server-wide download defaults for every request it handles.</p>"},{"location":"reference/configuration/#subtitle","title":"<code>subtitle</code>","text":"<ul> <li>Type: <code>dict</code> \u00a0\u00b7\u00a0 Default: <code>{}</code></li> </ul> <p>Subtitle handling: SDH stripping, format conversion, and whether subtitles are muxed in or written as sidecar files. See Subtitles for the full guide.</p> Sub-key Type Default Description <code>strip_sdh</code> bool <code>true</code> Strip SDH/CC cues (hearing-impaired annotations) into a clean track. <code>sdh_method</code> str <code>\"auto\"</code> SDH-stripping backend to use. <code>preserve_formatting</code> bool <code>true</code> Keep styling/positioning when converting or stripping. <code>convert_before_strip</code> bool <code>true</code> Convert to the working format before stripping SDH. <code>conversion_method</code> str <code>\"auto\"</code> Subtitle conversion backend. <code>preferred_conversion_method</code> str (unset) Preferred converter when several are available. <code>output_mode</code> str <code>\"mux\"</code> <code>mux</code> embeds subtitles in the MKV; <code>sidecar</code> writes separate files. <code>sidecar_format</code> str <code>\"srt\"</code> Format for sidecar files when <code>output_mode: sidecar</code>. <code>type_priority</code> list (unset) Ordered ranking of subtitle types (<code>forced</code>, <code>normal</code>, <code>sdh</code>; CC counts as SDH) that sorts the variants within each language. Types you leave out fall to the end. <pre><code>subtitle:\n strip_sdh: true\n output_mode: sidecar\n sidecar_format: srt\n</code></pre> <p><code>type_priority</code> also picks the default subtitle</p> <p><code>type_priority</code> sorts the tracks within each language, and at mux time the first track in the default subtitle language gets the <code>default</code> flag. The built-in order is <code>forced</code>, <code>normal</code>, <code>sdh</code>, which means a forced track becomes default whenever one exists. If you want the full dialogue track as default instead, set:</p> <pre><code>subtitle:\n type_priority: [normal, sdh, forced]\n</code></pre>"},{"location":"reference/configuration/#audio","title":"<code>audio</code>","text":"<ul> <li>Type: <code>dict</code> \u00a0\u00b7\u00a0 Default: <code>{}</code></li> </ul> <p>Audio handling options. The most notable sub-key is <code>codec_priority</code>, an ordered list of audio codecs used to break ties in track selection.</p> <pre><code>audio:\n codec_priority:\n - EAC3\n - AC3\n</code></pre> <p><code>codec_priority</code> is a soft priority: nothing is dropped</p> <p><code>codec_priority</code> only breaks ties among tracks that share the same bitrate and language. Codecs not in the list keep their normal bitrate-based ordering and are simply placed after all listed codecs, and none are ever removed. Two higher-level rules still override it: Atmos tracks always take precedence over <code>codec_priority</code>, and audio-description tracks are always forced to the end regardless of it. When <code>codec_priority</code> is unset, tracks sort by bitrate alone, with those same Atmos/descriptive rules still applied.</p>"},{"location":"reference/configuration/#muxing","title":"<code>muxing</code>","text":"<ul> <li>Type: <code>dict</code> \u00a0\u00b7\u00a0 Default: <code>{}</code></li> </ul> <p>Matroska (MKV) muxing options.</p> Sub-key Type Default Description <code>set_title</code> bool <code>true</code> Write a human-readable title into the MKV container. <code>default_language</code> dict <code>{}</code> Force which language is flagged default per track type, e.g. <code>{audio: en, subtitle: en}</code>. <code>merge_audio</code> bool <code>true</code> Merge all audio into one file. <code>--split-audio</code> on the CLI flips this off. <code>merge_video</code> bool <code>false</code> Merge all video tracks into one file. <code>--merge-video</code> on the CLI flips this on. <pre><code>muxing:\n set_title: true\n default_language:\n audio: en\n subtitle: en\n</code></pre>"},{"location":"reference/configuration/#language_tags","title":"<code>language_tags</code>","text":"<ul> <li>Type: <code>dict</code> \u00a0\u00b7\u00a0 Default: <code>{}</code></li> </ul> <p>Language-tag remapping and the rule engine behind the <code>{lang_tag}</code> filename variable. When a <code>rules</code> list is present, each rule is evaluated in order and the first match's <code>tag</code> is used. A rule may test:</p> Condition Meaning <code>audio</code> Matches against the audio track languages. <code>subs_contain</code> At least one subtitle language matches. <code>subs_contain_all</code> Every listed language must be present (scalar or list). <pre><code>language_tags:\n rules:\n - audio: [en]\n subs_contain_all: [en]\n tag: \"\" # native English release, no tag\n - audio: [ja]\n subs_contain: [en]\n tag: \"SUBBED\"\n</code></pre>"},{"location":"reference/configuration/#output-naming","title":"Output &amp; naming","text":"<p>For the full picture of how templates render, see Output &amp; naming. The keys are summarised here.</p>"},{"location":"reference/configuration/#output_template","title":"<code>output_template</code>","text":"<ul> <li>Type: <code>dict</code> \u00a0\u00b7\u00a0 Default: <code>{}</code></li> </ul> <p>Filename templates keyed by media kind, using <code>{variable}</code> placeholders. Recognised kinds are <code>movies</code>, <code>series</code>, and <code>songs</code> (and <code>albums</code> for folder templates). A trailing <code>?</code> on a variable (e.g. <code>{quality?}</code>) marks it optional: if empty, it and one adjacent separator are dropped.</p> unshackle.yaml<pre><code>output_template:\n movies: \"{title}.{year}.{quality?}.{source}-{tag}\"\n series: \"{title}.{season_episode}.{episode_name?}.{quality?}.{source}-{tag}\"\n songs: \"{track_number}. {title}\"\n folder: # special nested key, see below\n movies: \"{title} ({year})\"\n series: \"{title} ({year})\"\n</code></pre> <p>The nested <code>folder</code> sub-key controls output subfolders and is popped out of <code>output_template</code>:</p> <ul> <li>A dict sets per-kind folder templates (kinds: <code>movies</code>, <code>series</code>, <code>songs</code>, <code>albums</code>).</li> <li>A str sets a single folder template for everything.</li> </ul> <p>unshackle validates templates on load and emits warnings for unknown variables, non-string values, filesystem-unsafe characters (<code>&lt; &gt; : \" / \\ | ? *</code>), empty templates, and unknown folder-kind keys.</p> All valid template variables <p><code>title</code>, <code>year</code>, <code>season</code>, <code>episode</code>, <code>season_episode</code>, <code>episode_name</code>, <code>date</code>, <code>quality</code>, <code>resolution</code>, <code>source</code>, <code>tag</code>, <code>track_number</code>, <code>artist</code>, <code>album_artist</code>, <code>album</code>, <code>disc</code>, <code>track_total</code>, <code>disc_total</code>, <code>release_type</code>, <code>genre</code>, <code>explicit</code>, <code>isrc</code>, <code>upc</code>, <code>label</code>, <code>audio</code>, <code>audio_channels</code>, <code>audio_full</code>, <code>atmos</code>, <code>dual</code>, <code>multi</code>, <code>video</code>, <code>hdr</code>, <code>hfr</code>, <code>edition</code>, <code>repack</code>, <code>lang_tag</code>.</p>"},{"location":"reference/configuration/#tagging-naming-keys","title":"Tagging &amp; naming keys","text":"Key Type Default Description <code>tag</code> str <code>\"\"</code> Release-group tag appended to filenames and written into MKV tags. <code>tag_group_name</code> bool <code>true</code> Include the group name (<code>tag</code>) in the MKV <code>Group</code> tag. <code>tag_imdb_tmdb</code> bool <code>true</code> Write IMDb/TMDB/TVDB external-ID tags into the MKV (needs metadata providers). <code>chapter_fallback_name</code> str <code>\"\"</code> Fallback chapter-name template, e.g. <code>\"Chapter {i:02}\"</code>. <code>unicode_filenames</code> bool <code>false</code> Allow Unicode in filenames; when <code>false</code>, names are ASCII-sanitised."},{"location":"reference/configuration/#drm-cdm","title":"DRM &amp; CDM","text":"<p>The full conceptual guide lives at DRM &amp; CDM. These are the config keys. Device files themselves live in <code>directories.wvds</code> (<code>.wvd</code>) and <code>directories.prds</code> (<code>.prd</code>).</p>"},{"location":"reference/configuration/#cdm","title":"<code>cdm</code>","text":"<ul> <li>Type: <code>dict</code> \u00a0\u00b7\u00a0 Default: <code>{}</code></li> </ul> <p>Maps a service tag to the CDM (Widevine/PlayReady device) to use, with a <code>default</code> fallback. Resolution is case-insensitive: an explicit CLI override wins, then the per-service entry, then <code>default</code>.</p> <pre><code>cdm:\n default: chromecdm_l3\n EXAMPLE2: android_l1\n</code></pre> <p>A value may also be a nested dict for advanced selection by quality, DRM system, or profile:</p> <pre><code>cdm:\n EXAMPLE1:\n \"&gt;=1080\": android_l1 # by track height\n \"&lt;1080\": chromecdm_l3\n widevine: android_l1 # by DRM system\n playready: sl3000\n default: chromecdm_l3\n</code></pre> <p>Quality keys support <code>1080</code>, <code>&gt;=1080</code>, <code>&gt;720</code>, <code>&lt;=576</code>, <code>&lt;480</code> style comparisons; DRM keys are <code>widevine</code> / <code>playready</code>.</p>"},{"location":"reference/configuration/#remote_cdm","title":"<code>remote_cdm</code>","text":"<ul> <li>Type: <code>list[dict]</code> \u00a0\u00b7\u00a0 Default: <code>[]</code></li> </ul> <p>A list of remote CDM server definitions. Each entry is matched by its <code>name</code> (referenced from <code>cdm</code>), and its <code>type</code> selects the backend:</p> <code>type</code> Backend Key fields <code>decrypt_labs</code> Decrypt Labs KeyXtractor <code>host</code> (default <code>https://keyxtractor.decryptlabs.com</code>), <code>device_name</code>, <code>secret</code> (falls back to <code>decrypt_labs_api_key</code>) <code>custom_api</code> Fully YAML-configurable remote API <code>device</code>, <code>auth</code>, <code>endpoints</code>, <code>request_mapping</code>, <code>response_mapping</code>, <code>caching</code>, <code>timeout</code> (none), <code>Device Type: PLAYREADY</code> pyplayready <code>RemoteCdm</code> <code>host</code>, <code>secret</code>, <code>device_name</code>, <code>security_level</code> (default 3000) (none), otherwise pywidevine <code>RemoteCdm</code> <code>host</code>, <code>secret</code>, <code>device_name</code>, <code>device_type</code>, <code>system_id</code>, <code>security_level</code> (default 3000) <pre><code>remote_cdm:\n - name: keyxtractor\n type: decrypt_labs\n device_name: L1\n - name: my_wv_server\n host: https://cdm.example.com\n secret: s3cr3t\n device_name: android_l1\n device_type: ANDROID\n system_id: 26830\n security_level: 1\n</code></pre>"},{"location":"reference/configuration/#decryption","title":"<code>decryption</code>","text":"<ul> <li>Type: <code>str</code> or <code>dict</code> \u00a0\u00b7\u00a0 Default: <code>\"shaka\"</code></li> </ul> <p>Selects the tool used to physically decrypt CENC content. The value is compared case-insensitively; <code>\"mp4decrypt\"</code> selects Bento4's mp4decrypt, and anything else (including <code>\"shaka\"</code>) selects shaka-packager.</p> GlobalPer-service <pre><code>decryption: shaka\n</code></pre> <pre><code>decryption:\n default: shaka\n SOMESERVICE: mp4decrypt\n</code></pre>"},{"location":"reference/configuration/#network-proxy","title":"Network &amp; proxy","text":""},{"location":"reference/configuration/#network","title":"<code>network</code>","text":"<ul> <li>Type: <code>dict</code> \u00a0\u00b7\u00a0 Default: <code>{}</code></li> </ul> <p>TLS-fingerprinting and HTTP client settings for the rnet-based session.</p> Sub-key Type Default Description <code>browser</code> str <code>\"Chrome131\"</code> Impersonation preset. Must be an exact preset name (e.g. <code>Chrome131</code>, <code>Firefox135</code>, <code>Edge101</code>, <code>Safari18</code>, <code>OkHttp4_12</code>, <code>OkHttp5</code>, <code>Opera118</code>); unknown names raise an error. <code>http1_only</code> bool (unset) Force HTTP/1.1. <code>http2_only</code> bool (unset) Force HTTP/2. <code>pool_max_idle_per_host</code> int (unset) Connection-pool tuning. <code>pool_max_size</code> int (unset) Connection-pool tuning. <code>tcp_nodelay</code> bool (unset) Disable Nagle's algorithm. <pre><code>network:\n browser: Firefox135\n http2_only: true\n</code></pre> <p>When to force <code>http1_only</code></p> <p>HTTP/2 is the right default on large CDNs, so leave it on. Force HTTP/1.1 only for a host that throttles per-connection, or a slow origin stuck behind HTTP/2 flow control. In benchmarks this won 30 to 50% on such hosts but cost up to 27% on fast CDNs, so enable it only when your own measurements justify it.</p> <p>Renamed from <code>curl_impersonate</code></p> <p>The old <code>curl_impersonate</code> section is a deprecated alias. If you still use it, unshackle honours it (only when <code>network</code> is absent) but emits a <code>DeprecationWarning</code>. Rename it to <code>network</code>.</p>"},{"location":"reference/configuration/#headers","title":"<code>headers</code>","text":"<ul> <li>Type: <code>dict</code> \u00a0\u00b7\u00a0 Default: <code>{}</code></li> </ul> <p>Default HTTP headers merged into every session unshackle creates.</p> <pre><code>headers:\n Accept-Language: en-US,en;q=0.9\n</code></pre> <p>Don't set <code>Accept-Encoding</code> (and similar) here</p> <p>Keep this block to sane cross-service defaults such as <code>Accept-Language</code> and <code>User-Agent</code>. Compatibility headers like <code>Accept-Encoding</code> are set for you by the rnet HTTP backend as part of its browser-impersonation profile, and overriding them can break the impersonation fingerprint. Anything useful to only some services belongs in that service's config, not here.</p>"},{"location":"reference/configuration/#proxy_providers","title":"<code>proxy_providers</code>","text":"<ul> <li>Type: <code>dict</code> \u00a0\u00b7\u00a0 Default: <code>{}</code></li> </ul> <p>Proxy/VPN provider configuration. Each sub-key names a provider, and its block is passed straight to that provider's constructor. See Proxies &amp; VPN for the full provider guide. Recognised providers and their exit ports:</p> Provider Config key Credentials Proxy scheme/port Basic (static) <code>basic</code> country \u2192 URI(s) as specified NordVPN <code>nordvpn</code> 48-char service credentials <code>https://...:89</code> Surfshark <code>surfsharkvpn</code> 48-char service credentials <code>https://...:443</code> Windscribe <code>windscribevpn</code> service credentials <code>https://...:443</code> ExpressVPN <code>expressvpn</code> device login (<code>enable: true</code>) / token cache <code>https://cat:...@...:443</code> ProtonVPN <code>protonvpn</code> TV login or exported cookies <code>https://...:4443</code> (or <code>:443</code> Secure Core) Gluetun <code>gluetun</code> per-VPN keys/creds <code>http://localhost:{port}</code> (local Docker) Hola (none, auto) none <code>http://...:{peer}</code> <pre><code>proxy_providers:\n basic:\n us: http://user:pass@1.2.3.4:8080\n de:\n - http://a.example:8080\n - socks5://b.example:1080\n nordvpn:\n username: &lt;48-char service username&gt;\n password: &lt;48-char service password&gt;\n</code></pre> <p>Provider loading differs between CLI and REST server</p> <p>The <code>dl</code> CLI loads all providers, including <code>windscribevpn</code> and <code>gluetun</code>. The REST API / remote-client path uses a separate resolver that does not load <code>windscribevpn</code> or <code>gluetun</code>. ExpressVPN and ProtonVPN also auto-load when their cached session exists, and Hola auto-loads whenever the <code>hola-proxy</code> binary is present.</p>"},{"location":"reference/configuration/#key-vaults","title":"Key vaults","text":"<p>The full guide is at Vaults. Two keys configure them.</p>"},{"location":"reference/configuration/#key_vaults","title":"<code>key_vaults</code>","text":"<ul> <li>Type: <code>list[dict]</code> \u00a0\u00b7\u00a0 Default: <code>[]</code></li> </ul> <p>An ordered list of key-vault backends. unshackle queries them in order and reuses content keys instead of re-licensing. Each entry needs a <code>type</code> (the backend module name) and a <code>name</code>, plus backend-specific keys.</p> <code>type</code> Purpose Required keys Notes <code>SQLite</code> Local SQLite database <code>name</code>, <code>path</code> Loaded critically; a failure aborts the run. <code>MySQL</code> Remote MySQL database <code>name</code>, <code>host</code>, <code>database</code>, <code>username</code> Extra keys (e.g. <code>password</code>, <code>port</code>) forwarded to pymysql. <code>API</code> RESTful JSON API <code>name</code>, <code>uri</code>, <code>token</code> Honours <code>vault_timeout</code>. <code>HTTP</code> HTTP API with modes <code>name</code>, <code>host</code>, one of <code>password</code>/<code>api_key</code> <code>api_mode</code>: <code>query</code> (default), <code>json</code>, <code>decrypt_labs</code>. <pre><code>key_vaults:\n - type: SQLite\n name: Local\n path: ~/.unshackle/keys.db\n - type: MySQL\n name: Team\n host: db.example.com\n database: keys\n username: unshackle\n password: hunter2\n no_push: false\n</code></pre> <p>Common per-entry options</p> <ul> <li><code>no_push: true</code> makes a vault read-only (keys are fetched but never written to it).</li> <li>A vault of <code>type: api</code> whose <code>name</code> contains <code>decrypt_labs</code> auto-fills its <code>token</code> from <code>decrypt_labs_api_key</code> when not set inline.</li> <li>An all-zero content key (32 zeros) is treated as \"no key\" everywhere and is never stored.</li> </ul>"},{"location":"reference/configuration/#vault_timeout","title":"<code>vault_timeout</code>","text":"<ul> <li>Type: <code>float</code> \u00a0\u00b7\u00a0 Default: <code>10.0</code></li> </ul> <p>Timeout in seconds for vault operations. Injected automatically into any backend whose constructor accepts a <code>timeout</code> parameter (a per-vault <code>timeout</code> still wins).</p>"},{"location":"reference/configuration/#external-api-keys","title":"External API keys","text":"<p>All default to an empty string and enable optional metadata/geolocation features.</p> Key Type Default Description <code>imdb_api_enabled</code> bool <code>false</code> Use the free IMDxAPI (api.tiffara.com) metadata provider, which needs no API key. Off by default since the site has been unreliable. <code>omdb_api_key</code> str <code>\"\"</code> OMDb API key for IMDb metadata lookups; a more reliable alternative to IMDxAPI. Free keys are available on the OMDb site. <code>tmdb_api_key</code> str <code>\"\"</code> TMDB API key for metadata enrichment and external-ID tags. <code>simkl_client_id</code> str <code>\"\"</code> SIMKL client ID for metadata lookups; an alternative/fallback source to TMDB. <code>decrypt_labs_api_key</code> str <code>\"\"</code> Global Decrypt Labs API key (used by remote CDM / vault). <code>ipinfo_api_key</code> str <code>\"\"</code> ipinfo.io API key for IP/region lookups. <p>SIMKL is a fallback for TMDB</p> <p>SIMKL is positioned as an alternative metadata source, and it is most valuable precisely when no <code>tmdb_api_key</code> is configured. It improves title-matching and tagging reliability in that case rather than replacing TMDB where TMDB is available.</p> <p><code>ipinfo_api_key</code> never touches your service sessions</p> <p>The token is only ever sent to <code>api.ipinfo.io</code> as a per-request <code>Authorization</code> header; it is never attached to your service session, so it cannot leak to a streaming provider. Lookups degrade gracefully through a fallback chain: the authenticated Lite endpoint (higher rate limits and richer fields) \u2192 anonymous ipinfo \u2192 <code>ip-api.in</code> as a last resort.</p>"},{"location":"reference/configuration/#caching-updates","title":"Caching &amp; updates","text":""},{"location":"reference/configuration/#title-cache","title":"Title cache","text":"<p>unshackle caches fetched title metadata (region- and account-aware) to avoid repeat API calls.</p> Key Type Default Description <code>title_cache_enabled</code> bool <code>true</code> Master switch for the title cache. <code>title_cache_time</code> int (seconds) <code>1800</code> (30 min) Lifetime of fresh cached titles. <code>title_cache_max_retention</code> int (seconds) <code>86400</code> (24 h) How long stale cached data may still be served as a fallback when a live fetch fails."},{"location":"reference/configuration/#update-checks","title":"Update checks","text":"Key Type Default Description <code>update_checks</code> bool <code>true</code> Whether to check for new unshackle releases. <code>update_check_interval</code> int (hours) <code>24</code> Minimum hours between update checks. <p>Note</p> <p>Update checks query the GitHub releases API with a fixed 5-second timeout and cache the result in <code>directories.cache/update_check.json</code>.</p>"},{"location":"reference/configuration/#logging-privacy-debug","title":"Logging, privacy &amp; debug","text":"Key Type Default Description <code>redact_paths</code> bool <code>true</code> Mask install-root / venv / home prefixes in logged paths (<code>&lt;unshackle&gt;</code>, <code>&lt;venv&gt;</code>, <code>~</code>). Set <code>false</code> to show full paths. <code>debug</code> bool <code>false</code> Global debug mode. <code>debug_keys</code> bool <code>false</code> Log decryption keys. <code>debug_requests</code> bool <code>false</code> Log HTTP requests. <code>set_terminal_bg</code> bool <code>false</code> Append the theme's background colour to output styling. <p>When to enable <code>set_terminal_bg</code></p> <p>When on, the theme's background colour is appended to the foreground styles so the full colour palette renders correctly on terminals whose default background differs from unshackle's theme. Turn it on if the ASCII-art banner or coloured output looks off on your terminal. Otherwise leave it off.</p> <p>Key exposure</p> <p>Decryption content keys are written to the structured debug log at INFO level during the DRM handshake. Treat <code>debug</code>, <code>debug_keys</code>, and the <code>unshackle_debug_*.jsonl</code> files as sensitive, and keep <code>redact_paths</code> enabled when sharing logs.</p> <p><code>debug_keys</code> affects only content-encryption keys (the <code>content_key</code>/<code>key</code> fields). Passwords, tokens, cookies, and session tokens are always redacted regardless of this setting, and KIDs, key counts, and other metadata are always logged either way.</p>"},{"location":"reference/configuration/#deprecated-removed-keys","title":"Deprecated &amp; removed keys","text":"Key Status Behaviour <code>curl_impersonate</code> Deprecated \u2192 use <code>network</code> Emits a <code>DeprecationWarning</code>; still honoured only if <code>network</code> is absent. <code>downloader</code> Deprecated Any value other than <code>\"requests\"</code> emits a <code>DeprecationWarning</code>; the value is otherwise ignored (the unified requests downloader is always used). <code>scene_naming</code> Removed If present at all, unshackle exits with an error directing you to configure <code>output_template</code> instead."},{"location":"reference/configuration/#a-complete-annotated-example","title":"A complete annotated example","text":"<p>The following config sets a handful of common keys. Every key not shown keeps its default.</p> unshackle.yaml<pre><code>directories:\n downloads: ~/Media/unshackle\n temp: /mnt/scratch/unshackle\n\nnetwork:\n browser: Chrome131\n\nheaders:\n Accept-Language: en-US,en;q=0.9\n\ncdm:\n default: chromecdm_l3\n EXAMPLE2: android_l1\n\ndecryption: shaka\n\ncredentials:\n EXAMPLE2: user@example.com:hunter2\n\noutput_template:\n movies: \"{title}.{year}.{quality?}.{source}-{tag}\"\n series: \"{title}.{season_episode}.{quality?}.{source}-{tag}\"\n folder:\n movies: \"{title} ({year})\"\n series: \"{title} ({year})\"\n\ntag: MYGRP\n\nkey_vaults:\n - type: SQLite\n name: Local\n path: ~/.unshackle/keys.db\n\nproxy_providers:\n basic:\n us: http://user:pass@1.2.3.4:8080\n\nomdb_api_key: \"your-omdb-key\"\ntmdb_api_key: \"your-tmdb-key\"\ntitle_cache_time: 3600\nredact_paths: true\n</code></pre> <p>For how these interact at runtime, continue to Downloading, DRM &amp; CDM, and Output &amp; naming.</p>"},{"location":"reference/api/config/","title":"Config API","text":"<p>Auto-generated reference for the <code>Config</code> object that models the <code>unshackle</code> configuration file. For a human-friendly walkthrough of every key, see the Configuration Reference.</p>"},{"location":"reference/api/config/#unshackle.core.config.Config","title":"Config","text":"<pre><code>Config(**kwargs)\n</code></pre>"},{"location":"reference/api/config/#unshackle.core.config.Config.get_folder_template","title":"get_folder_template","text":"<pre><code>get_folder_template(kind)\n</code></pre> <p>Resolve the folder template for the given title kind.</p> <p>kind: one of \"movies\", \"series\", \"songs\", \"albums\". Falls back to the legacy single-string folder template, then \"\".</p>"},{"location":"reference/api/config/#unshackle.core.config.Config.get_template_separator","title":"get_template_separator","text":"<pre><code>get_template_separator(template_type='movies')\n</code></pre> <p>Get the filename separator for the given template type.</p> <p>Analyzes the active template to determine whether it uses dots or spaces between variables. Falls back to dot separator (scene-style) by default.</p> <p>Parameters:</p> Name Type Description Default <code>template_type</code> <code>str</code> <p>One of \"movies\", \"series\", or \"songs\".</p> <code>'movies'</code>"},{"location":"reference/api/config/#unshackle.core.config.resolve_decryption","title":"resolve_decryption","text":"<pre><code>resolve_decryption(decryption_map, default, service)\n</code></pre> <p>Pick the decryption tool for a service (case-insensitive), falling back to default.</p>"},{"location":"reference/api/config/#unshackle.core.config.resolve_cdm_name","title":"resolve_cdm_name","text":"<pre><code>resolve_cdm_name(cdm, service, override=None)\n</code></pre> <p>Resolve a service's top-level CDM entry (case-insensitive), with default fallback.</p>"},{"location":"reference/api/config/#unshackle.core.config.get_config_path","title":"get_config_path","text":"<pre><code>get_config_path()\n</code></pre> <p>Get Path to Config from any one of the possible locations.</p> <p>Returns None if no config file could be found.</p>"},{"location":"reference/api/drm/","title":"DRM API","text":"<p>Auto-generated reference for the DRM systems: Widevine, PlayReady, ClearKey, and related helpers. For configuring DRM as a user, see DRM &amp; CDM Setup.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKey","title":"ClearKey","text":"<pre><code>ClearKey(key, iv=None)\n</code></pre> <p>AES Clear Key DRM System.</p> <p>Generally IV should be provided where possible. If not provided, it will be set to \u0000 of the same bit-size of the key.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKey.decrypt","title":"decrypt","text":"<pre><code>decrypt(path)\n</code></pre> <p>Decrypt a Track with AES Clear Key DRM.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKey.from_m3u_key","title":"from_m3u_key <code>classmethod</code>","text":"<pre><code>from_m3u_key(m3u_key, session=None)\n</code></pre> <p>Load a ClearKey from an M3U(8) Playlist's EXT-X-KEY.</p> <p>Parameters:</p> Name Type Description Default <code>m3u_key</code> <code>Key</code> <p>A Key object parsed from a m3u(8) playlist using the <code>m3u8</code> library.</p> required <code>session</code> <code>Optional[Session]</code> <p>Optional session used to request external URIs with. Useful to set headers, proxies, cookies, and so forth.</p> <code>None</code>"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC","title":"ClearKeyCENC","text":"<pre><code>ClearKeyCENC(kids, laurl=None, content_keys=None, **kwargs)\n</code></pre> <p>W3C EME ClearKey (org.w3.clearkey) DRM System over MPEG-CENC content.</p> <p>Distinct from the HLS AES-128 <code>ClearKey</code> class: keys here are delivered by a license server as a JWK Set keyed by KID, and content is standard CENC (decrypted with shaka-packager/mp4decrypt KID:KEY pairs, same as Widevine).</p>"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.kid","title":"kid <code>property</code>","text":"<pre><code>kid\n</code></pre> <p>Get first Key ID, if any.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.Exceptions","title":"Exceptions","text":""},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.Exceptions.KIDNotFound","title":"KIDNotFound","text":"<p> Bases: <code>Exception</code></p> <p>KID (Encryption Key ID) was not found.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.Exceptions.CEKNotFound","title":"CEKNotFound","text":"<p> Bases: <code>Exception</code></p> <p>CEK (Content Encryption Key) for KID was not found in License.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.Exceptions.EmptyLicense","title":"EmptyLicense","text":"<p> Bases: <code>Exception</code></p> <p>License returned no Content Encryption Keys.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.to_dict","title":"to_dict","text":"<pre><code>to_dict()\n</code></pre> <p>Serialise this DRM instance for export/import (KIDs + license URL).</p> <p>Content keys are stored once at the export's track level, not duplicated here.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.get_license_challenge","title":"get_license_challenge","text":"<pre><code>get_license_challenge()\n</code></pre> <p>Build the W3C EME ClearKey JSON license request for the unkeyed KIDs.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.get_content_keys","title":"get_content_keys","text":"<pre><code>get_content_keys(*, licence, session=None)\n</code></pre> <p>Obtain Content Keys for this DRM Instance from a ClearKey license server.</p> <p>The licence param is expected to be a function and will be provided with the W3C JSON license request as <code>challenge</code>. It may return the JWK Set license as a dict, JSON str, or bytes. If it returns None and the manifest provided a Laurl, the challenge is POSTed there directly instead.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.decrypt","title":"decrypt","text":"<pre><code>decrypt(path)\n</code></pre> <p>Decrypt a Track with ClearKey DRM (standard CENC). Args: path: Path to the encrypted file to decrypt Raises: EnvironmentError if the required decryption executable could not be found. ValueError if the track has not yet been downloaded. SubprocessError if the decryption process returned a non-zero exit code.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.decrypt_with_mp4decrypt","title":"decrypt_with_mp4decrypt","text":"<pre><code>decrypt_with_mp4decrypt(path)\n</code></pre> <p>Decrypt using mp4decrypt</p>"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.decrypt_with_shaka_packager","title":"decrypt_with_shaka_packager","text":"<pre><code>decrypt_with_shaka_packager(path)\n</code></pre> <p>Decrypt using Shaka Packager</p>"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa","title":"MonaLisa","text":"<pre><code>MonaLisa(ticket, aes_key, device_path, **kwargs)\n</code></pre> <p>MonaLisa DRM System.</p> <p>Unlike Widevine/PlayReady, MonaLisa does not use a challenge/response flow with a license server. Instead, the PSSH value (ticket) is provided directly by the service API, and keys are extracted locally via a WASM module.</p> <p>Decryption is performed in two stages: 1. ML-Worker binary: Removes MonaLisa encryption layer (bbts -&gt; ents) 2. AES-ECB decryption: Final decryption with service-provided key</p> <p>Initialize MonaLisa DRM.</p> <p>Parameters:</p> Name Type Description Default <code>ticket</code> <code>Union[str, bytes]</code> <p>PSSH value from service API (base64 string or raw bytes).</p> required <code>aes_key</code> <code>Union[str, bytes]</code> <p>AES-ECB key for second-stage decryption (hex string or bytes).</p> required <code>device_path</code> <code>Path</code> <p>Path to the CDM device file (.mld).</p> required <code>**kwargs</code> <code>Any</code> <p>Additional metadata stored in self.data.</p> <code>{}</code> <p>Raises:</p> Type Description <code>TicketNotFound</code> <p>If ticket/PSSH is empty.</p> <code>KeyExtractionFailed</code> <p>If key extraction fails.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.kid","title":"kid <code>property</code>","text":"<pre><code>kid\n</code></pre> <p>Get the Key ID.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.key","title":"key <code>property</code>","text":"<pre><code>key\n</code></pre> <p>Get the content key as hex string.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.pssh","title":"pssh <code>property</code>","text":"<pre><code>pssh\n</code></pre> <p>Get the raw PSSH/ticket value as a string.</p> <p>Returns:</p> Type Description <code>str</code> <p>The raw PSSH value as a base64 string.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.content_id","title":"content_id <code>property</code>","text":"<pre><code>content_id\n</code></pre> <p>Extract the Content ID from the PSSH for display.</p> <p>The PSSH contains an embedded Content ID at bytes 21-75 with format: H5DCID-V3-P1-YYYYMMDD-HHMMSS-MEDIAID-TIMESTAMP-SUFFIX</p> <p>Returns:</p> Type Description <code>Optional[str]</code> <p>The Content ID string if extractable, None otherwise.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.content_keys","title":"content_keys <code>property</code>","text":"<pre><code>content_keys\n</code></pre> <p>Get content keys in the same format as Widevine/PlayReady.</p> <p>Returns:</p> Type Description <code>dict[UUID, str]</code> <p>Dictionary mapping KID to key hex string.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.Exceptions","title":"Exceptions","text":""},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.Exceptions.TicketNotFound","title":"TicketNotFound","text":"<p> Bases: <code>Exception</code></p> <p>Raised when no PSSH/ticket data is provided.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.Exceptions.KeyExtractionFailed","title":"KeyExtractionFailed","text":"<p> Bases: <code>Exception</code></p> <p>Raised when key extraction from the ticket fails.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.Exceptions.WorkerNotFound","title":"WorkerNotFound","text":"<p> Bases: <code>Exception</code></p> <p>Raised when the ML-Worker binary is not found.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.Exceptions.DecryptionFailed","title":"DecryptionFailed","text":"<p> Bases: <code>Exception</code></p> <p>Raised when segment decryption fails.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.from_ticket","title":"from_ticket <code>classmethod</code>","text":"<pre><code>from_ticket(ticket, aes_key, device_path)\n</code></pre> <p>Create a MonaLisa DRM instance from a PSSH/ticket.</p> <p>Parameters:</p> Name Type Description Default <code>ticket</code> <code>Union[str, bytes]</code> <p>PSSH value from service API.</p> required <code>aes_key</code> <code>Union[str, bytes]</code> <p>AES-ECB key for second-stage decryption.</p> required <code>device_path</code> <code>Path</code> <p>Path to the CDM device file (.mld).</p> required <p>Returns:</p> Type Description <code>MonaLisa</code> <p>MonaLisa DRM instance with extracted keys.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.decrypt_segment","title":"decrypt_segment","text":"<pre><code>decrypt_segment(segment_path)\n</code></pre> <p>Decrypt a single segment using two-stage decryption.</p> <p>Stage 1: ML-Worker binary (bbts -&gt; ents) Stage 2: AES-ECB decryption (ents -&gt; ts)</p> <p>Parameters:</p> Name Type Description Default <code>segment_path</code> <code>Path</code> <p>Path to the encrypted segment file.</p> required <p>Raises:</p> Type Description <code>WorkerNotFound</code> <p>If ML-Worker binary is not available.</p> <code>DecryptionFailed</code> <p>If decryption fails at any stage.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.decrypt","title":"decrypt","text":"<pre><code>decrypt(_path)\n</code></pre> <p>MonaLisa uses per-segment decryption during download via the on_segment_downloaded callback. By the time this method is called, the content has already been decrypted and muxed into a container.</p> <p>Parameters:</p> Name Type Description Default <code>_path</code> <code>Path</code> <p>Path to the file (ignored).</p> required"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady","title":"PlayReady","text":"<pre><code>PlayReady(pssh, kid=None, pssh_b64=None, **kwargs)\n</code></pre> <p>PlayReady DRM System.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.to_dict","title":"to_dict","text":"<pre><code>to_dict()\n</code></pre> <p>Serialise this DRM instance for export/import (PSSH + KIDs).</p> <p>Content keys are stored once at the export's track level, not duplicated here.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.decrypt","title":"decrypt","text":"<pre><code>decrypt(path)\n</code></pre> <p>Decrypt a Track with PlayReady DRM. Args: path: Path to the encrypted file to decrypt Raises: EnvironmentError if the required decryption executable could not be found. ValueError if the track has not yet been downloaded. SubprocessError if the decryption process returned a non-zero exit code.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine","title":"Widevine","text":"<pre><code>Widevine(pssh, kid=None, **kwargs)\n</code></pre> <p>Widevine DRM System.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.pssh","title":"pssh <code>property</code>","text":"<pre><code>pssh\n</code></pre> <p>Get Protection System Specific Header Box.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.kid","title":"kid <code>property</code>","text":"<pre><code>kid\n</code></pre> <p>Get first Key ID, if any.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.kids","title":"kids <code>property</code>","text":"<pre><code>kids\n</code></pre> <p>Get all Key IDs from PSSH, falling back to the externally provided KID.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.Exceptions","title":"Exceptions","text":""},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.Exceptions.PSSHNotFound","title":"PSSHNotFound","text":"<p> Bases: <code>Exception</code></p> <p>PSSH (Protection System Specific Header) was not found.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.Exceptions.KIDNotFound","title":"KIDNotFound","text":"<p> Bases: <code>Exception</code></p> <p>KID (Encryption Key ID) was not found.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.Exceptions.CEKNotFound","title":"CEKNotFound","text":"<p> Bases: <code>Exception</code></p> <p>CEK (Content Encryption Key) for KID was not found in License.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.Exceptions.EmptyLicense","title":"EmptyLicense","text":"<p> Bases: <code>Exception</code></p> <p>License returned no Content Encryption Keys.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.from_track","title":"from_track <code>classmethod</code>","text":"<pre><code>from_track(track, session=None)\n</code></pre> <p>Get PSSH and KID from within the Initiation Segment of the Track Data. It also tries to get PSSH and KID from other track data like M3U8 data as well as through ffprobe.</p> <p>Create a Widevine DRM System object from a track's information. This should only be used if a PSSH could not be provided directly. It is rare to need to use this.</p> <p>You may provide your own requests session to be able to use custom headers and more.</p> <p>Raises:</p> Type Description <code>PSSHNotFound</code> <p>If the PSSH was not found within the data.</p> <code>KIDNotFound</code> <p>If the KID was not found within the data or PSSH.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.from_init_data","title":"from_init_data <code>classmethod</code>","text":"<pre><code>from_init_data(init_data)\n</code></pre> <p>Get PSSH and KID from within Initialization Segment Data.</p> <p>This should only be used if a PSSH could not be provided directly. It is rare to need to use this.</p> <p>Raises:</p> Type Description <code>PSSHNotFound</code> <p>If the PSSH was not found within the data.</p> <code>KIDNotFound</code> <p>If the KID was not found within the data or PSSH.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.to_dict","title":"to_dict","text":"<pre><code>to_dict()\n</code></pre> <p>Serialise this DRM instance for export/import (PSSH + KIDs).</p> <p>Content keys are stored once at the export's track level, not duplicated here.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.get_content_keys","title":"get_content_keys","text":"<pre><code>get_content_keys(cdm, certificate, licence)\n</code></pre> <p>Create a CDM Session and obtain Content Keys for this DRM Instance. The certificate and license params are expected to be a function and will be provided with the challenge and session ID.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.get_NF_content_keys","title":"get_NF_content_keys","text":"<pre><code>get_NF_content_keys(cdm, certificate, licence)\n</code></pre> <p>Create a CDM Session and obtain Content Keys for this DRM Instance. The certificate and license params are expected to be a function and will be provided with the challenge and session ID.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.decrypt","title":"decrypt","text":"<pre><code>decrypt(path)\n</code></pre> <p>Decrypt a Track with Widevine DRM. Args: path: Path to the encrypted file to decrypt Raises: EnvironmentError if the required decryption executable could not be found. ValueError if the track has not yet been downloaded. SubprocessError if the decryption process returned a non-zero exit code.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.drm_from_dict","title":"drm_from_dict","text":"<pre><code>drm_from_dict(data)\n</code></pre> <p>Reconstruct a Widevine/PlayReady/ClearKeyCENC DRM instance from its <code>to_dict()</code> form.</p> <p>Rebuilds the PSSH from the stored base64 (KIDs for ClearKey, which has no PSSH) and re-injects any saved content keys so the resulting object can decrypt without contacting a license server.</p>"},{"location":"reference/api/service/","title":"Service API","text":"<p>Auto-generated reference for the <code>Service</code> base class that every service plugin subclasses. See Creating a Service for a guided walkthrough and Service Architecture for the wider object model.</p>"},{"location":"reference/api/service/#unshackle.core.service.TrackRequest","title":"TrackRequest <code>dataclass</code>","text":"<pre><code>TrackRequest(\n codecs=list(),\n ranges=(lambda: [SDR])(),\n best_available=False,\n)\n</code></pre> <p>Holds what the user requested for video codec and range selection.</p> <p>Services read from this instead of ctx.parent.params for vcodec/range.</p> <p>Attributes:</p> Name Type Description <code>codecs</code> <code>list[Codec]</code> <p>Requested codecs from CLI. Empty list means no filter (accept any).</p> <code>ranges</code> <code>list[Range]</code> <p>Requested ranges from CLI. Defaults to [SDR].</p>"},{"location":"reference/api/service/#unshackle.core.service.Service","title":"Service","text":"<pre><code>Service(ctx)\n</code></pre> <p>The Service Base Class.</p> Source code in <code>unshackle/core/service.py</code> <pre><code>def __init__(self, ctx: click.Context):\n console.print(Padding(Rule(f\"[rule.text]Service: {self.__class__.__name__}\"), (1, 2)))\n\n self.config = ctx.obj.config\n\n self.log = logging.getLogger(self.__class__.__name__)\n\n self.session = self.get_session()\n self.cache = Cacher(self.__class__.__name__)\n self.title_cache = TitleCacher(self.__class__.__name__)\n self.cache_dir = config.directories.cache / self.__class__.__name__\n\n # Store context for cache control flags and credential\n self.ctx = ctx\n self.credential = None # Will be set in authenticate()\n self.current_region = None # Will be set based on proxy/geolocation\n self._input_bridge: Optional[InputBridge] = None\n\n # Set track request from CLI params - services can read/override in their __init__\n vcodec = ctx.parent.params.get(\"vcodec\") if ctx.parent else None\n range_ = ctx.parent.params.get(\"range_\") if ctx.parent else None\n best_available = ctx.parent.params.get(\"best_available\", False) if ctx.parent else False\n self.track_request = TrackRequest(\n codecs=list(vcodec) if vcodec else [],\n ranges=list(range_) if range_ else [Video.Range.SDR],\n best_available=bool(best_available),\n )\n\n if not ctx.parent or not ctx.parent.params.get(\"no_proxy\"):\n if ctx.parent:\n proxy = ctx.parent.params[\"proxy\"]\n proxy_query = ctx.parent.params.get(\"proxy_query\")\n proxy_provider_name = ctx.parent.params.get(\"proxy_provider\")\n else:\n proxy = None\n proxy_query = None\n proxy_provider_name = None\n\n # Check for service-specific proxy mapping\n service_name = self.__class__.__name__\n service_config_dict = config.services.get(service_name, {})\n proxy_map = service_config_dict.get(\"proxy_map\", {})\n\n if proxy_map and proxy_query:\n # Build the full proxy query key (e.g., \"nordvpn:ca\" or \"us\")\n if proxy_provider_name:\n full_proxy_key = f\"{proxy_provider_name}:{proxy_query}\"\n else:\n full_proxy_key = proxy_query\n\n # Check if there's a mapping for this query\n mapped_value = proxy_map.get(full_proxy_key)\n if mapped_value:\n self.log.info(\n f\"Found service-specific proxy mapping: {full_proxy_key} -&gt; {sanitize_proxy_for_log(mapped_value)}\"\n )\n # Query the proxy provider with the mapped value\n if proxy_provider_name:\n # Specific provider requested\n proxy_provider = next(\n (x for x in ctx.obj.proxy_providers if x.__class__.__name__.lower() == proxy_provider_name),\n None,\n )\n if proxy_provider:\n mapped_proxy_uri = proxy_provider.get_proxy(mapped_value)\n if mapped_proxy_uri:\n proxy = mapped_proxy_uri\n self.log.info(\n f\"Using mapped proxy from {proxy_provider.__class__.__name__}: {sanitize_proxy_for_log(proxy)}\"\n )\n else:\n self.log.warning(\n f\"Failed to get proxy for mapped value '{sanitize_proxy_for_log(mapped_value)}', using default\"\n )\n else:\n self.log.warning(f\"Proxy provider '{proxy_provider_name}' not found, using default proxy\")\n else:\n # No specific provider, try all providers\n for proxy_provider in ctx.obj.proxy_providers:\n mapped_proxy_uri = proxy_provider.get_proxy(mapped_value)\n if mapped_proxy_uri:\n proxy = mapped_proxy_uri\n self.log.info(\n f\"Using mapped proxy from {proxy_provider.__class__.__name__}: {sanitize_proxy_for_log(proxy)}\"\n )\n break\n else:\n self.log.warning(\n f\"No provider could resolve mapped value '{sanitize_proxy_for_log(mapped_value)}', using default\"\n )\n\n if not proxy:\n # don't override the explicit proxy set by the user, even if they may be geoblocked\n with console.status(\"Checking if current region is Geoblocked...\", spinner=\"dots\"):\n if self.GEOFENCE:\n # Service has geofence - need fresh IP check to determine if proxy needed\n try:\n current_region = get_ip_info(self.session)[\"country\"].lower()\n if any(x.lower() == current_region for x in self.GEOFENCE):\n self.log.info(\"Service is not Geoblocked in your region\")\n else:\n requested_proxy = self.GEOFENCE[0] # first is likely main region\n self.log.info(\n f\"Service is Geoblocked in your region, getting a Proxy to {requested_proxy}\"\n )\n for proxy_provider in ctx.obj.proxy_providers:\n proxy = proxy_provider.get_proxy(requested_proxy)\n if proxy:\n self.log.info(f\"Got Proxy from {proxy_provider.__class__.__name__}\")\n break\n except Exception as e:\n self.log.warning(f\"Failed to check geofence: {e}\")\n current_region = None\n else:\n self.log.info(\"Service has no Geofence\")\n\n if proxy:\n self.session.proxies.update({\"all\": proxy})\n # Don't set Proxy-Authorization manually: both rnet (Proxy.all) and\n # requests authenticate from the credentials embedded in the proxy URL.\n # A manual header here was malformed (no \"Basic \" scheme) and broke\n # plaintext-http forward-proxy requests with HTTP 407.\n # Always verify proxy IP - proxies can change exit nodes\n try:\n proxy_ip_info = get_ip_info(self.session)\n self.current_region = proxy_ip_info.get(\"country\", \"\").lower() if proxy_ip_info else None\n except Exception as e:\n self.log.warning(f\"Failed to verify proxy IP: {e}\")\n # Fallback to extracting region from proxy config\n self.current_region = get_region_from_proxy(proxy)\n else:\n # No proxy, use cached IP info for title caching (non-critical)\n try:\n ip_info = get_ip_info(self.session, cached=True)\n self.current_region = ip_info.get(\"country\", \"\").lower() if ip_info else None\n except Exception as e:\n self.log.debug(f\"Failed to get cached IP info: {e}\")\n self.current_region = None\n</code></pre>"},{"location":"reference/api/service/#unshackle.core.service.Service.get_session","title":"get_session <code>staticmethod</code>","text":"<pre><code>get_session()\n</code></pre> <p>Creates a Python-requests Session, adds common headers from config, cookies, retry handler, and a proxy if available. :returns: Prepared Python-requests Session</p> Source code in <code>unshackle/core/service.py</code> <pre><code>@staticmethod\ndef get_session() -&gt; requests.Session:\n \"\"\"\n Creates a Python-requests Session, adds common headers\n from config, cookies, retry handler, and a proxy if available.\n :returns: Prepared Python-requests Session\n \"\"\"\n session = requests.Session()\n session.headers.update(config.headers)\n session.mount(\n \"https://\",\n HTTPAdapter(\n max_retries=Retry(total=5, backoff_factor=0.2, status_forcelist=[429, 500, 502, 503, 504]),\n pool_block=True,\n ),\n )\n session.mount(\"http://\", session.adapters[\"https://\"])\n return session\n</code></pre>"},{"location":"reference/api/service/#unshackle.core.service.Service.authenticate","title":"authenticate","text":"<pre><code>authenticate(cookies=None, credential=None)\n</code></pre> <p>Authenticate the Service with Cookies and/or Credentials (Email/Username and Password).</p> <p>This is effectively a login() function. Any API calls or object initializations needing to be made, should be made here. This will be run before any of the following abstract functions.</p> <p>You should avoid storing or using the Credential outside this function. Make any calls you need for any Cookies, Tokens, or such, then use those.</p> <p>The Cookie jar should also not be stored outside this function. However, you may load the Cookie jar into the service session.</p> Source code in <code>unshackle/core/service.py</code> <pre><code>def authenticate(self, cookies: Optional[CookieJar] = None, credential: Optional[Credential] = None) -&gt; None:\n \"\"\"\n Authenticate the Service with Cookies and/or Credentials (Email/Username and Password).\n\n This is effectively a login() function. Any API calls or object initializations\n needing to be made, should be made here. This will be run before any of the\n following abstract functions.\n\n You should avoid storing or using the Credential outside this function.\n Make any calls you need for any Cookies, Tokens, or such, then use those.\n\n The Cookie jar should also not be stored outside this function. However, you may load\n the Cookie jar into the service session.\n \"\"\"\n if cookies is not None:\n if not isinstance(cookies, CookieJar):\n raise TypeError(f\"Expected cookies to be a {CookieJar}, not {cookies!r}.\")\n self.session.cookies.update(cookies)\n\n # Store credential for cache key generation\n self.credential = credential\n</code></pre>"},{"location":"reference/api/service/#unshackle.core.service.Service.request_input","title":"request_input","text":"<pre><code>request_input(prompt)\n</code></pre> <p>Request interactive input from the user.</p> <p>When running locally (CLI), prompts via the shared rich console so the prompt renders correctly alongside Live progress / log handlers. When running in serve mode with an :class:<code>InputBridge</code> attached, delegates to the bridge which relays the prompt to the remote client.</p> Source code in <code>unshackle/core/service.py</code> <pre><code>def request_input(self, prompt: str) -&gt; str:\n \"\"\"Request interactive input from the user.\n\n When running locally (CLI), prompts via the shared rich console so the\n prompt renders correctly alongside Live progress / log handlers.\n When running in serve mode with an :class:`InputBridge` attached,\n delegates to the bridge which relays the prompt to the remote client.\n \"\"\"\n if self._input_bridge is not None:\n return self._input_bridge.request_input(prompt)\n indent = \" \" * 5\n padded = indent + prompt.replace(\"\\n\", \"\\n\" + indent)\n return console.input(Text(padded, style=\"text\"))\n</code></pre>"},{"location":"reference/api/service/#unshackle.core.service.Service.search","title":"search","text":"<pre><code>search()\n</code></pre> <p>Search by query for titles from the Service.</p> <p>The query must be taken as a CLI argument by the Service class. Ideally just re-use the title ID argument (i.e. self.title).</p> <p>Search results will be displayed in the order yielded.</p> Source code in <code>unshackle/core/service.py</code> <pre><code>def search(self) -&gt; Generator[SearchResult, None, None]:\n \"\"\"\n Search by query for titles from the Service.\n\n The query must be taken as a CLI argument by the Service class.\n Ideally just re-use the title ID argument (i.e. self.title).\n\n Search results will be displayed in the order yielded.\n \"\"\"\n raise NotImplementedError(f\"Search functionality has not been implemented by {self.__class__.__name__}\")\n</code></pre>"},{"location":"reference/api/service/#unshackle.core.service.Service.get_widevine_service_certificate","title":"get_widevine_service_certificate","text":"<pre><code>get_widevine_service_certificate(\n *, challenge, title, track\n)\n</code></pre> <p>Get the Widevine Service Certificate used for Privacy Mode.</p> <p>:param challenge: The service challenge, providing this to a License endpoint should return the privacy certificate that the service uses. :param title: The current <code>Title</code> from get_titles that is being executed. This is provided in case it has data needed to be used, e.g. for a HTTP request. :param track: The current <code>Track</code> needing decryption. Provided for same reason as <code>title</code>. :return: The Service Privacy Certificate as Bytes or a Base64 string. Don't Base64 Encode or Decode the data, return as is to reduce unnecessary computations.</p> Source code in <code>unshackle/core/service.py</code> <pre><code>def get_widevine_service_certificate(\n self, *, challenge: bytes, title: Title_T, track: AnyTrack\n) -&gt; Union[bytes, str]:\n \"\"\"\n Get the Widevine Service Certificate used for Privacy Mode.\n\n :param challenge: The service challenge, providing this to a License endpoint should return the\n privacy certificate that the service uses.\n :param title: The current `Title` from get_titles that is being executed. This is provided in\n case it has data needed to be used, e.g. for a HTTP request.\n :param track: The current `Track` needing decryption. Provided for same reason as `title`.\n :return: The Service Privacy Certificate as Bytes or a Base64 string. Don't Base64 Encode or\n Decode the data, return as is to reduce unnecessary computations.\n \"\"\"\n</code></pre>"},{"location":"reference/api/service/#unshackle.core.service.Service.get_widevine_license","title":"get_widevine_license","text":"<pre><code>get_widevine_license(*, challenge, title, track)\n</code></pre> <p>Get a Widevine License message by sending a License Request (challenge).</p> <p>This License message contains the encrypted Content Decryption Keys and will be read by the Cdm and decrypted.</p> <p>This is a very important request to get correct. A bad, unexpected, or missing value in the request can cause your key to be detected and promptly banned, revoked, disabled, or downgraded.</p> <p>:param challenge: The license challenge from the Widevine CDM. :param title: The current <code>Title</code> from get_titles that is being executed. This is provided in case it has data needed to be used, e.g. for a HTTP request. :param track: The current <code>Track</code> needing decryption. Provided for same reason as <code>title</code>. :return: The License response as Bytes or a Base64 string. Don't Base64 Encode or Decode the data, return as is to reduce unnecessary computations.</p> Source code in <code>unshackle/core/service.py</code> <pre><code>def get_widevine_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -&gt; Optional[Union[bytes, str]]:\n \"\"\"\n Get a Widevine License message by sending a License Request (challenge).\n\n This License message contains the encrypted Content Decryption Keys and will be\n read by the Cdm and decrypted.\n\n This is a very important request to get correct. A bad, unexpected, or missing\n value in the request can cause your key to be detected and promptly banned,\n revoked, disabled, or downgraded.\n\n :param challenge: The license challenge from the Widevine CDM.\n :param title: The current `Title` from get_titles that is being executed. This is provided in\n case it has data needed to be used, e.g. for a HTTP request.\n :param track: The current `Track` needing decryption. Provided for same reason as `title`.\n :return: The License response as Bytes or a Base64 string. Don't Base64 Encode or\n Decode the data, return as is to reduce unnecessary computations.\n \"\"\"\n</code></pre>"},{"location":"reference/api/service/#unshackle.core.service.Service.get_playready_license","title":"get_playready_license","text":"<pre><code>get_playready_license(*, challenge, title, track)\n</code></pre> <p>Get a PlayReady License message by sending a License Request (challenge).</p> <p>This License message contains the encrypted Content Decryption Keys and will be read by the CDM and decrypted.</p> <p>This is a very important request to get correct. A bad, unexpected, or missing value in the request can cause your key to be detected and promptly banned, revoked, disabled, or downgraded.</p> <p>:param challenge: The license challenge from the PlayReady CDM. :param title: The current <code>Title</code> from get_titles that is being executed. This is provided in case it has data needed to be used, e.g. for a HTTP request. :param track: The current <code>Track</code> needing decryption. Provided for same reason as <code>title</code>. :return: The License response as Bytes or a Base64 string. Don't Base64 Encode or Decode the data, return as is to reduce unnecessary computations.</p> Source code in <code>unshackle/core/service.py</code> <pre><code>def get_playready_license(\n self, *, challenge: bytes, title: Title_T, track: AnyTrack\n) -&gt; Optional[Union[bytes, str]]:\n \"\"\"\n Get a PlayReady License message by sending a License Request (challenge).\n\n This License message contains the encrypted Content Decryption Keys and will be\n read by the CDM and decrypted.\n\n This is a very important request to get correct. A bad, unexpected, or missing\n value in the request can cause your key to be detected and promptly banned,\n revoked, disabled, or downgraded.\n\n :param challenge: The license challenge from the PlayReady CDM.\n :param title: The current `Title` from get_titles that is being executed. This is provided in\n case it has data needed to be used, e.g. for a HTTP request.\n :param track: The current `Track` needing decryption. Provided for same reason as `title`.\n :return: The License response as Bytes or a Base64 string. Don't Base64 Encode or\n Decode the data, return as is to reduce unnecessary computations.\n \"\"\"\n # Delegates license handling to the Widevine license method by default if a service-specific PlayReady implementation is not provided.\n return self.get_widevine_license(challenge=challenge, title=title, track=track)\n</code></pre>"},{"location":"reference/api/service/#unshackle.core.service.Service.get_clearkey_license","title":"get_clearkey_license","text":"<pre><code>get_clearkey_license(*, challenge, title, track)\n</code></pre> <p>Get a W3C ClearKey License (JWK Set) by sending a License Request (challenge).</p> <p>Used for DASH <code>org.w3.clearkey</code> content. No CDM is involved: the challenge is the W3C EME JSON license request, e.g. <code>{\"kids\": [\"&lt;base64url&gt;\"], \"type\": \"temporary\"}</code>, and the license is a JWK Set, e.g. <code>{\"keys\": [{\"kty\": \"oct\", \"k\": \"...\", \"kid\": \"...\"}]}</code>.</p> <p>:param challenge: The JSON license request bytes to POST to the license server. :param title: The current <code>Title</code> from get_titles that is being executed. This is provided in case it has data needed to be used, e.g. for a HTTP request. :param track: The current <code>Track</code> needing decryption. Provided for same reason as <code>title</code>. :return: The JWK Set license as a dict, JSON str, or raw bytes. Return None (the default) to let the framework POST the challenge to the manifest-provided Laurl, if any. Services with no license server can instead pre-populate the DRM object's <code>content_keys</code> in get_tracks.</p> Source code in <code>unshackle/core/service.py</code> <pre><code>def get_clearkey_license(\n self, *, challenge: bytes, title: Title_T, track: AnyTrack\n) -&gt; Optional[Union[bytes, str, dict]]:\n \"\"\"\n Get a W3C ClearKey License (JWK Set) by sending a License Request (challenge).\n\n Used for DASH `org.w3.clearkey` content. No CDM is involved: the challenge is\n the W3C EME JSON license request, e.g. ``{\"kids\": [\"&lt;base64url&gt;\"], \"type\": \"temporary\"}``,\n and the license is a JWK Set, e.g. ``{\"keys\": [{\"kty\": \"oct\", \"k\": \"...\", \"kid\": \"...\"}]}``.\n\n :param challenge: The JSON license request bytes to POST to the license server.\n :param title: The current `Title` from get_titles that is being executed. This is provided in\n case it has data needed to be used, e.g. for a HTTP request.\n :param track: The current `Track` needing decryption. Provided for same reason as `title`.\n :return: The JWK Set license as a dict, JSON str, or raw bytes. Return None (the default)\n to let the framework POST the challenge to the manifest-provided Laurl, if any.\n Services with no license server can instead pre-populate the DRM object's\n `content_keys` in get_tracks.\n \"\"\"\n return None\n</code></pre>"},{"location":"reference/api/service/#unshackle.core.service.Service.get_titles","title":"get_titles <code>abstractmethod</code>","text":"<pre><code>get_titles()\n</code></pre> <p>Get Titles for the provided title ID.</p> <p>Return a Movies, Series, or Album objects containing Movie, Episode, or Song title objects respectively. The returned data must be for the given title ID, or a spawn of the title ID.</p> <p>At least one object is expected to be returned, or it will presume an invalid Title ID was provided.</p> <p>You can use the <code>data</code> dictionary class instance attribute of each Title to store data you may need later on. This can be useful to store information on each title that will be required like any sub-asset IDs, or such.</p> Source code in <code>unshackle/core/service.py</code> <pre><code>@abstractmethod\ndef get_titles(self) -&gt; Titles_T:\n \"\"\"\n Get Titles for the provided title ID.\n\n Return a Movies, Series, or Album objects containing Movie, Episode, or Song title objects respectively.\n The returned data must be for the given title ID, or a spawn of the title ID.\n\n At least one object is expected to be returned, or it will presume an invalid Title ID was\n provided.\n\n You can use the `data` dictionary class instance attribute of each Title to store data you may need later on.\n This can be useful to store information on each title that will be required like any sub-asset IDs, or such.\n \"\"\"\n</code></pre>"},{"location":"reference/api/service/#unshackle.core.service.Service.get_titles_cached","title":"get_titles_cached","text":"<pre><code>get_titles_cached(title_id=None)\n</code></pre> <p>Cached wrapper around get_titles() to reduce redundant API calls.</p> <p>This method checks the cache before calling get_titles() and handles fallback to cached data when API calls fail.</p> <p>Parameters:</p> Name Type Description Default <code>title_id</code> <code>str</code> <p>Optional title ID for cache key generation. If not provided, will try to extract from service instance.</p> <code>None</code> <p>Returns:</p> Type Description <code>Titles_T</code> <p>Titles object (Movies, Series, or Album)</p> Source code in <code>unshackle/core/service.py</code> <pre><code>def get_titles_cached(self, title_id: str = None) -&gt; Titles_T:\n \"\"\"\n Cached wrapper around get_titles() to reduce redundant API calls.\n\n This method checks the cache before calling get_titles() and handles\n fallback to cached data when API calls fail.\n\n Args:\n title_id: Optional title ID for cache key generation.\n If not provided, will try to extract from service instance.\n\n Returns:\n Titles object (Movies, Series, or Album)\n \"\"\"\n # Try to get title_id from service instance if not provided\n if title_id is None:\n # Different services store the title ID in different attributes\n if hasattr(self, \"title\"):\n title_id = self.title\n elif hasattr(self, \"title_id\"):\n title_id = self.title_id\n else:\n # If we can't determine title_id, just call get_titles directly\n self.log.debug(\"Cannot determine title_id for caching, bypassing cache\")\n return self.apply_title_map(self.get_titles())\n\n # Get cache control flags from context\n no_cache = False\n reset_cache = False\n if self.ctx and self.ctx.parent:\n no_cache = self.ctx.parent.params.get(\"no_cache\", False)\n reset_cache = self.ctx.parent.params.get(\"reset_cache\", False)\n\n # Get account hash for cache key\n account_hash = get_account_hash(self.credential)\n\n # Use title cache to get titles with fallback support\n titles = self.title_cache.get_cached_titles(\n title_id=str(title_id),\n fetch_function=self.get_titles,\n region=self.current_region,\n account_hash=account_hash,\n no_cache=no_cache,\n reset_cache=reset_cache,\n )\n return self.apply_title_map(titles)\n</code></pre>"},{"location":"reference/api/service/#unshackle.core.service.Service.apply_title_map","title":"apply_title_map","text":"<pre><code>apply_title_map(titles)\n</code></pre> <p>Rewrite service-provided titles using the per-service <code>title_map</code> config.</p> <p><code>title_map</code> lives under <code>services.&lt;TAG&gt;</code> in unshackle.yaml. Applied after the title cache so config edits take effect without a cache reset, and before any <code>--enrich</code> override so enrich wins. See <code>remap_titles</code> for the match rules.</p> Source code in <code>unshackle/core/service.py</code> <pre><code>def apply_title_map(self, titles: Titles_T) -&gt; Titles_T:\n \"\"\"\n Rewrite service-provided titles using the per-service ``title_map`` config.\n\n ``title_map`` lives under ``services.&lt;TAG&gt;`` in unshackle.yaml. Applied after the\n title cache so config edits take effect without a cache reset, and before any\n ``--enrich`` override so enrich wins. See ``remap_titles`` for the match rules.\n \"\"\"\n return remap_titles(titles, (self.config or {}).get(\"title_map\") or {})\n</code></pre>"},{"location":"reference/api/service/#unshackle.core.service.Service.get_tracks","title":"get_tracks <code>abstractmethod</code>","text":"<pre><code>get_tracks(title)\n</code></pre> <p>Get Track objects of the Title.</p> <p>Return a Tracks object, which itself can contain Video, Audio, Subtitle or even Chapters. Tracks.videos, Tracks.audio, Tracks.subtitles, and Track.chapters should be a List of Track objects.</p> <p>Each Track in the Tracks should represent a Video/Audio Stream/Representation/Adaptation or a Subtitle file.</p> <p>While one Track should only hold information for one stream/downloadable, try to get as many unique Track objects per stream type so Stream selection by the root code can give you more options in terms of Resolution, Bitrate, Codecs, Language, e.t.c.</p> <p>No decision making or filtering of which Tracks get returned should happen here. It can be considered an error to filter for e.g. resolution, codec, and such. All filtering based on arguments will be done by the root code automatically when needed.</p> <p>Make sure you correctly mark which Tracks are encrypted or not, and by which DRM System via its <code>drm</code> property.</p> <p>If you are able to obtain the Track's KID (Key ID) as a 32 char (16 bit) HEX string, provide it to the Track's <code>kid</code> variable as it will speed up the decryption process later on. It may or may not be needed, that depends on the service. Generally if you can provide it, without downloading any of the Track's stream data, then do.</p> <p>:param title: The current <code>Title</code> from get_titles that is being executed. :return: Tracks object containing Video, Audio, Subtitles, and Chapters, if available.</p> Source code in <code>unshackle/core/service.py</code> <pre><code>@abstractmethod\ndef get_tracks(self, title: Title_T) -&gt; Tracks:\n \"\"\"\n Get Track objects of the Title.\n\n Return a Tracks object, which itself can contain Video, Audio, Subtitle or even Chapters.\n Tracks.videos, Tracks.audio, Tracks.subtitles, and Track.chapters should be a List of Track objects.\n\n Each Track in the Tracks should represent a Video/Audio Stream/Representation/Adaptation or\n a Subtitle file.\n\n While one Track should only hold information for one stream/downloadable, try to get as many\n unique Track objects per stream type so Stream selection by the root code can give you more\n options in terms of Resolution, Bitrate, Codecs, Language, e.t.c.\n\n No decision making or filtering of which Tracks get returned should happen here. It can be\n considered an error to filter for e.g. resolution, codec, and such. All filtering based on\n arguments will be done by the root code automatically when needed.\n\n Make sure you correctly mark which Tracks are encrypted or not, and by which DRM System\n via its `drm` property.\n\n If you are able to obtain the Track's KID (Key ID) as a 32 char (16 bit) HEX string, provide\n it to the Track's `kid` variable as it will speed up the decryption process later on. It may\n or may not be needed, that depends on the service. Generally if you can provide it, without\n downloading any of the Track's stream data, then do.\n\n :param title: The current `Title` from get_titles that is being executed.\n :return: Tracks object containing Video, Audio, Subtitles, and Chapters, if available.\n \"\"\"\n</code></pre>"},{"location":"reference/api/service/#unshackle.core.service.Service.get_chapters","title":"get_chapters <code>abstractmethod</code>","text":"<pre><code>get_chapters(title)\n</code></pre> <p>Get Chapters for the Title.</p> <p>Parameters:</p> Name Type Description Default <code>title</code> <code>Title_T</code> <p>The current Title from <code>get_titles</code> that is being processed.</p> required <p>You must return a Chapters object containing 0 or more Chapter objects.</p> <p>You do not need to set a Chapter number or sort/order the chapters in any way as the Chapters class automatically handles all of that for you. If there's no descriptive name for a Chapter then do not set a name at all.</p> <p>You must not set Chapter names to \"Chapter {n}\" or such. If you (or the user) wants \"Chapter {n}\" style Chapter names (or similar) then they can use the config option <code>chapter_fallback_name</code>. For example, <code>\"Chapter {i:02}\"</code> for \"Chapter 01\".</p> Source code in <code>unshackle/core/service.py</code> <pre><code>@abstractmethod\ndef get_chapters(self, title: Title_T) -&gt; Chapters:\n \"\"\"\n Get Chapters for the Title.\n\n Parameters:\n title: The current Title from `get_titles` that is being processed.\n\n You must return a Chapters object containing 0 or more Chapter objects.\n\n You do not need to set a Chapter number or sort/order the chapters in any way as\n the Chapters class automatically handles all of that for you. If there's no\n descriptive name for a Chapter then do not set a name at all.\n\n You must not set Chapter names to \"Chapter {n}\" or such. If you (or the user)\n wants \"Chapter {n}\" style Chapter names (or similar) then they can use the config\n option `chapter_fallback_name`. For example, `\"Chapter {i:02}\"` for \"Chapter 01\".\n \"\"\"\n</code></pre>"},{"location":"reference/api/service/#unshackle.core.service.Service.on_segment_downloaded","title":"on_segment_downloaded","text":"<pre><code>on_segment_downloaded(track, segment)\n</code></pre> <p>Called when one of a Track's Segments has finished downloading.</p> <p>Parameters:</p> Name Type Description Default <code>track</code> <code>AnyTrack</code> <p>The Track object that had a Segment downloaded.</p> required <code>segment</code> <code>Path</code> <p>The Path to the Segment that was downloaded.</p> required Source code in <code>unshackle/core/service.py</code> <pre><code>def on_segment_downloaded(self, track: AnyTrack, segment: Path) -&gt; None:\n \"\"\"\n Called when one of a Track's Segments has finished downloading.\n\n Parameters:\n track: The Track object that had a Segment downloaded.\n segment: The Path to the Segment that was downloaded.\n \"\"\"\n</code></pre>"},{"location":"reference/api/service/#unshackle.core.service.Service.on_track_downloaded","title":"on_track_downloaded","text":"<pre><code>on_track_downloaded(track)\n</code></pre> <p>Called when a Track has finished downloading.</p> <p>Parameters:</p> Name Type Description Default <code>track</code> <code>AnyTrack</code> <p>The Track object that was downloaded.</p> required Source code in <code>unshackle/core/service.py</code> <pre><code>def on_track_downloaded(self, track: AnyTrack) -&gt; None:\n \"\"\"\n Called when a Track has finished downloading.\n\n Parameters:\n track: The Track object that was downloaded.\n \"\"\"\n</code></pre>"},{"location":"reference/api/service/#unshackle.core.service.Service.on_track_decrypted","title":"on_track_decrypted","text":"<pre><code>on_track_decrypted(track, drm, segment=None)\n</code></pre> <p>Called when a Track has finished decrypting.</p> <p>Parameters:</p> Name Type Description Default <code>track</code> <code>AnyTrack</code> <p>The Track object that was decrypted.</p> required <code>drm</code> <code>DRM_T</code> <p>The DRM object it decrypted with.</p> required <code>segment</code> <code>Optional[Segment]</code> <p>The HLS segment information that was decrypted.</p> <code>None</code> Source code in <code>unshackle/core/service.py</code> <pre><code>def on_track_decrypted(self, track: AnyTrack, drm: DRM_T, segment: Optional[m3u8.Segment] = None) -&gt; None:\n \"\"\"\n Called when a Track has finished decrypting.\n\n Parameters:\n track: The Track object that was decrypted.\n drm: The DRM object it decrypted with.\n segment: The HLS segment information that was decrypted.\n \"\"\"\n</code></pre>"},{"location":"reference/api/service/#unshackle.core.service.Service.on_track_repacked","title":"on_track_repacked","text":"<pre><code>on_track_repacked(track)\n</code></pre> <p>Called when a Track has finished repacking.</p> <p>Parameters:</p> Name Type Description Default <code>track</code> <code>AnyTrack</code> <p>The Track object that was repacked.</p> required Source code in <code>unshackle/core/service.py</code> <pre><code>def on_track_repacked(self, track: AnyTrack) -&gt; None:\n \"\"\"\n Called when a Track has finished repacking.\n\n Parameters:\n track: The Track object that was repacked.\n \"\"\"\n</code></pre>"},{"location":"reference/api/service/#unshackle.core.service.Service.on_track_multiplex","title":"on_track_multiplex","text":"<pre><code>on_track_multiplex(track)\n</code></pre> <p>Called when a Track is about to be Multiplexed into a Container.</p> <p>Note: Right now only MKV containers are multiplexed but in the future this may also be called when multiplexing to other containers like MP4 via ffmpeg/mp4box.</p> <p>Parameters:</p> Name Type Description Default <code>track</code> <code>AnyTrack</code> <p>The Track object that was repacked.</p> required Source code in <code>unshackle/core/service.py</code> <pre><code>def on_track_multiplex(self, track: AnyTrack) -&gt; None:\n \"\"\"\n Called when a Track is about to be Multiplexed into a Container.\n\n Note: Right now only MKV containers are multiplexed but in the future\n this may also be called when multiplexing to other containers like\n MP4 via ffmpeg/mp4box.\n\n Parameters:\n track: The Track object that was repacked.\n \"\"\"\n</code></pre>"},{"location":"reference/api/service/#unshackle.core.service.sanitize_proxy_for_log","title":"sanitize_proxy_for_log","text":"<pre><code>sanitize_proxy_for_log(uri)\n</code></pre> <p>Sanitize a proxy URI for logs by redacting any embedded userinfo (username/password).</p> <p>Examples:</p> <ul> <li>http://user:pass@host:8080 -&gt; http://REDACTED@host:8080</li> <li>socks5h://user@host:1080 -&gt; socks5h://REDACTED@host:1080</li> </ul> Source code in <code>unshackle/core/service.py</code> <pre><code>def sanitize_proxy_for_log(uri: Optional[str]) -&gt; Optional[str]:\n \"\"\"\n Sanitize a proxy URI for logs by redacting any embedded userinfo (username/password).\n\n Examples:\n - http://user:pass@host:8080 -&gt; http://REDACTED@host:8080\n - socks5h://user@host:1080 -&gt; socks5h://REDACTED@host:1080\n \"\"\"\n if uri is None:\n return None\n if not isinstance(uri, str):\n return str(uri)\n if not uri:\n return uri\n\n try:\n parsed = urlparse(uri)\n\n # Handle schemeless proxies like \"user:pass@host:port\"\n if not parsed.scheme and not parsed.netloc and \"@\" in uri and \"://\" not in uri:\n # Parse as netloc using a dummy scheme, then strip scheme back out.\n dummy = urlparse(f\"http://{uri}\")\n netloc = dummy.netloc\n if \"@\" in netloc:\n netloc = f\"REDACTED@{netloc.split('@', 1)[1]}\"\n # urlparse(\"http://...\") sets path to \"\" for typical netloc-only strings; keep it just in case.\n return f\"{netloc}{dummy.path}\"\n\n netloc = parsed.netloc\n if \"@\" in netloc:\n netloc = f\"REDACTED@{netloc.split('@', 1)[1]}\"\n\n return urlunparse(parsed._replace(netloc=netloc))\n except Exception:\n if \"@\" in uri:\n return f\"REDACTED@{uri.split('@', 1)[1]}\"\n return uri\n</code></pre>"},{"location":"reference/api/titles/","title":"Titles API","text":"<p>Auto-generated reference for the title model: Movies, Series/Episodes, and Music/Albums/Songs. A service returns one of these collections from its title lookup. See Creating a Service.</p>"},{"location":"reference/api/titles/#unshackle.core.titles.Episode","title":"Episode","text":"<pre><code>Episode(\n id_,\n service,\n title,\n season,\n number,\n name=None,\n year=None,\n language=None,\n data=None,\n description=None,\n air_date=None,\n)\n</code></pre> <p> Bases: <code>Title</code></p>"},{"location":"reference/api/titles/#unshackle.core.titles.Movie","title":"Movie","text":"<pre><code>Movie(\n id_,\n service,\n name,\n year=None,\n language=None,\n data=None,\n description=None,\n)\n</code></pre> <p> Bases: <code>Title</code></p>"},{"location":"reference/api/titles/#unshackle.core.titles.Album","title":"Album","text":"<pre><code>Album(\n iterable=None,\n kind=\"album\",\n title=None,\n artist=None,\n year=None,\n total_tracks=None,\n total_discs=None,\n artwork_url=None,\n total_duration=None,\n owner=None,\n description=None,\n)\n</code></pre> <p> Bases: <code>Music</code></p> <p>Backward-compatible collection name for album-style music releases.</p>"},{"location":"reference/api/titles/#unshackle.core.titles.Music","title":"Music","text":"<pre><code>Music(\n iterable=None,\n kind=\"album\",\n title=None,\n artist=None,\n year=None,\n total_tracks=None,\n total_discs=None,\n artwork_url=None,\n total_duration=None,\n owner=None,\n description=None,\n)\n</code></pre> <p> Bases: <code>SortedKeyList</code>, <code>ABC</code></p> <p>A grouped music release, such as an album, EP, single, compilation, or playlist.</p>"},{"location":"reference/api/titles/#unshackle.core.titles.Song","title":"Song","text":"<pre><code>Song(\n id_,\n service,\n name,\n artist,\n album,\n track,\n disc,\n year,\n language=None,\n data=None,\n album_artist=None,\n release_type=\"album\",\n total_tracks=None,\n total_discs=None,\n genre=None,\n explicit=None,\n isrc=None,\n upc=None,\n copyright=None,\n label=None,\n lyrics=None,\n artwork_url=None,\n)\n</code></pre> <p> Bases: <code>Title</code></p>"},{"location":"reference/api/titles/#unshackle.core.titles.remap_titles","title":"remap_titles","text":"<pre><code>remap_titles(titles, title_map)\n</code></pre> <p>Rewrite titles in-place using an exact-match <code>title_map</code>.</p> <p>Some services name a title differently from how the user wants it stored, which can break library matching. <code>title_map</code> maps a source title string to the desired output title. Episodes are matched on their <code>title</code> (the show name), Movies and Songs on their <code>name</code>. Returns the same collection for convenient chaining.</p>"},{"location":"reference/api/tracks/","title":"Tracks API","text":"<p>Auto-generated reference for the track model: <code>Tracks</code>, <code>Track</code>, and the media-specific subclasses. See Service Architecture for how these fit together.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Attachment","title":"Attachment","text":"<pre><code>Attachment(\n path=None,\n url=None,\n name=None,\n mime_type=None,\n description=None,\n session=None,\n)\n</code></pre> <p>Create a new Attachment.</p> <p>If providing a path, the file must already exist. If providing a URL, the file will be downloaded to the temp directory. Either path or url must be provided.</p> <p>If name is not provided it will use the file name (without extension). If mime_type is not provided, it will try to guess it.</p> <p>Parameters:</p> Name Type Description Default <code>path</code> <code>Union[Path, str, None]</code> <p>Path to an existing file.</p> <code>None</code> <code>url</code> <code>Optional[str]</code> <p>URL to download the attachment from.</p> <code>None</code> <code>name</code> <code>Optional[str]</code> <p>Name of the attachment.</p> <code>None</code> <code>mime_type</code> <code>Optional[str]</code> <p>MIME type of the attachment.</p> <code>None</code> <code>description</code> <code>Optional[str]</code> <p>Description of the attachment.</p> <code>None</code> <code>session</code> <code>Optional[Session]</code> <p>Optional requests session to use for downloading.</p> <code>None</code>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Attachment.id","title":"id <code>property</code>","text":"<pre><code>id\n</code></pre> <p>Compute an ID from the attachment data.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Attachment.to_dict","title":"to_dict","text":"<pre><code>to_dict()\n</code></pre> <p>Serialise a URL-backed attachment for export/import.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Attachment.from_url","title":"from_url <code>classmethod</code>","text":"<pre><code>from_url(\n url,\n name=None,\n mime_type=None,\n description=None,\n session=None,\n)\n</code></pre> <p>Create an attachment from a URL.</p> <p>Parameters:</p> Name Type Description Default <code>url</code> <code>str</code> <p>URL to download the attachment from.</p> required <code>name</code> <code>Optional[str]</code> <p>Name of the attachment.</p> <code>None</code> <code>mime_type</code> <code>Optional[str]</code> <p>MIME type of the attachment.</p> <code>None</code> <code>description</code> <code>Optional[str]</code> <p>Description of the attachment.</p> <code>None</code> <code>session</code> <code>Optional[Session]</code> <p>Optional requests session to use for downloading.</p> <code>None</code> <p>Returns:</p> Name Type Description <code>Attachment</code> <code>'Attachment'</code> <p>A new attachment instance.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Audio","title":"Audio","text":"<pre><code>Audio(\n *args,\n codec=None,\n bitrate=None,\n channels=None,\n joc=None,\n descriptive=False,\n **kwargs,\n)\n</code></pre> <p> Bases: <code>Track</code></p> <p>Create a new Audio track object.</p> <p>Parameters:</p> Name Type Description Default <code>codec</code> <code>Optional[Codec]</code> <p>An Audio.Codec enum representing the audio codec. If not specified, MediaInfo will be used to retrieve the codec once the track has been downloaded.</p> <code>None</code> <code>bitrate</code> <code>Optional[Union[str, int, float]]</code> <p>A number or float representing the average bandwidth in bytes/s. Float values are rounded up to the nearest integer.</p> <code>None</code> <code>channels</code> <code>Optional[Union[str, int, float]]</code> <p>A number, float, or string representing the number of audio channels. Strings may represent numbers or floats. Expanded layouts like 7.1.1 is not supported. All numbers and strings will be cast to float.</p> <code>None</code> <code>joc</code> <code>Optional[int]</code> <p>The number of Joint-Object-Coding Channels/Objects in the audio stream.</p> <code>None</code> <code>descriptive</code> <code>Union[bool, int]</code> <p>Mark this audio as being descriptive audio for the blind.</p> <code>False</code> <p>Note: If codec, bitrate, channels, or joc is not specified some checks may be skipped or assume a value. Specifying as much information as possible is highly recommended.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Audio.atmos","title":"atmos <code>property</code>","text":"<pre><code>atmos\n</code></pre> <p>Return True if the audio track contains Dolby Atmos.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Audio.parse_channels","title":"parse_channels <code>staticmethod</code>","text":"<pre><code>parse_channels(channels)\n</code></pre> <p>Converts a Channel string to a float representing audio channel count and layout. E.g. \"3\" -&gt; \"3.0\", \"2.1\" -&gt; \"2.1\", \".1\" -&gt; \"0.1\".</p> <p>This does not validate channel strings as genuine channel counts or valid layouts. It does not convert the value to assume a sub speaker channel layout, e.g. 5.1-&gt;6.0. It also does not support expanded surround sound channel layout strings like 7.1.2.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Audio.get_track_name","title":"get_track_name","text":"<pre><code>get_track_name()\n</code></pre> <p>Return the base Track Name.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapter","title":"Chapter","text":"<pre><code>Chapter(timestamp, name=None)\n</code></pre> <p>Create a new Chapter with a Timestamp and optional name.</p> <p>The timestamp may be in the following formats: - \"HH:MM:SS\" string, e.g., <code>25:05:23</code>. - \"HH:MM:SS.mss\" string, e.g., <code>25:05:23.120</code>. - a timecode integer in milliseconds, e.g., <code>90323120</code> is <code>25:05:23.120</code>. - a timecode float in seconds, e.g., <code>90323.12</code> is <code>25:05:23.120</code>.</p> <p>If you have a timecode integer in seconds, just multiply it by 1000. If you have a timecode float in milliseconds (no decimal value), just convert it to an integer.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapter.id","title":"id <code>property</code>","text":"<pre><code>id\n</code></pre> <p>Compute an ID from the Chapter data.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapter.named","title":"named <code>property</code>","text":"<pre><code>named\n</code></pre> <p>Check if Chapter is named.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapters","title":"Chapters","text":"<pre><code>Chapters(iterable=None)\n</code></pre> <p> Bases: <code>SortedKeyList</code>, <code>ABC</code></p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapters.id","title":"id <code>property</code>","text":"<pre><code>id\n</code></pre> <p>Compute an ID from the Chapter data.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapters.loads","title":"loads <code>classmethod</code>","text":"<pre><code>loads(data)\n</code></pre> <p>Load chapter data from a string.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapters.load","title":"load <code>classmethod</code>","text":"<pre><code>load(path)\n</code></pre> <p>Load chapter data from a file.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapters.dumps","title":"dumps","text":"<pre><code>dumps(fallback_name='')\n</code></pre> <p>Return chapter data in OGM-based Simple Chapter format. https://mkvtoolnix.download/doc/mkvmerge.html#mkvmerge.chapters.simple</p> <p>Parameters:</p> Name Type Description Default <code>fallback_name</code> <code>str</code> <p>Name used for Chapters without a Name set.</p> <code>''</code> <p>The fallback name can use the following variables in f-string style:</p> <ul> <li>{i}: The Chapter number starting at 1. E.g., <code>\"Chapter {i}\"</code>: \"Chapter 1\", \"Intro\", \"Chapter 3\".</li> <li>{j}: A number starting at 1 that increments any time a Chapter has no name. E.g., <code>\"Chapter {j}\"</code>: \"Chapter 1\", \"Intro\", \"Chapter 2\".</li> </ul> <p>These are formatted with f-strings, directives are supported. For example, <code>\"Chapter {i:02}\"</code> will result in <code>\"Chapter 01\"</code>.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapters.dump","title":"dump","text":"<pre><code>dump(path, *args, **kwargs)\n</code></pre> <p>Write chapter data in OGM-based Simple Chapter format to a file.</p> <p>Parameters:</p> Name Type Description Default <code>path</code> <code>Union[Path, str]</code> <p>The file path to write the Chapter data to, overwriting any existing data.</p> required <p>See <code>Chapters.dumps</code> for more parameter documentation.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Hybrid","title":"Hybrid","text":"<pre><code>Hybrid(videos, source)\n</code></pre>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Hybrid.log","title":"log <code>instance-attribute</code>","text":"<pre><code>log = logging.getLogger('hybrid')\n</code></pre> <p>Takes the Dolby Vision and HDR10(+) streams out of the VideoTracks. It will then attempt to inject the Dolby Vision metadata layer to the HDR10(+) stream. If no DV track is available but HDR10+ is present, it will convert HDR10+ to DV.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Hybrid.level_5","title":"level_5","text":"<pre><code>level_5(input_video)\n</code></pre> <p>Generate Level 5 active area metadata via crop detection on the HDR10 stream.</p> <p>This resolves mismatches where DV has no black bars but HDR10 does (or vice versa) by telling the display the correct active area.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Hybrid.sanitize_l6","title":"sanitize_l6 <code>staticmethod</code>","text":"<pre><code>sanitize_l6(max_mdl, min_mdl, max_cll, max_fall)\n</code></pre> <p>Clamp static L6 values to a valid relationship.</p> <p>MaxCLL must not exceed the mastering-display peak (some sources, e.g. ATV HDR10+, ship MaxCLL 10000 on a 1000-nit master), and MaxFALL must not exceed MaxCLL. A value of 0 means \"unknown\" and is preserved as-is.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Hybrid.level_6","title":"level_6","text":"<pre><code>level_6()\n</code></pre> <p>Edit RPU Level 6 values using the static L6 luminance data from the RPU.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Hybrid.extract_hdr10plus","title":"extract_hdr10plus","text":"<pre><code>extract_hdr10plus(_video)\n</code></pre> <p>Extract HDR10+ metadata from the video stream</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Hybrid.convert_hdr10plus_to_dv","title":"convert_hdr10plus_to_dv","text":"<pre><code>convert_hdr10plus_to_dv()\n</code></pre> <p>Convert HDR10+ metadata to Dolby Vision RPU</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle","title":"Subtitle","text":"<pre><code>Subtitle(\n *args,\n codec=None,\n cc=False,\n sdh=False,\n forced=False,\n **kwargs,\n)\n</code></pre> <p> Bases: <code>Track</code></p> <p>Create a new Subtitle track object.</p> <p>Parameters:</p> Name Type Description Default <code>codec</code> <code>Optional[Codec]</code> <p>A Subtitle.Codec enum representing the subtitle format. If not specified, MediaInfo will be used to retrieve the format once the track has been downloaded.</p> <code>None</code> <code>cc</code> <code>bool</code> <p>Closed Caption. - Intended as if you couldn't hear the audio at all. - Can have Sound as well as Dialogue, but doesn't have to. - Original source would be from an EIA-CC encoded stream. Typically all upper-case characters. Indicators of it being CC without knowing original source: - Extracted with CCExtractor, or - &gt;&gt;&gt; (or similar) being used at the start of some or all lines, or - All text is uppercase or at least the majority, or - Subtitles are Scrolling-text style (one line appears, oldest line then disappears). Just because you downloaded it as a SRT or VTT or such, doesn't mean it isn't from an EIA-CC stream. And I wouldn't take the streaming services (CC) as gospel either as they tend to get it wrong too.</p> <code>False</code> <code>sdh</code> <code>bool</code> <p>Deaf or Hard-of-Hearing. Also known as HOH in the UK (EU?). - Intended as if you couldn't hear the audio at all. - MUST have Sound as well as Dialogue to be considered SDH. - It has no \"syntax\" or \"format\" but is not transmitted using archaic forms like EIA-CC streams, would be intended for transmission via SubRip (SRT), WebVTT (VTT), TTML, etc. If you can see important audio/sound transcriptions and not just dialogue and it doesn't have the indicators of CC, then it's most likely SDH. If it doesn't have important audio/sounds transcriptions it might just be regular subtitling (you wouldn't mark as CC or SDH). This would be the case for most translation subtitles. Like Anime for example.</p> <code>False</code> <code>forced</code> <code>bool</code> <p>Typically used if there's important information at some point in time like watching Dubbed content and an important Sign or Letter is shown or someone talking in a different language. Forced tracks are recommended by the Matroska Spec to be played if the player's current playback audio language matches a subtitle marked as \"forced\". However, that doesn't mean every player works like this but there is no other way to reliably work with Forced subtitles where multiple forced subtitles may be in the output file. Just know what to expect with \"forced\" subtitles.</p> <code>False</code> <p>Note: If codec is not specified some checks may be skipped or assume a value. Specifying as much information as possible is highly recommended.</p> Information on Subtitle Types <p>https://bit.ly/2Oe4fLC (3PlayMedia Blog on SUB vs CC vs SDH). However, I wouldn't pay much attention to the claims about SDH needing to be in the original source language. It's logically not true.</p> <p>CC == Closed Captions. Source: Basically every site. SDH = Subtitles for the Deaf or Hard-of-Hearing. Source: Basically every site. HOH = Exact same as SDH. Is a term used in the UK. Source: https://bit.ly/2PGJatz (ICO UK)</p> <p>More in-depth information, examples, and stuff to look for can be found in the Parameter explanation list above.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.get_track_name","title":"get_track_name","text":"<pre><code>get_track_name()\n</code></pre> <p>Return the base Track Name.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.sanitize_webvtt_timestamps","title":"sanitize_webvtt_timestamps <code>staticmethod</code>","text":"<pre><code>sanitize_webvtt_timestamps(text)\n</code></pre> <p>Fix invalid timestamps in WebVTT files, particularly negative timestamps.</p> <p>Parameters:</p> Name Type Description Default <code>text</code> <code>str</code> <p>The WebVTT content as string</p> required <p>Returns:</p> Type Description <code>str</code> <p>Sanitized WebVTT content</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.has_webvtt_cue_identifiers","title":"has_webvtt_cue_identifiers <code>staticmethod</code>","text":"<pre><code>has_webvtt_cue_identifiers(text)\n</code></pre> <p>Check if WebVTT content has cue identifiers that need removal.</p> <p>Parameters:</p> Name Type Description Default <code>text</code> <code>str</code> <p>The WebVTT content as string</p> required <p>Returns:</p> Type Description <code>bool</code> <p>True if cue identifiers are detected, False otherwise</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.sanitize_webvtt_cue_identifiers","title":"sanitize_webvtt_cue_identifiers <code>staticmethod</code>","text":"<pre><code>sanitize_webvtt_cue_identifiers(text)\n</code></pre> <p>Remove WebVTT cue identifiers that can confuse subtitle parsers.</p> <p>Some services use cue identifiers like \"Q0\", \"Q1\", etc. that appear on their own line before the timing line. These can be incorrectly parsed as part of the previous cue's text content by some parsers (like pysubs2).</p> <p>Parameters:</p> Name Type Description Default <code>text</code> <code>str</code> <p>The WebVTT content as string</p> required <p>Returns:</p> Type Description <code>str</code> <p>Sanitized WebVTT content with cue identifiers removed</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.has_overlapping_webvtt_cues","title":"has_overlapping_webvtt_cues <code>staticmethod</code>","text":"<pre><code>has_overlapping_webvtt_cues(text)\n</code></pre> <p>Check if WebVTT content has overlapping cues that need merging.</p> <p>Detects cues with start times within 50ms of each other and the same end time, which indicates multi-line subtitles split into separate cues.</p> <p>Parameters:</p> Name Type Description Default <code>text</code> <code>str</code> <p>The WebVTT content as string</p> required <p>Returns:</p> Type Description <code>bool</code> <p>True if overlapping cues are detected, False otherwise</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.merge_overlapping_webvtt_cues","title":"merge_overlapping_webvtt_cues <code>staticmethod</code>","text":"<pre><code>merge_overlapping_webvtt_cues(text)\n</code></pre> <p>Merge WebVTT cues that have overlapping/near-identical times but different line positions.</p> <p>Some services use separate cues for each line of a multi-line subtitle, with slightly different start times (1ms apart) and different line: positions. This merges them into single cues with proper line ordering based on the line: position (lower percentage = higher on screen = first line).</p> <p>Parameters:</p> Name Type Description Default <code>text</code> <code>str</code> <p>The WebVTT content as string</p> required <p>Returns:</p> Type Description <code>str</code> <p>WebVTT content with overlapping cues merged</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.sanitize_webvtt","title":"sanitize_webvtt <code>staticmethod</code>","text":"<pre><code>sanitize_webvtt(text)\n</code></pre> <p>More thorough sanitization of WebVTT files to handle multiple potential issues.</p> <p>Parameters:</p> Name Type Description Default <code>text</code> <code>str</code> <p>The WebVTT content as string</p> required <p>Returns:</p> Type Description <code>str</code> <p>Sanitized WebVTT content</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.convert","title":"convert","text":"<pre><code>convert(codec, *, forced=False)\n</code></pre> <p>Convert this Subtitle to another format.</p> <p>Backend selection is data-driven (see <code>tracks/subtitle_convert.py</code>): the best available backend that supports source-&gt;target is used, falling back through the capability chain on failure. The backend can be pinned via the <code>conversion_method</code> config key (<code>auto</code> | <code>subby</code> | <code>pysubs2</code> | <code>subtitleedit</code> | <code>pycaption</code>), or nudged per-service via <code>preferred_conversion_method</code>; an explicit config value always wins.</p> <p><code>forced</code> marks an explicit user request (<code>--sub-format</code>). Lossy downconverts of styled formats (SSA/ASS -&gt; SRT) are skipped unless <code>forced</code> is True.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.extract_fonts","title":"extract_fonts <code>staticmethod</code>","text":"<pre><code>extract_fonts(text)\n</code></pre> <p>Font names referenced by an ASS/SSA subtitle.</p> <p>Covers both sources that need attaching for correct rendering: - the <code>Fontname</code> column of every <code>Style:</code> line in <code>[V4+ Styles]</code>/<code>[V4 Styles]</code> (column located from the section's <code>Format:</code> line, not assumed by index), and - inline <code>\\fn</code> font overrides inside <code>Dialogue</code> override blocks.</p> <p>Leading <code>@</code> (vertical-writing prefix) is stripped and names are de-duplicated case-insensitively, preferring a mixed-case spelling over an all-lowercase one.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.sanitize_broken_webvtt","title":"sanitize_broken_webvtt <code>staticmethod</code>","text":"<pre><code>sanitize_broken_webvtt(text)\n</code></pre> <p>Remove or fix corrupted WebVTT lines, particularly those with invalid timestamps.</p> <p>Parameters:</p> Name Type Description Default <code>text</code> <code>str</code> <p>The WebVTT content as string</p> required <p>Returns:</p> Type Description <code>str</code> <p>Sanitized WebVTT content with corrupted lines removed</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.space_webvtt_headers","title":"space_webvtt_headers <code>staticmethod</code>","text":"<pre><code>space_webvtt_headers(data)\n</code></pre> <p>Space out the WEBVTT Headers from Captions.</p> <p>Segmented VTT when merged may have the WEBVTT headers part of the next caption as they were not separated far enough from the previous caption and ended up being considered as caption text rather than the header for the next segment.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.merge_same_cues","title":"merge_same_cues <code>staticmethod</code>","text":"<pre><code>merge_same_cues(caption_set)\n</code></pre> <p>Merge captions with the same timecodes and text as one in-place.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.filter_unwanted_cues","title":"filter_unwanted_cues <code>staticmethod</code>","text":"<pre><code>filter_unwanted_cues(caption_set)\n</code></pre> <p>Filter out subtitle cues containing only \u00a0 or whitespace.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.merge_segmented_wvtt","title":"merge_segmented_wvtt <code>staticmethod</code>","text":"<pre><code>merge_segmented_wvtt(data, period_start=0.0)\n</code></pre> <p>Convert Segmented DASH WebVTT cues into a pycaption Caption List. Also returns an ISO 639-2 alpha-3 language code if available.</p> <p>Code ported originally by xhlove to Python from shaka-player. Has since been improved upon by rlaphoenix using pymp4 and pycaption functions.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.strip_hearing_impaired","title":"strip_hearing_impaired","text":"<pre><code>strip_hearing_impaired()\n</code></pre> <p>Strip captions for hearing impaired (SDH).</p> <p>The SDH stripping method is determined by the 'sdh_method' setting in config: - 'auto' (default): Tries subby first, then SubtitleEdit, then filter-subs - 'subby': Uses subby's SDHStripper - 'subtitleedit': Uses SubtitleEdit when available - 'filter-subs': Uses subtitle-filter library</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.reverse_rtl","title":"reverse_rtl","text":"<pre><code>reverse_rtl()\n</code></pre> <p>Reverse RTL (Right to Left) Start/End on Captions. This can be used to fix the positioning of sentence-ending characters.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.DownloadContext","title":"DownloadContext <code>dataclass</code>","text":"<pre><code>DownloadContext(\n save_path,\n save_dir,\n progress,\n session=None,\n proxy=None,\n max_workers=None,\n license_widevine=None,\n cdm=None,\n)\n</code></pre> <p>Shared arguments passed to each manifest's <code>download_track</code>.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.DownloadContext.ensure_session","title":"ensure_session","text":"<pre><code>ensure_session()\n</code></pre> <p>Return the session, or a new <code>Session</code> if none was set.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track","title":"Track","text":"<pre><code>Track(\n url,\n language,\n is_original_lang=False,\n descriptor=URL,\n needs_repack=False,\n name=None,\n drm=None,\n edition=None,\n session=None,\n downloader=None,\n downloader_args=None,\n from_file=None,\n data=None,\n id_=None,\n extra=None,\n)\n</code></pre>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.data","title":"data <code>property</code> <code>writable</code>","text":"<pre><code>data\n</code></pre> <p>Arbitrary track data dictionary.</p> <p>A defaultdict is used with a dict as the factory for easier nested saving and safer exists-checks.</p> <p>Reserved keys:</p> <ul> <li>\"hls\" used by the HLS class.</li> <li>playlist: m3u8.model.Playlist - The primary track information.</li> <li>media: m3u8.model.Media - The audio/subtitle track information.</li> <li>segment_durations: list[int] - A list of each segment's duration.</li> <li>\"dash\" used by the DASH class.</li> <li>manifest: lxml.ElementTree - DASH MPD manifest.</li> <li>period: lxml.Element - The period of this track.</li> <li>adaptation_set: lxml.Element - The adaptation set of this track.</li> <li>representation: lxml.Element - The representation of this track.</li> <li>timescale: int - The timescale of the track's segments.</li> <li>segment_durations: list[int] - A list of each segment's duration.</li> </ul> <p>You should not add, change, or remove any data within reserved keys. You may use their data but do note that the values of them may change or be removed at any point.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.download","title":"download","text":"<pre><code>download(\n session,\n prepare_drm,\n max_workers=None,\n progress=None,\n *,\n cdm=None,\n no_proxy_download=False,\n)\n</code></pre> <p>Download and optionally Decrypt this Track.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.move","title":"move","text":"<pre><code>move(target)\n</code></pre> <p>Move the Track's file from current location, to target location. This will overwrite anything at the target path.</p> <p>Raises:</p> Type Description <code>TypeError</code> <p>If the target argument is not the expected type.</p> <code>ValueError</code> <p>If track has no file to move, or the target does not exist.</p> <code>OSError</code> <p>If the file somehow failed to move.</p> <p>Returns the new location of the track.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.to_dict","title":"to_dict","text":"<pre><code>to_dict()\n</code></pre> <p>Serialise the track for export/import (identity/URL/descriptor/language).</p> <p>DRM is not serialised here; the export writer attaches the licensed DRM + keys. Subclasses add their own codec/quality fields.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.base_kwargs_from_dict","title":"base_kwargs_from_dict <code>staticmethod</code>","text":"<pre><code>base_kwargs_from_dict(data)\n</code></pre> <p>Build the shared Track constructor kwargs from a <code>to_dict()</code> payload.</p> <p>DRM is not reconstructed here \u2014 <code>to_dict</code> does not serialise it, and the import flow attaches the licensed DRM + content keys separately.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.from_dict","title":"from_dict <code>classmethod</code>","text":"<pre><code>from_dict(data)\n</code></pre> <p>Reconstruct the correct Track subclass from a <code>to_dict()</code> payload.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.get_track_name","title":"get_track_name","text":"<pre><code>get_track_name()\n</code></pre> <p>Get the Track Name.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.get_drm_for_cdm","title":"get_drm_for_cdm","text":"<pre><code>get_drm_for_cdm(cdm)\n</code></pre> <p>Return the DRM matching the provided CDM, if available.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.get_key_id","title":"get_key_id","text":"<pre><code>get_key_id(init_data=None, *args, **kwargs)\n</code></pre> <p>Probe the DRM encryption Key ID (KID) for this specific track.</p> <p>It currently supports finding the Key ID by probing the track's stream with ffprobe for <code>enc_key_id</code> data, as well as for mp4 <code>tenc</code> (Track Encryption) boxes.</p> <p>It explicitly ignores PSSH information like the <code>PSSH</code> box, as the box is likely to contain multiple Key IDs that may or may not be for this specific track.</p> <p>To retrieve the initialization segment, this method calls :meth:<code>get_init_segment</code> with the positional and keyword arguments. The return value of <code>get_init_segment</code> is then used to determine the Key ID.</p> <p>Returns:</p> Type Description <code>Optional[UUID]</code> <p>The Key ID as a UUID object, or None if the Key ID could not be determined.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.load_drm_if_needed","title":"load_drm_if_needed","text":"<pre><code>load_drm_if_needed(service=None)\n</code></pre> <p>Load DRM information for this track if it was deferred during parsing.</p> <p>Parameters:</p> Name Type Description Default <code>service</code> <code>Service | None</code> <p>Service instance that can fetch track-specific DRM info</p> <code>None</code> <p>Returns:</p> Type Description <code>bool</code> <p>True if DRM was loaded or already present, False if failed</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.load_drm_from_playlist","title":"load_drm_from_playlist","text":"<pre><code>load_drm_from_playlist()\n</code></pre> <p>Fallback method to load DRM by fetching this track's individual playlist.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.get_init_segment","title":"get_init_segment","text":"<pre><code>get_init_segment(\n maximum_size=20000,\n url=None,\n byte_range=None,\n session=None,\n)\n</code></pre> <p>Get the Track's Initial Segment Data Stream.</p> <p>HLS and DASH tracks must explicitly provide a URL to the init segment or file. Providing the byte-range for the init segment is recommended where possible.</p> <p>If <code>byte_range</code> is not set, it will make a HEAD request and check the size of the file. If the size could not be determined, it will download up to the first 20KB only, which should contain the entirety of the init segment. You may override this by changing the <code>maximum_size</code>.</p> <p>The default maximum_size of 20000 (20KB) is a tried-and-tested value that seems to work well across the board.</p> <p>Parameters:</p> Name Type Description Default <code>maximum_size</code> <code>int</code> <p>Size to assume as the content length if byte-range is not used, the content size could not be determined, or the content size is larger than it. A value of 20000 (20KB) or higher is recommended.</p> <code>20000</code> <code>url</code> <code>Optional[str]</code> <p>Explicit init map or file URL to probe from.</p> <code>None</code> <code>byte_range</code> <code>Optional[str]</code> <p>Range of bytes to download from the explicit or implicit URL.</p> <code>None</code> <code>session</code> <code>Optional[Session]</code> <p>Session context, e.g., authorization and headers.</p> <code>None</code>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks","title":"Tracks","text":"<pre><code>Tracks(*args, manifest_url=None)\n</code></pre> <p>Video, Audio, Subtitle, Chapter, and Attachment Track Store. It provides convenience functions for listing, sorting, and selecting tracks.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.exists","title":"exists","text":"<pre><code>exists(by_id=None, by_url=None)\n</code></pre> <p>Check if a track already exists by various methods.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.add","title":"add","text":"<pre><code>add(tracks, warn_only=False)\n</code></pre> <p>Add a provided track to its appropriate array and ensuring it's not a duplicate.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.sort_videos","title":"sort_videos","text":"<pre><code>sort_videos(by_language=None)\n</code></pre> <p>Sort video tracks by resolution then bitrate, and optionally language.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.sort_audio","title":"sort_audio","text":"<pre><code>sort_audio(by_language=None, codec_priority=None)\n</code></pre> <p>Sort audio tracks by bitrate, codec priority, Atmos, descriptive, and optionally language.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.sort_subtitles","title":"sort_subtitles","text":"<pre><code>sort_subtitles(by_language=None, type_priority=None)\n</code></pre> <p>Sort subtitle tracks by various track attributes to a common P2P standard. You may optionally provide a sequence of languages to prioritize to the top.</p> Section Order <ul> <li>by_language groups prioritized to top, and ascending alphabetically</li> <li>then rest ascending alphabetically after the prioritized groups (Each section ascending alphabetically, but separated)</li> </ul> Language Group Order <ul> <li>Forced</li> <li>Normal</li> <li>Hard of Hearing (SDH/CC) (Least to most captions expected in the subtitle)</li> </ul> <p>type_priority overrides the Language Group Order with an explicit ranking of \"forced\", \"normal\", and \"sdh\" (cc counts as sdh); unlisted types fall to the end. The first track after sorting receives the default flag at mux time, so this also controls which subtitle type becomes default.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.filter","title":"filter","text":"<pre><code>filter(predicate)\n</code></pre> <p>Return a new Tracks with tracks filtered by predicate, preserving metadata.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.merge_video_selections","title":"merge_video_selections <code>staticmethod</code>","text":"<pre><code>merge_video_selections(*groups)\n</code></pre> <p>Concatenate video selections, dropping duplicates (by track id, order-preserving).</p> <p>A DV track can be chosen as both the hybrid ingredient (lowest) and an explicit deliverable; without dedup the same track would be muxed/downloaded twice.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.partition_hybrid_videos","title":"partition_hybrid_videos <code>staticmethod</code>","text":"<pre><code>partition_hybrid_videos(videos, non_hybrid_ranges)\n</code></pre> <p>Split videos into hybrid-ingredient candidates and the standalone-deliverable pool.</p> <p>HDR10/HDR10+/DV tracks are hybrid ingredients; they only enter the standalone pool when their range was explicitly requested alongside HYBRID, so e.g. <code>-r HYBRID</code> muxes only the hybrid while <code>-r HYBRID,HDR10P</code> also delivers HDR10+.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.flag_hybrid_ingredients","title":"flag_hybrid_ingredients <code>staticmethod</code>","text":"<pre><code>flag_hybrid_ingredients(\n hybrid_selected, non_hybrid_selected\n)\n</code></pre> <p>Mark tracks selected only as hybrid ingredients so the standalone mux loop skips them.</p> <p>A track that was also picked as an explicit deliverable (same track in both selections) stays unflagged and is muxed standalone alongside the hybrid.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.mux","title":"mux","text":"<pre><code>mux(\n title,\n delete=True,\n progress=None,\n audio_expected=True,\n title_language=None,\n skip_subtitles=False,\n)\n</code></pre> <p>Multiplex all the Tracks into a Matroska Container file.</p> <p>Parameters:</p> Name Type Description Default <code>title</code> <code>str</code> <p>Set the Matroska Container file title. Usually displayed in players instead of the filename if set.</p> required <code>delete</code> <code>bool</code> <p>Delete all track files after multiplexing.</p> <code>True</code> <code>progress</code> <code>Optional[partial]</code> <p>Update a rich progress bar via <code>completed=...</code>. This must be the progress object's update() func, pre-set with task id via functools.partial.</p> <code>None</code> <code>audio_expected</code> <code>bool</code> <p>Whether audio is expected in the output. Used to determine if embedded audio metadata should be added.</p> <code>True</code> <code>title_language</code> <code>Optional[Language]</code> <p>The title's intended language. Used to select the best video track for audio metadata when multiple video tracks exist.</p> <code>None</code> <code>skip_subtitles</code> <code>bool</code> <p>Skip muxing subtitle tracks into the container.</p> <code>False</code>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video","title":"Video","text":"<pre><code>Video(\n *args,\n codec=None,\n range_=None,\n bitrate=None,\n width=None,\n height=None,\n fps=None,\n scan_type=None,\n closed_captions=None,\n dv_compatible_bitstream=False,\n **kwargs,\n)\n</code></pre> <p> Bases: <code>Track</code></p> <p>Create a new Video track object.</p> <p>Parameters:</p> Name Type Description Default <code>codec</code> <code>Optional[Codec]</code> <p>A Video.Codec enum representing the video codec. If not specified, MediaInfo will be used to retrieve the codec once the track has been downloaded.</p> <code>None</code> <code>range_</code> <code>Optional[Range]</code> <p>A Video.Range enum representing the video color range. Defaults to SDR if not specified.</p> <code>None</code> <code>bitrate</code> <code>Optional[Union[str, int, float]]</code> <p>A number or float representing the average bandwidth in bytes/s. Float values are rounded up to the nearest integer.</p> <code>None</code> <code>width</code> <code>Optional[int]</code> <p>The horizontal resolution of the video.</p> <code>None</code> <code>height</code> <code>Optional[int]</code> <p>The vertical resolution of the video.</p> <code>None</code> <code>fps</code> <code>Optional[Union[str, int, float]]</code> <p>A number, float, or string representing the frames/s of the video. Strings may represent numbers, floats, or a fraction (num/den). All strings will be cast to either a number or float.</p> <code>None</code> <p>Note: If codec, bitrate, width, height, or fps is not specified some checks may be skipped or assume a value. Specifying as much information as possible is highly recommended.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.Range","title":"Range","text":"<p> Bases: <code>str</code>, <code>Enum</code></p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.Range.from_cicp","title":"from_cicp <code>staticmethod</code>","text":"<pre><code>from_cicp(primaries, transfer, matrix)\n</code></pre> <p>Convert CICP (Coding-Independent Code Points) values to Video Range.</p> <p>CICP is defined in ITU-T H.273 and ISO/IEC 23091-2 for signaling video color properties independently of the compression codec. These values are used across AVC (H.264), HEVC (H.265), VVC, AV1, and other modern codecs.</p> <p>The enum values (Primaries, Transfer, Matrix) match the official specifications: - ITU-T H.273: Coding-independent code points for video signal type identification - ISO/IEC 23091-2: Information technology \u2014 Coding-independent code points \u2014 Part 2: Video - H.264 Table E-3 (Colour Primaries) and Table E-4 (Transfer Characteristics) - H.265 Table E.3 and E.4 (identical to H.264)</p> <p>Note: Value 0 = \"Reserved\" and Value 2 = \"Unspecified\" per specification. While both effectively mean \"unknown\" in practice, the distinction matters for spec compliance. Value 2 was added based on user feedback (GitHub issue) and verified against FFmpeg's AVColorPrimaries/AVColorTransferCharacteristic enums.</p> <p>Sources: - https://www.itu.int/rec/T-REC-H.273 - https://www.itu.int/rec/T-REC-H.Sup19-202104-I - https://github.com/FFmpeg/FFmpeg/blob/master/libavutil/pixfmt.h</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.change_color_range","title":"change_color_range","text":"<pre><code>change_color_range(range_)\n</code></pre> <p>Change the Video's Color Range to Limited (0) or Full (1).</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.normalize_vui","title":"normalize_vui","text":"<pre><code>normalize_vui()\n</code></pre> <p>Rewrite SPS VUI colour metadata to match <code>self.range</code>.</p> <p>Some services ship HDR10/HLG bitstreams with stale BT.709 VUI, which makes downstream tools mis-classify the file. The manifest-derived range is the source of truth. Skips SDR, DV, and HYBRID. Returns True if the bitstream was rewritten.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.ccextractor","title":"ccextractor","text":"<pre><code>ccextractor(track_id, out_path, language, original=False)\n</code></pre> <p>Return a TextTrack object representing CC track extracted by CCExtractor.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.extract_c608","title":"extract_c608","text":"<pre><code>extract_c608()\n</code></pre> <p>Extract Apple-Style c608 box (CEA-608) subtitle using ccextractor.</p> <p>This isn't much more than a wrapper to the track.ccextractor function. All this does, is actually check if a c608 box exists and only if so does it actually call ccextractor.</p> <p>Even though there is a possibility of more than one c608 box, only one can actually be extracted. Not only that but it's very possible this needs to be done before any decryption as the decryption may destroy some of the metadata.</p> Need a test file with more than one c608 box to add support for <p>more than one CEA-608 extraction.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.remove_eia_cc","title":"remove_eia_cc","text":"<pre><code>remove_eia_cc()\n</code></pre> <p>Remove EIA-CC data from Bitstream while keeping SEI data.</p> <p>This works by removing all NAL Unit's with the Type of 6 from the bistream and then re-adding SEI data (effectively a new NAL Unit with just the SEI data). Only bitstreams with x264 encoding information is currently supported due to the obscurity on the MDAT mp4 box structure. Therefore, we need to use hacky regex.</p>"}]}