Files
unshackle/search/search_index.json
T
2026-08-23 18:26:25 +00:00

1 line
713 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 DASH, HLS, and Smooth Streaming (ISM) parsing, both Widevine and PlayReady DRM, and a built-in HTTP server.</p> <p>Use responsibly</p> <p>The GPL-3.0 licence covers unshackle. Do not use it for content you do not have the rights to. Keep the core free and open, keep your own services private, and be kind.</p>"},{"location":"#what-it-does","title":"What it does","text":"<p>unshackle does everything except talk to the streaming platform. You write that part as a service module (Creating a Service). Point unshackle at a title 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>Get the content keys through a Widevine or PlayReady CDM, with optional key vaults that let unshackle reuse a content key instead of licensing it again.</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 A plugin API for the service modules you write. unshackle includes none 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<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 unshackle passes the value after it 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 do your first download.</li> <li>Downloading. The full <code>dl</code> command guide: quality, codecs, languages, track selection, and output.</li> <li>Configuration. Where <code>unshackle.yaml</code> lives, the directory layout, and how to edit values. Full config key list in the Configuration Reference.</li> <li>REST API. Operate the <code>serve</code> HTTP server and drive downloads programmatically.</li> </ul> <p>Getting help</p> <p>Operate <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 platform: how to log in, how to look up a title, what video/audio/subtitle tracks exist, and how to license any DRM. The unshackle core does everything else (track selection, downloading, decryption, muxing, naming).</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. You do not need anything here to operate the CLI. The code of a service is deliberately separate from the core, so it can live in its own private repository.</p> <p>unshackle ships two reference services. EXAMPLE, at <code>unshackle/services/EXAMPLE/</code>, is a non-runnable showcase of every framework feature in a single file. Read it alongside this page. Most snippets below come from it. MUSIC_EXAMPLE, at <code>unshackle/services/MUSIC_EXAMPLE/</code>, is the same kind of showcase for a music service. If your platform has songs, read that one too.</p>"},{"location":"dev/creating-a-service/#how-unshackle-finds-a-service","title":"How unshackle finds a service","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 unshackle clones for you). 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 match the folder/tag name exactly. 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, and unshackle ignores the later duplicates. Put your own local overrides last to use them as fallbacks, or first to override a repo.</li> </ol> <p>After installation, you call a service 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 everyone who runs the service shares it. 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 Python cannot find the absolute <code>unshackle.services.&lt;TAG&gt;.*</code> path 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. <code>ANIME</code> <code>bool</code> Set <code>True</code> when the catalogue is anime, so metadata lookups prefer AniList. A title's own <code>anime</code> flag overrides it. <code>DAILY</code> <code>bool</code> Set <code>True</code> when the catalogue is daily/date-based (talk shows, news, sports), so episodes are named by air date. A title's own <code>daily</code> flag overrides it. <p><code>NO_SUBTITLES</code> is a convention, not a base-class attribute</p> <p><code>dl.py</code> uses <code>hasattr</code> to find <code>NO_SUBTITLES</code>, and the <code>Service</code> base class deliberately does not declare it, 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, for example authentication tokens. <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. \"this service delivers HDR only 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 streaming platform 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-write","title":"The methods you write","text":"<p>unshackle calls the methods 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>unshackle chooses the command from the folder/class name, not from the <code>name=</code> in <code>@click.command</code>. A mismatched <code>name=</code> still loads and runs. It only 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 requirement of the command lookup.</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 work correctly for 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 come 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>prompt_user</code>) so the prompt renders correctly alongside progress and log output.</p> <p>Make each token cache entry unique</p> <p>The cache above uses <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 is not obvious from the caching API, which happily lets you use a single flat name.</p> <p>Use the credential carefully</p> <p>Use the <code>Credential</code> only inside <code>authenticate()</code> to get tokens. Do not 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 the kind of title:</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. You must return at least one title. If you return none, unshackle treats the ID 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 part=None)\n</code></pre> <p>Pass <code>air_date</code> for daily and sports titles to name by date instead of <code>SxxExx</code>. Return a <code>Series([...])</code> of episodes. Pass <code>part</code> only when the service splits one episode into several videos, see Split episodes.</p> <pre><code>Song(id_, service, name, artist, album, track, disc=1, year=None,\n language=None, data=None, ...)\n</code></pre> <p>Return an <code>Album([...])</code> of songs. <code>disc</code> defaults to 1 and <code>year</code> is optional. Optional metadata keywords such as <code>album_artist</code>, <code>genre</code>, <code>isrc</code>, <code>label</code>, <code>lyrics</code> and <code>artwork_url</code> feed the tagger and the naming templates. Read the class for the current list.</p> <p>From <code>get_tracks()</code>, give one <code>Audio</code> track for each codec and bitrate you offer for the song. The framework then selects one with its usual audio options. A <code>Song</code> skips the muxer, so restore the real container suffix on the track path in <code>on_track_downloaded</code>. The MUSIC_EXAMPLE service shows the full music surface.</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/#split-episodes","title":"Split episodes","text":"<p>Some services split one logical episode into several separately playable videos, for example a variety show that ships episode 1 as Episode 1 (Part 1), (Part 2) and (Part 3). <code>Episode.number</code> stays an <code>int</code>. The optional <code>part</code> carries the index.</p> <pre><code>Episode(..., season=1, number=1, part=1, name=\"The Reckoning\")\nEpisode(..., season=1, number=1, part=2, name=\"The Reckoning\")\n</code></pre> <ol> <li><code>part</code> counts from 1, contiguous. unshackle rejects <code>part=0</code>, and <code>-w</code> can only address parts up to 99.</li> <li>Every part of one episode shares the same <code>season</code> and <code>number</code>.</li> <li>Each part is a separate <code>Episode</code> with its own unique <code>id_</code>.</li> <li>Unsplit episode: leave <code>part</code> unset. Never pass <code>part=1</code> for a whole episode.</li> <li>Do not put the part in <code>name</code> or <code>number</code>. Pass a clean <code>name</code> (or <code>None</code>) and set <code>part</code>.</li> <li><code>part</code> is a split episode, not a split season. A service listing Season 1 Part 2 describes a group of episodes. Keep numbering those in sequence, the way the shipped services do.</li> </ol> <p><code>part</code> accepts an <code>int</code> or a digit string. A value that is not an integer raises <code>TypeError</code>. A value of <code>0</code> or less raises <code>ValueError</code>.</p> <p>The framework never infers a part from the episode name</p> <p>Rule 6 is the reason. Shipped services already use the word \"Part\" to mean a season part, so name-sniffing would misread every one of them. The part has to arrive structurally, as the <code>part</code> argument.</p> <p>Clean the part out of the name</p> <p><code>Episode</code> discards any <code>name</code> that starts with <code>Episode &lt;number&gt;</code>, so a raw <code>\"Episode 1 (Part 2): The Reckoning\"</code> leaves you with no episode name at all. Remove the prefix before you pass it, or pass <code>None</code>.</p> <p>Once <code>part</code> is set, the filename gains a part token (<code>S01E01.Part.2</code>, see Output &amp; naming), <code>-w S01E01.2</code> selects a single part while a bare <code>-w S01E01</code> selects them all, and the <code>--list-titles</code> tree labels the episode <code>01.2</code>. The REST API reports it as an extra <code>part</code> field on the serialized title, described in Endpoints.</p> <p>Opt-in and additive</p> <p>Leaving <code>part</code> unset costs you nothing: filenames, sort order, <code>-w</code> matching and the API JSON are identical to a plain episode, so a service that does not split episodes has nothing to adopt.</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 assemble 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 <code>to_tracks</code> cannot derive a track's language and you gave no valid fallback, it raises <code>ValueError</code>. It is also what lets the parser flag <code>is_original_lang</code> on each track (through <code>is_close_match</code>), which drives <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 bitstream, 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 is wrong. Only the service author knows the platform embeds HDR10+, so it is 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> and the others) 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 you must stash anything a license call needs (the license URL, <code>dt-custom-data</code>, a session token) now, during <code>get_tracks</code>, onto <code>self.license_data</code> or <code>title.data</code>. This is a lifecycle-timing consequence you cannot infer from the callback signatures.</p> <p>Give the KID if you cheaply can</p> <p>If you can get a track's Key ID (32-char hex) without downloading the track data, set <code>track.kid</code>. It speeds up the decryption and 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 of 0 or more <code>Chapter</code>s. It sorts by timestamp, numbers the chapters at mux time, and adds a <code>00:00:00.000</code> chapter if none exists. Timestamps take <code>\"HH:MM:SS[.mmm]\"</code>, int milliseconds, or float seconds.</p> <pre><code>def get_chapters(self, title: Title_T) -&gt; Chapters:\n chapters = [Chapter(name=c.get(\"name\"), timestamp=c[\"start\"]) for c in title.data.get(\"chapters\", [])]\n return Chapters(sorted(chapters, key=lambda c: c.timestamp))\n</code></pre> <p>Sort by timestamp before you build the <code>Chapters</code></p> <p><code>Chapters.add()</code> adds its own unnamed <code>Chapter(0)</code> once you add a chapter that is not at <code>0</code>, and a duplicate timestamp raises <code>ValueError</code>. Sort first, so yours lands before it.</p> <p>You never need to add <code>Chapter(0)</code>. An API chapter at <code>0</code> keeps its name. Drop duplicate timestamps.</p> <p>Close a named range with an unnamed chapter</p> <p>An unnamed <code>Chapter</code> ends the range before it: <code>Chapter(name=\"Intro\")</code> at the start, an unnamed one where the intro ends.</p> <p>Don't invent chapter names</p> <p>Never write <code>\"Chapter 1\"</code>; leave unnamed chapters unnamed. Users set <code>chapter_fallback_name</code> in their config (for example, <code>\"Chapter {i:02}\"</code>).</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 write 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>: write nothing. The framework POSTs the challenge to that URL itself.</li> <li>Your service needs a custom endpoint or extra headers: 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 content 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 the service does not do:</p> <ul> <li>HLS AES-128 (<code>ClearKey</code>) tracks and DRM-free tracks have no license callback. The content key comes from the manifest, and unshackle applies it 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>Try 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> that returns an instance. <code>__init__</code> calls <code>super().__init__(ctx)</code>.</li> <li> <code>get_titles</code>, <code>get_tracks</code> and <code>get_chapters</code> written. 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 or language.</li> <li> Encrypted tracks carry their DRM. The license callbacks you need return responses unmodified.</li> <li> URLs, user agents, and certificates live in <code>config.yaml</code>, read through <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. For a music service, read <code>unshackle/services/MUSIC_EXAMPLE/</code> too.</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 make tracks, the DRM hooks that license and decrypt them, and the request and HTTP 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 download titles, you never touch these classes directly. See Downloading and the CLI reference instead. If you write or read a service plugin, this page explains what each object is and how the pieces connect. For a guided, step-by-step walkthrough, 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 only 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 (movie / episode)\n \u2502 a Song skips the muxer and keeps its own container\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>The core does everything after that (track selection, licensing, decryption, repacking, subtitle conversion, and muxing) with the objects your service returned. Your job is to give 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 give the details of 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>. <code>ANIME</code> <code>bool</code> The catalogue is anime, so metadata lookups prefer AniList. A title's own <code>anime</code> flag overrides it. <code>DAILY</code> <code>bool</code> The catalogue is daily/date-based, so episodes are named by air date. A title's own <code>daily</code> flag overrides it."},{"location":"dev/service-architecture/#required-methods","title":"Required methods","text":"<p>These are abstract. A service will not load unless it defines all three:</p> <ul> <li><code>get_titles() -&gt; Titles_T</code>: find the title collection for the requested ID.</li> <li><code>get_tracks(title) -&gt; Tracks</code>: assemble 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 do a real login handshake.</li> <li><code>search()</code>: raises <code>NotImplementedError</code> by default. Write it so that the <code>search</code> command can operate.</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. It goes 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 your service must fetch or inject keys 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 HTTP 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> and the <code>proxy_query</code> and <code>proxy_provider</code> context params that <code>dl</code> derives from it, consults the per-service <code>proxy_map</code>, and, if <code>GEOFENCE</code> is set and you did not give an explicit proxy, 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>You must give <code>name</code>. <code>year</code> is optional, but it must be a positive integer if you give it.</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. You must give <code>season</code> and <code>number</code>, and <code>0</code> is a valid value. unshackle converts an <code>air_date</code> to a <code>date</code> so the <code>{date}</code> naming token stays clean, and it discards a placeholder episode <code>name</code> like <code>\"Episode 4\"</code> automatically.</p> <pre><code>Song(id_, service, name, artist, album, track, disc=1, year=None,\n language=None, data=None, ...)\n</code></pre> <p>You must give <code>name</code>, <code>artist</code>, <code>album</code>, and <code>track</code>, and unshackle validates them. <code>disc</code> defaults to 1, and <code>year</code> is optional. A single therefore needs no <code>disc</code>, and an undated release needs no <code>year</code>.</p> <p>A <code>Song</code> also takes optional metadata keywords that the tagger and the naming templates read: <code>album_artist</code>, <code>release_type</code>, <code>total_tracks</code>, <code>total_discs</code>, <code>genre</code>, <code>explicit</code>, <code>isrc</code>, <code>upc</code>, <code>copyright</code>, <code>label</code>, <code>lyrics</code>, and <code>artwork_url</code>. Read the class for the current list.</p> <p>The tagger also falls back to <code>Song.data</code> for fields the constructor did not get, such as the composer or a full release date. It reads the top level of that dict and a nested <code>metadata</code> sub-dict, with the nested keys winning, so either shape works.</p> <p>From <code>get_tracks()</code>, a music service gives one <code>Audio</code> track for each codec and bitrate it offers for a <code>Song</code>. The framework then selects one with its usual audio options, <code>-a</code>/<code>--acodec</code> and <code>--abitrate</code>, and its usual audio sorting. A movie or an episode uses the same options. <code>-q</code>/<code>--quality</code> sets the video height only and does not apply to music. <code>Audio</code> has no <code>bit_depth</code> or <code>sample_rate</code> field. Therefore <code>bitrate</code> separates a hi-res FLAC from a CD FLAC, and the audio sort already ranks it.</p> <p>A <code>Song</code> is an ordinary <code>Title</code> on the one generic download path. unshackle has no music-specific service API and no separate music download loop. The <code>GROUP_AUDIO_DOWNLOADS</code> flag, <code>get_music_track_options</code> and <code>get_music_collection_label</code> no longer exist, and a music service does not need them.</p> <p>Restore the container in <code>on_track_downloaded</code></p> <p>Every track downloads to a temp file named <code>Audio_&lt;id&gt;.mp4</code> whatever it holds, and the final move keeps that suffix. A <code>Song</code> skips the muxer, so its download is the delivered file, and the tagger picks its metadata format from the suffix. Rename the track path to the true container in <code>on_track_downloaded</code>, or a FLAC lands as an untaggable <code>.mp4</code>. The event fires twice, once before decryption and once at the end, so wait until <code>track.drm</code> is clear before you rename.</p> <p>The MUSIC_EXAMPLE reference service, at <code>unshackle/services/MUSIC_EXAMPLE/</code>, shows the full music surface.</p>"},{"location":"dev/service-architecture/#title-remapping","title":"Title remapping","text":"<p>After the service fetches the titles (and after any cache), the framework applies <code>remap_titles(titles, title_map)</code> with the per-service <code>title_map</code> config. This does an exact-string rename (it compares <code>Episode</code>s on their show <code>title</code>, and <code>Movie</code>s and <code>Song</code>s on their <code>name</code>), so you can change a platform's odd naming to what your library expects. <code>get_titles_cached()</code> also cache-wraps the titles, and it is region- and account-aware. See the TitleCacher notes.</p> <p>The ordering here is deliberate on both sides. The framework applies <code>title_map</code> 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 assemble 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 records its delivery method in <code>Track.Descriptor</code>, which tells unshackle how to download it:</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>The main 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>. If you do not give a <code>name</code>, unshackle derives a human-readable name from the language.</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 track 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 bits per second (rounded up). The string form displays kb/s, and <code>--vbitrate</code> and <code>--abitrate</code> compare in 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 (for example, 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 only return correct tracks.</p>"},{"location":"dev/service-architecture/#manifest-parsers","title":"Manifest parsers","text":"<p>Most services do not assemble tracks by hand. They give 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 the parser needs it to make relative segment paths absolute.</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 only 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 they cannot derive a track's language and you gave no valid fallback. Always pass the title's original recorded language. For HLS, <code>to_tracks</code> uses this fallback directly for the primary track, because 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). A dropped segment is invisible to the whole download: unshackle ignores its <code>EXT-X-KEY</code> and its <code>EXT-X-DISCONTINUITY</code>, so a clear ad break inside an encrypted track does not disturb decryption.</li> <li>DASH: pass a <code>period_filter</code> callable to <code>to_tracks</code> to drop whole periods. unshackle automatically drops the caching-breadth periods that some services send, and the non-<code>content</code> segment types.</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. The parser reads <code>SegmentTemplate</code>, <code>SegmentList</code>, and <code>SegmentBase</code> addressing, and <code>$Number%0Nd$</code> padding.</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 have no explicit IV.</li> <li>ISM has no list of segments and no init segments: the parser synthesizes segment URLs from the <code>&lt;c&gt;</code> fragment timeline, and rebuilds a <code>moov</code>/<code>ftyp</code> init box 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 content 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 backend. Your service gives the network calls that must carry the CDM's challenge. 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 operate shaka-packager yourself. The <code>Widevine</code>/<code>PlayReady</code> classes drive the CDM handshake and call the decryption backend. Your hook is only the \"send this challenge, give me back the license\" step.</p>"},{"location":"dev/service-architecture/#how-unshackle-chooses-a-cdm-and-finds-keys","title":"How unshackle chooses a CDM and finds keys","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 cache of content keys and the configured key vaults. Only unresolved KIDs trigger an actual license request, and the framework writes newly licensed keys back to every vault. This is why the same content key is rarely re-licensed twice. Users configure all of this in DRM and CDM and Key vaults. The DRM API reference gives the API surface.</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 signalling 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, to make a single track that carries both HDR10 metadata and the DV RPU. Both are automatic once the pipeline selects the right tracks. A service only needs to give accurate ranges.</p>"},{"location":"dev/service-architecture/#request-and-http-session-objects","title":"Request and HTTP 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 HTTP session into the manifest parsers and DRM calls so headers, cookies, and proxies flow everywhere. (unshackle also ships an rnet-based TLS-fingerprinting HTTP session that the newer <code>session()</code> factory uses and that the <code>network</code> config key configures.)</li> <li><code>self.credential</code>: the active <code>Credential</code> (<code>username:password[:extra]</code>), populated by <code>authenticate</code>. unshackle uses its <code>sha1</code> 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 <code>--no-cache</code> bypasses it.</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 match the class name exactly. 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 operate <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 for people who make 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: show the services available on the server, use 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 follow its status and live progress (by polling, or by subscribing to its Server-Sent Events stream), 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, examine 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 job 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 find titles, download them, 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 routes the server mounts depend on how you start the server:</p> Default (CDM + REST)<code>--api-only</code><code>--remote-only</code> <p>The server mounts both the pywidevine/pyplayready CDM endpoints and the full REST API. This is the mode you get when you operate <code>unshackle serve</code> with no mode flags.</p> <p>The server mounts only the REST API. It does not mount the CDM HTTP endpoints. Authentication uses the single configured API key (or none, with <code>--no-key</code>).</p> <p>The server mounts only the remote-session subset of routes (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>. The server generates it from the same route table it serves, so it always matches the version you operate. 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 API 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 gives 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 an API 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>GET</code> <code>/api/download/jobs/{job_id}/events</code> Stream one job's progress as Server-Sent Events. <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> Remote 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 API key returns <code>401</code>. Authentication gives the full model, including per-key service allowlists.</p>"},{"location":"dev/rest-api/#where-to-go-next","title":"Where to go next","text":"<ul> <li>Quick Start: start the server, set an API key, and operate 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 API key in a request header, and the server examines it against the API keys in your configuration. This page explains how that check works, how to configure API keys, and how clients send them. It also explains the extra controls on top of the API key: per-key service allowlists, per-key CDM device access, and remote session IP binding.</p> <p>You start the API 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 operate in two shapes, and each uses a slightly different piece of code to examine your API 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 the developer notes below give them.</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 API key that the server accepts. The server allows requests that present it in the <code>X-Secret-Key</code> header. The server rejects everything else.</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 API 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 API key. A user entry can also grant CDM device access and restrict which services that API 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 config 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 server automatically adds the configured <code>api_secret</code> as an extra accepted API key alongside everyone in <code>users</code>. It gives that API key access to all loaded Widevine and PlayReady devices, and labels it <code>api_user</code>. So <code>api_secret</code> behaves as an admin-level API key in addition to any named users you define.</p> <p>On the API-only server, the server accepts only <code>api_secret</code>: the single-key model. (See the developer notes for the exact difference.)</p>"},{"location":"dev/rest-api/authentication/#cdm-device-access-per-api-key","title":"CDM device access per API key","text":"<p>Under the integrated server, an API key can do DRM licensing only 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>, the server gives that API key no PlayReady access, and logs a warning at startup. You must name the PlayReady devices explicitly for any API 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 content keys (<code>KID:KEY</code>) for a remote session download. The presence of devices on the calling API key decides it. With empty <code>devices</code> and <code>playready_devices</code>, the server can only proxy CDM challenges, so the client must operate its own CDM. Once those lists are populated, the client may request <code>mode:server_cdm</code> and receive content keys back. Do not look for a tier setting. The devices you configure are 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. The server allows every request, ignores <code>X-Secret-Key</code>, and needs no API key in your configuration.</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>, any client that can reach the port can show your services, start downloads, and use your CDM devices. Never put a <code>--no-key</code> server on 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 match one of the configured API keys exactly (<code>api_secret</code>, or one of the keys under <code>users</code>). There is no login step, no HTTP session cookie, and no token exchange for API access. The client sends the same static API key on each request.</p> <p>One route also accepts the key as a query parameter</p> <p>The job event stream, <code>GET /api/download/jobs/{job_id}/events</code>, also accepts the API key in a <code>secret_key</code> query parameter. This is for browsers: the <code>EventSource</code> API cannot set request headers. The exception applies to that one route only, and it works in both server modes.</p> <pre><code>new EventSource(`http://127.0.0.1:8786/api/download/jobs/${jobId}/events?secret_key=${key}`);\n</code></pre> <p>The header always wins. If the request has an <code>X-Secret-Key</code> header, the server examines that header and ignores the query parameter. The server rejects a wrong header even when the query parameter holds a valid API key.</p> <p>An API key in a URL is easier to leak than an API key in a header, because proxies and browser history can record it. Use the header wherever your client can set one.</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 API 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 an API 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 API key.</p>"},{"location":"dev/rest-api/authentication/#authentication-failures","title":"Authentication failures","text":"<p>When the server rejects a request 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 an API 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>In your client, treat any <code>401</code> as an authentication problem and parse both shapes, because the standard error body is not always present.</p>"},{"location":"dev/rest-api/authentication/#access-controls-on-top-of-the-api-key","title":"Access controls on top of the API key","text":"<p>After the server authenticates a request, several additional controls decide what that specific API key can do.</p>"},{"location":"dev/rest-api/authentication/#per-key-service-allowlists","title":"Per-key service allowlists","text":"<p>You can restrict which services an API key may use. Two layers combine:</p> <ul> <li>Global allowlist: <code>serve.services</code>, applied to every API 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. The server rejects a request for a service outside the API key's allowlist as an invalid service. The server matches service tags after normalisation, so casing and aliases give the same result.</p>"},{"location":"dev/rest-api/authentication/#cdm-overrides-and-per-job-credentials","title":"CDM overrides and per-job credentials","text":"<p>The server config gates two download-time capabilities. Unless you enable them, the server refuses them with <code>403 Forbidden</code>, even for an authenticated API 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 you can combine them. For a locked-down or public-facing deployment, leave both unset. They then default off and reject with <code>403</code>, so client requests can never steer the server's CDM or feed it their own logins. Enable them only 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 you enable <code>allow_job_credentials</code> and a download job supplies its own <code>credential</code> / <code>credentials</code>, the server gives each distinct credential its own isolated token cache. The server never shares or merges client-supplied logins with its configured-credential caches. They cannot cross-contaminate or read the server's own token state, and they do not clobber each other.</p> <p>See Downloads for how the download endpoint uses these fields.</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 API key. When the server creates a remote session, it records the client's IP address. Any later request for that remote session must come from the same IP, or the server rejects it with <code>403 Forbidden</code>. Thus the server binds a remote session both to the API key that created it and to the address it came from.</p>"},{"location":"dev/rest-api/authentication/#transport-security-https","title":"Transport security (HTTPS)","text":"<p>The API server speaks plain HTTP. Because the client sends your API key on every request, do not use it over an unencrypted connection on an untrusted network. To serve over HTTPS, operate 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 Caddy end the TLS connection 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> Query-parameter alternative <code>?secret_key=</code> on <code>GET /api/download/jobs/{job_id}/events</code> only 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-server-does-the-check","title":"Developer notes: how the server does the check","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 holds your <code>api_secret</code> (labelled <code>api_user</code>, with no devices) plus every key under <code>serve.users</code>. A per-user key therefore authenticates here exactly as it does on the integrated server, and that user's <code>services</code> allowlist applies as usual. With <code>--no-key</code>, this middleware is 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> <p>Both middlewares read the caller's API key through the shared <code>request_secret_key()</code> helper in <code>unshackle/core/api/handlers.py</code>. That helper returns the <code>X-Secret-Key</code> header, and falls back to the <code>secret_key</code> query parameter only when the matched route is the job event stream. The integrated server needs one extra branch for this. pywidevine's <code>authentication</code> is header-only. So <code>serve_authentication</code> compares the API key from the query parameter itself when the header is absent, and delegates to pywidevine in every other case. That is why both modes reject a present-but-wrong header.</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>. The middleware advertises <code>Authorization</code> 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> have routes.</p>"},{"location":"dev/rest-api/authentication/#where-device-access-is-read","title":"Where device access is read","text":"<p>The map of accepted API keys lives at <code>request.app[\"config\"][\"users\"]</code>. For DRM operations, an API key's permitted Widevine devices come from its <code>devices</code> list, and PlayReady devices from <code>playready_devices</code>. The server uses the first configured device 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 API key's device list when the server chooses 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 give. This page groups the routes 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. The Authentication page gives authentication, server modes, and the <code>X-Secret-Key</code> header in detail. 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 so that they match your own <code>unshackle serve -h &lt;host&gt; -p &lt;port&gt;</code> invocation.</p> <p>Interactive docs</p> <p>The server mounts a live Swagger UI at <code>/api/docs/</code> whenever it does not operate 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 an API 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 you configure an API key. <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 this page documents a <code>204 No Content</code>.</li> <li>CORS. Every response carries permissive CORS headers, and the server answers <code>OPTIONS</code> preflight requests 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. The effective allowlist for your API key filters the service-facing endpoints (the intersection of the global <code>serve.services</code> list and your per-key list). The server treats services you cannot use 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 accept both shapes. The Error responses section at the bottom of this page gives the full error model.</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 \"code_hash\": \"1d22a1e\",\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><code>code_hash</code> fingerprints the framework source the server operates, so it names the code itself rather than the release. It is the same value for a git checkout and for an installed package built from that checkout. It changes when you edit anything under <code>unshackle/core</code>, <code>unshackle/commands</code>, <code>unshackle/utils</code>, or <code>unshackle/vaults</code>. Service modules are not included. unshackle sets the value to <code>null</code> only when it cannot read the source files.</p> <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>Show the streaming services available on this server, filtered by your allowlist. Each entry gives the service's tag, matching rules, capability flags, and its CLI parameters (useful when you make 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>Find titles in a service by query string. The service must have a <code>search()</code> method (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 initialise, or does not support search."},{"location":"dev/rest-api/endpoints/#post-apilist-titles","title":"<code>POST /api/list-titles</code>","text":"<p>Get the list of titles behind a title ID, for example episodes or a movie, 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>You can also pass service-specific CLI options 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 also add <code>series_title</code>, <code>season</code>, and <code>number</code>.</p> <p>A song serializes as <code>\"other\"</code></p> <p>A song has no <code>type</code> of its own. The server sends it as <code>\"other\"</code>, and the response carries none of its music fields: no artist, no album, no track or disc number, and no <code>year</code>. <code>name</code> holds the song name. To read the disc and track numbers of a release, operate the CLI with <code>--list-titles</code>. You can still select songs over the API, through the <code>wanted</code> parameter.</p> <p>These keys are sent only when the title carries them, so a title without them serializes exactly as before:</p> Key Type On Meaning <code>part</code> integer episode Part index of a split episode, counting from 1. <code>air_date</code> string episode ISO air date of daily and date-based content. unshackle names the episode by date instead of <code>SxxExx</code>. <code>absolute</code> integer episode Absolute episode number across all seasons. <code>daily</code> boolean episode The episode is daily/date-based. Set from the title, or from the service's <code>DAILY</code> class attribute. <code>anime</code> boolean episode, movie The title is anime, so metadata lookups prefer AniList. Set from the title, or from the service's <code>ANIME</code> class attribute. <p><code>part</code> on a split episode</p> <p>A service that splits one episode into several separately playable videos reports each one as its own episode. Those titles share a <code>season</code> and <code>number</code> and add a <code>part</code> integer counting from 1. No other title carries the <code>part</code> field, so a client can ignore it safely. See Split episodes.</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>Show the video, audio, and subtitle tracks for a title. For series, you can scope to specific episodes.</p> <p>Spotting the original-language audio</p> <p>Each audio track carries <code>is_original</code>, which marks the track the default <code>lang</code> of <code>orig</code> selects. unshackle finds it with the same language matcher the downloader uses. Thus it stays correct for regional variants a client cannot separate from tag text alone (<code>pt</code> marks <code>pt-BR</code> rather than <code>pt-PT</code>). Services need not report a title's language, so every track can legitimately come back <code>false</code>.</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 / string[] no Episode/season range (e.g. <code>\"S01E01-S01E03\"</code>), or a song selector (e.g. <code>\"1-5\"</code>, <code>\"1,3,7\"</code>, or <code>\"2x3\"</code> for disc 2 track 3). A list of selectors is accepted too. <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>part</code> int/string no Part index of a split episode (combined with <code>season</code> and <code>episode</code>). <code>profile</code>, <code>proxy</code>, <code>no_proxy</code>, <code>cdm_type</code> - no As on <code>list-titles</code>. <p>When you give both <code>season</code> and <code>episode</code>, the server combines them into a <code>\"{season}x{episode}\"</code> selector. <code>part</code> narrows that to <code>\"{season}x{episode}.{part}\"</code>, one part of a split episode. Without <code>part</code> you get every part of the episode. The server reads <code>part</code> only when you give both <code>season</code> and <code>episode</code>, and <code>wanted</code> takes precedence over all three. To scope a part by range, put it in <code>wanted</code> instead (<code>\"S01E01.2\"</code>).</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\", \"is_original\": true,\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>The server sorts tracks by bitrate, descending. Episodes the server cannot get go into <code>unavailable_episodes</code>, rather than failing the whole request. Track objects here do not include a download <code>url</code>. Only the remote session endpoints give segment URLs.</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 job 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>. You can prioritise only queued jobs. You can retry or remove only terminal jobs.</p>"},{"location":"dev/rest-api/endpoints/#post-apidownload","title":"<code>POST /api/download</code>","text":"<p>Make a download job. It 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 layout. <code>no_atmos</code> boolean <code>false</code> Exclude Atmos tracks. <code>wanted</code> string / string[] <code>[]</code> Episode/season selectors, as a list or as one comma-separated string. Accepts the part form, <code>\"S01E01.2\"</code>, and the air-date form, <code>\"2026-08-11\"</code> or <code>\"2026-08-01:2026-08-31\"</code>. For a music release, a selector is a track number, <code>\"1-5\"</code> or <code>\"1,3,7\"</code>, or <code>\"{disc}x{track}\"</code> such as <code>\"2x3\"</code>. <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_audio</code> string[] <code>[]</code> Audio languages that must exist. The job fails if one is missing, even with <code>best_available</code>. <code>require_video</code> string[] <code>[]</code> Video languages that must exist. The job fails if one is missing, even with <code>best_available</code>. <code>require_subs</code> string[] <code>[]</code> Subtitle languages that must exist. The job fails if one is missing. <code>s_lang</code> still decides what to keep. <code>forced_subs</code> boolean <code>false</code> Include forced subtitles. <code>forced_s_lang</code> string[] <code>[]</code> Forced subtitle language(s); implies <code>forced_subs</code>. <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>adaptive_workers</code> boolean <code>false</code> Scale segment workers to measured CDN throughput, up to the <code>workers</code> cap. <code>download_processes</code> int <code>1</code> Split a track's segments across this many processes. Only engages for large batches. <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>tvdb_id</code> / <code>anilist_id</code> - <code>null</code> External ID overrides. Each resolves its metadata directly instead of by a title search, and is used for tagging. Set <code>enrich</code> to also take the title, year and original language. Give at most one of <code>tmdb_id</code>, <code>imdb_id</code> and <code>tvdb_id</code>, since unshackle resolves the others from it. Sending two returns <code>400</code>. <code>anilist_id</code> still combines with one of them. <code>tmdb_id</code> and <code>tvdb_id</code> must be positive integers, <code>imdb_id</code> must look like <code>tt1375666</code>, and <code>anilist_id</code> must be a positive integer or a string like <code>mal:12345</code>, or the request returns <code>400</code>. An ID whose provider is unconfigured, such as <code>tmdb_id</code> with no <code>tmdb_api_key</code>, fails the job rather than returning <code>400</code>. <code>anilist_id</code> needs no API key. <code>tvdb_order</code> <code>official</code>, <code>dvd</code>, <code>absolute</code>, <code>alternate</code>, <code>regional</code> <code>null</code> Renumber episodes to a TVDB season order. Falls back to the <code>tvdb_order</code> config option. <code>enrich</code> boolean <code>false</code> Overwrite title, year and original language with the external source's. Needs one of <code>tmdb_id</code>, <code>imdb_id</code>, <code>tvdb_id</code> or <code>anilist_id</code>. Without one the job fails instead of returning <code>400</code>. <code>daily</code> boolean <code>false</code> Treat the title as daily/date-based content and fill missing episode air dates from TVDB. The fill needs <code>enrich</code> and a TVDB ID. An air date the service already set is kept. <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>. <code>vcodec</code> must be one of H264/H265/H.264/H.265/AVC/HEVC/VC1/VC-1/VP8/VP9/AV1. <code>acodec</code> must be one of AAC/AC3/EC3/EAC3/DD/DD+/AC4/OPUS/FLAC/ALAC/VORBIS/OGG/DTS. <code>range</code> must be one of SDR/HDR10/HDR10P/DV/HLG/HYBRID, and <code>HDR10+</code> is also valid. The bitrate, download worker, and download counts must be positive integers. You may set at most one of the <code>*_only</code> flags. You cannot combine <code>no_subs</code> with <code>subs_only</code>, or <code>no_audio</code> with <code>audio_only</code>.</p> <p>Rejected parameters</p> <p><code>postscript</code>, <code>post_script</code> and <code>post_scripts</code> are never accepted. A body containing any of them gets <code>400 INVALID_PARAMETERS</code>, because a command string that arrives from an HTTP caller would be remote code execution. You configure post-download hooks only in <code>unshackle.yaml</code>, where they still operate for API jobs. See Post-download scripts.</p> <p>Gated parameters (developer)</p> <p>The server accepts a few keys, but permits them only when the server config opts in. Otherwise the server rejects the request 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>On the server, unshackle merges the effective parameters in this order: 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>Show 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/#get-apidownloadjobsjob_idevents","title":"<code>GET /api/download/jobs/{job_id}/events</code>","text":"<p>Stream the job's progress as Server-Sent Events. Use this instead of polling <code>GET /api/download/jobs/{job_id}</code>.</p> <p>The response has the content type <code>text/event-stream</code>. Each event has this format:</p> <pre><code>event: &lt;name&gt;\ndata: &lt;job JSON&gt;\n</code></pre> <p>The <code>data</code> field of every event is the same job object that <code>GET /api/download/jobs/{job_id}</code> returns.</p> Event When it is sent <code>snapshot</code> Immediately, as the first event. Gives the job's current state. <code>status</code> The job leaves the queue and starts to download. <code>progress</code> The worker's progress record changed. The server reads that record every 0.5 seconds, so you get at most two of these events each second, and none while the record stays the same. <code>completed</code> The job finished. The server then closes the event stream. <code>failed</code> The job failed. The server then closes the event stream. <code>cancelled</code> The job was cancelled. The server then closes the event stream. <p>The server sends a <code>: keep-alive</code> comment each 15 seconds while the job is quiet, to keep proxies from closing an idle connection. Ignore these lines.</p> <p>If the job is already in a terminal state, the server sends the <code>snapshot</code> event, then the terminal event, and closes the event stream immediately.</p> <p>Authentication from a browser</p> <p><code>EventSource</code> cannot set headers. For this endpoint only, the server also accepts the API key in the <code>secret_key</code> query parameter. This works in both server modes, the default integrated server and <code>--api-only</code>:</p> <pre><code>const events = new EventSource(\n `http://127.0.0.1:8786/api/download/jobs/${jobId}/events?secret_key=${key}`\n);\nevents.addEventListener(\"progress\", (e) =&gt; console.log(JSON.parse(e.data).progress));\nevents.addEventListener(\"completed\", () =&gt; events.close());\n</code></pre> <p>The header always wins. Send the API key in the query parameter or in the header, not both. If an <code>X-Secret-Key</code> header is present, the server examines that header and ignores the query parameter. See Authentication.</p> RequestResponse <code>200</code> <pre><code>curl -N -H \"X-Secret-Key: $KEY\" \\\n \"http://127.0.0.1:8786/api/download/jobs/b0f7c8e2-.../events\"\n</code></pre> <pre><code>event: snapshot\ndata: {\"job_id\":\"b0f7c8e2-...\",\"status\":\"downloading\",\"progress\":42.5,...}\n\nevent: progress\ndata: {\"job_id\":\"b0f7c8e2-...\",\"status\":\"downloading\",\"progress\":48.0,...}\n\n: keep-alive\n\nevent: completed\ndata: {\"job_id\":\"b0f7c8e2-...\",\"status\":\"completed\",\"progress\":100.0,...}\n</code></pre> Status Error code Meaning <code>200</code> - Event stream started. <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 try 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>A retry replays the finished job's stored parameters exactly as the original client submitted them, including any secrets such as <code>credential</code>/<code>credentials</code>. It does not use the redacted <code>parameters</code> view that <code>GET /api/download/jobs</code> and <code>GET /api/history</code> give. This is deliberate: it lets a retried job reproduce a credentialed download that the redacted job record alone never could. The API masks those credentials everywhere else. But anyone who can retry a job can operate it again with the original credentials.</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>Show the named credential profiles configured per service (usable as the <code>profile</code> parameter elsewhere). The response holds only services whose credentials are a mapping of profile name to credential. It leaves out services with a single unnamed credential. Your allowlist filters the response.</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. The server never sends secrets: it masks every config key whose name contains <code>secret</code>, <code>password</code>, <code>token</code>, <code>api_key</code>, or <code>credential</code>, and any userinfo in proxy URLs.</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. unshackle stores the history in <code>api_history.jsonl</code> in the cache directory. It skips corrupt lines, 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. The server blocks both 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. The removal of either directory mid-download would corrupt those jobs, so the endpoints refuse while a download is in progress.</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 only 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> becomes <code>true</code> when all repos updated successfully, or when you configure no repository.</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. A thin local client authenticates once against a remote server, then fetches titles, tracks, and segments, and proxies DRM licensing back through it. The server mounts these endpoints 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>The server holds remote sessions in memory. They expire after <code>serve.session_ttl</code> (default 300s), except while awaiting interactive authentication input, which uses a 600s window. A remote session binds to the IP that made it, so the server rejects a request from a different IP with <code>403 FORBIDDEN</code>.</p>"},{"location":"dev/rest-api/endpoints/#remote-session-lifecycle-overview","title":"Remote 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>Make a remote 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). It also accepts a broad set of optional keys, because the body allows <code>additionalProperties</code>. These are <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 remote 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 remote 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 remote session. Otherwise it returns <code>404 SESSION_NOT_FOUND</code>.</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 remote 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>Get the download URL, DRM info, headers, cookies, and raw track data for the 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>Get the content keys for the DRM. The <code>mode</code> field selects one of two modes.</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 API 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 remote 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 remote 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 remote session. The server cancels its input bridge, harvests any updated cache files, and deletes the remote session and its cache directory.</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 remote session produced cache files. <code>404 SESSION_NOT_FOUND</code> if the remote session does not exist.</p>"},{"location":"dev/rest-api/endpoints/#error-responses","title":"Error responses","text":"<p>The server serialises every structured error raised inside a handler 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 you start the server 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. The cause can be a missing field, a service that refuses to authenticate, or a download worker that crashed. In each case 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 send.</p> <p>If you write a client against the API, read this page alongside the endpoint reference. Each endpoint lists the specific codes it raises, and this page gives the meanings of those codes.</p> <p>Where this comes from</p> <p><code>unshackle/core/api/errors.py</code> defines the error format, 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 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, you can back off and try the request again. 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 remote session IP binding. <code>GEOFENCE</code> 403 The title 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 remote 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-the-server-produces-errors","title":"How the server produces errors","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 <code>auth</code>, <code>login</code>, <code>credential</code>, <code>unauthorized</code>, <code>forbidden</code>, <code>token</code> <code>AUTH_FAILED</code> (401) no <code>connection</code>, <code>timeout</code>, <code>network</code>, <code>unreachable</code>, <code>socket</code>, <code>dns</code>, <code>resolve</code> (or <code>ConnectionError</code>, <code>TimeoutError</code>, <code>URLError</code>, <code>SSLError</code>) <code>NETWORK_ERROR</code> (503) yes <code>geofence</code>, <code>region</code>, <code>not available in</code>, <code>territory</code> <code>GEOFENCE</code> (403) no <code>not found</code>, <code>404</code>, <code>does not exist</code>, <code>invalid id</code> <code>NOT_FOUND</code> (404) no <code>rate limit</code>, <code>too many requests</code>, <code>429</code>, <code>throttle</code> <code>RATE_LIMITED</code> (429) yes <code>drm</code>, <code>license</code>, <code>widevine</code>, <code>playready</code>, <code>decrypt</code> <code>DRM_ERROR</code> (502) no <code>service unavailable</code>, <code>503</code>, <code>maintenance</code>, <code>temporarily unavailable</code> <code>SERVICE_UNAVAILABLE</code> (503) yes <code>invalid</code>, <code>malformed</code>, <code>validation</code> (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 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 examine the status code before they 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 you start the server 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 job 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 it lets you find the <code>204</code>/no-body and authentication-error cases before you read the body.</li> <li>Branch on <code>error_code</code>. For structured errors, this is the stable identifier to switch on. Do not use <code>message</code> as the identifier.</li> <li>Respect <code>retryable</code>. When it is <code>true</code>, back off and try the request again. 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. For an unrecognised code, show the <code>message</code> and 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 it writes the file. 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 the server reports live progress, and how to cancel or retry. Clearly marked developer sections tell you how the job worker and the manager behind the queue operate 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 give the internal job worker and manager model, for contributors and for people who debug 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 the server reports errors, 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 job worker. No download has started yet. <code>downloading</code> A job 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. You can remove, retry, or read terminal jobs 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 job worker 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>You queue a download 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>. The job workers auto-start on the first job you submit, so you switch nothing else on. Keep the <code>job_id</code>. Every later call uses 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 do not write. The Endpoints page gives the complete list, their defaults, and the validation rules.</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>You can filter the list by <code>status</code> and <code>service</code>, and order it 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>Or subscribe instead of polling</p> <p><code>GET /api/download/jobs/{job_id}/events</code> pushes the same job object as Server-Sent Events, and closes the event stream when the job ends. See Endpoints.</p> <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 want.</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 you start the server with <code>--debug-api</code>, <code>error_traceback</code> and <code>worker_stderr</code> are also filled in, to help you find the cause.</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>The server stopped a <code>cancelled</code> job on request, before it finished. 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. Examine 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 retry does not change the original job. It stays in its terminal state, and the response gives you the new job's ID with <code>202</code>.</p> <ul> <li>You can retry only terminal jobs. A retry of 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 server examines the service allowlist and any download gates again for the new job, exactly as for the original submission. Thus the server can reject a retry 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 job 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 job worker starts it.</p>"},{"location":"dev/rest-api/job-lifecycle/#history-and-retention","title":"History and retention","text":"<p>The server also writes every job that reaches a terminal state once to a persistent history log. The job survives there even after the server removes it from the live list.</p> <ul> <li>Read it with <code>GET /api/history</code> (newest first, with <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>unshackle puts <code>api_history.jsonl</code> 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-job-worker-and-manager-model","title":"Under the hood: the job worker and 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 the jobs it bumped to the front. On the first job, it starts a fixed pool of job worker tasks plus one cleanup task. The start is idempotent, so later jobs reuse the same pool.</p> <ul> <li>Concurrency: <code>max_concurrent_downloads</code> (default 2) caps it. That many jobs can be in <code>downloading</code> at once. The rest wait in <code>queued</code>.</li> <li>Retention: <code>job_retention_hours</code> (default 24) controls it. 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 operate 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. <code>GET /api/config</code> gives the live values. The related <code>serve.history_limit</code> (default 100) instead controls how many entries the on-disk history file keeps.</p> <p>Each job worker loop drains the priority deque first, then the FIFO queue. The loop skips the stale FIFO copy of a promoted job, so it does not do the job twice. When a job worker takes a job it flips it to <code>downloading</code>, stamps <code>started_time</code>, does the download, 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 operate 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 job worker:</p> <ul> <li><code>payload.json</code>: the manager writes it before launch. It contains the job ID, service, title ID, and merged parameters.</li> <li><code>progress.json</code>: the job worker writes it continuously as the download proceeds.</li> <li><code>result.json</code>: the job worker writes it 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 job 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 job 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 job worker operates, 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>The job worker aggregates progress across all selected tracks. It weights each track's completion fraction 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 job worker scales the download portion to fill <code>0</code> to <code>90</code>. The download engine drives the remaining <code>90</code> to <code>100</code> 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-works","title":"How cancellation 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>, the manager records its history immediately (it never reaches a job worker), and the job 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 job 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. The manager also scrubs 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 job worker stdout/stderr in the logs). It removes the job's known secret values, longest-match first, before it returns or logs them.</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. The <code>unshackle serve</code> command serves it 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. The <code>curl</code> commands here come 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 only 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>The server authenticates every request (except the health check) with an API key that you send in the <code>X-Secret-Key</code> header. The server reads this API 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 license and download DRM-protected titles, you must also grant CDM devices to the API 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><code>--no-key</code> turns authentication off entirely: the server allows every request and ignores the <code>X-Secret-Key</code> header. This is convenient for a throwaway local test, but never put a <code>--no-key</code> server on 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 only the REST API and omits the Widevine/PlayReady CDM HTTP endpoints. Drop it when you also want those endpoints.</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, the same as 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 an environment 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-make-sure-that-the-server-is-alive","title":"Step 3: Make sure that the server is alive","text":"<p>The health endpoint is the one route that never requires an API key. Use it to make sure that the server operates, 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 API key works is to show 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 API 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. Parse both shapes in your client.</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>, or music tracks, e.g. <code>[\"1-5\"]</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>The server refuses a per-request CDM (<code>cdm</code>) or inline credentials (<code>credential</code> / <code>credentials</code>) with <code>403 FORBIDDEN</code>, unless the server operator has explicitly opted in with <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 runs 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 updates a job's progress roughly twice a second internally, and each poll reads the current snapshot.</p> <p>Or let the server push the updates</p> <p><code>GET /api/download/jobs/{job_id}/events</code> streams the same job record as Server-Sent Events, and closes the event stream when the job ends. It removes the polling loop above. See Endpoints.</p> <pre><code>curl -N \"$BASE/api/download/jobs/$JOB/events\" \\\n -H \"X-Secret-Key: $SECRET\"\n</code></pre> <p>If a job ends in <code>failed</code>, the full record includes <code>error_message</code>, <code>error_code</code>, and (when you start the server with <code>--debug-api</code>) <code>error_traceback</code> and <code>worker_stderr</code> to help you find the cause. The server scrubs sensitive values in these fields before it returns them.</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), the manager removes it. You get <code>204 No Content</code> with an empty body.</li> <li>If the job is still queued or downloading, the manager cancels it instead. 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. Examine the status code before you 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 with <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>A retry reuses the original job's service, title, and parameters to enqueue a brand new job, and returns <code>202</code> with a fresh <code>job_id</code>. A retry works only on terminal jobs, and returns <code>409 CONFLICT</code> otherwise. A priority change works only 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 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 the machine has.</li> <li>Maintenance: <code>POST /api/maintenance/clear-cache</code>, <code>.../clear-temp</code>, and <code>.../refresh-services</code> do housekeeping (the server blocks the cache and temp clears 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 the server has more to add. <code>retryable: true</code> appears only for transient failures. The server includes a <code>debug_info</code> block (exception type and traceback) only when it 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 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 remote session.</p> <p>Why you'd use this</p> <ul> <li>The server has service accounts, cookies, or a CDM you do not want to copy to every machine.</li> <li>You want to do downloads on a fast/local machine but keep credentials and licensing centralised.</li> <li>A service is region-locked to where the server lives, and the client is not.</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> through <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 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 you configure exactly one server, unshackle uses it implicitly:</p> <pre><code>unshackle dl EXAMPLE 0ABCDEF\n</code></pre> <p>If you configure more than one server, 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 remote 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 does not 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 did not set one, your detected client region so the server can auto-proxy to match it</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 remote 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 the server ships DASH/ISM manifests 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 a DRM-protected title the client either proxies its CDM challenge through the server, or, if <code>server_cdm: true</code>, asks the server to do 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 remote session. If the server has updated cache files (for example a refreshed token), the delete returns them and the client saves them locally, so the next remote session can skip interactive auth.</p> <p>Renaming remote titles locally</p> <p>You can rename titles for a remote service you do not 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 only 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. The client needs no CDM.</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 used (<code>widevine</code> or <code>playready</code>).</li> </ul>"},{"location":"dev/rest-api/remote-sessions/#remote-session-lifecycle-and-expiry","title":"Remote session lifecycle and expiry","text":"<p>Remote sessions live in an in-memory store on the server and expire on a timer. You generally never touch this directly, but it explains behaviour 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 remote 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 remote 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 remote session request carries <code>X-Secret-Key</code>. The server rejects requests without a valid API key (health check aside). See Authentication.</li> <li>IP binding. A remote session records the creator's IP when the server makes it. If a later request for the same remote session comes from a different IP, the server returns <code>403 FORBIDDEN</code>. Remote sessions are not portable between hosts.</li> <li>Namespaced, isolated cache. Each remote session gets its own cache directory, namespaced by a hash of the API key and the remote session ID, so remote sessions cannot read each other's cached tokens. The server deletes the directory when the remote session ends.</li> <li>The server redacts secrets in logs. It redacts remote session IDs, service tags, and other user values before it writes them to the log.</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/#remote-session-endpoints","title":"Remote session endpoints","text":"<p>The server mounts all these routes, even in <code>--remote-only</code> mode. Paths use the <code>session_id</code> that <code>create</code> returns.</p> <p>Why <code>--remote-only</code> exists</p> <p><code>--remote-only</code> narrows the server to only the health, services, search, and remote 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 want only 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 remote 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 remote 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 remote 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 remote 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>. A post 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 you get from <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 remote session when at capacity, then stores a new <code>SessionEntry</code>. It defaults <code>auth_status</code> to <code>AUTHENTICATED</code>, and the <code>create</code> handler overrides it to <code>AUTHENTICATING</code>.</li> <li><code>get()</code> refreshes <code>last_accessed</code> through <code>touch()</code>. It returns <code>None</code> (and deletes the entry) if an authenticated remote session has been idle longer than the TTL. Remote sessions in <code>AUTHENTICATING</code> / <code>PENDING_INPUT</code> are exempt from TTL expiry.</li> <li><code>cleanup_expired()</code> runs every 60s: authenticated remote sessions expire at <code>ttl</code>, in-flight-auth remote sessions expire at <code>AUTH_INPUT_TIMEOUT</code>. The removal of a remote 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>The server calls <code>cancel_all_bridges()</code> on 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 <code>create</code> 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>The handler writes forwarded <code>cache</code> files 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> field, so the client can keep refreshed tokens:</p> <pre><code>{ \"status\": \"ok\", \"cache\": { \"tokens\": \"...base64(zlib(bytes))...\" } }\n</code></pre>"},{"location":"dev/rest-api/remote-sessions/#remote-session-info-response","title":"Remote 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 remote 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 remote 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. With stdin closed the client logs an error and raises <code>SystemExit(1)</code> instead of posting an empty answer) \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 get the licence in proxy mode or <code>server_cdm</code> mode \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 could not reach the URL. Make sure that <code>unshackle serve</code> operates 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 made the remote session. Remote sessions are IP-bound. Do not 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 server marks the remote session <code>failed</code> and cleans it up. Operate the download again. If the server never prompts you, make sure that the credentials and cookies the client forwarded 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>A single configuration file named <code>unshackle.yaml</code> controls almost everything about how unshackle behaves. It sets where unshackle saves downloads, which CDM it uses, your credentials, proxies, filename templates, and more. This page gives where that file lives, how unshackle finds it, and the shape of its contents. It also gives the directory layout unshackle makes 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 uses plain YAML. 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>Operate <code>unshackle env info</code>. It prints the path unshackle loaded the config from, or tells you that it found none. It also prints every directory unshackle currently uses.</p> <p>The config is read exactly once, when unshackle starts. If you edit the file, the change takes effect on the next command.</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 config keys. Each config key configures one area of the program. You include only the config 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>tvdb_api_key</code>, <code>simkl_client_id</code>, <code>ipinfo_api_key</code>, <code>metadata_providers</code> Behaviour &amp; logging <code>update_checks</code>, <code>redact_paths</code>, <code>debug</code>, <code>unicode_filenames</code> Post-download scripts <code>post_scripts</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 config key, unshackle skips it and uses the default. You will not get an error. Examine the config 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> config key once and unshackle applies them to every download. Any flag from Downloading works here. The config 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: [H.265] # -v H.265\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>tvdb_id</code> (<code>--tvdb</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 config key.</p>"},{"location":"getting-started/configuration-file/#the-directory-layout","title":"The directory layout","text":"<p>The <code>directories</code> config 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. A path can use <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>unshackle protects five internal entries: <code>app_dirs</code>, <code>core_dir</code>, <code>namespace_dir</code>, <code>user_configs</code>, and <code>data</code>. If you write any of them under <code>directories</code>, unshackle ignores the override. This is intentional. Those paths come from the package location and your OS user directories.</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 services with services pulled from Git:</p> unshackle.yaml<pre><code>directories:\n services:\n - you/your-services # a GitHub owner/repo shorthand\n - https://example.com/private-services.git\n - ~/code/local-services # a local folder\n</code></pre> <p>unshackle examines the entries in the order you wrote them, and the first source to define a given service tag wins. Put local folders last if you want them to act as fallbacks and not overrides. unshackle clones remote repositories on first use and refreshes them at most once a day. See Creating a Service for how service discovery and repositories work.</p>"},{"location":"getting-started/configuration-file/#the-filenames-config-key","title":"The <code>filenames</code> config key","text":"<p>Alongside <code>directories</code>, the <code>filenames</code> config key lets you override the templates unshackle uses when it names its own working and log files. Two examples are the log filename and the temporary chapters file. Most users never need to touch this. The Configuration Reference gives the available names and their default templates.</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 config key. Nested config 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 config key and a value:</p> <pre><code>$ unshackle cfg tag MYGRP\n$ unshackle cfg cdm.default my_device_l3\n</code></pre> <p>unshackle parses the value as a Python literal, so write booleans as <code>True</code>/<code>False</code> and quote the strings inside a list (<code>\"['en']\"</code>). unshackle stores anything that is not valid Python literal syntax as a plain 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>Show 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 unshackle loaded. If none exists yet, it makes <code>unshackle.yaml</code> inside the <code>unshackle</code> package folder (location 1 above), not your OS user-config directory. To keep the config outside the package, make the file at the user-config path yourself first, then <code>unshackle cfg</code> writes to it.</p> <p>Editing with <code>cfg</code> strips comments</p> <p>Because <code>unshackle cfg</code> rewrites the whole file when it saves, a write removes any comments in <code>unshackle.yaml</code>. 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 config key and default.</li> <li>Set up your first download in Downloading.</li> <li>Learn how unshackle discovers and updates services in Creating a Service.</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, or \u2265 3.10.0 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 tell you about each of these, and how to make sure that your setup is complete.</p>"},{"location":"getting-started/installation/#python-versions","title":"Python versions","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 refuses to assemble 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 work inside an existing virtual environment, make sure that 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 you installed it from a git URL, re-run the same <code>uv tool install</code> command (uv will update in place) to get a newer version, 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 your own local services 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. 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 the <code>binaries/</code> folder inside 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, track 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> config key if you want to switch to <code>mp4decrypt</code>.</p> <p>Do not use shaka-packager 3.0 through 3.9.x</p> <p>These versions stop with a segmentation fault on a single-track MP4 whose internal <code>track_id</code> is 2 or more. A track that unshackle downloads from a DASH or HLS manifest usually has such a <code>track_id</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 download Dolby Vision video.</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 installation, make sure that the command works and that unshackle can see the tools it depends on.</p>"},{"location":"getting-started/installation/#make-sure-the-command-is-available","title":"Make sure the command is available","text":"<pre><code>unshackle --help\n</code></pre> <p>This prints 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>. Operate <code>uv tool update-shell</code> and open a new terminal.</p>"},{"location":"getting-started/installation/#examine-the-external-dependencies","title":"Examine the 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 make 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 titles when <code>env check</code> finds every required tool.</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 make the one piece of configuration unshackle insists on, supply the service module and CDM it needs to fetch and decrypt media, operate 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> <p>unshackle includes no services</p> <p>unshackle handles manifests, DRM, downloading, and muxing. It does not include a module for any streaming platform, so you write that part yourself (step 3). <code>EXAMPLE</code> in this guide stands in for the tag you give yours.</p>"},{"location":"getting-started/quickstart/#1-examine-your-environment","title":"1. Examine your environment","text":"<p>unshackle drives several external tools (FFmpeg, MKVToolNix, shaka-packager, and others) to decrypt, repack, and mux media. Make sure that 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-make-a-minimal-config","title":"2. Make a minimal config","text":"<p>unshackle reads a single configuration 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, use this command:</p> <pre><code>unshackle env info\n</code></pre> <p>If no config exists, this prints the candidate locations. In the order unshackle examines them, 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. Make <code>unshackle.yaml</code> in one of those locations.</p>"},{"location":"getting-started/quickstart/#the-one-config-key-you-must-set","title":"The one config 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} {season_episode} {episode_name?} {quality} {source}\"\n</code></pre> <p>unshackle fills in each <code>{variable}</code> from the title and the tracks you downloaded. Output and Naming gives 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.</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 makes 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-write-a-service","title":"3. Write a service","text":"<p>The service tag you pass to <code>dl</code> (like <code>EXAMPLE</code>) maps to a service module, the plugin that talks to one streaming platform. unshackle includes none, so you write the one you need. Creating a Service covers how.</p> <p>Put the finished module in your <code>directories.services</code> folder (<code>unshackle env info</code> shows the path). The tag then works with <code>dl</code>, <code>search</code>, and the other service commands.</p>"},{"location":"getting-started/quickstart/#4-add-a-cdm-for-drm","title":"4. Add a CDM for DRM","text":"<p>Most streaming services encrypt their titles. To fetch content keys, unshackle needs a CDM, a Widevine device (<code>.wvd</code>) or a PlayReady device (<code>.prd</code>). Add 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 uses the service tag as its config key, 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, unshackle needs no CDM.</p> <p>Tip</p> <p>Operate <code>unshackle wvd parse my_device</code> to inspect a device's security level and contents, and <code>unshackle env info</code> to show where unshackle stores WVDs and PRDs.</p>"},{"location":"getting-started/quickstart/#5-supply-authentication","title":"5. Supply 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 unshackle finds a file at <code>cookies/EXAMPLE.txt</code> 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, find a title on the service and note the <code>id</code> it prints, because that is what you feed to <code>dl</code>:</p> <pre><code>unshackle search EXAMPLE \"My Show\"\n</code></pre> <p>You can also show what a service gives 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-do-your-first-download","title":"7. Do 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:</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 that match your flags, and get the content keys through your CDM (and any key vaults). It then decrypts, muxes, and tags 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. Defaults to <code>orig</code>. <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>. For music, which tracks, e.g. <code>-w 1-5</code> or <code>-w 2x3</code> for disc 2 track 3. <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, unshackle writes finished files 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 one level above the installed <code>unshackle</code> package. Override it for one command with <code>-o</code>:</p> <pre><code>unshackle dl -q 1080 -o /mnt/media/incoming EXAMPLE 81234567\n</code></pre> <ul> <li>unshackle writes movies as a single <code>.mkv</code> file named from your <code>movies</code> template.</li> <li>unshackle groups TV episodes into a per-show / per-season folder (from your <code>series</code> template) unless you pass <code>--no-folder</code>.</li> <li>unshackle builds the filename from your <code>output_template</code> and adds IMDb/TMDB/TVDB IDs 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> config key, plus directories, key vaults, proxies, and naming templates.</li> <li>REST API. Operate 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> show every option. 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. This page groups the commands 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>: operate the local CDM and 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>. Each service defines its own arguments for <code>dl</code> and <code>search</code> (such as a title ID or a query), so examine <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 you enable <code>update_checks</code> 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 (for example <code>EXAMPLE1</code> or <code>EXAMPLE2</code>). Tags are case-insensitive and honour each service's aliases (<code>example+</code>, <code>EXAMPLE2</code>, and the other alias forms all give 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>You can give any <code>dl</code> flag 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>, <code>--warn-only</code> off Warn and continue when a requested resolution, range, or 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>. A <code>-</code> prefix excludes, e.g. <code>all,-es</code>. <code>-vl</code>, <code>--v-lang</code> - Video-only language (overrides <code>-l</code> for video). A <code>-</code> prefix excludes. <code>-al</code>, <code>--a-lang</code> - Audio-only language (overrides <code>-l</code> for audio). A <code>-</code> prefix excludes. <code>-sl</code>, <code>--s-lang</code> <code>all</code> Subtitle language(s). A <code>-</code> prefix excludes, e.g. <code>all,-es</code>. <code>--require-audio</code> - Audio langs that must exist. The title fails even with <code>--best-available</code>. Does not select tracks. <code>--require-video</code> - Video langs that must exist. The title fails even with <code>--best-available</code>. Does not select tracks. <code>--require-subs</code> - Subtitle langs that must exist. Fails the title if one is missing. <code>--s-lang</code> still decides what to keep. <code>-fs</code>, <code>--forced-subs</code> off Include forced subtitle tracks. <code>-fsl</code>, <code>--forced-s-lang</code> none Language(s) wanted for forced subtitles; implies <code>-fs</code>. A <code>-</code> prefix excludes. <code>--exact-lang</code> off Exact matching only: <code>-l es-419</code> matches <code>es-419</code>, not <code>es-ES</code>. Applies to selection and to sort order. <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>These flags select languages, they do not order them</p> <p>Naming languages with <code>-l</code> or <code>-sl</code> removes the others. To keep every language but put your preferred ones first, use <code>audio.language_priority</code> and <code>subtitle.language_priority</code> in your configuration file.</p> <p>unshackle honours the special language tokens <code>orig</code>, <code>all</code>, and <code>best</code> everywhere it expects a language.</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>). For a split episode, <code>.N</code> picks one part (<code>S01E01.2</code>), a range must stay inside the episode (<code>S01E01.1-S01E01.3</code>), and <code>S01E01</code> on its own takes every part. For a dated episode, a token can also be an ISO air date (<code>2026-08-11</code>) or a date range with a colon (<code>2026-08-01:2026-08-31</code>). For a music release, a token is a track number (<code>1-5</code>, <code>1,3,7</code>), or <code>{disc}x{track}</code> (<code>2x3</code>) when the release has more than one disc. <code>--select-titles</code> Interactively select what to download: episodes of a series, or films when a title has more than one. 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. <code>--postscript</code> Run a command after each output file, with <code>{variable}</code> placeholders substituted. Repeatable. Replaces the <code>post_scripts</code> config for this run. See Post-download scripts."},{"location":"guide/cli-reference/#metadata-tagging","title":"Metadata &amp; tagging","text":"Flag Description <code>--tmdb</code> TMDB ID (integer). Used for the tags. Skips the title search. <code>--enrich</code> reads it too. Needs <code>tmdb_api_key</code>. <code>--imdb</code> IMDb ID, e.g. <code>tt1375666</code>. Used for the tags. Skips the title search. <code>--enrich</code> reads it too. Needs no API key. <code>--tvdb</code> TVDB ID (integer). Used for the tags. Skips the series lookup that <code>--tvdb-order</code> would otherwise do. <code>--enrich</code> reads it too. Needs <code>tvdb_api_key</code>. <code>--anilist</code> AniList ID (integer), e.g. <code>--anilist 21</code>. A MyAnimeList ID is accepted as <code>mal:12345</code> and resolved to the AniList entry. Used for the tags. Skips the title search. <code>--enrich</code> reads it too. Needs no API key. <code>--enrich</code> Overwrite show title, year and original language with the external source's. Requires one of <code>--tmdb</code>, <code>--imdb</code>, <code>--tvdb</code>, or <code>--anilist</code>. <code>--daily</code> Treat the title as daily/date-based content and fill missing episode air dates from TVDB. The fill needs <code>--enrich</code> and a TVDB ID. See Daily and date-based content. <code>--tvdb-order</code> Renumber episodes to a TVDB season order: <code>official</code> (aired), <code>dvd</code>, <code>absolute</code>, <code>alternate</code>, or <code>regional</code>. Needs <code>tvdb_api_key</code>. <p>One ID at a time</p> <p>You cannot combine <code>--tmdb</code>, <code>--imdb</code> and <code>--tvdb</code>. Give one and unshackle finds the others from it, and writes all three to the tags. <code>--anilist</code> is outside that rule and pairs with one of them, which is how you attach a western ID to an anime title. An ID with no metadata provider that can find it, such as <code>--tmdb</code> with no <code>tmdb_api_key</code>, fails before the download starts. <code>--anilist</code> needs no API key, so it never fails this check.</p>"},{"location":"guide/cli-reference/#episode-ordering","title":"Episode ordering","text":"<p>A service does not always number a series the way TVDB's aired order does. Some services use TVDB's <code>alternate</code> (Streaming) order for Futurama, for example. <code>--tvdb-order</code> works out which order the service used, then renumbers the episodes into the order you asked for.</p> <p>Orders that do not cover the whole series</p> <p>An order can ignore episodes the service carries. TVDB's <code>dvd</code> order for Futurama leaves out the four movies. Those episodes keep their original numbering. If that would give two episodes the same season/episode slot, and so the same filename, unshackle logs an error and keeps the service's numbering unchanged. Pick an order that covers the whole series.</p>"},{"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 all downloads (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>--adaptive-workers</code> off Scale per-track segment workers dynamically (up to the <code>--workers</code> cap) based on measured CDN throughput and errors. <code>--download-processes</code> <code>1</code> Split large segment batches (24+) across this many download processes to exceed the single-process throughput cap on multi-gigabit connections. Ignored while a speed limit is set: the cap is one shared budget, which extra processes cannot share, so the download stays in a single process. <code>--continue-downloads</code> off Keep completed segment files across runs and resume a previously failed download. One-off enable of the <code>continue_downloads</code> config option. <code>--downloads</code> <code>1</code> Number of tracks downloaded concurrently. <code>--speed-limit</code> unlimited Cap total download speed across all threads and tracks, e.g. <code>500k</code>, <code>5M</code>, <code>1.5G</code> or plain bytes/sec. Values are bytes, not bits (<code>5M</code> = 5.0 MB/s). <code>off</code> disables a configured limit. <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>--select-titles</code> and <code>--wanted</code> are mutually exclusive. <code>--worst</code> needs <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>Find titles on a service. 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>Each service defines its own query syntax. unshackle prints the results 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>unshackle forwards any <code>dl</code> options after the file 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 from a current version of unshackle, made with <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 show 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 configuration 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) that shows which external tools unshackle finds on your <code>PATH</code>. It also gives a summary of how many required tools are present.</p> Category Tools Core FFmpeg*, FFprobe*, MKVToolNix*, mkvpropedit* DRM shaka-packager*, mp4decrypt 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 the location unshackle loaded the configuration file from. If it found no file, it shows the candidate locations instead. It then prints a table of every configured directory (downloads, temp, cache, cookies, logs, exports, WVDs, PRDs, services, and more).</p>"},{"location":"guide/cli-reference/#env-theme","title":"<code>env theme</code>","text":"<pre><code>unshackle env theme\n</code></pre> <p>Prints a sample of every available CLI theme. Each sample has colour swatches, help text with option rows, and a track listing with video, audio and subtitle entries. It also has log lines, a progress bar, and the gradient pulse bar. unshackle marks the active theme and shows each theme's aliases. Set your choice with the <code>theme</code> config key.</p>"},{"location":"guide/cli-reference/#env-clear","title":"<code>env clear</code>","text":"<p>Clear an environment directory. unshackle empties the directory, makes it again, and reports the number of files and bytes it freed.</p> Command Description <code>unshackle env clear cache [SERVICE]</code> Clear the cache directory, or only 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 theme\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. You configure vaults 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. unshackle normalises service tags 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 content keys from one or more source vaults into a destination vault. unshackle skips rows whose KIDs match, unless the existing row has no content key. unshackle never alters or deletes existing data.</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>Make sure that two or more vaults hold the same set of content keys, essentially a chained bidirectional copy. More than one vault is necessary. 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). unshackle skips every line that does not match that form.</p>"},{"location":"guide/cli-reference/#kv-search-kid","title":"<code>kv search KID</code>","text":"<p>Find a KID (32 hex characters, no dashes) in the configured vaults and report its content 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>unshackle cannot enumerate remote vaults without a service, so pass <code>--service</code> when you examine them.</p>"},{"location":"guide/cli-reference/#kv-prepare-vault","title":"<code>kv prepare VAULT...</code>","text":"<p>Make service tables on vaults that use tables, for every installed service, where they do not 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>Make a new <code>.prd</code>. Give either a single folder that contains <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. Only a device of version 3 or higher can do reprovisioning. Accepts the same <code>-e</code> / <code>-s</code> / <code>-o</code> options. By default it overwrites the device in place.</p>"},{"location":"guide/cli-reference/#prd-test-device","title":"<code>prd test DEVICE</code>","text":"<p>Do a test of a device against the Microsoft PlayReady demo server and print the returned content 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. <code>--no-key</code> disables authentication entirely. Only use it 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 you give a command 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. By default it does a test of every track. It cannot do a test of subtitles.</p> Option Default Description <code>-m</code>, <code>--map</code> <code>0</code> Do a test of specific tracks with FFmpeg's <code>-map</code>, for example <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.</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, use <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 unshackle parses all the flags below), 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. unshackle parses all of the options on this page 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 each service defines its own positional argument, use <code>unshackle dl SERVICE --help</code> (for example <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 start a download, <code>dl</code> moves through the pipeline below. The order tells you why, for example, <code>--list</code> stops early, and why unshackle fetches the content keys 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: get the 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> prints the tracks a title exposes and stops before selection. <code>--list-titles</code> prints every title the service returned and stops before <code>--wanted</code>/<code>--latest-episode</code> filtering. <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 height matches exactly, unshackle falls back to a 16:9-canvas match, so <code>-q 1080</code> also selects 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> (<code>--warn-only</code>) If the requested resolution(s) are not 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-colour-range","title":"Video codec and colour 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/#colour-range","title":"Colour range","text":"<p><code>-r</code> / <code>--range</code> selects one or more colour 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> makes a single hybrid track by injecting the Dolby Vision RPU metadata onto an HDR10/HDR10+ base layer with dovi_tool. It requires the <code>dovi_tool</code> binary, resolved from unshackle's <code>binaries/</code> folder or your <code>PATH</code>. The normal case is a DV track plus an HDR10 or HDR10+ base. With HDR10+ and no DV, unshackle converts the HDR10+ metadata to DV instead, which also needs <code>hdr10plus_tool</code>. With no DV and no HDR10+, the title fails. When HDR10+ is present, unshackle prefers it 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>You cannot combine <code>--vbitrate</code> 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 track'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 probe 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>unshackle measures a single-file track (DASH <code>SegmentBase</code>/<code>BaseURL</code>) 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. unshackle probes only the five highest declared-bitrate renditions of each quality tier, in parallel (video grouped by codec and range, audio by codec, channels, language, and descriptive flag). It extends a group downward while a lower unprobed rendition could still outrank a probed one. This keeps probing fast even when a service exposes dozens of renditions. A track whose duration unshackle cannot find falls back to <code>ffprobe</code>. A probe failure is non-fatal: the manifest value stays 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>unshackle accepts names, values, and a few aliases: <code>eac3</code> and <code>ddp</code> both give <code>EC3</code>, and <code>vorbis</code> gives <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, for example <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 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/#music-quality","title":"Music quality","text":"<p>A music service gives one <code>Audio</code> track for each codec and bitrate it offers for a song. The audio options above choose between them: <code>-a</code> picks the codec and <code>-ab</code> or <code>-ab-range</code> picks the bitrate. If you set neither, unshackle takes the best track.</p> <p><code>-q</code> / <code>--quality</code> is a video height. It has no effect on a music download.</p> Take the lossless track<pre><code>unshackle dl -a FLAC EXAMPLE 81234567\n</code></pre> Take the lossy track at 320 kb/s<pre><code>unshackle dl -a AAC -ab 320 EXAMPLE 81234567\n</code></pre> <p>Two FLAC tracks in one release</p> <p>A service can offer both a CD FLAC and a hi-res FLAC. The two have the same codec, so the bitrate is what separates them. Use <code>--list</code> to read the bitrates, then give <code>-ab</code> the one you want.</p>"},{"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>unshackle changes the special token <code>orig</code> to the title's own original language everywhere you use it. You can override each track 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/#excluding-languages","title":"Excluding languages","text":"<p>Put a <code>-</code> in front of a language to remove it from the selection. This works on <code>-l</code>, <code>-vl</code>, <code>-al</code>, <code>-sl</code>, and <code>-fsl</code>, in the same way as it works on <code>-w</code> / <code>--wanted</code>.</p> Every subtitle language except Spanish<pre><code>unshackle dl -sl all,-es EXAMPLE 81234567\n</code></pre> <p>unshackle subtracts the exclusions from the languages the flag would otherwise select, and the order of the values does not matter. If you give only exclusions, the flag keeps its own default: <code>-sl -es</code> is the same as <code>-sl all,-es</code>, and <code>-l -es</code> is the same as <code>-l orig,-es</code>.</p> Only exclusions<pre><code># every subtitle language except Spanish and French\nunshackle dl -sl -es,-fr EXAMPLE 81234567\n\n# the original audio language, unless it is Spanish\nunshackle dl -l -es EXAMPLE 81234567\n</code></pre> <p><code>-vl</code> and <code>-al</code> have no default of their own: they cascade to <code>-l</code>. An override that names a language replaces <code>-l</code> for that track type, exclusions included. An override that gives only exclusions adds them to the ones from <code>-l</code>.</p> Cascade<pre><code># video keeps the Japanese track; only the audio drops Spanish\nunshackle dl -l en,-es -vl ja EXAMPLE 81234567\n</code></pre> <p>Rules for exclusion tokens</p> <ul> <li><code>orig</code> becomes the title's own original language, so <code>-sl -orig</code> drops the subtitles in that language.</li> <li><code>--exact-lang</code> applies to exclusions with the same matching rules as selection: <code>-es</code> removes exactly the tracks that <code>es</code> would select. Without it, <code>-es</code> also removes <code>es-419</code> and <code>es-ES</code>.</li> <li>Tracks with no language tag are never excluded.</li> <li>unshackle rejects <code>-all</code>. Name the languages you do not want instead.</li> <li>The comma form is the documented style. <code>-sl -es</code> also works, but a shell can read a lone <code>-es</code> as another option.</li> </ul>"},{"location":"guide/downloading/#sort-order","title":"Sort order","text":"<p><code>-l</code> and <code>-sl</code> select languages: naming some removes the rest. To keep every language but decide which ones come first, set a priority list in your configuration file:</p> unshackle.yaml<pre><code>audio:\n language_priority: [orig, en]\nsubtitle:\n group_by: language\n language_priority: [en, es, fr]\n</code></pre> <p>Subtitles then start with English, Spanish, and French. The languages you leave out follow alphabetically, after the title's original language. unshackle removes nothing. Audio works the same way, but the languages you leave out keep their bitrate and codec order instead of an alphabetical one.</p> <p>See <code>subtitle.language_priority</code> for the details.</p>"},{"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>, and the other regional forms (up to a small distance). Pass <code>--exact-lang</code> when only an exact match is acceptable: with it, <code>-l es-419</code> selects 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>, so unshackle downloads every available subtitle language.</p> Only English and Spanish subtitles<pre><code>unshackle dl -sl en,es EXAMPLE 81234567\n</code></pre> <p>To keep the default and drop one language, use the <code>-</code> prefix described in Excluding languages. <code>-sl all,-es</code> keeps every subtitle language except Spanish, forced Spanish subtitles included.</p>"},{"location":"guide/downloading/#requiring-subtitles","title":"Requiring subtitles","text":"<p><code>--require-subs</code> takes a list of languages that must exist. If any is missing, the title fails, even under <code>--best-available</code> / <code>--warn-only</code>. Use it when a download is only worth keeping if a specific subtitle track is present.</p> <p>It gates the title. It does not select tracks: <code>--s-lang</code> still decides what to keep, and it defaults to <code>all</code>:</p> <pre><code># every subtitle language, but only if English is one of them\nunshackle dl --require-subs en EXAMPLE 0ABC123\n\n# English, Korean and Japanese only, and only if English is present\nunshackle dl -sl en,ko,ja --require-subs en EXAMPLE 0ABC123\n</code></pre>"},{"location":"guide/downloading/#requiring-audio-and-video-languages","title":"Requiring audio and video languages","text":"<p><code>--require-audio</code> and <code>--require-video</code> take a list of languages that must exist. If one is missing, the title fails, even under <code>--best-available</code> / <code>--warn-only</code>. Like <code>--require-subs</code>, they gate the title without selecting tracks: <code>-l</code> / <code>-al</code> / <code>-vl</code> still decide what unshackle downloads.</p> <p>This matters most with <code>-l best</code> or <code>-l all</code>, which accept whatever the service offers and so never report a missing language on their own:</p> <pre><code># every audio language except French, but only if English is one of them\nunshackle dl -l best,-fr --require-audio en EXAMPLE 0ABC123\n\n# English is required, French is optional\nunshackle dl -l en,fr --require-audio en --warn-only EXAMPLE 0ABC123\n</code></pre> <p>The check runs against the full track list, before any language selection or exclusion. <code>orig</code> resolves to the title language, and <code>--exact-lang</code> applies. Audio carried inside the video track counts. <code>--no-audio</code> and <code>--no-video</code> drop the matching requirement.</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, unshackle drops forced subtitle tracks from the selection.</li> <li><code>-fsl</code> / <code>--forced-s-lang</code>: keep forced subtitles only in these languages (implies <code>-fs</code>). Works independently of <code>--s-lang</code>, so <code>-sl all -fsl en</code> grabs every full subtitle but only the English forced track. It accepts exclusions too: <code>-fsl all,-es</code> keeps every forced subtitle except the Spanish one, and <code>-fsl -es</code> means the same.</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>, and the other codec aliases), 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 carries the SDH flag (for the deaf/hard-of-hearing) and there is no plain same-language subtitle, unshackle makes a stripped, non-SDH track automatically. The <code>subtitle.strip_sdh</code> config option controls this behaviour (default on).</p>"},{"location":"guide/downloading/#selecting-episodes-and-tracks","title":"Selecting episodes and tracks","text":"<p>For series, several flags control which episodes unshackle downloads. The same flags select the tracks of a music release. By default, unshackle downloads all episodes and all tracks.</p>"},{"location":"guide/downloading/#wanted-ranges","title":"Wanted ranges","text":"<p><code>-w</code> / <code>--wanted</code> accepts season and episode ranges, comma-separated. Prefix a token with <code>-</code> to exclude it. For a music release, the same option takes track numbers. Read music tracks below.</p> Whole seasonsSpecific episodesExclusionsSplit episodesAir dates <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> <pre><code># Part 2 of episode 1 only\nunshackle dl -w S01E01.2 EXAMPLE 81234567\n\n# Parts 1 through 3 of episode 1\nunshackle dl -w S01E01.1-S01E01.3 EXAMPLE 81234567\n\n# All of season 1 except episode 1 part 2\nunshackle dl -w S01,-S01E01.2 EXAMPLE 81234567\n</code></pre> <pre><code># One day\nunshackle dl -w 2026-08-11 EXAMPLE 81234567\n\n# A range of days, colon separated\nunshackle dl -w 2026-08-01:2026-08-31 EXAMPLE 81234567\n\n# August, but not the 15th\nunshackle dl -w 2026-08-01:2026-08-31,-2026-08-15 EXAMPLE 81234567\n</code></pre>"},{"location":"guide/downloading/#music-tracks","title":"Music tracks","text":"<p><code>-w</code> selects the tracks of an album, EP, single, or playlist. Give a track by its number. A release with more than one disc uses the <code>{disc}x{track}</code> form. A number on its own is a track on disc 1, which is the number the track list shows for a single-disc release.</p> TracksMore than one discExclusions <pre><code># Track 3\nunshackle dl -w 3 EXAMPLE 81234567\n\n# Tracks 1 through 5\nunshackle dl -w 1-5 EXAMPLE 81234567\n\n# Tracks 1, 3 and 7\nunshackle dl -w 1,3,7 EXAMPLE 81234567\n</code></pre> <pre><code># Disc 2, track 3\nunshackle dl -w 2x3 EXAMPLE 81234567\n\n# Disc 2, tracks 1 through 4\nunshackle dl -w 2x1-2x4 EXAMPLE 81234567\n\n# Disc 1 track 3, through disc 2 track 2\nunshackle dl -w 1x3-2x2 EXAMPLE 81234567\n</code></pre> <pre><code># Tracks 1 through 8, but not track 4\nunshackle dl -w 1-8,-4 EXAMPLE 81234567\n</code></pre> <p>Read the track list first</p> <p><code>--list-titles</code> prints the release with its disc and track numbers, so you can see which numbers to give <code>-w</code>.</p>"},{"location":"guide/downloading/#daily-and-date-based-content","title":"Daily and date-based content","text":"<p>Talk shows, news and sports have no official episode numbering, so unshackle names them by air date. unshackle writes an episode that carries an air date as <code>Show.YYYY.MM.DD</code> instead of <code>SxxExx</code>, the <code>{date}</code> token holds the ISO date, and the season folder becomes the year.</p> <p>A service that only carries this kind of title sets <code>DAILY = True</code> on its class, and a service can set <code>air_date</code> on each episode itself. Add <code>--daily</code> to mark any other title as date-based:</p> <pre><code>unshackle dl --daily --tvdb 73871 --enrich EXAMPLE 81234567\n</code></pre> <p>With <code>--enrich</code> and a TVDB ID, <code>--daily</code> fills in the air date of every episode that has none. An air date the service already set is kept. unshackle skips dates before 1970 and dates in the future, because TVDB carries placeholder schedule dates for episodes that have not aired. Without <code>--enrich</code> unshackle has no source to fill from, and says so.</p> <p>A dated episode answers to its air date in <code>-w</code>, as well as to its <code>SxxExx</code> token. A date token is a plain ISO date (<code>2026-08-11</code>). A date range uses a colon (<code>2026-08-01:2026-08-31</code>), because the dashes in a date are part of the date. A range cannot span more than 1000 days. You can mix date tokens and <code>SxxExx</code> tokens in one <code>-w</code>.</p>"},{"location":"guide/downloading/#split-episodes","title":"Split episodes","text":"<p>A few services split one episode into several separately playable videos. Where a service reports that, add <code>.N</code> after the episode to pick one part.</p> Token Selects <code>S01E01</code> All parts of episode 1. <code>S01E01.2</code> Part 2 of episode 1, and nothing else. <code>S01E01.1-S01E01.3</code> Parts 1 to 3 of episode 1. <code>S01,-S01E01.2</code> All of season 1 except episode 1 part 2. Parts 1 and 3 are kept. <p>A season token such as <code>S01</code> covers every episode and every part, so you only need <code>.N</code> when you want a part on its own.</p> <p>A part range stays inside one episode</p> <p><code>S01E01.1-S01E01.3</code> is valid. unshackle rejects <code>S01E01.1-S01E02.3</code>, because the parser cannot know how many parts episode 1 has and so cannot work out where the range ends. To span episodes, write the parts you want as separate tokens: <code>-w S01E01.2,S01E02.1</code>.</p> <p>A part of an unsplit episode selects nothing</p> <p><code>-w S01E02.2</code> on an episode that was never split is deliberately empty: it tells you the episode has no parts, rather than quietly handing you the whole episode. Use <code>--list-titles</code> to see which episodes carry parts.</p>"},{"location":"guide/downloading/#other-selection-flags","title":"Other selection flags","text":"Flag Behaviour <code>--select-titles</code> Interactively pick episodes of a series, or films when a title has more than one. Cannot combine with <code>-w</code>. <code>--latest-episode</code> Download only the single most recent episode. <code>--list-titles</code> List every title the service returned, then stop. <code>-w</code>/<code>--latest-episode</code> are not applied to this listing. 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 unshackle drops 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 (for example 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 tracks the service exposes for each title, then stop. No selection, no download. <code>--list-titles</code> List every title the service returned, then stop. <code>-w</code>/<code>--latest-episode</code> are not applied to this listing. <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 unshackle uses the configured downloads directory).</li> <li><code>--no-folder</code>: do not make 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, <code>mkvmerge</code> muxes the tracks of a movie or an episode into a single Matroska (<code>.mkv</code>) file. These flags change how unshackle assembles the output:</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 video tracks that share a height, range, and codec into one file, so only language varies inside a file. config <code>muxing.merge_video</code> (off) <p>Music is never muxed</p> <p>A song skips the muxer. unshackle keeps the container that the service delivered, such as <code>.flac</code>, <code>.m4a</code>, or <code>.mp3</code>, and writes the metadata into that file. Read Music output files.</p>"},{"location":"guide/downloading/#after-the-download","title":"After the download","text":"<p><code>--postscript \"&lt;command&gt;\"</code> runs your own command once per output file, with unshackle's metadata substituted into <code>{variable}</code> placeholders. It is repeatable, and it replaces the <code>post_scripts</code> config for that run. No <code>success</code> hook operates under <code>--no-mux</code>, because that run writes no muxed output. A <code>failure</code> hook still operates if the download fails.</p> Hand each finished file to an uploader<pre><code>unshackle dl --postscript \"python /opt/upload.py {filepath} --service={service}\" EXAMPLE 81234567\n</code></pre> <p>For hooks that continue across runs, for the <code>season</code> and <code>run</code> modes, for <code>failure</code> hooks and for the full variable list, see Post-download scripts.</p>"},{"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 all downloads. The manifest, license, and authentication requests still go through the proxy. This is useful when you need the proxy only 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>--adaptive-workers</code> Opt-in: start with a moderate per-track worker count and ramp it up or back off based on measured CDN throughput and errors, capped at <code>--workers</code>. Off by default (fixed worker count). <code>--download-processes N</code> Opt-in: split a large segment batch across <code>N</code> download processes, each with its own worker pool. A single process tops out around 1.3 Gb/s (Python interpreter limit); <code>2</code> reaches 2.5GbE line rate on fast CDNs. Only engages for batches of 24+ segments. Ignored while <code>--speed-limit</code> (or serve's <code>global_speed_limit</code>) is set: the cap is one shared budget, which extra processes cannot share, so the download stays in a single process. Default <code>1</code>. <code>--continue-downloads</code> Opt-in: keep completed segment files when a download fails so the next run resumes instead of restarting from zero. One-off enable of the <code>continue_downloads</code> config option, which documents what can and cannot resume. <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 content 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 and never license through the CDM. A missing content 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 you use <code>--proxy</code>, the export records the region so an import can reproduce the correct geofence. Without a proxy, the export stores no region.</p> <p>Some DASH and Smooth exports need a title language</p> <p>An import re-fetches the DASH or ISM manifest and parses it again. Most manifests label their own streams, and those import fine. When a manifest labels nothing, the parse falls back to the title's original language, which comes from <code>Title.language</code> on the exporting service. If a service never sets it, importing that export fails with a message naming the service. Neither end guesses a language for you, so the fix belongs in the service.</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. An ID you give is authoritative: unshackle looks it up directly instead of searching by title, and the ID stays in the tags. An ID only settles which title this is. To also take that source's title, year and original language, add <code>--enrich</code>. Give at most one of <code>--tmdb</code>, <code>--imdb</code> and <code>--tvdb</code>, and unshackle works the rest out from it. To stop the automatic lookups but keep the IDs you give, set <code>disable_metadata</code> in your config.</p> Flag Example Purpose <code>--tmdb</code> <code>--tmdb 27205</code> Use this TMDB ID instead of an automatic search. Needs <code>tmdb_api_key</code>. <code>--imdb</code> <code>--imdb tt1375666</code> Use this IMDb ID instead of an automatic search. Needs no API key. <code>--tvdb</code> <code>--tvdb 73871</code> Use this TVDB ID instead of looking the series up. Needs <code>tvdb_api_key</code>. <code>--anilist</code> <code>--anilist 21</code> Use this AniList ID instead of an automatic search. <code>mal:12345</code> is also accepted. Needs no API key. <code>--enrich</code> - Overwrite the show title, year and original language with the external source's. Requires one of <code>--tmdb</code>, <code>--imdb</code>, <code>--tvdb</code>, or <code>--anilist</code>. <code>--tvdb-order</code> <code>--tvdb-order dvd</code> Renumber episodes to a TVDB season order. Needs <code>tvdb_api_key</code>. Force the right IMDb match, and keep the service's own naming<pre><code>unshackle dl --imdb tt1375666 EXAMPLE 81234567\n</code></pre> Force the match and take IMDb's title, year and language too<pre><code>unshackle dl --imdb tt1375666 --enrich EXAMPLE 81234567\n</code></pre>"},{"location":"guide/downloading/#what-each-metadata-provider-supplies","title":"What each metadata provider supplies","text":"<p>Metadata providers differ in what they answer with, so the fields <code>--enrich</code> can replace depend on which ID you gave. Every metadata provider except <code>imdb</code> and <code>anilist</code> only operates when you set its config key:</p> Provider Config key Title and year Original language External IDs it returns TMDB <code>tmdb_api_key</code> yes yes, alpha-2 such as <code>ko</code> IMDb, TMDB, TVDB TVDB <code>tvdb_api_key</code> yes yes, alpha-3 such as <code>kor</code> TMDB, TVDB, sometimes IMDb OMDb <code>omdb_api_key</code> yes yes, as an English name such as <code>Korean</code> IMDb IMDb (no config key needed) yes yes, alpha-2 such as <code>ko</code> IMDb SIMKL <code>simkl_client_id</code> yes no, it publishes a country and no language IMDb, TMDB, TVDB AniList (no config key needed) yes yes, worked out from the country of origin, such as <code>ja</code> AniList <p>Whatever the tag looks like, unshackle normalises it before use, so <code>ko</code>, <code>kor</code> and <code>Korean</code> all end up as the same language.</p> <p>AniList only answers for anime</p> <p>It is last in the default metadata provider order and returns nothing for a title that is not anime. The only cost is one search that misses. Put <code>anilist</code> earlier in <code>metadata_providers</code> if you mostly download anime. <code>anilist_title_language</code> sets which of the three AniList title variants unshackle uses.</p> <p>A service can also mark its titles as anime. For those titles unshackle tries AniList first. When AniList has no match, it falls through to the normal order.</p> <p>Each ID goes to the providers that read that kind of ID, in <code>metadata_providers</code> order:</p> <ul> <li><code>--tmdb</code> reads TMDB.</li> <li><code>--imdb</code> reads IMDb, then falls back to OMDb. IMDb needs no API key, so this path works out of the box, and an OMDb API key only matters when IMDb has no answer.</li> <li><code>--tvdb</code> reads TVDB. It needs <code>tvdb_api_key</code>.</li> <li><code>--anilist</code> reads AniList, which needs no API key. It supplies the title, the year and the original language, and writes an AniList tag. It knows no TMDB, IMDB or TVDB ID, so pair it with <code>--tmdb</code>, <code>--imdb</code> or <code>--tvdb</code> when you want those tags as well.</li> </ul> <p>Give one of <code>--tmdb</code>, <code>--imdb</code> and <code>--tvdb</code>. You cannot combine them, because one ID does the job on its own: unshackle finds the other two from it and writes all three to the tags. Passing two is an error rather than a silent choice between them. <code>--anilist</code> is the exception and still pairs with one of the three, which is how you tag an anime title with a western ID.</p> <p>The ID you give must have a metadata provider that can find it, so unshackle makes sure of that before it downloads anything. <code>--tmdb</code> without <code>tmdb_api_key</code>, or an ID whose metadata providers your <code>metadata_providers</code> list leaves out, fails immediately with a message naming what to set. <code>--imdb</code> needs no API key, because the <code>imdb</code> metadata provider is keyless and in the default order.</p> <p>With <code>--enrich</code>, the title, year and original language are all replaced with the external source's values, whether or not the service already filled them in. A field the source does not answer with is left alone, and unshackle logs which fields those were, so a metadata provider with a thin record cannot blank out what the service told you.</p> <p><code>--enrich</code> also fills in the absolute episode number of each episode from TVDB's absolute order, for any series that has one and where the service did not supply it. Anime is the usual beneficiary, but nothing here applies only to anime. This only adds the <code>{absolute}</code> naming variable. <code>--enrich</code> never changes the season and episode numbers.</p> <p>With <code>--daily</code>, <code>--enrich</code> also fills in the air date of each episode from TVDB. See Daily and date-based content.</p> <p><code>--enrich</code> replaces the original language, which affects more than the filename</p> <p>Track selection reads the original language, so replacing it changes which audio is treated as the original. That is the point when a service mislabels it, but it means a wrong ID can pick the wrong audio track and not only write a wrong name. Without <code>--enrich</code>, unshackle keeps the service's own value and does not change track selection.</p>"},{"location":"guide/downloading/#episode-ordering","title":"Episode ordering","text":"<p>A service does not always number a series the way TVDB's aired order does. Some services use TVDB's <code>alternate</code> (Streaming) order for Futurama, for example, while TVDB's <code>official</code> order holds back four season-one episodes to the start of season two. <code>--tvdb-order</code> works out which order the service used, then renumbers the episodes into the order you asked for:</p> Download Futurama in DVD order<pre><code>unshackle dl --tvdb-order dvd EXAMPLE 81234567\n</code></pre> <p>Available orders are <code>official</code> (aired), <code>dvd</code>, <code>absolute</code>, <code>alternate</code>, and <code>regional</code>. Set <code>tvdb_order</code> in your config to apply one by default.</p> <p>Orders that do not cover the whole series</p> <p>An order can leave out episodes the service carries. TVDB's <code>dvd</code> order does not contain Futurama's four movies. Those episodes keep their original numbering. If that would give two episodes the same season/episode slot, and so the same filename, unshackle logs an error and leaves the numbering untouched. Pick an order that covers the whole series.</p>"},{"location":"guide/downloading/#configuration-defaults","title":"Configuration defaults","text":"<p>You can set every flag on this page as a default in your configuration file so you do not have to type it each time, and you can scope defaults 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 through 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 did not set explicitly.</p>"},{"location":"guide/downloading/#quick-reference","title":"Quick reference","text":"<p>A condensed lookup of the most-used options. Use <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> Colour 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>-</code> excludes, e.g. <code>all,-es</code>. <code>--a-lang</code> <code>-al</code> Audio-only language override. <code>-</code> excludes. <code>--v-lang</code> <code>-vl</code> Video-only language override. <code>-</code> excludes. <code>--s-lang</code> <code>-sl</code> Subtitle language(s); default <code>all</code>. <code>-</code> excludes, e.g. <code>all,-es</code>. <code>--forced-subs</code> <code>-fs</code> Include forced subtitles. <code>--forced-s-lang</code> <code>-fsl</code> Forced subtitle language(s); implies <code>-fs</code>. <code>-</code> excludes. <code>--sub-format</code> Output subtitle format. <code>--wanted</code> <code>-w</code> Episode/season range, an air date, or a track number for a music release (<code>1-5</code>, <code>2x3</code>). <code>--daily</code> Fill missing air dates from TVDB during <code>--enrich</code>. <code>--select-titles</code> Interactively pick episodes or films. <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>--require-audio</code> Audio languages that must exist. The title fails if one is missing. <code>--require-video</code> Video languages that must exist. The title fails if one is missing. <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>--postscript</code> Run a command after each output file. Repeatable. <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> Content key source control. <code>--export</code> Export track info and keys to JSON. <code>--tmdb</code> / <code>--imdb</code> / <code>--tvdb</code> / <code>--anilist</code> / <code>--enrich</code> Metadata overrides. <code>--tvdb-order</code> Renumber episodes to a TVDB season order."},{"location":"guide/drm-and-cdm/","title":"DRM &amp; CDM Setup","text":"<p>A Digital Rights Management (DRM) system protects most commercial streaming titles. To download a title and play it back, unshackle needs to get the content keys for the encrypted tracks and then decrypt them. This page explains the DRM systems unshackle supports, how to install 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 have a Developer mark. They give internal behaviour that is useful when you write a service, but you do not need them to download a protected title.</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. A device backs it: a file that carries the cryptographic identity of a real client, such as a phone or a browser.</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 AES content 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 content key that an <code>EXT-X-KEY</code> tag references, and unshackle decrypts it in-process. The CENC variant is the W3C EME <code>org.w3.clearkey</code> scheme. It delivers keys as a JWK Set, and shaka-packager or mp4decrypt decrypts it 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 make 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 cryptographic 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>unshackle validates the file and moves it 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. unshackle finds a bare name (no extension) inside the WVDs directory. It uses a path with an extension 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>unshackle makes a fresh leaf certificate and writes the device 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 be able to reprovision (a group key must be present, that is, 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>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>unshackle compares each config key 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>). The most specific one wins.</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>unshackle compares each config key 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 operate 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 CDM host. unshackle sends it PSSH/challenge data and receives keys back. This is useful for sharing a high-security-level device, using a hosted content 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>You declare remote CDMs 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, unshackle treats the entry 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. unshackle reads field names case-insensitively, so <code>Device Type</code>/<code>device_type</code>, <code>System ID</code>/<code>system_id</code>, and the other field names 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>, unshackle routes the entry 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>unshackle sends the API key as the <code>decrypt-labs-api-key</code> header. If you do not write <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 for developers who integrate a bespoke CDM API. 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:</p> <ul> <li><code>device</code> (<code>name</code>, <code>type</code>, <code>system_id</code>, <code>security_level</code>)</li> <li><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>)</li> <li><code>endpoints</code> (<code>get_request</code> and <code>decrypt_response</code>, each <code>{path, method, timeout}</code>)</li> <li>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>)</li> <li><code>caching</code> (<code>enabled</code>, <code>use_vaults</code>, <code>check_cached_first</code>)</li> <li><code>legacy</code> and <code>timeout</code></li> </ul> <p>unshackle infers PlayReady mode 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 unshackle knows the content keys, one of two external tools decrypts the encrypted file (for Widevine, PlayReady, and ClearKey-CENC):</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> config 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 give equivalent output for a standard CENC title. In most conditions shaka-packager is the better backend. Switch a specific service to <code>mp4decrypt</code> if you find a track that shaka-packager cannot decrypt.</p> <p>ClearKey (HLS) does not use these tools</p> <p>unshackle decrypts an HLS AES-128 ClearKey title in-process with AES-CBC, and ignores the <code>decryption</code> setting entirely. You do not need to configure anything.</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 content key with an <code>EXT-X-KEY</code> tag, unshackle fetches the content 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 you do not set anything up. unshackle decrypts such tracks 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\" returns the keys as a JWK Set and not 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. You do not need a device file. The decrypted file 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 cannot supply, 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 cache of content keys, for the current <code>dl</code> run.</li> <li>Your configured key vaults.</li> <li>Only if still missing, a live license request.</li> </ol> <p>After a successful license request, unshackle writes the recovered keys 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 content 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 you enable key logging, unshackle writes content keys (KID:key pairs) 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 tells you 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). Both take <code>{variable}</code> placeholders that unshackle fills in from the downloaded media. This page 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-unshackle-assembles-an-output-path","title":"How unshackle assembles an output path","text":"<p>When a download finishes, 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. unshackle always puts TV episodes and songs 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 for a movie or an episode: <code>.mkv</code> for video, <code>.mka</code> for audio-only, <code>.mks</code> for subtitle-only. unshackle does not mux a song. It remuxes a song into the container of its codec, such as <code>.flac</code>, <code>.opus</code>, or <code>.m4a</code>. Read Music output files.</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> config 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. A variable that does not apply becomes an empty string, so \"present but empty\" is different from \"missing\".</li> <li><code>{variable?}</code>: optional. A trailing <code>?</code> marks the variable conditional. When it is 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 is not always there</p> <p>Episode names, editions, tags, HDR labels and audio extras are not 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 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 sanitises with spaces. If not, it uses dots (the scene-style default). unshackle also applies this style to the auto-generated date separators of daily content, and to every segment of a nested folder template.</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. unshackle takes the values from the downloaded media (through MediaInfo), from the title metadata, or from your config. A variable that does not apply to a title becomes 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>title_type</code> Media kind of the title <code>movie</code>, <code>series</code>, <code>music</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.HDR</code>, <code>DV.HDR10P</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>unshackle tries the rules 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> form. Within a single rule, all conditions must match (AND logic) for it to apply. The first rule that fully matches wins. If none match, unshackle removes <code>{lang_tag?}</code> 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>part</code> Part index of a split episode, empty otherwise <code>2</code> <code>absolute</code> Absolute episode number, zero-padded to 3 digits, empty when unknown <code>007</code> <code>date</code> ISO air date, empty when the episode has none <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, unshackle clears <code>episode</code> and <code>year</code>, 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/#split-episodes","title":"Split episodes","text":"<p>A few services split one episode into several separately playable videos. Where a service reports that, unshackle folds the part index into <code>{episode}</code> and <code>{season_episode}</code>, so the stock <code>series</code> template names it with no change to your config.</p> <pre><code>Show.Name.S01E01.Part.2.1080p.EXAMPLE.WEB-DL.DDP5.1.H.264-TAG.mkv\n</code></pre> <p>The part token sits immediately after the episode token, before the quality tags, and the group tag stays last. Its separator follows your template's own style, the same way daily content does, so a spaced template gives <code>S01E01 Part 2</code> instead.</p> <p>The part is left out of the folder name, so every part of an episode lands in the same season folder:</p> <pre><code>The.Show.S01.1080p.EXAMPLE.WEB-DL.DDP5.1.H.264-TAG/\n \u251c\u2500 The.Show.S01E01.Part.1.1080p.EXAMPLE.WEB-DL.DDP5.1.H.264-TAG.mkv\n \u251c\u2500 The.Show.S01E01.Part.2.1080p.EXAMPLE.WEB-DL.DDP5.1.H.264-TAG.mkv\n \u2514\u2500 The.Show.S01E02.1080p.EXAMPLE.WEB-DL.DDP5.1.H.264-TAG.mkv\n</code></pre> <p>The same holds for a folder template of your own: <code>{season}</code> never picks up the part, and <code>{season_episode}</code> drops it inside a folder template. unshackle names an episode with no part like any other episode.</p> <p>What media servers do with the part token</p> <p>The form above follows scene practice for genuinely split episodes. Kodi stacks the parts back into one playable episode automatically. Jellyfin lists two versions of S01E01, still correct and playable, because its stacking pattern expects the part marker at the end of the name. Plex uses a closed-source scanner, so what it does with text after the part token is not known.</p> <p>For custom templates there is also a standalone <code>{part}</code> variable. You rarely want it, see the caveat on that page.</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 two audio languages (see <code>dual_multi_mode</code>) <code>DUAL</code> <code>multi</code> <code>MULTi</code> for more than two audio languages <code>MULTi</code> <code>dubbed</code> <code>DUBBED</code> for a single audio language that is not the original (strict mode only) <code>DUBBED</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>, or another type the service supplies <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 is not in the list above, unshackle gives a warning at startup but continues. Double-check spelling. A typo'd <code>{quailty}</code> stays in the filename literally, or unshackle drops it. unshackle does not fill it in.</p>"},{"location":"guide/output-and-naming/#folder-templates","title":"Folder templates","text":"<p>Folder templates sit under a special <code>folder</code> config key inside <code>output_template</code>. unshackle reads this config key separately from the filename kinds. You can give it a single string (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 config keys are <code>movies</code>, <code>series</code>, <code>songs</code>, and <code>albums</code>. Any other config key gives a startup warning. Folder templates permit path separators (<code>/</code> or <code>\\</code>). unshackle formats each segment independently, so you can assemble nested directory structures like <code>Show/Season 01</code>. unshackle reads the separator style from the whole template, so it spaces every segment alike.</p> <p>Fallback behaviour:</p> <ul> <li>A per-kind folder template wins if present. If there is none, unshackle uses the single <code>folder</code> string. If there is no <code>folder</code> string either, 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>. If the song has no year, the folder name is only <code>{artist} - {album}</code>.</li> </ul> <p>Movies are flat by default</p> <p>Episodes and songs are always foldered. unshackle writes movies 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/#music-output-files","title":"Music output files","text":"<p>A song does not go through the muxer. Music services deliver audio in a fragmented MP4, which is not a music file. Its header states a length of zero, so a player stops after the first fragment. FLAC inside an MP4 is also not a FLAC stream. A rename cannot correct either fault, so unshackle remuxes each downloaded audio track into the container of its codec, then moves the file to its final path.</p> Codec Extension FLAC <code>.flac</code> Opus <code>.opus</code> Vorbis <code>.ogg</code> AAC, ALAC, and all other codecs <code>.m4a</code> <p>unshackle re-encodes FLAC in this step. The audio does not change, but the new file states its true length. A plain copy cannot, because it keeps the source header and the zero in it.</p> <p>unshackle writes no <code>.mkv</code> file for music, and the muxing options below do not apply.</p> <p>The <code>songs</code> output template names the file. The <code>albums</code> folder template names the folder around it.</p> <pre><code>/home/user/Downloads/\n \u2514\u2500 The Artist - The Album (2024)/\n \u251c\u2500 01. First Track.flac\n \u2514\u2500 02. Second Track.flac\n</code></pre>"},{"location":"guide/output-and-naming/#music-metadata","title":"Music metadata","text":"<p>After the file moves, unshackle writes the metadata into the audio file. It uses Vorbis comments for FLAC and Ogg, ID3 frames for MP3, and MP4 atoms for M4A. The tags hold the track title, artist, album artist, track and disc numbers, date, genre, ISRC, UPC, copyright, and record label. When <code>tag</code> and <code>tag_group_name</code> are set, unshackle also writes the group name into a <code>GROUP</code> tag.</p> <p>unshackle embeds cover art when the service gives an artwork URL. It downloads the image and puts it in the file.</p> <p>unshackle writes lyrics when the service supplies them: a <code>LYRICS</code> Vorbis comment for FLAC, a <code>USLT</code> frame for MP3, and a <code>\u00a9lyr</code> atom for M4A. Ogg uses the same <code>LYRICS</code> field as FLAC. unshackle does not write synchronized lyrics (<code>SYLT</code>).</p> <p>A metadata fault does not stop the run. The file is already in place, so unshackle writes a warning and continues.</p> <p><code>--no-mux</code> leaves music files untagged</p> <p><code>--no-mux</code> moves each downloaded track file to the output path without the tagging step. A music file from such a run holds only the metadata that the service put in it.</p>"},{"location":"guide/output-and-naming/#muxing-options","title":"Muxing options","text":"<p>You configure muxing (the combination of video, audio, subtitle, chapter and attachment tracks into a single Matroska file with <code>mkvmerge</code>) under the <code>muxing</code> config key. unshackle muxes only movies and episodes. Read Music output files for what a music download does instead.</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 track has the preferred language, unshackle applies sensible defaults. The video default falls back to the title language, then the original-language track, then the first track. The audio default is the original-language track. The subtitle default is a forced track in 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>--a-lang</code> and friends). It also does not touch which track carries the original flag: <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 is not 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> gives one file per range, never a single fused file. English and French video of identical resolution, range, and codec gives one file that holds 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>unshackle writes the chapters 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, which the <code>{tag}</code> variable gives. You can swap it per release with <code>tag_rules</code>: ordered rules whose conditions read the release-attribute variables only (<code>quality</code>, <code>resolution</code>, <code>hdr</code>, <code>source</code>, <code>lang_tag</code>, <code>title_type</code>, and so on), and the first rule that matches wins. <code>tag_rules</code> cannot read the title's own fields, such as <code>title</code> and <code>season_episode</code>. See the reference page for the exact list.</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>tvdb_api_key</code> / <code>simkl_client_id</code> when available). <p>unshackle writes the IDs as the Matroska <code>IMDB</code>, <code>TMDB</code>, and <code>TVDB2</code> tags. <code>TVDB2</code> values carry the entity prefix the Matroska tagging spec requires: <code>series/73871</code> for a show, <code>movies/113</code> for a film.</p> <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 into ASCII equivalents. Korean, Japanese, Chinese, and accented Latin are examples. This 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, unshackle always removes or replaces a set of filesystem-unsafe and structural characters during sanitisation. For example, <code>/</code> and <code>;</code> become <code>&amp;</code>, and unshackle removes characters like <code>\\ * ! ? , ' \" &lt; &gt; | $ # ~</code>. This is why you must never put path-unsafe characters directly in a template.</p> <p>unshackle warns at startup about a template that contains <code>&lt; &gt; : \" / \\ | ? *</code>. It examines a folder template per path segment, so you can use <code>/</code> 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> config key relocates unshackle's working folders. You can move only the folders in the table below. unshackle protects the core package paths and silently ignores them 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 can hold a <code>~</code> for expansion. unshackle protects the names <code>app_dirs</code>, <code>core_dir</code>, <code>namespace_dir</code>, <code>user_configs</code>, and <code>data</code>, so you cannot change them.</p>"},{"location":"guide/output-and-naming/#filename-patterns","title":"Filename patterns","text":"<p>The <code>filenames</code> config 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, unshackle writes them to an OGM chapters file (<code>filenames.chapters</code>) and passes it 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 can hold two placeholders: <code>{i}</code> (chapter number, starting at 1) and <code>{j}</code> (which increments only for unnamed chapters). It permits standard format directives like <code>{i:02}</code>.</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":"<p>Each tab shows a template and what it produces for a few different downloads, so you can see how the optional (<code>?</code>) variables appear and disappear.</p> MoviesTV seriesMulti-languageDaily showsMusic <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> <p>A 4K Atmos HDR download fills every placeholder:</p> <pre><code>The Movie (2024)/\n \u2514\u2500 The.Movie.2024.2160p.EXAMPLE.WEB-DL.DDP5.1.Atmos.H.265.HDR-TAG.mkv\n</code></pre> <p>The same template on a plain 1080p SDR stereo download, where <code>{edition?}</code>, <code>{atmos?}</code> and <code>{hdr?}</code> collapse along with their dots:</p> <pre><code>The Movie (2024)/\n \u2514\u2500 The.Movie.2024.1080p.EXAMPLE.WEB-DL.AAC2.0.H.264-TAG.mkv\n</code></pre> <p>A director's cut fills <code>{edition?}</code>:</p> <pre><code>The Movie (2024)/\n \u2514\u2500 The.Movie.2024.Directors.Cut.2160p.EXAMPLE.WEB-DL.DDP5.1.Atmos.H.265.DV.HDR-TAG.mkv\n</code></pre> <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>unshackle decides the separator style once for the whole folder template, and every segment then follows it. Spaces outnumber dots in <code>{title} ({year})/Season {season}</code>, so <code>Season {season}</code> keeps its space even though it holds only one variable.</p> <p>When an episode has no on-screen name, <code>{episode_name?}</code> disappears cleanly:</p> <pre><code>The Show (2023)/Season S02/\n \u2514\u2500 The.Show.S02E05.2160p.EXAMPLE.WEB-DL.DDP5.1.H.265-TAG.mkv\n</code></pre> <p>Place <code>{dual?}</code>, <code>{multi?}</code> and <code>{dubbed?}</code> next to each other. At most one of them is ever set (see <code>dual_multi_mode</code>), and the empty ones collapse:</p> <pre><code>output_template:\n movies: \"{title}.{year}.{quality}.{source}.WEB-DL.{dual?}.{multi?}.{dubbed?}.{audio_full}.{video}-{tag}\"\n</code></pre> <p>Original English audio plus a French dub (<code>-l en,fr</code>):</p> <pre><code>The.Movie.2024.1080p.EXAMPLE.WEB-DL.DUAL.DDP5.1.H.264-TAG.mkv\n</code></pre> <p>Original plus several dubs (<code>-l en,fr,de,es</code>):</p> <pre><code>The.Movie.2024.1080p.EXAMPLE.WEB-DL.MULTi.DDP5.1.H.264-TAG.mkv\n</code></pre> <p>Only a dub, original audio left out (<code>-l de</code> on an English-original title):</p> <pre><code>The.Movie.2024.1080p.EXAMPLE.WEB-DL.DUBBED.DDP5.1.H.264-TAG.mkv\n</code></pre> <p>Two dialects of one language (<code>en-US</code> + <code>en-GB</code>) count as a single language, so none of the three variables is set:</p> <pre><code>The.Movie.2024.1080p.EXAMPLE.WEB-DL.DDP5.1.H.264-TAG.mkv\n</code></pre> <p>For finer control (for example a <code>SUBBED</code> tag driven by subtitle languages), use <code>{lang_tag?}</code> with <code>language_tags</code> rules instead.</p> <p>Daily content needs no special template. When an episode carries an air date, <code>{season_episode}</code> becomes the date automatically and <code>{episode}</code> and <code>{year}</code> clear:</p> <pre><code>output_template:\n series: \"{title}.{season_episode}.{episode_name?}.{quality}.{source}.WEB-DL.{audio_full}.{video}-{tag}\"\n</code></pre> <p>A normal episode and a dated one, same template:</p> <pre><code>The.Daily.Show.S28E101.1080p.EXAMPLE.WEB-DL.DDP5.1.H.264-TAG.mkv\nThe.Daily.Show.2024.06.01.1080p.EXAMPLE.WEB-DL.DDP5.1.H.264-TAG.mkv\n</code></pre> <p>The date separator follows your template style: dots here, spaces if your <code>series</code> template uses spaces.</p> <p>In folder names, <code>{season}</code> becomes the air year (<code>Season 2024</code> style grouping), and unshackle skips a <code>{year?}</code> in the folder template when it would only repeat that year.</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> <p>In <code>\"{track_number}. {title}\"</code> the number of dots and spaces is equal, and a tie goes to dot style. Add more spaces between variables (as below) if you want space-separated names.</p> <p>A multi-disc album with explicit tracks, using more of the music variables. <code>{disc}</code> is empty on disc 1, so <code>{disc?}</code> and its separator only appear from disc 2 onward:</p> <p><pre><code>output_template:\n songs: \"{disc?}-{track_number}. {title} {explicit?}\"\n folder:\n albums: \"{album_artist} - {album} ({year}) [{label?}]\"\n</code></pre> <pre><code>The Artist - The Album (2024) [The Label]/\n \u251c\u2500 01. Opening Track.mka\n \u2514\u2500 02-03. Closing Track Explicit.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 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 the proxy providers unshackle supports change a query to a real proxy URL: 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 proxy provider configuration lives under the top-level <code>proxy_providers:</code> config key in your <code>unshackle.yaml</code>. Each proxy provider has its own sub-key, and the config keys inside it map directly onto that proxy provider's settings. See the Configuration file page for where the file lives and how unshackle loads it.</p>"},{"location":"guide/proxies-and-vpn/#the-proxy-flag","title":"The <code>--proxy</code> flag","text":"<p>Three options on the <code>dl</code> command control proxying at download time:</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 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, you can give <code>--proxy</code> 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 frequently the slowest part of 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 files themselves over your normal connection at 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>unshackle interprets the value you pass to <code>--proxy</code> in one of three ways. It tries them in this 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. unshackle uses anything shaped like <code>http://...</code>, <code>https://...</code>, or a <code>socks...</code> URI exactly as you give it. 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 proxy provider whose name matches the prefix (case-insensitive). It then asks only that proxy provider to find a proxy for the remainder. If unshackle loads no such proxy provider, or if that proxy provider 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 proxy provider in order and uses the first proxy any of them returns.</li> </ol> <p>unshackle compares the query 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. It then lowercases the query and hands it to the proxy provider. Its section below gives the exact forms each proxy provider accepts.</p>"},{"location":"guide/proxies-and-vpn/#provider-load-order","title":"Provider load order","text":"<p>When you do a download without <code>--no-proxy</code>, unshackle instantiates every configured proxy provider once, in this fixed order. It uses that same order 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 use <code>--proxy us</code>, a <code>us</code> entry in your Basic config wins, because unshackle tries Basic first. To skip ahead to a specific proxy 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 cache 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 proxy provider resolves a query, unshackle prints a line so you can see 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 proxy 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> proxy provider is pure static configuration, with no accounts and no network calls. You record proxy URLs under each 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, unshackle picks one at random. Append an index (<code>de1</code>, <code>de2</code>) to pin a specific entry.</li> <li>unshackle normalises each URL (a missing scheme defaults to <code>http</code>) and validates it, so it rejects a malformed URI up front and does not fail 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 proxy 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 proxy 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 proxy provider receives exactly <code>provider:region</code>. It must be two colon-separated parts, and anything else is an error. The <code>&lt;vpn-provider&gt;</code> must be one you have configured under <code>gluetun.providers</code>, and unshackle normalises friendly names 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 config 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 <code>preshared_key</code>). OpenVPN is the simplest to configure (only a username and password) at the cost of some speed. If you start out, or if you have 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>unshackle changes a <code>us1239</code>-style query (country code + number) with no explicit mapping 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>unshackle expands a bare two-letter code to the full country name Gluetun expects.</li> </ol> <p>A few providers (Windscribe, VyprVPN, VPN Secure) select by region rather than country, and unshackle converts Windscribe region names 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. unshackle pulls <code>qmcgaw/gluetun:latest</code> if it is not already present.</li> <li>Reuse. If a container for this exact <code>provider:region</code> already runs (from a concurrent unshackle process), unshackle adopts it and does not start a new one. It removes stopped or dead containers with the same name 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. unshackle chooses a free local port, starting from <code>base_port</code>.</li> <li>Start. unshackle launches the container bound to <code>127.0.0.1:{port}</code>. It passes credentials through a temporary, <code>0600</code>-permission env-file (never as <code>-e</code> flags), and it overwrites and deletes that file immediately after.</li> <li>Readiness wait. unshackle polls the container logs (up to 60 seconds) until the HTTP proxy listens and the VPN reports a completed connection. Fatal errors like <code>authentication failed</code> or <code>invalid credentials</code> abort early, and unshackle attaches recent logs 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>unshackle cleans up containers with 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 something kills a run hard (for example <code>kill -9</code>), a container can stay behind. With <code>auto_cleanup: true</code> the next run that adopts that name still works, 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 make sure that <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. Examine your <code>server_countries</code> mapping, or set <code>verify_ip: false</code> if you intentionally use 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 you signed in headlessly.</p> <p>Enable it and do 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 you approve it, unshackle caches the tokens and reuses them 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>unshackle writes ExpressVPN's token cache 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. Make 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 to tune performance: for a given streaming service one specific server often performs noticeably better than NordVPN's recommended pick. So you can hard-code that server for a day or two as a 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 Proton limits them to its free-tier exit countries.</p> TV login (recommended)Exported cookies <p>Proton's TV device-login flow gives a self-sustaining, refreshable sign-in. This is the only method that can refresh itself headlessly, so it keeps working without re-exporting anything. Enable it and do 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 you approve it, unshackle caches the sign-in and reuses it automatically.</p> <p>Export your <code>account.proton.me</code> 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 \"does not 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. That is why the sign-in lapses at Proton's ~24h TTL and you must export it again. This is exactly why TV login is the better method 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, unshackle writes its cache file with <code>0600</code> permissions.</p> <p>Cache vs cookie precedence</p> <p>If both a TV-login cache and a cookie file exist, unshackle prefers the cache unless the cookie file is newer. unshackle reads cookies fresh every run and never writes them back to the cache. So to deliberately force use of the cookie file, re-save (re-export) it 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). unshackle excludes Secure Core and Tor servers 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>, do not guess a low number. A country may have 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 proxy provider raises an error that tells 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. Make 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. unshackle only makes sure that a username and a password are present (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 <code>dl</code> command loads the standalone Windscribe proxy provider (and Gluetun), but the proxy resolver that the REST API and the remote-download client use does not. If you drive downloads through the API and need Windscribe or Gluetun exits, get the proxy on the CLI side, or use a different proxy 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 you add a proxy provider: an entry in <code>dl.py</code> does not make it available over the API, and the opposite is also true.</p> <p>Implementing a new provider (developers)</p> <p>Every proxy provider subclasses <code>unshackle.core.proxies.proxy.Proxy</code> and has 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 catalogue 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 add <code>get_connection_info(query)</code> (as Gluetun does) or <code>last_connection_display()</code> (as ExpressVPN and Proton VPN do) to make <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, unshackle parses the subtitle tracks from the manifest alongside video and audio. It downloads them, cleans them up, and optionally converts them to the format you want. It then muxes them into the final Matroska file, or writes them out as sidecar files next to it. The sections below cover the supported formats, how unshackle normalizes tracks after download, how to select and filter subtitles, and every subtitle-related configuration option.</p> <p>A handful of <code>dl</code> flags and a small <code>subtitle</code> block in your configuration file control most of this. 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 write 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 make a single, valid file:</p> <ul> <li>Encoding: unshackle forces non-boxed subtitles to UTF-8, and unescapes stray <code>&amp;lrm;</code> / <code>&amp;rlm;</code> bidirectional entities.</li> <li>Segment merging: when a WebVTT or boxed subtitle arrives as many DASH/HLS segments, unshackle merges the segments 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 unshackle keeps the original styling and layout (see <code>preserve_formatting</code>).</li> <li>TTML for muxing: Matroska cannot carry TTML. If you do not request a specific output format, unshackle automatically converts any plain TTML track 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 gives 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>. A <code>-</code> prefix excludes, e.g. <code>all,-es</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>-fsl</code>, <code>--forced-s-lang</code> Language(s) wanted for forced subtitles; implies <code>-fs</code>. A <code>-</code> prefix excludes. <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> matches <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 name is present. If any is missing, the title errors out. This is useful for batch jobs where you want a title without your must-have language to fail loudly, and not to silently give 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 watch 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> <p><code>-fs</code> keeps forced tracks in every selected language. If you only want forced tracks in certain languages, use <code>-fsl</code> / <code>--forced-s-lang</code> instead. It implies <code>-fs</code>, so you do not need both:</p> All full subtitles, but only the English forced track<pre><code>unshackle dl --s-lang all --forced-s-lang en EXAMPLE 81234567\n</code></pre> <p>If you pass both flags, <code>-fsl</code> wins and keeps only forced tracks in its languages. It also understands <code>orig</code> (the title's original language) and <code>all</code> (every forced track, same as plain <code>-fs</code>).</p>"},{"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 it 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>unshackle orders subtitles from fewest to most captions: Forced \u2192 Normal \u2192 SDH/CC. For hearing-impaired handling, unshackle groups SDH and CC tracks as the \"most captions\" variant.</p> <p>By default this type order is the primary sort, so all forced tracks come first, then all normal tracks, then all SDH/CC tracks, each block sorted by language. To keep each language next to its own variants instead, set <code>subtitle.group_by</code> to <code>language</code>. Use <code>subtitle.type_priority</code> to change the Forced \u2192 Normal \u2192 SDH/CC order itself.</p> <p>A single track cannot be both CC and SDH, and a forced track cannot also carry the CC or SDH flag. unshackle rejects these combinations 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 track. After unshackle downloads and decrypts a video track, it probes the track for these captions and, when it finds them, 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 make 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 <code>sdh_method</code> config key selects the stripping engine itself. The default (<code>auto</code>) prefers the <code>subby</code> cleaner for SRT, falls back to SubtitleEdit when you install it, 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 stay in the file.</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 with <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 unshackle skips the conversion and keeps the styled original. 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 convert the pair.</p>"},{"location":"guide/subtitles/#what-each-backend-preserves","title":"What each backend 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 shows the styling that survives. <code>\u2014</code> means that the backend cannot convert 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 it is best 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>: removes 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 you install it, 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 unshackle muxes subtitles 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>unshackle embeds the subtitles in the Matroska file. It writes nothing separately.</p> unshackle.yaml<pre><code>subtitle:\n output_mode: sidecar\n sidecar_format: srt\n</code></pre> <p>unshackle writes the subtitles as standalone files and does not mux them 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>unshackle muxes the subtitles into the video and writes them as sidecar files.</p> <p>unshackle names sidecar files 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 <code>sidecar_format</code> config key sets the sidecar file format. 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>You can set defaults for all of the behaviour above 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. <code>group_by</code> <code>type</code> <code>type</code>, <code>language</code> Whether all tracks of one type stay together, or each language stays next to its own variants. <code>language_priority</code> (unset) a list of languages Languages to sort to the top. The rest keep the default order. Nothing is removed. <p>SubtitleEdit is optional but recommended</p> <p>Several high-fidelity paths (the best-quality conversions and the SubtitleEdit SDH stripper) only activate when you install the SubtitleEdit CLI and put it 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 you cannot combine <code>forced</code> 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 to permit lossy styled down-converts such as ASS\u2192SRT. 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 with 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 have a small protocol (<code>is_available()</code>, <code>can_convert()</code>, <code>rank()</code>, <code>convert()</code>), and unshackle tries them 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 unshackle cannot get a content key, 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>: make sure that unshackle finds the external tools it depends on, 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 give, 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 with 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 want only 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. unshackle automatically redacts secrets, URLs, and local paths (see Redaction), but you should still read a log before you share 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. You can filter, examine, and analyse this file with standard tooling (<code>jq</code>, <code>grep</code>, a text editor). It is safe to attach to a bug report, because unshackle redacts it.</p>"},{"location":"guide/troubleshooting/#where-it-is-written","title":"Where it is written","text":"<p>unshackle makes the debug log during a <code>dl</code> run, and during <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 you can move it with the <code>directories.logs</code> config key. To see the exact resolved path on your machine, use <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 each log file 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\",\"unshackle_code_hash\":\"1d22a1e\",\"python_version\":\"3.12.4 ...\",\"platform\":\"Linux-6.18.5-x86_64\",\"platform_system\":\"Linux\",\"platform_release\":\"6.18.5\"}}\n</code></pre> <p>Quote <code>unshackle_code_hash</code> in a bug report. It fingerprints the framework source you operate, so it tells us the exact code state even when you did not install from git. A hash that matches no release means that someone edited the source locally.</p> <p>Subsequent lines record the 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>unshackle logs the binary-tool versions (shaka-packager, mp4decrypt, mkvmerge, FFmpeg, FFprobe) near the start of a <code>dl</code> run. Often that is the fastest way to make sure that 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, unshackle redacts the content keys in the JSON debug log. It writes any field that looks like a content key as <code>[REDACTED]</code>. This keeps logs shareable. When you specifically debug a key-retrieval or decryption problem and need to see the actual KID/KEY values unshackle 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 content key fields. You can then see which content 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 content keys into the log file in cleartext. Only enable it while you diagnose a content key problem. Never share a log written with it on, and set it back to <code>false</code> when you are 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>Sometimes a request fails at the TLS or connection layer, and you need the underlying library's own logs. If you need that low-level traffic, 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>, unshackle leaves those libraries at <code>DEBUG</code> level when you operate it 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 unshackle silences the HTTP libraries when the <code>-d</code> flag is active. If you do not operate unshackle 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. It applies three passes to every logged message, error, and structured value:</p> <ul> <li>Secrets: unshackle replaces passwords, tokens, API secrets, auth values, and cookies with <code>[REDACTED]</code>.</li> <li>URLs: unshackle collapses every <code>http(s)</code> URL to <code>redacted</code>. It keeps only the file extension, so a manifest still shows as <code>redacted.mpd</code> and a segment as <code>redacted.m4s</code>. This hides the CDN, manifest, segment, and licence-server locations, but keeps the type of resource.</li> <li>Local paths: unshackle replaces install-root, virtualenv, and home-directory prefixes with tokens, so your username and machine layout do not appear in logs.</li> </ul> <p>The <code>redact_paths</code> config key controls path redaction, and it 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 debug a path problem locally and want to see full, unmasked paths in the console and logs. unshackle always applies secret and URL redaction in the JSON debug log, and this toggle does not change that.</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 is not 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 is 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 will not process, use <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 reads configuration from and where every working directory lives:</p> <pre><code>unshackle env info\n</code></pre> <ul> <li>If unshackle found a config file, it prints the path it was loaded from. If it found none, it shows every location it would accept one (see Config file discovery below). You can then make 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 do my logs, downloads and cookies go?\" The defaults are relative to the installed package. The table also shows any <code>directories:</code> overrides from your config.</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: use <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 will not play, or the decrypt step errors.</p> <p>Inspect: enable <code>debug_keys</code> and operate unshackle with <code>-d</code>. Then examine the JSON debug log's <code>drm_*</code> and <code>vault_*</code> operations to see which content keys unshackle fetched, and from where. Also make sure that 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, and unshackle's own logs do not give the full cause.</p> <p>Inspect: set <code>debug_requests: true</code> and operate unshackle with <code>-d</code> to show 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 you use a proxy, also read 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: use <code>unshackle env info</code> to see which config file unshackle loaded, and <code>unshackle cfg --list</code> to dump the effective values. It is common to edit a config file in a location unshackle does not read 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 unshackle silently ignores your edits to a later file. <code>unshackle env info</code> prints the path it loaded (or, if none exists, shows all three candidate locations so you can make 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 sends 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 you disable debug logging, so they are always safe to leave in place. When you add a new feature, call <code>log_event(\"my_feature_event\", message=\"...\", context={...})</code>. Do not write the \"is the logger enabled?\" guard again. unshackle does the redaction and the JSON-serialisation for you, and redacts any field whose name looks like a content key, a secret, or a token. Content 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. The <code>log_event</code> signature does not enforce them, 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. Send 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>. A sparse <code>INFO</code> 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 title 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 that follow 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>. We write them inline at each call site on purpose. There is no central registry or enum. Do not look for one, and do not make 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. Put all structured data (<code>context</code>, counts, ids, <code>duration_ms</code>) in fields, not in the prose. This separation 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 cannot 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 unshackle has recovered a title's keys, it 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. The same pair frequently covers several resolutions or bitrates of the same title. Once unshackle has recovered a key it writes it to your vaults immediately. The moment the next track presents a KID it has already seen, the key comes from the vault instead of 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>A vault stores every content key as a KID \u2192 KEY pair, grouped by service:</p> <ul> <li>KID (Key ID): a 16-byte identifier for a specific encrypted track, stored as 32 lowercase hex characters with no dashes.</li> <li>KEY: the 16-byte content key that decrypts that track, 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 content 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 content key during a download it asks your vaults in the order they appear 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, unshackle skips it and continues the search with the next one.</p> <p>When unshackle recovers new keys from a license, it 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>unshackle skips keys that already exist in a vault (it never overwrites or deletes existing data).</li> <li>A vault marked <code>no_push: true</code> receives lookups, but unshackle never writes to it. 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>Declare vaults 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 multiple threads can safely use the same database file.</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 create a fresh empty database at the old location. That leaves 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>. Prefer MariaDB 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. A database on shared hosting is therefore 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 only <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 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 content 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>Query mode requires <code>username</code>. 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 API 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 you give both, <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 headers:\n CF-Access-Client-Id: \"CLIENT_ID_HERE\"\n CF-Access-Client-Secret: \"CLIENT_SECRET_HERE\"\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>. <code>headers</code> no Extra HTTP <code>headers</code> sent with every request, for example the Cloudflare Access service-token headers <code>CF-Access-Client-Id</code> and <code>CF-Access-Client-Secret</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). It 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 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 API 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-content-key-by-kid","title":"<code>kv search</code>: find a content key by KID","text":"<p>Search your vaults for a KID and print any matching content 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 the search scans every configured vault and every service table; narrow it 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 content key from one or more source vaults into a single destination vault. <code>kv copy</code> never alters existing rows; it adds only genuinely new KIDs and skips null keys.</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>Make each of two or more vaults hold every content 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/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 config 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.validate_output_templates","title":"validate_output_templates","text":"<pre><code>validate_output_templates()\n</code></pre> <p>Validate output template configurations and warn about potential issues.</p>"},{"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>Find 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 backend 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>Find 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-128 ClearKey (HLS) DRM system.</p> <p>Give the IV where possible. If you do not give an IV, unshackle sets it to \u0000 of the same bit-size as the content key.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKey.warn_clear","title":"warn_clear","text":"<pre><code>warn_clear(reason)\n</code></pre> <p>Warn once per track that unshackle passed a segment through undecrypted.</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-128 ClearKey (HLS) 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 <code>Key</code> object parsed from a m3u(8) playlist using the <code>m3u8</code> library.</p> required <code>session</code> <code>Optional[Session]</code> <p>Optional HTTP 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 tracks.</p> <p>Distinct from the HLS AES-128 <code>ClearKey</code> class: a license server gives the keys here as a JWK Set keyed by KID, and the media 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>unshackle stores the content keys once at the export's track level, and does not duplicate them 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>Assemble 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>Get Content Keys for this DRM Instance from a ClearKey license server.</p> <p>The licence param is a function. unshackle gives it 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 gave a Laurl, unshackle POSTs the challenge 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 unshackle has not yet downloaded the track. 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 with 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 service API gives the PSSH value (ticket) directly, and a WASM module extracts the content keys locally.</p> <p>Decryption has two stages: 1. ML-Worker binary: Removes MonaLisa encryption layer (bbts -&gt; ents) 2. AES-ECB decryption: Final decryption with the service-supplied content key</p> <p>Initialise 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 content 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 content 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 the content 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 the caller gives no PSSH/ticket data.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.Exceptions.KeyExtractionFailed","title":"KeyExtractionFailed","text":"<p> Bases: <code>Exception</code></p> <p>Raised when content 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.extract_keys","title":"extract_keys","text":"<pre><code>extract_keys()\n</code></pre> <p>Extract keys from the ticket using the MonaLisa CDM.</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>Make 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 content 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, through the on_segment_downloaded callback. When the caller calls this method, unshackle has already decrypted the media and muxed it 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.extract_kids_from_pssh_b64","title":"extract_kids_from_pssh_b64","text":"<pre><code>extract_kids_from_pssh_b64(pssh_b64)\n</code></pre> <p>Extract all KIDs from base64-encoded PSSH data.</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>unshackle stores the content keys once at the export's track level, and does not duplicate them here.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.extract_keys_from_cdm","title":"extract_keys_from_cdm","text":"<pre><code>extract_keys_from_cdm(cdm, session_id)\n</code></pre> <p>Extract keys from CDM session with cross-library compatibility.</p> <p>Parameters:</p> Name Type Description Default <code>cdm</code> <code>Cdm</code> <p>CDM instance</p> required <code>session_id</code> <code>bytes</code> <p>Session identifier</p> required <p>Returns:</p> Type Description <code>dict</code> <p>Dictionary mapping KID UUIDs to hex keys</p>"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.detect_revocation","title":"detect_revocation <code>staticmethod</code>","text":"<pre><code>detect_revocation(text)\n</code></pre> <p>Return the decoded error string if a revocation HRESULT is present, else None.</p> <p>Reads the code from the raw SOAP body (0x8004C065) or from an exception message that carries it, so this method covers any service.</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 unshackle has not yet downloaded the track. SubprocessError if the decryption process returned a non-zero exit code.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.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.PlayReady.decrypt_with_shaka_packager","title":"decrypt_with_shaka_packager","text":"<pre><code>decrypt_with_shaka_packager(path)\n</code></pre> <p>Decrypt with shaka-packager (original method)</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>Make a Widevine DRM System object from a track's information. Use this method only when a PSSH cannot be given directly. It is rare to need to use this.</p> <p>You can give your own <code>requests.Session</code> 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>Use this method only when a PSSH cannot be given 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>unshackle stores the content keys once at the export's track level, and does not duplicate them 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>Make a CDM Session and get Content Keys for this DRM Instance. The certificate and license params are functions. unshackle gives them the challenge and the 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>Make a CDM Session and get Content Keys for this DRM Instance. The certificate and license params are functions. unshackle gives them the challenge and the 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 unshackle has not yet downloaded the track. SubprocessError if the decryption process returned a non-zero exit code.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.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.Widevine.decrypt_with_shaka_packager","title":"decrypt_with_shaka_packager","text":"<pre><code>decrypt_with_shaka_packager(path)\n</code></pre> <p>Decrypt with shaka-packager (original method)</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.TimeoutSession","title":"TimeoutSession","text":"<p> Bases: <code>Session</code></p> <p>requests.Session applying DEFAULT_TIMEOUT when the caller passes none.</p> <p>requests has no native default timeout. Without one, a stalled connect or read hangs forever. RnetSession bounds every request through its client's connect_timeout/read_timeout, so this mirrors that on the requests path. A per-request non-None <code>timeout=</code> wins. :class:<code>TimeoutHTTPAdapter</code> on the mounted adapters still replaces an explicit <code>timeout=None</code> with the default, so there is no unbounded read, as with RnetSession where the client-level timeouts always apply. Pass a large timeout instead.</p>"},{"location":"reference/api/service/#unshackle.core.service.TimeoutHTTPAdapter","title":"TimeoutHTTPAdapter","text":"<pre><code>TimeoutHTTPAdapter(\n *args, timeout=DEFAULT_TIMEOUT, **kwargs\n)\n</code></pre> <p> Bases: <code>HTTPAdapter</code></p> <p>HTTPAdapter applying DEFAULT_TIMEOUT when the caller passes none.</p> <p>Backstops :class:<code>TimeoutSession</code> for the <code>session.send(prepared)</code> path, which bypasses <code>Session.request</code>. RnetSession bounds those too through its client, so this keeps parity. A per-request non-None <code>timeout=</code> wins. <code>None</code> (unset, or explicitly passed) gets the default, because the adapter cannot distinguish the two, and rnet has no unbounded mode either.</p> Source code in <code>unshackle/core/service.py</code> <pre><code>def __init__(self, *args: Any, timeout: Any = DEFAULT_TIMEOUT, **kwargs: Any) -&gt; None:\n self.default_timeout = timeout\n super().__init__(*args, **kwargs)\n</code></pre>"},{"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> <p>A Service must define the abstract methods. The rest are optional overrides that fall back to the base implementation when a Service does not define them. The main flow operates the HTTP session and authentication methods first, then titles, then tracks and chapters. The license callbacks operate later still, during track download.</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 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 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 if proxy_provider_name:\n full_proxy_key = f\"{proxy_provider_name}:{proxy_query}\"\n else:\n full_proxy_key = proxy_query\n\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 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 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 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 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_tracks_for_variants","title":"get_tracks_for_variants","text":"<pre><code>get_tracks_for_variants(title, fetch_fn)\n</code></pre> <p>Call fetch_fn for each codec/range combo in track_request, merge results.</p> <p>Services that need separate API calls per codec/range combo can use this helper from their get_tracks() implementation.</p> <p>The fetch_fn signature should be: (title, codec, range_) -&gt; Tracks</p> <p>For HYBRID range, this helper calls fetch_fn with HDR10 and DV separately, then merges the DV video tracks into the HDR10 result.</p> <p>Parameters:</p> Name Type Description Default <code>title</code> <code>Title_T</code> <p>The title to process.</p> required <code>fetch_fn</code> <code>Callable[..., Tracks]</code> <p>A callable that fetches tracks for a specific codec/range.</p> required Source code in <code>unshackle/core/service.py</code> <pre><code>def get_tracks_for_variants(\n self,\n title: Title_T,\n fetch_fn: Callable[..., Tracks],\n) -&gt; Tracks:\n \"\"\"Call fetch_fn for each codec/range combo in track_request, merge results.\n\n Services that need separate API calls per codec/range combo can use this\n helper from their get_tracks() implementation.\n\n The fetch_fn signature should be: (title, codec, range_) -&gt; Tracks\n\n For HYBRID range, this helper calls fetch_fn with HDR10 and DV separately,\n then merges the DV video tracks into the HDR10 result.\n\n Args:\n title: The title to process.\n fetch_fn: A callable that fetches tracks for a specific codec/range.\n \"\"\"\n all_tracks = Tracks()\n first = True\n\n codecs = self.track_request.codecs or [None]\n ranges = self.track_request.ranges or [Video.Range.SDR]\n\n for range_val in ranges:\n if range_val == Video.Range.HYBRID:\n # HYBRID: fetch HDR10 first (full tracks), then DV (video only)\n for codec_val in codecs:\n try:\n hdr_tracks = fetch_fn(title, codec=codec_val, range_=Video.Range.HDR10)\n except (ValueError, SystemExit) as e:\n if self.track_request.best_available:\n self.log.warning(f\" - HDR10 not available for HYBRID, skipping ({e})\")\n continue\n raise\n if first:\n all_tracks.add(hdr_tracks, warn_only=True)\n if hdr_tracks.manifest_url and not all_tracks.manifest_url:\n all_tracks.manifest_url = hdr_tracks.manifest_url\n first = False\n else:\n for video in hdr_tracks.videos:\n all_tracks.add(video, warn_only=True)\n\n try:\n dv_tracks = fetch_fn(title, codec=codec_val, range_=Video.Range.DV)\n for video in dv_tracks.videos:\n all_tracks.add(video, warn_only=True)\n except (ValueError, SystemExit):\n self.log.info(\" - No DolbyVision manifest available for HYBRID\")\n else:\n for codec_val in codecs:\n try:\n tracks = fetch_fn(title, codec=codec_val, range_=range_val)\n except (ValueError, SystemExit) as e:\n if self.track_request.best_available:\n codec_name = codec_val.name if codec_val else \"default\"\n self.log.warning(f\" - {range_val.name}/{codec_name} not available, skipping ({e})\")\n continue\n raise\n if first:\n all_tracks.add(tracks, warn_only=True)\n if tracks.manifest_url and not all_tracks.manifest_url:\n all_tracks.manifest_url = tracks.manifest_url\n first = False\n else:\n for video in tracks.videos:\n all_tracks.add(video, warn_only=True)\n\n return all_tracks\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 HTTP session, adds common headers from config, cookies, retry handler, and a proxy if available. :returns: Prepared Python-requests HTTP 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 HTTP session, adds common headers\n from config, cookies, retry handler, and a proxy if available.\n :returns: Prepared Python-requests HTTP session\n \"\"\"\n session = TimeoutSession()\n session.headers.update(config.headers)\n # Retry / pool policy mirrors RnetSession via the shared constants in session.py:\n # same total, forcelist, backoff cap, allowed_methods (incl. POST, so license\n # requests retry on both paths), and pool size. Accepted divergence: urllib3's\n # backoff_jitter adds an absolute 0..N seconds whereas rnet jitters \u00b110% of the\n # backoff, the only intentional difference, not worth hand-rolling a retry loop.\n session.mount(\n \"https://\",\n TimeoutHTTPAdapter(\n max_retries=Retry(\n total=MAX_RETRIES,\n backoff_factor=BACKOFF_FACTOR,\n backoff_max=MAX_BACKOFF,\n backoff_jitter=0.2,\n status_forcelist=STATUS_FORCELIST,\n allowed_methods=RETRY_METHODS,\n respect_retry_after_header=True,\n ),\n pool_connections=POOL_MAX_SIZE,\n pool_maxsize=POOL_MAX_SIZE,\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. unshackle operates this method 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>Do not store the cookies outside this function either. However, you can load the cookies into the service HTTP 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. unshackle operates this method before\n any of the 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 Do not store the cookies outside this function either. However, you can load\n the cookies into the service HTTP 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 through 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 through 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 return prompt_user(prompt)\n</code></pre>"},{"location":"reference/api/service/#unshackle.core.service.Service.search","title":"search","text":"<pre><code>search()\n</code></pre> <p>Find titles from the Service by query.</p> <p>The Service class must take the query as a CLI argument. Ideally re-use the title ID argument (that is, self.title).</p> <p>unshackle displays the search results 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 Find titles from the Service by query.\n\n The Service class must take the query as a CLI argument.\n Ideally re-use the title ID argument (that is, self.title).\n\n unshackle displays the search results 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 unshackle processes now. unshackle gives this in case it holds data you need, for example for an 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. Do not 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 unshackle processes now. unshackle\n gives this in case it holds data you need, for example for an 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. Do not 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 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 the service to detect your CDM device. The device can then be 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 unshackle processes now. unshackle gives this in case it holds data you need, for example for an 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. Do not 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 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 the service to detect your CDM device. The device\n can then be banned, 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 unshackle processes now. unshackle\n gives this in case it holds data you need, for example for an 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. Do not 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 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 the service to detect your CDM device. The device can then be 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 unshackle processes now. unshackle gives this in case it holds data you need, for example for an 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. Do not 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 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 the service to detect your CDM device. The device\n can then be banned, 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 unshackle processes now. unshackle\n gives this in case it holds data you need, for example for an 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. Do not 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> tracks. unshackle uses no CDM here: 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 unshackle processes now. unshackle gives this in case it holds data you need, for example for an 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` tracks. unshackle uses no CDM here: 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 unshackle processes now. unshackle\n gives this in case it holds data you need, for example for an 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>You must return at least one object. If you do not, unshackle presumes an invalid Title ID.</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 you need later, 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 You must return at least one object. If you do not, unshackle presumes an invalid\n Title ID.\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 you need later, 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 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 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 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 track, Representation, or Adaptation, or a Subtitle file.</p> <p>While one Track should only hold information for one downloadable track, try to get as many unique Track objects per track type so track selection by the root code can give you more options in terms of Resolution, Bitrate, Codecs, Language, and such.</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 have encryption, and which DRM System they use, with the <code>drm</code> property.</p> <p>If you can get the Track's KID (Key ID) as a 32 char (16 bit) HEX string, give it to the Track's <code>kid</code> variable, as it will speed up the decryption process later on. The service decides whether it is necessary. Generally if you can give it, without downloading any of the Track's media data, then do.</p> <p>:param title: The current <code>Title</code> from get_titles that unshackle processes now. :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 track, Representation, or\n Adaptation, or a Subtitle file.\n\n While one Track should only hold information for one downloadable track, try to get as many\n unique Track objects per track type so track selection by the root code can give you more\n options in terms of Resolution, Bitrate, Codecs, Language, and such.\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 have encryption, and which DRM System they\n use, with the `drm` property.\n\n If you can get the Track's KID (Key ID) as a 32 char (16 bit) HEX string, give it to the\n Track's `kid` variable, as it will speed up the decryption process later on. The service\n decides whether it is necessary. Generally if you can give it, without downloading any of\n the Track's media data, then do.\n\n :param title: The current `Title` from get_titles that unshackle processes now.\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 unshackle processes now.</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 is 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 unshackle processes now.\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 is 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 downloaded Segment.</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 downloaded Segment.\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 downloaded Track object.</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 downloaded Track object.\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 decrypted Track object.</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 decrypted HLS segment information.</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 decrypted Track object.\n drm: The DRM object it decrypted with.\n segment: The decrypted HLS segment information.\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 repacked Track object.</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 repacked Track object.\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 immediately before unshackle multiplexes a Track into a Container.</p> <p>Note: Right now unshackle multiplexes only MKV containers. In the future unshackle can also call this when it multiplexes to other containers like MP4 with FFmpeg/mp4box.</p> <p>Parameters:</p> Name Type Description Default <code>track</code> <code>AnyTrack</code> <p>The repacked Track object.</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 immediately before unshackle multiplexes a Track into a Container.\n\n Note: Right now unshackle multiplexes only MKV containers. In the future\n unshackle can also call this when it multiplexes to other containers like\n MP4 with FFmpeg/mp4box.\n\n Parameters:\n track: The repacked Track object.\n \"\"\"\n</code></pre>"},{"location":"reference/api/service/#unshackle.core.service.grow_session_pool","title":"grow_session_pool","text":"<pre><code>grow_session_pool(session, size)\n</code></pre> <p>Grow a shared requests session's connection pool to <code>size</code> before track downloads start.</p> <p>The worker threads of every track draw on this one pool, because the downloader never remounts an HTTP session the caller passes in (see downloaders/requests.py). The pool must hold <code>downloads * workers</code> connections, or threads queue for a slot instead of reading. Call this before any download thread exists: a remount races with other threads that call <code>get_adapter</code>. RnetSession does not block on its idle-pool cap, so this function skips it.</p> Source code in <code>unshackle/core/service.py</code> <pre><code>def grow_session_pool(session: Any, size: int) -&gt; None:\n \"\"\"Grow a shared requests session's connection pool to ``size`` before track downloads start.\n\n The worker threads of every track draw on this one pool, because the downloader never\n remounts an HTTP session the caller passes in (see downloaders/requests.py). The pool must hold\n ``downloads * workers`` connections, or threads queue for a slot instead of reading.\n Call this before any download thread exists: a remount races with other threads that call\n ``get_adapter``. RnetSession does not block on its idle-pool cap, so this function skips it.\n \"\"\"\n if not isinstance(session, requests.Session):\n return\n adapter = session.get_adapter(\"https://\")\n if not isinstance(adapter, HTTPAdapter) or getattr(adapter, \"_pool_maxsize\", 0) &gt;= size:\n return\n grown = TimeoutHTTPAdapter(\n max_retries=adapter.max_retries,\n pool_connections=size,\n pool_maxsize=size,\n pool_block=True,\n timeout=getattr(adapter, \"default_timeout\", DEFAULT_TIMEOUT),\n )\n session.mount(\"https://\", grown)\n session.mount(\"http://\", grown)\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>Sanitise 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 Sanitise 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 ValueError:\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 part=None,\n absolute=None,\n)\n</code></pre> <p> Bases: <code>Title</code></p>"},{"location":"reference/api/titles/#unshackle.core.titles.Episode.matches_wanted","title":"matches_wanted","text":"<pre><code>matches_wanted(wanted)\n</code></pre> <p>Whether a parsed <code>-w</code> key set selects this episode.</p> <p>A part-ful episode answers to both its base key and its part key, so <code>-w s1e1</code> takes every part. A dated episode also answers to its ISO air date. <code>!</code> keys are part-qualified exclusions resolved here.</p>"},{"location":"reference/api/titles/#unshackle.core.titles.Episode.part_suffix","title":"part_suffix","text":"<pre><code>part_suffix()\n</code></pre> <p><code>.Part.2</code> / <code>Part 2</code> in the series template's own separator style.</p>"},{"location":"reference/api/titles/#unshackle.core.titles.Episode.build_template_context","title":"build_template_context","text":"<pre><code>build_template_context(\n media_info, show_service=True, include_part=True\n)\n</code></pre> <p>Build template context dictionary from MediaInfo.</p>"},{"location":"reference/api/titles/#unshackle.core.titles.Episode.air_date_display","title":"air_date_display","text":"<pre><code>air_date_display()\n</code></pre> <p>Render air_date using the series template's own separator (dots or spaces).</p>"},{"location":"reference/api/titles/#unshackle.core.titles.Episode.folder_season","title":"folder_season","text":"<pre><code>folder_season()\n</code></pre> <p>Season folder label: air year when the air date parsed to a date, else SxxExx-style season.</p>"},{"location":"reference/api/titles/#unshackle.core.titles.Episode.part_label","title":"part_label","text":"<pre><code>part_label()\n</code></pre> <p><code>.2</code> selection-syntax suffix for console output, empty when part-less.</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.Movie.build_template_context","title":"build_template_context","text":"<pre><code>build_template_context(media_info, show_service=True)\n</code></pre> <p>Build template context dictionary from MediaInfo.</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=1,\n year=None,\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.Song.matches_wanted","title":"matches_wanted","text":"<pre><code>matches_wanted(wanted)\n</code></pre> <p>Whether a parsed <code>-w</code> key set selects this song.</p> <p>A song shares the episode key space, its disc reading as the season and its track as the episode, so <code>-w 1-5</code> takes tracks 1 to 5 and <code>-w 2x3</code> takes disc 2 track 3. A song has no parts and no air date, so it answers to its disc-and-track key only.</p>"},{"location":"reference/api/titles/#unshackle.core.titles.Song.build_template_context","title":"build_template_context","text":"<pre><code>build_template_context(media_info, show_service=True)\n</code></pre> <p>Build template context dictionary from MediaInfo.</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>Make a new Attachment.</p> <p>If providing a path, the file must already exist. If providing a URL, download() fetches the file during the download phase. You must give either path or url.</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[AnySession]</code> <p>Optional requests HTTP session to download the file with.</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.download","title":"download","text":"<pre><code>download(session=None, *, no_proxy_download=False)\n</code></pre> <p>Download a URL-backed attachment to the temp directory.</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>Make 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[AnySession]</code> <p>Optional requests HTTP session to download the file with.</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>Make 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, unshackle uses MediaInfo to get the codec after it downloads the track.</p> <code>None</code> <code>bitrate</code> <code>Optional[Union[str, int, float]]</code> <p>A number or float representing the average bandwidth in bits/s. unshackle rounds float values 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 track.</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 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 the audio channel 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 cannot read expanded surround sound channel layout strings like 7.1.2.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Audio.to_music_container","title":"to_music_container","text":"<pre><code>to_music_container()\n</code></pre> <p>Remux the track into the container of its codec, as a standalone audio file.</p> <p>Music titles never reach the muxer, so the downloaded file is the delivered file, and after decryption that is still a fragmented MP4. Its header states a length of zero, so a player stops after the first fragment. FLAC inside an MP4 is also not a FLAC stream. A rename cannot correct either fault. Returns True once the new file replaces the downloaded one; every failure raises.</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>Make 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, multiply it by 1000. If you have a timecode float in milliseconds (no decimal value), 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>True if the Chapter has a name.</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>unshackle formats these with f-strings, so format directives work. 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, output_name=None)\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>Make Level 5 active area metadata through crop detection on the HDR10 track.</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 HDR10+ sources ship MaxCLL 10000 on a 1000-nit master), and MaxFALL must not exceed MaxCLL. A value of 0 means \"unknown\", and this method keeps it 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 track</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Hybrid.probe_hdr_metadata","title":"probe_hdr_metadata","text":"<pre><code>probe_hdr_metadata()\n</code></pre> <p>Extract mastering display and Content Light Level metadata from the HDR10 track with FFprobe.</p> <p>Returns (max_mdl, min_mdl, max_cll, max_fall) in dovi_tool level6 units: - max_mdl: nits (integer) - min_mdl: 0.0001 nit units (integer) - max_cll / max_fall: nits (integer)</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>Make 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, unshackle uses MediaInfo to get the format after it downloads the track.</p> <code>None</code> <code>cc</code> <code>bool</code> <p>Closed Caption. - Intended as if you could not hear the audio at all. - Can have Sound as well as Dialogue, but does not have to. - Original source would be from EIA-CC encoded video. Typically all upper-case characters. Indicators of it being CC without knowing original source: - Extracted with CCExtractor, or - &gt;&gt;&gt; (or similar) at the start of some or all lines, or - All text is uppercase or at least the majority, or - Subtitles use the scrolling-text style (one line appears, oldest line then disappears). The fact that you downloaded it as a SRT or VTT or such does not mean it is not from an EIA-CC stream. And I would not 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 could not hear the audio at all. - MUST have Sound as well as Dialogue to count as SDH. - It has no \"syntax\" or \"format\", but it is not transmitted in archaic forms like EIA-CC streams. It is intended for transmission through SubRip (SRT), WebVTT (VTT), TTML, and the other modern subtitle formats. If you can see important audio/sound transcriptions and not only dialogue and it does not have the indicators of CC, then it is most likely SDH. If it does not have important audio/sounds transcriptions it might only be regular subtitling (you would not 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 is important information at some point in time like watching a Dubbed title and an important Sign or Letter is shown or someone talking in a different language. The Matroska Spec recommends that the player plays Forced tracks if the player's current playback audio language matches a subtitle marked as \"forced\". However, that does not 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. Know what to expect with \"forced\" subtitles.</p> <code>False</code> <p>Note: If codec is not specified, unshackle can skip some checks or assume a value. Give as much information as possible.</p> Information on Subtitle Types <p>https://bit.ly/2Oe4fLC (3PlayMedia Blog on SUB vs CC vs SDH). However, I would not pay much attention to the claims about SDH needing to be in the original language. It is logically not true.</p> <p>CC == Closed Captions. Source: Every site. SDH = Subtitles for the Deaf or Hard-of-Hearing. Source: 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.strip_webvtt_timestamp_map","title":"strip_webvtt_timestamp_map <code>staticmethod</code>","text":"<pre><code>strip_webvtt_timestamp_map(text)\n</code></pre> <p>Remove X-TIMESTAMP-MAP header lines (RFC 8216 \u00a73.5, HLS only).</p> <p>Cue times are already absolute, but SubtitleEdit reads the header and offsets every cue by it during conversion.</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 text as string</p> required <p>Returns:</p> Type Description <code>str</code> <p>Sanitized WebVTT text</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>Examine WebVTT text for cue identifiers that need removal.</p> <p>Parameters:</p> Name Type Description Default <code>text</code> <code>str</code> <p>The WebVTT text as string</p> required <p>Returns:</p> Type Description <code>bool</code> <p>True if the text has cue identifiers, 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 such as \"Q0\" and \"Q1\" that appear on their own line before the timing line. These can be incorrectly parsed as part of the previous cue's text by some parsers (like pysubs2).</p> <p>Parameters:</p> Name Type Description Default <code>text</code> <code>str</code> <p>The WebVTT text as string</p> required <p>Returns:</p> Type Description <code>str</code> <p>Sanitized WebVTT text with cue identifiers removed</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.parse_vtt_time","title":"parse_vtt_time <code>staticmethod</code>","text":"<pre><code>parse_vtt_time(t)\n</code></pre> <p>Parse WebVTT timestamp to milliseconds. Returns 0 for malformed input.</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>Examine WebVTT text for 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 text as string</p> required <p>Returns:</p> Type Description <code>bool</code> <p>True if the text has overlapping cues, 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 text as string</p> required <p>Returns:</p> Type Description <code>str</code> <p>WebVTT text 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 that corrects multiple potential issues.</p> <p>This is lossy, so use it only as a fallback once normal parsing has failed. This method discards everything before the WEBVTT header line and reduces the header itself to a bare \"WEBVTT\" line. Negative timestamps become 00:00:00.000, and it pads timestamps that have no hours field to HH:MM:SS.mmm.</p> <p>Parameters:</p> Name Type Description Default <code>text</code> <code>str</code> <p>The WebVTT text as string</p> required <p>Returns:</p> Type Description <code>str</code> <p>Sanitized WebVTT text</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>): unshackle uses the best available backend that can convert source-&gt;target, and falls back through the capability chain on failure. The <code>conversion_method</code> config key (<code>auto</code> | <code>subby</code> | <code>pysubs2</code> | <code>subtitleedit</code> | <code>pycaption</code>) pins the backend, and <code>preferred_conversion_method</code> nudges it per-service. An explicit config value always wins.</p> <p><code>forced</code> marks an explicit user request (<code>--sub-format</code>). unshackle skips lossy downconverts of styled formats (SSA/ASS -&gt; SRT) 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>This method removes a leading <code>@</code> (vertical-writing prefix), de-duplicates the names case-insensitively, and prefers 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 text as string</p> required <p>Returns:</p> Type Description <code>str</code> <p>Sanitized WebVTT text 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 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 tag if available.</p> <p>Code ported originally by xhlove to Python from shaka-player. rlaphoenix has since improved it with 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>Remove the SDH captions.</p> <p>The 'sdh_method' setting in config gives the SDH stripping method: - '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. Use this 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 adaptive_workers=False,\n download_processes=1,\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 HTTP 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>This uses a defaultdict 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 note that these values can 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 adaptive_workers=False,\n download_processes=1,\n)\n</code></pre> <p>Download and optionally Decrypt this Track.</p> <p>For a URL-descriptor Video or Audio track with no <code>drm</code> set, unshackle probes the DRM from the track's init data and stores it on the track, so a service need not declare <code>drm</code> itself.</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>Assemble the shared Track constructor kwargs from a <code>to_dict()</code> payload.</p> <p>DRM is not reconstructed here: <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 can find the Key ID by probing the track 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. This method then uses the return value of <code>get_init_segment</code> to find the Key ID.</p> <p>Returns:</p> Type Description <code>Optional[UUID]</code> <p>The Key ID as a UUID object, or None if unshackle cannot find the Key ID.</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 the parser deferred it.</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 the DRM loaded or is already present, False if the load 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.</p> <p>HLS and DASH tracks must explicitly give a URL to the init segment or file. Give the byte-range for the init segment where possible.</p> <p>If <code>byte_range</code> is not set, it will make a HEAD request and examine the size of the file. If it cannot find the size, 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 response body length if byte-range is not used, if unshackle cannot find the body size, or if the body size is larger than it. Use a value of 20000 (20KB) or higher.</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>HTTP session context, for example authorization and headers.</p> <code>None</code>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.repackage","title":"repackage","text":"<pre><code>repackage(bsf_v=None)\n</code></pre> <p>Remux the track with FFmpeg <code>-c copy</code>.</p> <p>A given <code>bsf_v</code> goes into the same pass as <code>-bsf:v</code>, which normalises video VUI colour metadata without a second full-file remux. Repackaging is mandatory. The bitstream filter is best-effort: if the combined pass fails, and it is not the AAC-retry case, unshackle tries it again once without <code>bsf_v</code> so the remux still succeeds. Returns True if unshackle applied the requested <code>bsf_v</code> (always False when <code>bsf_v</code> is None, because the caller requested nothing).</p>"},{"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>Examine whether 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.</p> <p>A track whose ID is already in the collection raises ValueError. With <code>warn_only</code> set, this method skips such a track and logs how many it skipped.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.sort_videos","title":"sort_videos","text":"<pre><code>sort_videos(by_language=None, exact_match=False)\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(\n by_language=None, codec_priority=None, exact_match=False\n)\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(\n by_language=None,\n type_priority=None,\n group_by=None,\n exact_match=False,\n)\n</code></pre> <p>Sort subtitle tracks by various track attributes to a common P2P standard. You may optionally give a sequence of languages to prioritise 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> Type 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 Type Order with an explicit ranking of \"forced\", \"normal\", and \"sdh\" (cc counts as sdh). Unlisted types fall to the end.</p> <p>group_by sets the major sort order. \"type\" (default) keeps every forced track together, then every normal, then every SDH, each block ascending by language. \"language\" groups by language instead, so Finnish sits next to Finnish SDH, with the Type Order applied inside each language.</p> <p>exact_match makes a by_language entry sort only its own tag. By default \"en\" also sorts \"en-US\" and \"en-GB\".</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 caller can choose a DV track as both the hybrid ingredient (lowest) and an explicit deliverable. Without dedup, unshackle would mux and download the same track 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 the user explicitly requested their range alongside HYBRID, so for example <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 the caller also selected as an explicit deliverable (same track in both selections) stays unflagged, and the standalone mux loop muxes it 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 output_path=None,\n)\n</code></pre> <p>Multiplex all the Tracks into a Matroska Container file.</p> <p>A failed mux does not raise. mkvmerge's exit code and error lines come back alongside the output path, and the caller must examine them.</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 with <code>completed=...</code>. This must be the progress object's update() func, pre-set with task id by functools.partial.</p> <code>None</code> <code>audio_expected</code> <code>bool</code> <p>Whether the output must have audio. unshackle uses this to decide if it adds embedded audio metadata.</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> <code>output_path</code> <code>Optional[Path]</code> <p>Explicit destination for the muxed container. When None (default) unshackle derives the path from the first track, so callers muxing several track groups that share a video list must pass distinct paths to avoid clobbering each other.</p> <code>None</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>Make 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, unshackle uses MediaInfo to get the codec after it downloads the track.</p> <code>None</code> <code>range_</code> <code>Optional[Range]</code> <p>A Video.Range enum representing the video colour 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. unshackle rounds float values 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, unshackle can skip some checks or assume a value. Give as much information as possible.</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>ITU-T H.273 and ISO/IEC 23091-2 define CICP for signalling video colour 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 - Coding-independent code points - 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 after user feedback (GitHub issue) and matches 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 Colour Range to Limited (0) or Full (1).</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.vui_bsf","title":"vui_bsf","text":"<pre><code>vui_bsf()\n</code></pre> <p>Return the <code>-bsf:v</code> value that rewrites SPS VUI colour metadata to match <code>self.range</code>.</p> <p>Returns None when a rewrite is not necessary: SDR/DV/HYBRID ranges, non-AVC/HEVC codecs, a missing file, or when the bitstream already ships the correct colour metadata. Otherwise returns a <code>{h264,hevc}_metadata=...</code> string suitable for FFmpeg <code>-bsf:v</code>.</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 unshackle rewrote the bitstream.</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 is not much more than a wrapper to the track.ccextractor function. All this does is examine if a c608 box exists, and only then does it call CCExtractor.</p> <p>Even though there is a possibility of more than one c608 box, unshackle can extract only one. It is also 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, before unshackle can <p>extract more than one CEA-608 track.</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 only the SEI data). unshackle can do this only for bitstreams with x264 encoding information, because of the obscurity on the MDAT mp4 box structure. Therefore, we need to use hacky regex.</p>"},{"location":"reference/configuration/","title":"Configuration Reference","text":"<p>Every config key you can set in <code>unshackle.yaml</code>, with its name, type, default value, and behaviour, split into one page per area. A worked config is on the annotated example page.</p> <p>Where the file lives, how unshackle discovers it, and how to edit it: The Configuration File.</p> <p>How defaults work</p> <p>Every config key is optional except <code>output_template</code>, which <code>dl</code> requires. Without it, <code>dl</code> aborts with an error. If you do not write any other config key, unshackle uses the built-in default listed here. There is no schema validation: unshackle silently ignores unknown config keys (they never become settings), and reads the file with <code>yaml.safe_load</code>. An empty or missing file means every other config key falls back to its default.</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 set to any value, unshackle exits immediately with an error telling you to use <code>output_template</code> instead.</li> </ul> <p>See Deprecated &amp; removed keys.</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>continue_downloads</code>, <code>subtitle</code>, <code>audio</code>, <code>muxing</code>, <code>language_tags</code>, <code>dual_multi_mode</code> Output &amp; naming <code>output_template</code>, <code>tag</code>, <code>tag_rules</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> Post-download scripts <code>post_scripts</code> External API keys <code>omdb_api_key</code>, <code>tmdb_api_key</code>, <code>tvdb_api_key</code>, <code>tvdb_pin</code>, <code>tvdb_order</code>, <code>simkl_client_id</code>, <code>metadata_providers</code>, <code>anilist_title_language</code>, <code>disable_metadata</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> Appearance <code>theme</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> config key is a dict mapping directory names to filesystem paths. unshackle honours only the names listed below. A handful are protected and you cannot move them, and unshackle silently ignores an override of one. unshackle computes all defaults relative to the installed package, and passes every user-settable path 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> Yes Default output directory for finished files. <code>temp</code> path <code>&lt;repo&gt;/temp</code> Yes Temporary working files during download/decrypt/mux. <code>cache</code> path <code>&lt;data&gt;/cache</code> Yes Generic cache, title cache, and the update-check store. <code>cookies</code> path <code>&lt;data&gt;/cookies</code> Yes Per-service cookie files (and VPN cookie files). <code>logs</code> path <code>&lt;data&gt;/logs</code> Yes Log files. <code>exports</code> path <code>&lt;data&gt;/exports</code> Yes Export JSON files. <code>wvds</code> path <code>&lt;data&gt;/WVDs</code> Yes Widevine device files (<code>.wvd</code>). <code>prds</code> path <code>&lt;data&gt;/PRDs</code> Yes PlayReady device files (<code>.prd</code>). <code>dcsl</code> path <code>&lt;data&gt;/DCSL</code> Yes DCSL data. <code>commands</code> path <code>unshackle/commands</code> Yes CLI command modules. <code>services</code> list | path <code>[unshackle/services]</code> Yes Service search paths and/or remote repo specs (see below). <code>vaults</code> path <code>unshackle/vaults</code> Yes Vault backend modules. <code>fonts</code> path <code>unshackle/fonts</code> Yes Bundled fonts. <code>user_configs</code> path <code>unshackle/</code> No protected Where <code>unshackle.yaml</code> lives. <code>data</code> path <code>unshackle/</code> No protected Base for the data subdirectories above. <code>core_dir</code> path <code>unshackle/core</code> No protected Package core. <code>namespace_dir</code> path <code>unshackle/</code> No protected Package root. <code>app_dirs</code> - <code>AppDirs(\"unshackle\", False)</code> No 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. unshackle clones and updates repo specs automatically, and uses plain paths as they are. List order is priority: the first source to define a service tag wins.</p> <pre><code>directories:\n services:\n - you/your-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 does a shallow <code>clone</code>, <code>fetch</code>, <code>pull</code>, and a local <code>reset</code>. unshackle never pushes anything. Your existing git credential helper authenticates private repos, and unshackle stores no tokens of its own. Clones live under <code>&lt;first-local-services-dir&gt;/_repos/&lt;host&gt;__&lt;owner&gt;__&lt;repo&gt;/</code> (or the bundled <code>unshackle/services</code>), and unshackle writes nothing 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>Automatic and manual refresh behave differently</p> <p>The automatic 24 h-TTL refresh that happens during a normal <code>dl</code>/<code>search</code> run refuses to refresh and exits (naming the offending clone) if that clone has uncommitted changes to tracked files or unpushed local commits. Untracked files (new service folders, <code>__pycache__</code>) never block it. The manual <code>unshackle util refresh-services</code> command instead hard-resets the clone to upstream, discarding any local edits.</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 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/directories/#filenames","title":"Filenames","text":"<p>The <code>filenames</code> config key is a dict of templated file/name patterns. unshackle uses each value verbatim (no path processing). It fills in braced fields like <code>{time}</code> and <code>{service}</code> 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/download/","title":"Download &amp; processing","text":""},{"location":"reference/configuration/download/#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. unshackle uses the block as Click's <code>default_map</code>, so you can give any <code>dl</code> flag a default here. See Downloading and the CLI Reference for what each flag does.</p> <p>Config key naming. A config 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 config keys use the flag's internal destination and not its visible name. Set these exact config 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>--anilist</code> <code>anilist_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 \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 config keys. This is a useful subset, and 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. A <code>-</code> prefix excludes, e.g. <code>[all, -es]</code>. <code>a_lang</code> / <code>v_lang</code> list <code>[]</code> Audio- / video-only language override. A <code>-</code> prefix excludes. <code>s_lang</code> list <code>[\"all\"]</code> Subtitle language(s). A <code>-</code> prefix excludes, e.g. <code>[all, -es]</code>. <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>HLG</code>, <code>HDR10</code>, <code>HDR10P</code>, <code>DV</code>, <code>HYBRID</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>forced_s_lang</code> list <code>[]</code> Forced subtitle language(s); implies <code>forced_subs</code>. A <code>-</code> prefix excludes. <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>speed_limit</code> str (unlimited) Total download speed cap across all downloads combined, e.g. <code>500k</code>, <code>5M</code>, <code>1.5G</code> or plain bytes/sec. Values are bytes, not bits (<code>5M</code> = 5.0 MB/s). <code>slow</code> str (unset) Inter-title delay, e.g. <code>\"20-40\"</code>. <code>best_available</code> bool <code>false</code> Warn instead of failing when a requested resolution, range, or language is missing. The CLI flag is <code>--best-available</code>, also spelled <code>--warn-only</code>. <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>Language exclusions in YAML</p> <p>The language keys accept the same <code>-</code> exclusion tokens as the command line. Give them as a list or as one comma-separated string.</p> <pre><code>dl:\n s_lang: [all, -es]\n a_lang: \"orig,-es\"\n</code></pre> <p>See Excluding languages for the rules.</p> <p>Per-service overrides</p> <p>A <code>dl</code> block nested under a service in <code>services</code> takes the same keys and applies to that service only.</p> <pre><code>dl:\n lang: [en]\nservices:\n EXAMPLE1:\n dl:\n lang: [en, ja]\n range: [DV]\n</code></pre> <p><code>serve</code> uses these same keys</p> <p>The <code>serve</code> block accepts most of the same <code>dl</code> option keys at its top level to set server-wide download defaults for every request it handles. The API ignores the config keys it does not know there, <code>speed_limit</code> for example. <code>serve</code> has its own <code>global_speed_limit</code>.</p>"},{"location":"reference/configuration/download/#continue_downloads","title":"<code>continue_downloads</code>","text":"<ul> <li>Type: <code>bool</code> \u00a0\u00b7\u00a0 Default: <code>false</code></li> </ul> <p>Keep a failed download's completed segment files so the next download resumes from where it stopped instead of restarting from byte zero.</p> <p>unshackle reuses only whole, fully downloaded segments. It always discards partially written segments, and no partial-byte (<code>Range</code>) resume across runs takes place. Reuse is possible only with proof that the segmentation did not change. The manifest URL, segment count, and byte ranges must all match the previous download, or the download silently restarts clean.</p> <p>What can and cannot resume</p> <ul> <li>Segmented DASH, ISM, and HLS tracks resume.</li> <li>Single-file (non-segmented) downloads and DASH tracks collapsed to a single ranged download never make segment files, so this option does not apply to them (the downloader has its own in-flight partial-file handling for those).</li> <li>HLS resumes Widevine/PlayReady and unencrypted titles only. An AES-128 title always restarts. An HLS failure during the post-download merge step also restarts.</li> </ul> <p>For a one-off resume without changing config, pass <code>dl --continue-downloads</code> on the command line (the flag can only enable resume, never disable it).</p> Resume failed downloads<pre><code>continue_downloads: true\n</code></pre>"},{"location":"reference/configuration/download/#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 unshackle muxes the subtitles in or writes them 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>output_mode</code> str <code>\"mux\"</code> <code>mux</code> embeds subtitles in the MKV; <code>sidecar</code> writes separate files; <code>both</code> writes sidecars and still muxes. <code>sidecar_format</code> str <code>\"srt\"</code> Format for sidecar files when <code>output_mode</code> is <code>sidecar</code> or <code>both</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). Types you leave out fall to the end. <code>group_by</code> str <code>\"type\"</code> Which key groups the subtitle tracks. <code>type</code> puts all forced tracks together, then all normal, then all SDH. <code>language</code> keeps each language next to its own variants. <code>language_priority</code> list (unset) Languages to sort to the top, in the order you give. The rest keep the default order: original language first, then alphabetical. Nothing is removed. <pre><code>subtitle:\n strip_sdh: true\n output_mode: sidecar\n sidecar_format: srt\n</code></pre> <p><code>group_by</code> track order</p> <code>group_by</code> Result <code>type</code> Danish, Finnish, French, \u2026 Danish SDH, Finnish SDH, French SDH <code>language</code> Danish, Danish SDH, Finnish, Finnish SDH, French, French SDH <p><code>type_priority</code> still sets the order of the variants, so with <code>group_by: language</code> it controls the order inside each language.</p> <p><code>language_priority</code> sorts languages, it does not select them</p> <pre><code>subtitle:\n group_by: language\n language_priority: [en, es, fr]\n</code></pre> Result for an English title Default English, Arabic, Bulgarian, Spanish, French, Japanese With the list above English, Spanish, French, Arabic, Bulgarian, Japanese <p>unshackle removes nothing, unlike <code>-sl</code>, which drops every subtitle language it does not name.</p> <p>Use <code>orig</code> in the list for the title's original language. A base tag also covers its regional forms, so <code>en</code> sorts <code>en-US</code> and <code>en-GB</code>, but <code>zh</code> does not cover <code>zh-Hant</code>, which you must name. The sort ignores entries that match no track, and it ignores entries that are not valid language tags.</p> <p><code>--exact-lang</code> applies here too: with it, <code>en</code> sorts only <code>en</code>, and <code>en-US</code> falls to the alphabetical tail with the rest. Name each tag you want when you use that flag.</p> <p><code>type_priority</code> picks the default subtitle only with <code>muxing.default_language</code></p> <p>At mux time the <code>default</code> flag goes to every forced subtitle whose language matches the first audio track, so a full dialogue track never becomes default on its own. <code>type_priority</code> alone does not change that. Name a subtitle language in <code>muxing.default_language</code> and the first track in that language gets the flag instead, which is where <code>type_priority</code> decides which track that is:</p> <pre><code>muxing:\n default_language:\n subtitle: en\nsubtitle:\n type_priority: [normal, sdh, forced]\n</code></pre>"},{"location":"reference/configuration/download/#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. <code>language_priority</code> is an ordered list of languages that sort to the top of the audio tracks.</p> <pre><code>audio:\n codec_priority:\n - EAC3\n - AC3\n language_priority:\n - orig\n - en\n</code></pre> <p><code>codec_priority</code> is a soft priority: nothing is dropped</p> <p><code>codec_priority</code> outranks bitrate: any listed codec sorts above every unlisted one, and among listed codecs the list order decides. Bitrate order survives only within a single codec rank. Nothing is 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/download/#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 video tracks that share height, range, and codec into one file, so only language varies inside a file. <code>--merge-video</code> on the CLI flips this on. <code>concurrency</code> int <code>4</code> How many mkvmerge processes run at the same time when a title muxes more than one output file (one per video variant or audio codec). Each process uses one CPU core, so this shortens the mux step on an SSD. Set it to <code>1</code> on a hard disk, where parallel writes are slower. <pre><code>muxing:\n set_title: true\n concurrency: 4\n default_language:\n audio: en\n subtitle: en\n</code></pre>"},{"location":"reference/configuration/download/#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, unshackle evaluates each rule in order and uses the first match's <code>tag</code>. A rule can examine:</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: [ja]\n subs_contain: [en]\n tag: \"SUBBED\"\n</code></pre>"},{"location":"reference/configuration/download/#dual_multi_mode","title":"<code>dual_multi_mode</code>","text":"<ul> <li>Type: <code>str</code> \u00a0\u00b7\u00a0 Default: <code>strict</code></li> </ul> <p>Rule set for the <code>{dual}</code>, <code>{multi}</code>, and <code>{dubbed}</code> filename variables.</p> <code>strict</code> (default)<code>count</code> (legacy) Variable Set when <code>{dual}</code> Exactly two audio languages and one is the title's original language. <code>{multi}</code> Three or more audio languages, even without the original. <code>{dubbed}</code> A single audio language that is not the title's original language (requires a known original). Variable Set when <code>{dual}</code> Exactly two audio languages (original language ignored). <code>{multi}</code> Three or more audio languages. <code>{dubbed}</code> Never set. <pre><code>dual_multi_mode: strict\n</code></pre> <p>Dialects count as one language</p> <p>Regional variants of the same base language (e.g. <code>en-US</code> and <code>en-GB</code>) collapse to a single language in both modes, so they never trigger <code>{dual}</code> on their own.</p>"},{"location":"reference/configuration/drm/","title":"DRM &amp; CDM","text":"<p>These are the config keys. For concepts, device provisioning, and the <code>wvd</code>/<code>prd</code> commands see the DRM &amp; CDM guide. Device files themselves live in <code>directories.wvds</code> (<code>.wvd</code>) and <code>directories.prds</code> (<code>.prd</code>).</p>"},{"location":"reference/configuration/drm/#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: a per-request API 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 can hold <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>. unshackle matches the quality keys first, but only when a video height is known. If the value is still a dict after that, unshackle uses <code>widevine</code>/<code>playready</code> when present, or else the credential profile name, then <code>default</code>.</p> <p>unshackle finds the resolved name in <code>remote_cdm</code> by <code>name</code> first. If no entry matches, unshackle loads it as a local device file, in this order: <code>&lt;name&gt;.prd</code> in <code>directories.prds</code>, <code>&lt;name&gt;.prd</code> in <code>directories.wvds</code>, then <code>&lt;name&gt;.wvd</code> in <code>directories.wvds</code>.</p>"},{"location":"reference/configuration/drm/#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 definitions. unshackle matches each entry 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>, <code>device_name</code>, <code>secret</code> (fields) <code>custom_api</code> Fully YAML-configurable remote API <code>host</code> (required), <code>device</code>, <code>auth</code>, <code>endpoints</code>, <code>request_mapping</code>, <code>response_mapping</code>, <code>caching</code>, <code>timeout</code> (fields) (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> <p>For the two pywidevine/pyplayready backends, field names are read case-insensitively in both styles: <code>Device Type</code>/<code>device_type</code>, <code>System ID</code>/<code>system_id</code>, <code>Security Level</code>/<code>security_level</code>, <code>Host</code>/<code>host</code>, <code>Secret</code>/<code>secret</code>, <code>Device Name</code>/<code>device_name</code>.</p> <p>PlayReady <code>host</code> needs a <code>/playready</code> suffix</p> <p>pyplayready's <code>RemoteCdm</code> treats <code>host</code> as a base URL and appends its own endpoint paths, so a PlayReady entry's <code>host</code> must include the trailing <code>/playready</code> segment (for example <code>https://cdm.example.com/playready</code>). Without it the server returns <code>404</code> rather than a configuration error.</p>"},{"location":"reference/configuration/drm/#remote-cdm-decrypt-labs","title":"<code>decrypt_labs</code> fields","text":"Field Default Notes <code>host</code> <code>https://keyxtractor.decryptlabs.com</code> <code>device_name</code> <code>ChromeCDM</code> <code>ChromeCDM</code>, <code>L1</code>, <code>L2</code> (Widevine) or <code>SL2</code>, <code>SL3</code> (PlayReady) <code>secret</code> from <code>decrypt_labs_api_key</code> Sent as the <code>decrypt-labs-api-key</code> header. An error is raised if neither is set. <code>system_id</code> <code>26830</code> (Widevine), <code>0</code> (PlayReady) <code>security_level</code> Widevine <code>3</code>; PlayReady <code>2000</code> for <code>SL2</code>, else <code>3000</code> <p>unshackle uses PlayReady mode when <code>device_type</code> is <code>PLAYREADY</code> or <code>device_name</code> starts with <code>SL</code>.</p>"},{"location":"reference/configuration/drm/#remote-cdm-custom-api","title":"<code>custom_api</code> fields","text":"Field Type Notes <code>host</code> str Required. Base URL of the API. <code>device</code> dict <code>name</code>, <code>type</code> (<code>CHROME</code>, <code>ANDROID</code>, <code>PLAYREADY</code>), <code>system_id</code>, <code>security_level</code> <code>auth</code> dict <code>type</code> (default <code>header</code>): <code>header</code> uses <code>header_name</code> (default <code>Authorization</code>) and <code>key</code>; <code>bearer</code> uses <code>bearer_token</code> or <code>key</code>; <code>basic</code> uses <code>username</code> and <code>password</code>. <code>custom_headers</code> is merged in for any type. <code>endpoints</code> dict <code>get_request</code> and <code>decrypt_response</code>, each <code>{path, method, timeout}</code> <code>request_mapping</code> dict Per endpoint: <code>param_names</code>, <code>static_params</code>, <code>conditional_params</code>, <code>transforms</code>, <code>nested_params</code>, <code>exclude_params</code> <code>response_mapping</code> dict Per endpoint: <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> dict <code>enabled</code>, <code>use_vaults</code>, <code>check_cached_first</code> <code>legacy</code> dict Legacy mode options. <code>timeout</code> int Default <code>30</code>. Request timeout in seconds. <p>Transforms cover base64/hex/JSON encoding and <code>kid:key</code> parsing. unshackle uses PlayReady mode when <code>device.type</code> is <code>PLAYREADY</code> or the device name is <code>SL2</code>/<code>SL3</code>.</p> <pre><code>remote_cdm:\n - name: my_custom\n type: custom_api\n host: https://cdm.example.com\n device:\n name: ChromeCDM\n type: CHROME\n system_id: 26830\n security_level: 3\n auth:\n type: bearer\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>"},{"location":"reference/configuration/drm/#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 that physically decrypts CENC-encrypted tracks. unshackle compares the value case-insensitively. <code>\"mp4decrypt\"</code> selects Bento4's mp4decrypt, and anything else (including <code>\"shaka\"</code>) selects shaka-packager. When the value is a dict, unshackle compares the service tag case-insensitively and uses the <code>default</code> entry as the fallback.</p> <p>unshackle decrypts HLS AES-128 ClearKey in-process and ignores this setting.</p> GlobalPer-service <pre><code>decryption: shaka\n</code></pre> <pre><code>decryption:\n default: shaka\n EXAMPLE1: mp4decrypt\n</code></pre>"},{"location":"reference/configuration/example/","title":"A complete annotated example","text":"<p>The following config sets a handful of common config keys. Every config 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\"\ntvdb_api_key: \"your-tvdb-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/configuration/misc/","title":"Other Settings","text":"<p>Smaller configuration areas: external metadata API keys, caching and update checks, logging and debug flags, and deprecated keys.</p>"},{"location":"reference/configuration/misc/#external-api-keys","title":"External API keys","text":"<p>All are unset by default and enable optional metadata/geolocation features. For which fields each metadata provider can answer with, see What each metadata provider supplies.</p> Key Type Default Description <code>omdb_api_key</code> str <code>\"\"</code> OMDb API key for IMDb metadata lookups; a fallback for when the keyless <code>imdb</code> provider has no answer. 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>tvdb_api_key</code> str <code>\"\"</code> TheTVDB v4 API key; a fallback source to TMDB, strongest on TV series. Also the source <code>--enrich --tvdb</code> reads. Free keys are available on the TVDB site. <code>tvdb_pin</code> str <code>\"\"</code> Subscriber PIN, only needed for a user-supported TVDB key. Leave empty for a normal project key. <code>tvdb_order</code> str <code>\"\"</code> Default for <code>--tvdb-order</code>: renumber episodes to a TVDB season order (<code>official</code>, <code>dvd</code>, <code>absolute</code>, <code>alternate</code>, <code>regional</code>). Empty keeps the numbering the service gives. <code>metadata_providers</code> list or map (see below) Metadata providers to use, in the order they are tried. <code>anilist_title_language</code> str <code>english</code> Which AniList title variant to use: <code>english</code>, <code>romaji</code>, or <code>native</code>. <code>disable_metadata</code> bool <code>false</code> Set to <code>true</code> to stop all automatic metadata lookups. An ID you give yourself is still looked up. <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>How <code>metadata_providers</code> is applied</p> <p>A lookup goes to each metadata provider in turn and stops at the first good match, so the order decides which source wins. <code>metadata_providers</code> sets that order:</p> <pre><code>metadata_providers: [tvdb, tmdb, simkl]\n</code></pre> <p>Names not in the list are never used, so this both orders and filters. Unknown names are ignored with a warning. Leave it unset for the default order:</p> <pre><code>metadata_providers: [imdb, omdb, simkl, tmdb, tvdb, anilist]\n</code></pre> <p>Whatever the order, unshackle skips a metadata provider that has no API key. <code>imdb</code> and <code>anilist</code> need no API key, so they are always available. Available names are <code>imdb</code>, <code>omdb</code>, <code>simkl</code>, <code>tmdb</code>, <code>tvdb</code>, and <code>anilist</code>. The old name <code>imdbapi</code> still works and is read as <code>imdb</code>.</p> <p><code>anilist</code> is last in the default order. It only answers for anime and returns nothing for anything else, so it is harmless there. Move it earlier if you mostly download anime.</p> <p>The order applies to a title search and to a direct lookup of an ID you give with <code>--tmdb</code>, <code>--imdb</code>, <code>--tvdb</code>, or <code>--anilist</code>. A supplied ID always goes to the providers that read that kind of ID, and it never falls back to a title search.</p> <p>Which AniList title <code>anilist_title_language</code> picks</p> <p>AniList holds up to three titles for a work: the English one, the romaji transliteration, and the native one. This option says which of them unshackle uses:</p> <pre><code>anilist_title_language: romaji\n</code></pre> <p>A work does not always have all three. When the one you asked for is unset on AniList's side, unshackle falls back in the order english \u2192 romaji \u2192 native. It takes the first one that is set, so you always get a title.</p> <p>What <code>disable_metadata</code> turns off</p> <p>With <code>disable_metadata: true</code>, unshackle never contacts a metadata provider on its own. The title search is dead, and that includes the keyless <code>imdb</code> metadata provider. Titles, years and languages then come only from the service.</p> <pre><code>disable_metadata: true\n</code></pre> <p>An ID you give with <code>--tmdb</code>, <code>--imdb</code>, <code>--tvdb</code>, or <code>--anilist</code> is your permission to use that ID. That lookup still works. unshackle looks the ID up directly, cross references the other IDs from it, and <code>--enrich</code> still reads that source. unshackle stops only the lookups you did not ask for.</p> <p>The <code>imdb</code> provider needs no key</p> <p>It replaces the earlier <code>imdbapi</code> metadata provider, which read a third-party mirror (api.tiffara.com) and needed the <code>imdb_api_enabled</code> switch. That option is gone: delete it from your config, where it is now ignored.</p> <p>A different order per title kind</p> <p>Give a map instead of one list when the best source differs by kind. TVDB is strongest on series, TMDB on films. There are two kinds, <code>tv</code> and <code>movie</code>, and this example sets both of them and names every metadata provider, so nothing is left to the default:</p> <pre><code>metadata_providers:\n tv: [tvdb, tmdb, simkl, imdb, omdb]\n movie: [tmdb, imdb, omdb, simkl, tvdb]\n</code></pre> <p>Each list is independent: it both orders and filters that kind on its own, so unshackle still uses for <code>movie</code> a metadata provider you leave out of <code>tv</code>. Here unshackle tries TVDB first for a series and last for a film.</p> <p>You do not need to give both keys, or a full list in each. A kind you leave out uses the default order:</p> <pre><code>metadata_providers:\n tv: [tvdb, tmdb] # movies keep the default order\n</code></pre> <p><code>tv</code> covers every episode and <code>movie</code> covers every film. unshackle only looks up metadata for those two kinds, so unshackle ignores any other config key, such as <code>anime</code> or <code>music</code>.</p> <p><code>ipinfo_api_key</code> never touches your service sessions</p> <p>unshackle sends the token only to <code>api.ipinfo.io</code>, as a per-request <code>Authorization</code> header. It never goes on your service HTTP session, so it cannot leak to a streaming service. Lookups degrade gracefully through a fallback chain: the authenticated Lite endpoint (higher rate limits, and ASN/continent data, but no city or region) \u2192 anonymous ipinfo \u2192 <code>ip-api.in</code> as a last resort.</p>"},{"location":"reference/configuration/misc/#caching-updates","title":"Caching &amp; updates","text":""},{"location":"reference/configuration/misc/#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) Total retention window for a cached title, counted from when it was cached. Past <code>title_cache_time</code> the stale copy is only served as a fallback when a live fetch fails."},{"location":"reference/configuration/misc/#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/misc/#appearance","title":"Appearance","text":"Key Type Default Description <code>theme</code> str <code>catppuccin-mocha</code> Named colour theme for all CLI output: banner, logs, progress bars, and help screens. One of <code>catppuccin-mocha</code> (aliases <code>default</code>, <code>catppuccin</code>, <code>mocha</code>), <code>dracula</code>, <code>nord</code>, <code>gruvbox</code>, <code>one-dark</code> (alias <code>onedark</code>), <code>tokyo-night</code> (alias <code>tokyonight</code>), <code>monokai</code>, <code>flexoki</code>, <code>solarized-dark</code> (alias <code>solarized</code>). Case-insensitive; underscores work in place of hyphens. Unknown names fall back to the default with a warning. Preview them all with <code>unshackle env theme</code>."},{"location":"reference/configuration/misc/#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>Effect of <code>set_terminal_bg</code></p> <p>When on, unshackle appends the theme's background colour to the foreground styles, which makes the full colour palette render correctly on terminals whose default background differs from unshackle's theme. When off, such terminals can render the ASCII-art banner and coloured output incorrectly.</p> <p>Key exposure</p> <p>With <code>debug_keys</code> on, unshackle writes the content keys 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, content key counts, and other metadata are always logged either way.</p>"},{"location":"reference/configuration/misc/#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 set to any non-null value, unshackle exits with an error directing you to configure <code>output_template</code> instead. <code>imdb_api_enabled</code> Removed Ignored. It gated the old <code>imdbapi</code> provider, which the keyless <code>imdb</code> provider replaces. Safe to delete from your config."},{"location":"reference/configuration/network/","title":"Network &amp; proxy","text":""},{"location":"reference/configuration/network/#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 HTTP 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>connect_timeout</code> int <code>10</code> Connect timeout in seconds. <code>read_timeout</code> int <code>30</code> Read timeout in seconds (max gap between response chunks). <code>timeout</code> int (unset) Total request timeout in seconds. <code>allow_redirects</code> bool (unset) Follow redirects automatically (rnet client default when unset). <code>pool_idle_timeout</code> int <code>55</code> Seconds an idle pooled connection is kept (default stays under typical ~60s CDN idle kills). <code>pool_max_idle_per_host</code> int <code>64</code> Max idle connections kept per host. <code>pool_max_size</code> int (unset) Max total connections in the pool. <code>tcp_keepalive</code> int <code>30</code> TCP keepalive time in seconds. <code>tcp_keepalive_interval</code> int (unset) TCP keepalive probe interval in seconds. <code>tcp_keepalive_retries</code> int (unset) TCP keepalive probe retry count. <code>tcp_nodelay</code> bool (unset) Disable Nagle's algorithm. <pre><code>network:\n browser: Firefox135\n http2_only: true\n</code></pre> <p>Measured effect of <code>http1_only</code></p> <p>Both <code>http1_only</code> and <code>http2_only</code> are unset by default. In benchmarks, forcing HTTP/1.1 gained 30 to 50% on hosts that throttle per-connection or stall behind HTTP/2 flow control, and cost up to 27% on fast CDNs.</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/network/#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 HTTP session unshackle makes.</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>Compatibility headers such as <code>Accept-Encoding</code> are set by the rnet HTTP backend as part of its browser-impersonation profile. If you override them, you break the impersonation fingerprint. This block is for cross-service defaults only (for example <code>Accept-Language</code>, <code>User-Agent</code>). Per-service headers belong in that service's own config.</p>"},{"location":"reference/configuration/network/#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 proxy provider, and unshackle passes its block straight to that provider's constructor. See Proxies &amp; VPN for the full proxy provider guide. Recognised proxy 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> service credentials (48 chars combined) <code>https://...:89</code> Surfshark <code>surfsharkvpn</code> service credentials (48 chars combined) <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;service username&gt;\n password: &lt;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/output/","title":"Output &amp; naming","text":"<p>Keys that control the output filename, the per-title subfolder, release-group tagging, and filename character handling. For template cookbook material and worked naming examples, see the Output &amp; naming guide.</p>"},{"location":"reference/configuration/output/#output_template","title":"<code>output_template</code>","text":"<ul> <li>Type: <code>dict</code> \u00a0\u00b7\u00a0 Required (no usable default; <code>dl</code> exits with an error if this is missing)</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 unshackle pops it 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>part</code>, <code>absolute</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>dubbed</code>, <code>video</code>, <code>hdr</code>, <code>hfr</code>, <code>edition</code>, <code>repack</code>, <code>lang_tag</code>, <code>title_type</code>.</p> <p><code>{part?}</code> is already inside <code>{season_episode}</code></p> <p><code>part</code> holds the bare part index of a split episode (<code>2</code>) and is empty on every other title. unshackle folds it into <code>{episode}</code> and <code>{season_episode}</code>, so the shipped <code>series</code> template names split episodes correctly with no edit. Putting <code>{part?}</code> next to either of them renders the part twice (<code>S01E01.Part.2.2</code>). Use the standalone variable only in a template that names neither <code>{episode}</code> nor <code>{season_episode}</code>, and note that it is always empty in a folder template, since folders do not carry the part.</p> <p><code>{absolute}</code> counts episodes across seasons</p> <p><code>absolute</code> holds the absolute episode number, zero-padded to 3 digits (<code>007</code>), and is empty on titles that have none. You add it to the name yourself, and it never replaces <code>{season}</code> or <code>{episode}</code>. Any series with a TVDB absolute order can use it, anime most often. Services can supply it, and <code>--enrich</code> fills it in from TVDB. Use <code>{absolute?}</code> so the name stays clean when it is unknown.</p>"},{"location":"reference/configuration/output/#tagging-naming-keys","title":"Tagging &amp; naming keys","text":"Key Type Default Description <code>tag</code> str <code>\"\"</code> Release-group tag. Fills the <code>{tag}</code> template variable and is written into MKV/audio 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 template for chapter names, 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/output/#tag_rules","title":"<code>tag_rules</code>","text":"<ul> <li>Type: <code>list</code> \u00a0\u00b7\u00a0 Default: <code>[]</code></li> </ul> <p>Conditionally replaces <code>tag</code> for a given download. Each rule pairs a <code>when</code> dict of conditions with the <code>tag</code> to use when they hold. unshackle evaluates the rules in order and the first match wins. If no rule matches, the global <code>tag</code> stays.</p> unshackle.yaml<pre><code>tag_rules:\n - when: { title_type: movie, lang_tag: SUBBED }\n tag: SUBMOVIES\n - when: { quality: 2160p, hdr: [DV, DV.HDR, DV.HDR10P, HDR, HDR10P] }\n tag: UHDGROUP\n</code></pre> <p>Rule semantics:</p> <ul> <li>Every condition in <code>when</code> must hold (they are AND-ed).</li> <li>A value can be a scalar or a list. A list matches if any entry matches.</li> <li>Comparison is case-insensitive string equality.</li> <li>The keys of <code>when</code> are the filename template variables for the release itself: <code>title_type</code>, <code>quality</code>, <code>resolution</code>, <code>source</code>, <code>video</code>, <code>hdr</code>, <code>hfr</code>, <code>audio</code>, <code>audio_channels</code>, <code>audio_full</code>, <code>atmos</code>, <code>dual</code>, <code>multi</code>, <code>dubbed</code>, <code>edition</code>, <code>repack</code>, and <code>lang_tag</code>. Only these are available. unshackle adds the title's own fields (<code>title</code>, <code>year</code>, <code>season</code>, <code>episode</code>, and so on) after it evaluates the rules, so a condition cannot use them.</li> <li>An unknown key in <code>when</code> is a mistake: unshackle logs a warning that names the key and skips that rule. unshackle also warns about a rule without conditions or without a <code>tag</code>, and skips it.</li> </ul> <p>Put the more specific rules first, because unshackle stops at the first match.</p> <p>Match <code>hdr</code> on the exact value</p> <p>Matching is exact, and <code>hdr</code> is a composite label for Dolby Vision titles: a DV title with an HDR10 base layer gives <code>DV.HDR</code>, and with an HDR10+ base layer <code>DV.HDR10P</code>. Plain <code>DV</code> does not match those. Name every variant you want, as the example above does. Note also that HDR10 gives <code>HDR</code>, not <code>HDR10</code>. The full set of values is <code>HDR</code>, <code>HDR10P</code>, <code>DV</code>, <code>DV.HDR</code>, <code>DV.HDR10P</code>, and <code>HLG</code>, as listed in the variable table.</p>"},{"location":"reference/configuration/output/#operators","title":"Operators","text":"<p>A condition value can start with a comparison operator, which unshackle applies to the rest of the value:</p> unshackle.yaml<pre><code>tag_rules:\n - when: { resolution: \"&lt;1080\" }\n tag: SDGROUP\n - when: { quality: \"&gt;=2160\" }\n tag: UHDGROUP\n - when: { video: \"!=H.265\" }\n tag: AVCGROUP\n</code></pre> <ul> <li><code>&gt;</code>, <code>&lt;</code>, <code>&gt;=</code>, <code>&lt;=</code> compare numbers. unshackle reads the first number out of the actual value, so <code>\"&gt;=2160\"</code> matches a quality of <code>2160p</code>. If the actual value has no number, the condition fails.</li> <li><code>=</code>, <code>==</code>, and <code>!=</code> compare text, case-insensitively, when the operand is not a number. With a numeric operand they compare numbers like the operators above. A value with no number in it is never equal to a number, so <code>\"!=2160\"</code> holds for it and <code>\"==2160\"</code> does not.</li> <li>An ordering operator with a text operand (for example <code>\"&gt;DV\"</code>) is a mistake: unshackle logs a warning and the condition fails. So does an operator with nothing after it (<code>\"&gt;=\"</code>).</li> <li>A value with no operator keeps the plain equality behaviour described above.</li> </ul> <p>Quote operator values in YAML</p> <p>Two of these operators break an unquoted YAML value, and both stop the config from loading:</p> <ul> <li><code>&gt;</code> opens a folded block scalar, so <code>quality: &gt;=2160</code> fails with a \"while scanning a block scalar\" error.</li> <li><code>!</code> starts a tag, so <code>hdr: !=DV</code> fails with a \"could not determine a constructor\" error.</li> </ul> <p>Quote every operator value: <code>quality: \"&gt;=2160\"</code>, <code>resolution: \"&lt;1080\"</code>, <code>video: \"!=H.265\"</code>.</p> <p>Keep a negation out of lists</p> <p>A list matches if any entry matches, so two or more <code>!=</code> entries in one list are always true. Give a negation as a single value, not as a list entry.</p> <p><code>title_type</code> is the media kind of the title: <code>movie</code>, <code>series</code>, or <code>music</code>. It is useful to give each kind its own group:</p> <pre><code>tag_rules:\n - when: { title_type: movie }\n tag: MOVIEGRP\n - when: { title_type: series }\n tag: TVGRP\n</code></pre> <p>The resolved tag applies to the <code>{tag}</code> filename variable only. The <code>Group</code> metadata tag written into MKV and music files always uses <code>tag</code>.</p> <p><code>--tag</code> wins</p> <p>An explicit <code>dl --tag</code> on the command line disables the rules completely and uses the given tag.</p>"},{"location":"reference/configuration/post-scripts/","title":"Post-download scripts","text":"<p>Operate your own script when a download finishes, with unshackle's metadata passed in as <code>{variable}</code> placeholders. Use it to hand a finished file to an uploader, send a notification, or start a library scan.</p>"},{"location":"reference/configuration/post-scripts/#post_scripts","title":"<code>post_scripts</code>","text":"<ul> <li>Type: <code>list[dict]</code> \u00a0\u00b7\u00a0 Default: <code>[]</code> (unshackle operates no scripts)</li> </ul> unshackle.yaml<pre><code>post_scripts:\n - command: \"python /opt/upload.py {filepath} --service={service} --season={season} --episode={episode} --tmdb={tmdb} --subs={sidecars}\"\n event: success # success | failure\n mode: file # file | season | run\n - command: \"python /opt/notify.py --title={title} --episode={episode}\"\n</code></pre> <p>Every entry that matches the event and mode runs, so one download can feed an uploader and a notifier without a wrapper script. You can also write an entry as a plain string, which is the same as <code>{command: \"...\", event: success, mode: file}</code>.</p> Key Default Meaning <code>command</code> required The command to run, with <code>{variable}</code> placeholders <code>event</code> <code>success</code> <code>success</code> when a file was written, <code>failure</code> when the download failed <code>mode</code> <code>file</code> <code>file</code>, <code>season</code>, or <code>run</code>. See Modes <p>unshackle skips an entry whose <code>event</code> or <code>mode</code> is not one of the listed values, and logs a warning that names the bad value, once per command. unshackle also skips an entry whose <code>command</code> it cannot split into arguments, such as one with an unbalanced quote, and logs a warning. Neither stops the download or the other entries.</p>"},{"location":"reference/configuration/post-scripts/#how-the-command-runs","title":"How the command runs","text":"<p>unshackle splits the command into arguments first, and then substitutes the variables into those arguments. The process runs without a shell.</p> <p>This is what keeps a title like <code>Bob\"; rm -rf ~</code> harmless: a value can never turn into an extra argument or a shell operator, and you never have to think about quoting. It also means a path containing spaces always arrives as a single argument on every OS.</p> <p>Prefix your variables</p> <p>Titles, episode names and IDs come from the streaming service, not from you. Tokenizing first stops a value becoming a new argument, but a value on its own can still be a whole argument. A bare <code>{title}</code> whose value is <code>--upload-file=/etc/passwd</code> would arrive as an option to your script, not as text. Write <code>--title={title}</code>, not a bare <code>{title}</code>, so a service can never forge a flag. unshackle refuses to operate a command when a substituted value would become an option-like token (one that starts with <code>-</code>), and logs a warning instead.</p> <p>No shell features, and name your interpreter</p> <p>Pipes, <code>&amp;&amp;</code>, <code>&gt;</code> redirection, <code>~</code> and globs do not work, because unshackle uses no shell. If you want them, make the shell explicit: <code>bash -c \"...\"</code>.</p> <p>For the same reason there is no interpreter lookup. Write <code>python /opt/upload.py</code> rather than <code>/opt/upload.py</code>. unshackle will not guess whether you meant the system Python or the one in its own virtual environment.</p> <p>On Windows, when a fixed part of an argument contains a space, quote the whole argument (<code>\"--out=C:\\My Dir\\{filename}\"</code>), not only the value. Substituted values never need quoting on any OS.</p> <p>On Windows, do not target a <code>.bat</code> or <code>.cmd</code> file directly. Windows runs batch files through <code>cmd.exe</code>, whose argument quoting differs from every other program and has a history of letting a crafted value break out (CVE-2024-3566). Call the interpreter and pass the script as an argument (<code>python upload.py</code>, <code>pwsh -File upload.ps1</code>) instead.</p> <p>Scripts are fire and forget. unshackle starts the process, writes the command to the debug log, and carries on. It does not wait for the script, capture its output, time it out, or change its own exit code when a script fails. A script keeps running if unshackle exits first, and Ctrl+C during a season pack does not kill the scripts already started.</p> <p>One process per file</p> <p>In <code>file</code> mode a large season pack starts one process per episode with nothing throttling them. If your script is heavy, queue the work inside it or use <code>mode: season</code>.</p>"},{"location":"reference/configuration/post-scripts/#variables","title":"Variables","text":"<p>Metadata comes from the same naming context that produced the file's name, built per output file. So <code>{quality}</code> and <code>{hdr}</code> always give the values for the file unshackle passes in. Downloading <code>-q 1080,2160 -r HDR10,SDR</code> produces four files, each with its own invocation and its own values.</p> Variable Value <code>{filepath}</code> Absolute path of the output file <code>{filename}</code> Its filename, with extension <code>{folder}</code> Absolute path of its parent folder <code>{ext}</code> Its extension, including the dot <code>{sidecars}</code> Sidecar subtitle files written for this output, newline separated <code>{title}</code> Show, movie or track name, sanitized <code>{title_raw}</code> Exactly what the service returned, untouched <code>{title_id}</code> The service's ID for the title <code>{service}</code> Service tag <code>{year}</code> <code>{season}</code> <code>{episode}</code> <code>{episode_name}</code> Season and episode are plain numbers (<code>1</code>, <code>5</code>) <code>{quality}</code> <code>{resolution}</code> <code>{hdr}</code> <code>{hfr}</code> <code>{vcodec}</code> <code>{acodec}</code> <code>{edition}</code> <code>{tag}</code> <code>{lang_tag}</code> As in the filename template, for this file <code>{tmdb}</code> <code>{imdb}</code> <code>{tvdb}</code> The tagging IDs in use, otherwise empty. See Tagging IDs <code>{error}</code> Failure message. Empty on success <p>Every variable from your <code>output_template</code> is available here as well, including <code>{video}</code> and <code>{audio}</code>, of which <code>{vcodec}</code> and <code>{acodec}</code> are aliases.</p> <p>Empty variables become an empty string</p> <p><code>--tmdb={tmdb}</code> with no ID resolved hands your script <code>--tmdb=</code>, so treat an empty string as absent. Write your script to accept an empty value for every variable.</p> <p>Empty is common, and not only when data is missing:</p> <ul> <li>No metadata provider found an ID. <code>{tmdb}</code> is empty when no metadata provider found the title, the matching API key is missing, or the title is a movie you gave no ID for.</li> <li>The title has no such field. Movies have no <code>{season}</code> or <code>{episode}</code>, and music has neither.</li> <li>The naming context renders it empty on purpose. <code>{hdr}</code> is empty for an SDR file, because SDR is the absence of an HDR tag in a filename rather than a tag that reads <code>SDR</code>. <code>{edition}</code>, <code>{atmos}</code>, <code>{multi}</code>, <code>{dual}</code> and <code>{hfr}</code> behave the same way. If your script needs the word <code>SDR</code>, derive it from an empty <code>{hdr}</code> yourself.</li> <li>The hook is a <code>failure</code> hook. A failed download has no output file to read metadata from, so everything that comes from the naming context is empty. See Events.</li> </ul> <p>There is no <code>{variable?}</code> conditional here, unlike <code>output_template</code>. The token is always passed, so the argument list your script receives keeps the same shape on every run and your argument parser does not have to cope with a flag appearing and disappearing.</p> <p>Season and episode are the plain numbers, not the <code>S01E05</code> form used in filenames. The padding and the separator belong to the filename template rather than to the data.</p>"},{"location":"reference/configuration/post-scripts/#music-variables","title":"Music variables","text":"<p>A music download builds its variables from the music naming context, so a hook gets the release fields instead of the season and episode ones. <code>{season}</code>, <code>{episode}</code> and <code>{episode_name}</code> are always empty for music.</p> Variable Value <code>{artist}</code> Track artist <code>{album_artist}</code> Album artist, falling back to the track artist <code>{album}</code> Album name <code>{track_number}</code> <code>{disc}</code> Zero padded. <code>{disc}</code> is empty on a single-disc release <code>{track_total}</code> <code>{disc_total}</code> Zero padded totals, empty when the service did not give them <code>{isrc}</code> <code>{upc}</code> <code>{label}</code> <code>{genre}</code> As the service reported them, empty when absent <code>{release_type}</code> <code>album</code>, <code>single</code>, <code>ep</code>, and so on. A service that reports nothing gives <code>album</code> <code>{explicit}</code> The word <code>Explicit</code> when the track is flagged, otherwise empty <p>In a <code>file</code> hook <code>{title}</code> is the track name. See Modes for what an album hook puts in <code>{title}</code>.</p> <p><code>{year}</code> is empty when the service gives the release no year. <code>{ext}</code> is the container the track arrived in, such as <code>.flac</code>, because a music download is not muxed.</p>"},{"location":"reference/configuration/post-scripts/#tagging-ids","title":"Tagging IDs","text":"<p><code>{tmdb}</code>, <code>{imdb}</code> and <code>{tvdb}</code> carry the IDs unshackle tags the file with. unshackle reads them at the moment it sends the hook, and not at the start of the run. The title search inside the download loop finds an episode's TMDB ID, so a hook fires with it already filled in.</p> <p>They hold an ID you passed with <code>--tmdb</code>, <code>--imdb</code> or <code>--tvdb</code>, plus a TMDB ID the episode search resolved. No such search runs for a movie, so a movie hook gets them empty unless you passed one.</p>"},{"location":"reference/configuration/post-scripts/#sidecar-files","title":"Sidecar files","text":"<p><code>{sidecars}</code> holds the sidecar subtitle files written beside the output, which are the only extra files a download leaves next to it. unshackle muxes attachments such as fonts into the container and deletes temporary artwork, so neither appears. Expect <code>{sidecars}</code> to be empty unless <code>subtitle.output_mode</code> is <code>sidecar</code> or <code>both</code>, which is not the default. A music download writes no sidecars at all.</p> <p>Paths are absolute and separated by a newline, because a newline is the only character that cannot appear in a filename on any supported OS. The whole list arrives as a single argument, so your template needs no quoting.</p> <p>When one download writes several outputs (<code>-q 1080,720</code>), each output's folder gets its own copy of the sidecar files, and each invocation lists the copies sitting beside its own <code>{filepath}</code>.</p> Reading {sidecars} in Python<pre><code>subs = [p for p in sys.argv[i].removeprefix(\"--subs=\").split(\"\\n\") if p]\n</code></pre>"},{"location":"reference/configuration/post-scripts/#modes","title":"Modes","text":"<code>mode</code> Runs <code>{filepath}</code> <code>{sidecars}</code> <code>file</code> Once per output file That file That output's sidecars <code>season</code> Once per season folder, after that season's last queued title Empty Empty <code>run</code> Once per folder written, at the end of the run Empty Empty <p><code>season</code> means everything this run asked for</p> <p>A <code>season</code> hook fires when the last title this run queued for that season finishes. With <code>-w S01-S02</code> the S01 hook runs while S02 is still downloading. It says nothing about whether the season is complete on disk. Downloading a single episode fires the hook for that season as soon as the episode lands.</p> <p>A title that fails stops the whole run. unshackle dispatches the <code>failure</code> hook for that title and then returns. It downloads no further title, and no <code>season</code> or <code>run</code> hook fires after that point. This applies to every title type. If one episode of S01 fails, the S01 hook does not fire at all.</p> <p>unshackle attaches the hook to the folder, not to the season, so one season landing in several folders (<code>-q 1080,720</code> with a quality-dependent folder template) fires it once per folder, each with its own <code>{folder}</code>. A movie is a group of its own: a <code>season</code> hook fires for a movie's folder as soon as the movie finishes.</p> <p>In <code>run</code> mode every variable except <code>{folder}</code> is empty, because one run can cover several shows. Only <code>{folder}</code> is meaningful, which makes it useful for starting a library scan once.</p>"},{"location":"reference/configuration/post-scripts/#music","title":"Music","text":"<p>Music uses the same three modes, with the album standing in for the season.</p> <code>mode</code> Runs <code>file</code> Once per track, after its metadata has been written <code>season</code> Once per album folder, after every queued track of that album has landed <code>run</code> Once per folder written, at the end of the run <p>In a <code>file</code> hook <code>{title}</code> and <code>{title_raw}</code> are the track name. In an album hook they are the album name, and the per-track variables <code>{track_number}</code>, <code>{disc}</code> and <code>{isrc}</code> are empty, in the same way that <code>{episode}</code> is empty in a season hook.</p> <p>An album hook obeys the same rule as a season hook. It fires when the last track this run queued for that album lands. This does not mean that the album is complete on disk. A one-track download fires the album hook as soon as that track lands. If a track fails, the run stops there, so the album hook never fires, in the same way as an episode and its season.</p>"},{"location":"reference/configuration/post-scripts/#events","title":"Events","text":"<p><code>success</code> runs after the file has moved to its final path. <code>failure</code> runs when the download fails, with <code>{filepath}</code> empty and <code>{error}</code> set. Each track of an album is its own title. A music <code>failure</code> hook therefore describes the track that failed, not the release.</p> <p><code>failure</code> only fires in <code>file</code> mode</p> <p>A <code>failure</code> entry with <code>mode: season</code> or <code>mode: run</code> never runs. Leave <code>mode</code> at its default on a failure entry.</p> <p>A <code>failure</code> hook has no output file to read metadata from, so it carries only what the title object already knew: <code>{title}</code>, <code>{title_raw}</code>, <code>{title_id}</code>, <code>{year}</code>, <code>{season}</code>, <code>{episode}</code>, <code>{episode_name}</code>, <code>{service}</code>, the tagging IDs and <code>{error}</code>. Everything that comes from the naming context, such as <code>{quality}</code>, <code>{hdr}</code>, <code>{artist}</code> and <code>{album}</code>, is empty.</p> <p>A resumed <code>--continue-downloads</code> download that finishes runs <code>success</code> as usual. Because unshackle does not wait for your script, it never sees its exit code, so a failing script is not reported anywhere. Your script owns its own error handling and logging.</p> <p>A <code>success</code> hook always names a file this run wrote. There is no skip-if-exists path in <code>dl</code> today, so nothing fires for a title that was not downloaded.</p>"},{"location":"reference/configuration/post-scripts/#-postscript","title":"<code>--postscript</code>","text":"<p><code>dl</code> accepts <code>--postscript \"&lt;command&gt;\"</code>, repeatable. Every command given this way runs with <code>event: success</code> and <code>mode: file</code>.</p> <pre><code>$ unshackle dl --postscript \"python /opt/upload.py {filepath}\" SERVICE TITLE_ID\n</code></pre> <p>It replaces the <code>post_scripts</code> config for that run rather than adding to it, so no configured entry runs while it is in use. That includes your <code>season</code>, <code>run</code> and <code>failure</code> entries, which have no <code>--postscript</code> equivalent.</p>"},{"location":"reference/configuration/post-scripts/#the-rest-api","title":"The REST API","text":"<p>The API never accepts a post-script command. <code>postscript</code>, <code>post_script</code> and <code>post_scripts</code> in a <code>POST /api/download</code> body get <code>400 INVALID_PARAMETERS</code>. A command that arrives from an HTTP caller would be remote code execution.</p> <p>unshackle does operate the scripts defined in <code>unshackle.yaml</code> for API jobs, music jobs included. Only the command itself may not cross the network.</p>"},{"location":"reference/configuration/post-scripts/#logging","title":"Logging","text":"<p>unshackle logs the command it operated twice: at <code>DEBUG</code> level on the console, and as a <code>post_script_dispatch</code> entry in the structured JSON debug log when that log is on.</p> <p>unshackle masks both the same way, and honours <code>redact_paths</code>, which is on by default. Debug logs get shared in issue reports, and a hook command line is mostly paths. URL credentials and <code>token=</code> / <code>api_key=</code> query parameters are also masked.</p> <p>Do not hardcode secrets in the command</p> <p>unshackle cannot recognise an arbitrary secret in the command line, such as <code>-H \"Authorization: Bearer &lt;key&gt;\"</code>, and logs it verbatim. Read the secret from a file or an environment variable inside your script rather than putting it in the <code>command</code>.</p>"},{"location":"reference/configuration/post-scripts/#limitations","title":"Limitations","text":"<ul> <li>No <code>success</code> hook operates under <code>--no-mux</code> or <code>--skip-dl</code>, because neither writes a muxed output. A <code>failure</code> hook still runs under <code>--no-mux</code> if the download itself fails.</li> <li><code>failure</code> hooks only operate in <code>file</code> mode.</li> <li>There is no webhook sender. Call <code>curl</code> from a script instead.</li> <li>Script output is not captured. Redirect it inside your own script if you want a log.</li> </ul>"},{"location":"reference/configuration/services/","title":"Services &amp; authentication","text":""},{"location":"reference/configuration/services/#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>: remaps the region query you passed to <code>-p/--proxy</code> for this service. A config key is that query, or <code>\"provider:query\"</code> when the flag also named a proxy provider. The value is the query asked of the proxy provider instead. It has no effect when you give <code>-p</code> a full proxy URL.</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> <li><code>dl</code>: per-service download defaults, using the same keys as the global <code>dl</code> block.</li> </ul> <p>Individual services may read any additional keys they define. unshackle hands the merged result (the service's own <code>config.yaml</code> with this block layered on top) to the service as <code>self.config</code>.</p> <p>User- or device-specific values (API keys, account IDs, device attributes) belong in this block rather than in the service's own <code>config.yaml</code>, which holds shared defaults. See creating a service.</p> <pre><code>services:\n EXAMPLE1:\n proxy_map:\n us: us-nyc\n \"nordvpn:ca\": ca-toronto\n title_map:\n \"My Show: The Movie\": \"My Show Presents The Movie\"\n</code></pre>"},{"location":"reference/configuration/services/#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, the same data as a <code>[username, password]</code> (or <code>[username, password, extra]</code>) list, or a dict of profile name to either of those. With the dict form, <code>-p/--profile</code> selects the entry, and unshackle uses the <code>default</code> config key when you give no profile, or when the named profile is missing. unshackle parses these into <code>Credential</code> objects. It also uses the credential's SHA-1 as an account hash for cache keys.</p> <pre><code>credentials:\n EXAMPLE2: user@example.com:hunter2\n EXAMPLE1:\n default: primary@example.com:pw1\n second: secondary@example.com:pw2\n</code></pre> <p>Cookies vs credentials</p> <p>unshackle stores cookies as files under <code>directories.cookies</code>, not in this config key. A service's <code>authenticate()</code> accepts cookies, credentials, or both.</p>"},{"location":"reference/configuration/services/#firefox_cookies","title":"<code>firefox_cookies</code>","text":"<ul> <li>Type: <code>dict</code> keyed by service tag \u00a0\u00b7\u00a0 Default: <code>{}</code></li> </ul> <p>Settings for extracting cookies directly from a local Firefox profile. A service block must give <code>hosts</code>, a list of cookie hostnames. unshackle ignores an entry shorter than 3 characters, to prevent a broad match dumping most of the profile. With an optional <code>local_storage</code> boolean, unshackle also pulls matching entries from <code>webappsstore.sqlite</code>, which only services that keep auth tokens in localStorage rather than in HTTP cookies need. 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, so the copy holds the writes Firefox has not yet flushed to the main DB. Extraction fails only if Firefox holds an exclusive write lock at the instant of the copy. The live profile is not modified.</p> <p>Extraction falls back 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>), with no error reported.</p>"},{"location":"reference/configuration/services/#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 is named by you (pick it with <code>--server</code>, or do not write that flag when you configure only one) and gives the server's <code>url</code> (required), an optional <code>api_key</code>, an optional <code>auth_headers</code> list, an optional <code>server_cdm</code> boolean, and an optional <code>services</code> sub-dict of per-service local overrides such as <code>title_map</code>.</p> <p><code>auth_headers</code> lists extra header names to send the API key in, tried before the defaults <code>X-Secret-Key</code> and <code>X-Api-Key</code>, which are always appended as fallbacks. unshackle sends the first name. If the server answers <code>401</code>, it retries the same request with the next name, and keeps the one that works for the rest of the HTTP session. Names you give keep your spelling and are not repeated in the fallbacks, so unshackle tries <code>auth_headers: [\"Authorization\", \"x-secret-key\"]</code> as <code>Authorization</code>, <code>x-secret-key</code>, <code>X-Api-Key</code>.</p> <p>In <code>--remote</code> mode unshackle turns the server's service list into synthetic CLI commands that operate against it, falling back to the tags in that <code>services</code> sub-dict when unshackle cannot fetch the list. Each synthetic command carries the server-side service's options and documentation, so <code>unshackle dl --remote &lt;TAG&gt; -h</code> shows the same help text as it does on the server. See remote sessions for the full setup.</p>"},{"location":"reference/configuration/services/#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. Required unless the server is started with <code>--no-key</code>. <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> Expose only the remote service session endpoints (health, services, search, session) and disable the rest of the REST API. <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>global_speed_limit</code> str (unlimited) Server-wide download speed cap, e.g. <code>10M</code>, <code>1.5G</code> or plain bytes/sec (same format as <code>speed_limit</code>). One shared budget across all concurrent jobs; per-job speed limits are ignored while it is set. <code>cdm_overrides</code> list or bool (unset) Allowed per-request CDM overrides: a list of permitted device names, or <code>true</code> for any. Unset rejects every override. <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>. <p>Each entry under <code>users</code> uses that user's API key as its name, and can set its own <code>services</code>, <code>devices</code>, and <code>playready_devices</code> allowlists, narrowing the global ones, plus an optional <code>username</code> used as the log label for that API key (defaults to a truncated form of the API key). A user with no <code>playready_devices</code> config key gets no PlayReady access at all, not the global list.</p> <p><code>server_cdm</code> decides whether the server runs the CDM licensing for that API key. It is <code>false</code> unless the entry sets it, so a remote client configured with <code>server_cdm: true</code> is told to license with its own local CDM instead, and a client that asks anyway gets a <code>FORBIDDEN</code> error. Because a download job always licenses with the server's CDM, an API key without <code>server_cdm</code> also cannot submit or retry <code>/api/download</code> jobs. Keys that have no <code>users</code> entry, such as <code>api_secret</code>, keep server CDM access.</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 e5f6a7b8:\n server_cdm: true # this key may have the server do the licensing\n</code></pre> <p><code>dl</code> keys inside <code>serve</code></p> <p>Most <code>dl</code> flag keys (<code>downloads</code>, <code>workers</code>, <code>best_available</code>, and so on) can be set directly inside <code>serve</code>, where they apply to every request the server handles. The server recognises a fixed subset of download parameters, so a few CLI-only flags are ignored here.</p>"},{"location":"reference/configuration/vaults/","title":"Key vaults","text":"<p>The full guide is at Vaults. Two keys configure them.</p>"},{"location":"reference/configuration/vaults/#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 the content keys instead of licensing them again. 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> Optional <code>headers</code> map is sent with every request. 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>, and <code>username</code> in query mode <code>api_mode</code>: <code>query</code> (default), <code>json</code>, <code>decrypt_labs</code>. Honours <code>vault_timeout</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>Per-entry options</p> <ul> <li><code>no_push: true</code> makes a vault read-only (unshackle fetches content keys from it but never writes 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. Vault <code>type</code> values are case-sensitive module names.</li> <li>unshackle treats an all-zero content key (32 zeros) as \"no key\" everywhere and never stores it.</li> </ul>"},{"location":"reference/configuration/vaults/#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>"}]}