Files
unshackle/search/search_index.json
T
2026-10-27 19:07:11 +00:00

1 line
943 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, DTS-X, ALAC, FLAC, MP3; 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 Control D, 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":"<p>A git clone with the install script is the recommended way to install unshackle.</p> Linux (recommended)Windows (recommended)Advanced: uv tool <pre><code>git clone https://github.com/unshackle-dl/unshackle.git\ncd unshackle\nsh install.sh\nuv run unshackle env check\n</code></pre> <pre><code>git clone https://github.com/unshackle-dl/unshackle.git\ncd unshackle\n.\\install.bat\nuv run unshackle env check\n</code></pre> <pre><code>uv tool install git+https://github.com/unshackle-dl/unshackle.git\nunshackle setup\n</code></pre> <p>This installs unshackle into the tool folder of <code>uv</code>, not a folder that you choose. <code>unshackle setup</code> then puts the tools, config, and data in your user data and config directories.</p> <p>The install script installs <code>uv</code> and unshackle, then runs <code>unshackle setup</code>. In a clone, run every command as <code>uv run unshackle ...</code>. The examples on this site use the bare <code>unshackle</code> command.</p> <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. <code>unshackle setup</code> downloads them when a portable build exists for your system. 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>). Case does not matter. Default <code>()</code>. <code>GEOFENCE</code> <code>tuple[str, ...]</code> IP region codes the service requires. Empty = no geofence. unshackle treats the first entry as the main region for auto-proxy. <code>GEOBLOCK</code> <code>tuple[str, ...]</code> IP region codes where the service refuses to work. Every other region is allowed. Default <code>()</code>. <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>ANONYMOUS_SEARCH</code> <code>bool</code> Set <code>True</code> when <code>search()</code> needs no login and no state from <code>authenticate()</code>. A search then skips the cookie load, <code>authenticate()</code> and the cookie save. Default <code>False</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 unshackle names episodes 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> <p><code>GEOBLOCK</code> is the negative form: the service works everywhere except the listed regions. With no <code>GEOFENCE</code> to name a main region, a <code>GEOBLOCK</code> hit stops the run with a \"not available in your region\" error; pass <code>--proxy</code> yourself.</p> <pre><code>class EXAMPLE(Service):\n ALIASES = (\"EX\", \"DOMAIN\")\n GEOFENCE = (\"US\", \"UK\")\n VAULT_TAG = \"DIFFERENT_NAME\"\n\n\nclass WORLDWIDE(Service):\n GEOBLOCK = (\"GB\",)\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> A dict: this service's <code>config.yaml</code>, with the user's <code>services.&lt;TAG&gt;</code> block from <code>unshackle.yaml</code> merged over it. Without a <code>config.yaml</code>, it holds only the user's block. See Services &amp; authentication for the override keys. <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). Send every request through it: with a proxy active, a request from service code that does not go through the proxy logs a warning. A separate HTTP session that goes direct on purpose sets <code>proxy_exempt = True</code>. <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 generate_dv: bool = False # --generate-dv: make Dolby Vision from HDR10+\n</code></pre> <p><code>generate_dv</code> and a hand-made HYBRID</p> <p>A service that fetches the HYBRID variants itself (HDR10 and DV) must also fetch HDR10P when <code>track_request.generate_dv</code> is set and the title has no DV track. The conversion needs an HEVC HDR10+ track as its base. <code>get_tracks_for_variants</code> does this for you.</p> <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 client: a remote-dl session gets it through the attached <code>InputBridge</code>, and a REST download job shows it as <code>input_prompt</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>For a login that the user approves on another device (a pair code, a QR code), use <code>self.wait_for_approval(message, check, timeout)</code>, never a hand-written loop. It shows the message, then calls <code>check</code> at each interval until <code>check</code> returns a value. <code>check</code> returns <code>None</code> while the approval is pending.</p> <pre><code>token = self.wait_for_approval(\n f\"Open {self.config['endpoints']['pair']} and enter code {code}\",\n check=lambda: self.poll_pair_token(code),\n timeout=expires_in,\n)\n</code></pre> <p>It raises <code>TimeoutError</code> after <code>timeout</code> seconds. Under <code>serve</code> mode it also stops when the client deletes the remote session, so the loop does not continue on the server with no client. The message goes out as a log line, so a remote session shows it. A REST download job shows it in its <code>notice</code> field until the wait ends.</p> <p>The wait sees a cancel only between two <code>check</code> calls, so <code>check</code> must return within a few seconds. A <code>check</code> that reads a socket keeps the socket open across calls and returns <code>None</code> after each short idle wait.</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>What the helper merges</p> <p>The helper adds the video, audio and subtitle tracks of every manifest. From a later manifest, it skips a track that has the ID of a held track. It also skips a track whose <code>Tracks.signature</code> matches a held track, because the same track can have a different ID in each manifest. Chapters and attachments come from the first manifest only.</p> <ul> <li><code>signature</code> holds the attributes that the track list and selection read: codec, range, resolution, frame rate, bitrate and name for video; language, codec, channels, JOC, descriptive, bitrate and name for audio; language, codec, flags and name for subtitles.</li> <li>The helper does not remove copies inside one manifest. To remove them, call <code>tracks.dedupe()</code>. Two tracks that differ only in a value outside the signature, such as a dialogue-boost mix, become one track, so remove the track you do not want before you call it.</li> <li>The audio that <code>dl</code> selects can come from a different manifest than the video. Keep licence data on each track (<code>track.data</code>), not in one value per title that the next fetch overwrites.</li> </ul> <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>HDR10+ in tracks labelled HDR10</p> <p>HDR10+ is a bitstream (SEI) feature, and many manifests label an HDR10+ variant as plain HDR10. Before unshackle lists or selects tracks, the <code>hdr10plus_probe</code> reads the first fragment of each HEVC HDR10 track and changes <code>video.range</code> to HDR10+ when the fragment carries HDR10+ metadata. Set <code>video.range</code> yourself only when the probe cannot read the fragment, for example an ISM track whose SEI is encrypted, or when the platform gives a reliable signal of its own. If the playback API has no HDR10+ value, request HDR10 for an HDR10+ request and let the probe relabel the tracks.</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.signatures[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> <p>Set <code>ANONYMOUS_SEARCH</code> only for a search that needs no account</p> <p>With <code>ANONYMOUS_SEARCH = True</code>, <code>search()</code> operates on an HTTP session with no cookies, and <code>authenticate()</code> does not run. Set it only when the search results do not depend on the account, and when <code>search()</code> does its own setup. A <code>search()</code> that reads a token, a header or a region from <code>authenticate()</code> fails or gives results for the wrong region.</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, in any case (resolved by <code>Services.get_tag</code>). <code>GEOFENCE</code> <code>tuple[str, ...]</code> ISO region codes the service requires; empty means no geofence. unshackle treats the first entry as the \"main region\" for automatic proxy selection. <code>GEOBLOCK</code> <code>tuple[str, ...]</code> ISO region codes where the service refuses to work; every other region is allowed. Use it for a service that works worldwide except in its home market. <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>ANONYMOUS_SEARCH</code> <code>bool</code> <code>search()</code> needs no login and no state from <code>authenticate()</code>. A search then skips the cookie load, <code>authenticate()</code> and the cookie save. Default <code>False</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 unshackle names episodes 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. unshackle calls <code>authenticate()</code> first, unless the service sets <code>ANONYMOUS_SEARCH</code>.</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 remote-dl input bridge, the REST download job relay, or the rich console.</li> <li><code>wait_for_approval(message, check, timeout, interval=3.0)</code>: shows a message, then calls <code>check</code> until it returns a value. Use it for a login that the user approves on another device, such as a pair code. A remote-dl session shows the message as a log line, and a REST download job shows it as the job's <code>notice</code>.</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 merged service config (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). Send every request through it: with a proxy active, a request from service code that does not go through the proxy logs a warning. A separate HTTP session that goes direct on purpose sets <code>proxy_exempt = True</code>. <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. A <code>GEOBLOCK</code> hit with no <code>GEOFENCE</code> stops the run with a \"not available in your region\" error, because there is no main region to fetch a proxy for; pass <code>--proxy</code> yourself. A proxy whose exit is in a <code>GEOBLOCK</code> region stops the run the same way. 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>), <code>best_available</code>, and <code>generate_dv</code> (from <code>--generate-dv</code>). Use it in <code>get_tracks</code> to decide which variants to fetch. A service that fetches the HYBRID variants itself must also fetch HDR10P when <code>generate_dv</code> is set and the title has no DV track, because the conversion needs an HEVC HDR10+ base.</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 use 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>, <code>synced_lyrics</code>, <code>lyrics_suffix</code>, and <code>artwork_url</code>. Read the class for the current list. Give <code>lyrics</code> as plain text: the tagger embeds it as is. With <code>synced_lyrics</code> (timed LRC or TTML) and <code>lyrics_suffix</code> (<code>\".lrc\"</code>, <code>\".ttml\"</code>), unshackle also saves the timed lyrics beside the final audio file under that suffix. You can set these fields in <code>get_tracks()</code> too, and a remote client gets them back.</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>, <code>LCEVC</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>DTSX</code>, <code>DTSHD</code>, <code>MPEGH</code>, <code>ALAC</code>, <code>FLAC</code>, and <code>MP3</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>). Always pass a <code>url</code>, even to <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). A track id covers the manifest URL, so a title you build from one ISM manifest per codec or range keeps every variant: <code>Tracks.add</code> no longer reads the second manifest's tracks as duplicates of the first.</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 six 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 <code>BlowfishStripe</code> Blowfish CBC stripe cipher the service gives the per-track key; no CDM, 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/#decrypting-a-cbcs-file-yourself","title":"Decrypting a cbcs file yourself","text":"<p>Some tracks cannot use the framework's decryption: a single cbcs file whose sample entries share a zero default KID, or a sample entry whose content key no CDM can license and only a separate process can use. For these, set no <code>drm</code> on the track and override two methods:</p> <ul> <li><code>decrypts_samples(track)</code> returns <code>True</code> for such a track.</li> <li><code>get_sample_decrypter(track, entry)</code> returns, for the 1-based <code>stsd</code> entry, the 16-byte content key or a <code>cbcs.SampleDecrypter</code>. A <code>SampleDecrypter</code> gets the protected bytes of each sample of one fragment, cut to whole AES blocks, and returns plaintexts of the same lengths. It handles full-sample cbcs only, not pattern encryption.</li> </ul> <p>When the download of the track ends, unshackle calls <code>unshackle.core.drm.cbcs.decrypt_file</code>, and the progress row shows \"Decrypting\". Your <code>on_track_downloaded</code> runs before this and gets the encrypted file. <code>decrypt_file</code> writes the plaintext back in place and removes the protection boxes, so the muxer reads a clear file. In a remote session <code>get_sample_decrypter</code> runs on the server: the client sends the samples through the <code>samples</code> route, so a decrypter that needs a process on the server also works for a remote client.</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 and DASH streams that carry a valid DV RPU but advertise plain HEVC, with DV only in the supplemental codecs (<code>dv_compatible_bitstream</code>). <code>--list</code> shows such a track as <code>HDR10+DV</code> or <code>HDR10P+DV</code>. A service sets <code>hdr10_base</code> on a DV track that has an HDR10 base layer (DV profile 8.1), and <code>--list</code> shows it as <code>DV+HDR10</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> <p>The fixup replaces the track file with a raw HEVC file. A raw HEVC file has no duration and FFmpeg cannot seek in it. When a hybrid base also gets the fixup, the pipeline keeps the container file of that track until its hybrid step is complete, and the hybrid step reads the container file.</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>: a plain dict. unshackle loads the service's own <code>config.yaml</code>, then merges the user's <code>services.&lt;TAG&gt;</code> block from <code>unshackle.yaml</code> over it. Nested keys merge one by one, the user's value wins, and a list in the user's block replaces the whole list. Use it for per-service settings like base URLs, an API key, or a <code>title_map</code>. See Services &amp; authentication for the override keys.</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>--cdm-only</code> off Serve only the Widevine/PlayReady CDM HTTP endpoints, plus <code>/api/health</code> and the dashboard. No REST API, no remote sessions, no Swagger UI. Cannot be combined with <code>--api-only</code> or <code>--remote-only</code>. <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><code>--cdm-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> <p>The server mounts only the pywidevine and pyplayready CDM endpoints. Under <code>/api/</code> it answers <code>/api/health</code> and, when <code>serve.dashboard.key</code> is set, the dashboard. It does not start the remote session store, the service refresh loop or the Swagger UI. Use it for a CDM backend that a proxy reaches on its own hostname.</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. <code>POST</code> <code>/api/download/jobs/{job_id}/input</code> Answer the prompt that a running job waits on."},{"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 and re-import the services that changed."},{"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}/segment_filter</code> Server-side HLS segment filter results for one track. <code>POST</code> <code>/api/session/{session_id}/samples</code> Server-side cbcs sample decryption for one track. <code>POST</code> <code>/api/session/{session_id}/license</code> Proxy or server-side DRM licensing. <code>POST</code> <code>/api/session/{session_id}/keys/bad</code> Report a server-vault content key that did not decrypt. <code>GET</code> <code>/api/session/{session_id}/logs</code> Drain the service's server-side log output. <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>No 'api_secret' in the 'serve' section of 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>Grants decide whether the server returns content keys</p> <p>The devices on an API key decide which CDM the server can use. Two grants in the same user entry decide whether the server returns content keys (<code>KID:KEY</code>) for a remote session. <code>server_cdm</code> lets the server license with those devices. <code>server_vault</code> lets a remote session that the client's own device licenses read the server vault, and the server then makes no live licence. Without either grant, the server can only proxy CDM challenges, so the client must operate its own CDM. See <code>serve</code> for both grants.</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/#rate-limit-rejections","title":"Rate limit rejections","text":"<p>An API key that carries a rate limit gets <code>429 Too Many Requests</code> once it goes over, from the same middleware and in the same shape as the <code>401</code> bodies above, with a <code>Retry-After</code> header in seconds:</p> <pre><code>{\n \"status\": 429,\n \"message\": \"Rate limit exceeded.\"\n}\n</code></pre> <p>A limit comes from <code>serve.tiers.&lt;name&gt;.rate_limit</code> or from the API key's own <code>serve.users.&lt;key&gt;.rate_limit</code>, in requests per hour. An API key with neither has no limit, and <code>GET /api/health</code> is never limited. See dashboard rate limits for the config and the counters, and services configuration for the keys themselves.</p> <p><code>429</code> is not the <code>RATE_LIMITED</code> error body</p> <p><code>RATE_LIMITED</code> in Errors is a service rate limit that a handler raises, and it arrives in the standard envelope with an <code>error_code</code>. The <code>429</code> here comes from the middleware before any handler runs, and has the integer-<code>status</code> shape shown above. A client that reads <code>error_code</code> to classify a <code>429</code> must cope with it being absent.</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>, or <code>429 Too Many Requests</code> for a key over its rate limit Missing-header body <code>{\"status\": 401, \"message\": \"Secret Key is Empty.\"}</code> Invalid-key body <code>{\"status\": 401, \"message\": \"Secret Key is Invalid.\"}</code> Over-limit body <code>{\"status\": 429, \"message\": \"Rate limit exceeded.\"}</code>, plus a <code>Retry-After</code> header Rate limit config <code>serve.tiers.&lt;name&gt;.rate_limit</code>, overridden by <code>serve.users.&lt;key&gt;.rate_limit</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/dashboard/","title":"Developer Dashboard","text":"<p>The dashboard endpoints show the operator of a <code>serve</code> instance what the server is doing: version and uptime, request counts, live remote sessions, download jobs, and the recent log lines. They exist so you can watch a headless server (<code>serve --quiet</code>) from a web page instead of a terminal.</p> <p>The dashboard endpoints are for the person who runs the server, not for API users. They have their own key: a user key or a tier key never opens them.</p>"},{"location":"dev/rest-api/dashboard/#enable","title":"Enable","text":"<p>Set a dashboard key under <code>serve.dashboard</code> in <code>unshackle.yaml</code>:</p> <pre><code>serve:\n api_secret: ...\n dashboard:\n key: a-long-random-string\n</code></pre> <p>Without <code>dashboard.key</code> the server does not register the routes, and they answer <code>404</code>. <code>serve --no-key</code> turns off user authentication only; the dashboard key stays required. Once the dashboard key is set, every <code>/api/dashboard/</code> request must carry it in <code>X-Secret-Key</code>. Every other endpoint refuses the dashboard key, and the dashboard refuses user keys. The routes are available in <code>--remote-only</code> mode too.</p> <p>Run the server headless with <code>--quiet</code>: no banner, no Rich output, one plain log line per event on stderr, and <code>api.*</code> loggers stay at <code>INFO</code> so remote session activity reaches the log ring. Add <code>--debug</code> to raise the level to <code>DEBUG</code> and also write the full log to <code>directories.logs</code> as <code>unshackle_serve_&lt;time&gt;.log</code>. Nothing else the dashboard shows reaches the disk: stats, the log ring and the event stream live in memory and reset on restart, so a dashboard UI that wants history must keep its own copy.</p> <pre><code>unshackle serve --remote-only --quiet\n</code></pre>"},{"location":"dev/rest-api/dashboard/#endpoints","title":"Endpoints","text":"<p>All are <code>GET</code>, except the two <code>drain</code> routes.</p> Path Returns <code>/api/dashboard/status</code> Version, <code>code_hash</code>, bind host and port, <code>mode</code> (<code>full</code>, <code>api_only</code>, <code>remote_only</code>), uptime, <code>requests_total</code>, <code>requests_rejected</code> (401s), <code>requests_by_key</code> (label \u2192 count), <code>errors</code> (error counts by service tag, then by <code>error_code</code>), configured service count (the same services as <code>/api/dashboard/services</code>), session count, <code>max_sessions</code> (<code>null</code> when the operator configured no limit), <code>session_ttl</code>, job counts by status. <code>draining</code> is <code>true</code> while a drain is on. The service count includes services that failed to import - use <code>/api/dashboard/services</code> for the number that loaded. <code>POST /api/dashboard/drain</code> Starts a drain before a restart and returns the <code>/status</code> body. The server then refuses each new remote session, download job and job retry with <code>SERVER_DRAINING</code> (409). Open remote sessions and jobs continue, and each open remote session gets a warning in its service log, which the client shows to the user. Poll <code>/status</code> until <code>sessions</code> and the queued and downloading jobs are 0, then restart. The drain ends when the process stops. A second call changes nothing. <code>DELETE /api/dashboard/drain</code> Cancels the drain and returns the <code>/status</code> body. The server accepts new work again. <code>/api/dashboard/sessions</code> Every live remote session: <code>id</code>, <code>owner</code> (username or masked key), <code>creator_ip</code>, <code>service</code>, <code>title_id</code>, <code>titles</code>, <code>tracks</code>, <code>title</code> (the display name of the title the client is on: the last one it asked tracks for, else the first resolved title), <code>auth_status</code>, <code>auth_error</code>, <code>server_account</code> (the server profile lent to the remote session, else <code>null</code>), <code>server_cdm</code> (<code>false</code> when the client's own device licenses the remote session), <code>server_cdm_max_height</code> (the tallest video the server CDM licenses live, else <code>null</code>), <code>client</code>, <code>actions</code>, <code>created_at</code> and <code>last_accessed</code> (ISO 8601) with <code>created_ts</code> and <code>last_accessed_ts</code> (Unix epoch, the same clock as log <code>ts</code>), <code>age_seconds</code>, <code>idle_seconds</code>, <code>log_seq</code>. <code>client</code> is whatever the remote client sent as <code>client</code> in its session create request. The CLI sends <code>version</code>, <code>code_hash</code> (the commit the client runs, <code>null</code> when its source cannot be read), <code>platform</code> and <code>argv</code>. <code>argv</code> is the command line the user ran: proxy and URL userinfo, secret query parameters and credential values become <code>***</code>, home and install paths shorten as in the logs, and the line is cut at 3000 characters. An older client sends less or nothing and the field is <code>{}</code>. <code>log_seq</code> is the last sequence number in the remote session's service log - poll <code>/api/dashboard/sessions/{id}/logs</code> when it changes. <code>actions</code> is the session's request log, newest last, capped at 500: <code>ts</code>, <code>method</code>, <code>action</code> (<code>titles</code>, <code>tracks</code>, <code>segments</code>, <code>license</code>, <code>prompt</code>, \u2026), <code>query</code>, <code>status</code>, <code>ms</code>, <code>bytes_in</code>, <code>bytes_out</code>. <code>/api/dashboard/jobs</code> Every download job with full detail, regardless of owner. Empty in <code>--remote-only</code> mode. <code>/api/dashboard/logs</code> <code>{\"seq\": N, \"records\": [...]}</code>: the last 1000 log records. <code>?since=&lt;seq&gt;</code> returns only newer records; <code>?level=WARNING</code> sets the minimum level; <code>?logger=serve</code> keeps one logger and its children (<code>aiohttp.access</code> is the noisiest). <code>ts</code> is a Unix epoch in seconds. <code>/api/dashboard/cdm-logs</code> <code>{\"seq\": N, \"records\": [...], \"sessions\": [...]}</code>: the last 5000 calls to the Widevine and PlayReady CDM device routes, and the open sessions of each device. <code>?since=&lt;seq&gt;</code> returns only newer records. See CDM calls. <code>/api/dashboard/sessions/{id}/logs</code> One remote session's service log: <code>{\"session_id\", \"last_seq\", \"records\": [...]}</code>. Each record has <code>seq</code>, <code>ts</code>, <code>level</code>, <code>message</code>. <code>?since=&lt;seq&gt;</code> returns only newer records. 404 when the remote session is unknown. <code>/api/dashboard/keys</code> Every configured API key: what it may do and what it has done. One row per key in <code>serve.users</code>, plus <code>serve.api_secret</code> when it is set. <code>/api/dashboard/services</code> Every service configured on this server and its load state, including the ones that failed to import. See Services for what configured means. <code>/api/dashboard/health</code> Preflight: whether this instance could finish a download. Cached 30 seconds. <code>/api/dashboard/events</code> Server-Sent Events stream. With <code>?since=&lt;seq&gt;</code> it returns <code>{\"seq\", \"stats\", \"events\": [...]}</code> instead: every event after <code>seq</code> (the server keeps the last 20000, log records included, so a poll every few seconds is safe even under a busy access log) as one JSON burst, so a UI that polls every few seconds still sees a remote session that opened and closed in between. <p><code>errors</code> counts every structured error response since the server started, for example <code>{\"EXAMPLE\": {\"SERVICE_ERROR\": 4}, \"-\": {\"SESSION_NOT_FOUND\": 1}}</code>. The service is the one of the remote session, else the <code>service</code> field of the JSON body. <code>-</code> holds an error with no installed service. Each error also logs its <code>ref</code>.</p> <p><code>requests_rejected</code> counts 401 responses; those never appear in <code>requests_by_key</code>. The label is the <code>username</code> from the <code>users</code> entry when one is set, else the first four characters of the API key.</p>"},{"location":"dev/rest-api/dashboard/#event-stream","title":"Event stream","text":"<p><code>/api/dashboard/events</code> sends a <code>stats</code> event (the same body as <code>/status</code>) on connect and then every 5 seconds, so the connection stays alive and the counters stay current. Between those it sends:</p> Event Data <code>log</code> One log record: <code>seq</code>, <code>ts</code>, <code>level</code>, <code>logger</code>, <code>msg</code>. <code>session</code> <code>action</code> (<code>create</code>, <code>update</code> on every request the session makes and when titles or tracks load, or <code>delete</code>) plus the full remote session summary, so each event is a complete snapshot. A <code>delete</code> also carries <code>reason</code>: <code>closed</code> (the client ended it), <code>expired</code> (TTL sweep) or <code>evicted</code> (<code>max_sessions</code> reached). A session opened by <code>--skip-dl</code> can live only a few seconds, so a UI that wants history must keep its own record of these events. <code>job</code> <code>event</code> (<code>queued</code>, <code>progress</code>, <code>status</code>, or the terminal status) plus the full job object. <code>service</code> <code>action</code> (<code>staged</code>, <code>applied</code> or <code>failed</code>) and <code>tags</code>, the services it applies to. A <code>failed</code> action carries <code>errors</code> and an empty <code>tags</code>. Refetch <code>/api/dashboard/services</code> when one arrives, instead of polling for a reload. <p>Every frame carries an <code>id:</code> (the event seq). After a dropped connection an <code>EventSource</code> reconnects with <code>Last-Event-ID</code> and the server replays the events it missed. The connection never closes on its own.</p> <p>A browser <code>EventSource</code> cannot set headers, so this route also accepts the dashboard key as <code>?secret_key=</code>. The dashboard key then appears in proxy and access logs and in browser history, so use the query parameter only for <code>/events</code> and send the header everywhere else.</p> <pre><code>const es = new EventSource(`${server}/api/dashboard/events?secret_key=${key}`);\nes.addEventListener(\"log\", (e) =&gt; console.log(JSON.parse(e.data).msg));\n</code></pre> <p>CORS is open (<code>Access-Control-Allow-Origin: *</code>), so a dashboard page served from another origin works without a proxy.</p>"},{"location":"dev/rest-api/dashboard/#remote-session-logs","title":"Remote session logs","text":"<p>A remote session mirrors the service's own <code>self.log</code> into a 500-record buffer at <code>INFO</code>, whatever level the server prints at. The remote session summary carries only a truncated <code>auth_error</code>; the buffer holds the real reason a login failed.</p> <pre><code>GET /api/dashboard/sessions/{session_id}/logs?since=12\n{\"session_id\": \"...\", \"last_seq\": 14,\n \"records\": [{\"seq\": 13, \"ts\": 1756909254.1, \"level\": \"ERROR\", \"message\": \"login rejected: MFA required\"}]}\n</code></pre> <p>The field name is <code>records</code>, the same one <code>/api/dashboard/logs</code> uses, so one dashboard reads both logs the same way. Each record has the shape the client route <code>/api/session/{id}/logs</code> returns. <code>last_seq</code> is the buffer's own last sequence number, so an empty page still reports the true value.</p> <p>Reading is a cursor read, not a drain: the client draining the same buffer still gets every record. It also does not refresh the remote session's idle timer, so polling a remote session here never keeps it alive or makes it look active.</p> <p><code>log_seq</code> is a poll trigger, not a push</p> <p>A remote session summary reaches the dashboard only when something publishes a <code>session</code> event - a request the remote session makes, or an auth transition. A log line on its own publishes nothing. Poll this route when <code>log_seq</code> changes, and on a timer while a drawer is open.</p>"},{"location":"dev/rest-api/dashboard/#cdm-calls","title":"CDM calls","text":"<p>A server in <code>full</code> mode also mounts the Widevine CDM device routes at <code>/{device}/...</code> and the PlayReady ones at <code>/playready/{device}/...</code>. The server records each call to these routes in a 5000-record buffer of its own, apart from the log records of <code>/api/dashboard/logs</code>.</p> <pre><code>GET /api/dashboard/cdm-logs?since=1230\n{\"seq\": 1231,\n \"records\": [{\"seq\": 1231, \"ts\": 1759750000.123, \"drm\": \"widevine\", \"op\": \"get_license_challenge\",\n \"device\": \"chrome_l3\", \"key_id\": \"ab12cd34ef56\", \"user\": \"tier1\",\n \"session_id\": \"0a1b2c3d4e5f60718293a4b5c6d7e8f9\",\n \"status\": 200, \"ok\": true, \"error\": null, \"ms\": 12.4}],\n \"sessions\": [{\"drm\": \"widevine\", \"device\": \"chrome_l3\", \"key_id\": \"ab12cd34ef56\", \"user\": \"tier1\",\n \"open\": 3, \"max\": 17}]}\n</code></pre> <p><code>since</code> and <code>seq</code> work as they do for <code>/api/dashboard/logs</code>: <code>records</code> holds the calls with a <code>seq</code> above <code>since</code>, oldest first. <code>seq</code> starts again at 1 when the server restarts, so a <code>seq</code> below your cursor means a restart: read again from 0.</p> Field Meaning <code>ts</code> Unix epoch in seconds, when the call arrived. <code>drm</code> <code>widevine</code>, or <code>playready</code> for a route below <code>/playready/</code>. <code>op</code> <code>open</code>, <code>close</code>, <code>set_service_certificate</code>, <code>get_service_certificate</code>, <code>get_license_challenge</code>, <code>parse_license</code> or <code>get_keys</code>. The licence type or content key type that follows in the path is not part of it. <code>device</code> The device name from the path, cut at 255 characters. <code>key_id</code>, <code>user</code> The <code>id</code> and <code>label</code> of the caller's row in <code>/api/dashboard/keys</code>. Both are <code>anonymous</code> when the API key is missing or unknown. <code>session_id</code> The CDM session, lowercase hexadecimal, so the calls of one licence exchange group together. <code>null</code> when there is none, for example a refused <code>open</code>. <code>status</code>, <code>ok</code> The HTTP status of the reply. <code>ok</code> is <code>true</code> below 400. <code>error</code> <code>null</code> when <code>ok</code>. Otherwise the <code>message</code> of the reply, cut at 300 characters. A handler that raised an error gives the error's class name only. <code>ms</code> Time the server took to answer, in milliseconds. <p>A record never holds the API key, <code>init_data</code>, a challenge, a certificate, a licence body or a content key. A refused call is in the log too, a 401 for a missing or unknown API key included.</p> <p><code>sessions</code> is a snapshot at read time, not a history. It has one row for each device an API key has opened since the server started: <code>open</code> is the number of sessions open now, and <code>max</code> is the number of sessions the device permits at one time. A PlayReady session older than the library's session timeout does not count: the library drops it on the next <code>open</code>. The list is <code>[]</code> until the first <code>open</code>, and on a server that mounts no CDM device routes.</p> <p>Polled only</p> <p>The event stream does not carry these records. One licence exchange is five calls, and that volume would push <code>session</code> events out of the stream's history.</p>"},{"location":"dev/rest-api/dashboard/#keys","title":"Keys","text":"<pre><code>GET /api/dashboard/keys\n[{\"id\": \"3ed054be9371\", \"role\": \"user\", \"label\": \"tier1\", \"services\": [\"EXAMPLE\", \"DEMO\"],\n \"server_cdm\": false, \"server_cdm_max_height\": null, \"server_accounts\": false, \"server_proxy\": false,\n \"tier\": \"bot\", \"rate_limit\": 600, \"window_used\": 412,\n \"requests\": 41300, \"rejected\": 4, \"bytes_out\": 103079215104, \"last_seen\": 1756909188.2},\n {\"id\": \"7c1d0f52a884\", \"role\": \"dashboard\", \"label\": \"dash\u2026\", \"services\": [],\n \"server_cdm\": false, \"server_cdm_max_height\": null, \"server_accounts\": false, \"server_proxy\": false,\n \"tier\": null, \"rate_limit\": null, \"window_used\": 0,\n \"requests\": 8140, \"rejected\": 0, \"bytes_out\": 41200311, \"last_seen\": 1756909350.9}]\n</code></pre> <p><code>id</code> is a hash of the API key, so it stays stable across restarts and carries no key material. Two API keys with no <code>username</code> merge into one label in <code>requests_by_key</code> but stay separate here, so use <code>id</code> as the identity and <code>label</code> only for display.</p> Field Meaning <code>role</code> Which key this is: <code>user</code> (a <code>serve.users</code> entry), <code>admin</code> (<code>serve.api_secret</code>) or <code>dashboard</code> (<code>serve.dashboard.key</code>). Identity, not capability - read the grant fields for what the API key may do. <code>services</code> The effective allowlist, the global list intersected with the API key's. <code>null</code> means unrestricted; <code>[]</code> means the API key reaches no service route at all. <code>server_cdm</code>, <code>server_accounts</code> <code>false</code>, <code>true</code>, or the list of service tags the grant covers. <code>server_cdm_max_height</code> The configured limit on live server CDM licences: a height, a map of service tag to height, or <code>null</code> for no limit. <code>server_proxy</code> Boolean. Only a literal <code>true</code> grants it, and an API key with no <code>users</code> entry does not get it. <code>rate_limit</code> Requests per hour, from the API key's own value or its tier's. <code>null</code> means no limit. <code>window_used</code> Requests counted in the current hourly window. <code>rejected</code> Responses of 400 or worse that the server attributes to this API key, 429s included. The global <code>requests_rejected</code> stays 401-only. <code>bytes_out</code> Response bodies only. An event stream reports no body length, so it counts as zero. <code>last_seen</code> <code>null</code> until the API key makes its first request. <p>Only a configured API key gets a row of counters. A request on an open route such as <code>/api/health</code> with an unknown key counts as <code>anonymous</code>, so an unauthenticated caller cannot grow the table.</p> <p>Every API key the server counts has a row here, the dashboard key included, so a <code>requests_by_key</code> bucket other than <code>anonymous</code> always matches one. A \"traffic by key\" panel reads the rows here, which are unambiguous, and takes <code>anonymous</code> from <code>requests_by_key</code>. Read <code>role</code> before you draw the bars: the <code>dashboard</code> row is the panel measuring its own polling.</p> <p>The dashboard key gets <code>services: []</code> and no grants unless the operator also gave it a <code>serve.users</code> entry, because it reaches nothing outside <code>/api/dashboard/</code>. An API key listed in more than one place still gets exactly one row.</p>"},{"location":"dev/rest-api/dashboard/#rate-limits","title":"Rate limits","text":"<p>An API key over its limit gets <code>429</code> with a <code>Retry-After</code> header:</p> <pre><code>serve:\n tiers:\n bot: { rate_limit: 600 } # requests per hour\n users:\n \"&lt;api key&gt;\":\n username: bot-relay\n tier: bot\n # rate_limit: 900 # optional, wins over the tier\n</code></pre> <p>The server keeps a fixed window, not a sliding one: it opens on the first request and resets an hour later. An API key with no tier and no override has no limit. A <code>tier</code> that names no entry under <code>serve.tiers</code>, or a <code>rate_limit</code> that is not a positive whole number, stops the server at startup, because the alternative is an API key that silently gets no limit. The rate limit never applies to the dashboard key, and never to <code>/api/health</code>.</p>"},{"location":"dev/rest-api/dashboard/#services","title":"Services","text":"<pre><code>GET /api/dashboard/services\n[{\"tag\": \"EXAMPLE\", \"state\": \"staged\", \"error\": null,\n \"commit\": \"9cc230c98f13b83f6c6fe831595b9702d3ba2786\", \"staged_commit\": \"5f0aa17...\",\n \"staged_since\": 1756908900.0, \"sessions\": 1, \"jobs\": 1,\n \"aliases\": [\"EXMPL\"], \"geofence\": [\"US\"], \"geoblock\": []}]\n</code></pre> <p>The list holds only the services configured on this server:</p> <ol> <li>The global <code>serve.services</code> list, when it is set.</li> <li>Else, the union of the <code>services</code> lists of all keys in <code>serve.users</code>.</li> <li>Else, every installed service.</li> </ol> <p>The union does not show what every API key can reach</p> <p>An API key with no <code>services</code> list can use every service, but it does not add to the union. The <code>api_secret</code> API key is the same. So with <code>k1: {services: [A]}</code> and a <code>k2</code> with no list, the list shows only <code>A</code>. To list every service, remove the <code>services</code> lists or set <code>serve.services</code>.</p> <p><code>GET /api/dashboard/services?all=1</code> lists every installed service. <code>/status</code> always counts only the configured services.</p> <p>A configured tag that names no installed service does not show. Name a service by its tag: an alias resolves only for a service that imported.</p> <p><code>state</code> is <code>loaded</code>, <code>staged</code> or <code>failed</code>. A service that failed to import keeps its error here instead of disappearing, and <code>/status</code> still counts it in the service total - count the <code>state</code> values here for the number that loaded.</p> <p>A <code>staged</code> service has an update on disk that a busy service blocks from the import: the repo pull already happened, so <code>commit</code> (what runs now) and <code>staged_commit</code> (what waits) differ. It swaps in when the last job and the last remote session for that tag finish. Both commits are <code>null</code> for a service from a plain local directory rather than a git repo.</p> <p>Watch the <code>service</code> event rather than polling for the swap.</p>"},{"location":"dev/rest-api/dashboard/#health","title":"Health","text":"<pre><code>GET /api/dashboard/health\n{\"generated_at\": 1756909350.4, \"status\": \"ok\",\n \"checks\": [{\"id\": \"ffmpeg\", \"label\": \"ffmpeg\", \"status\": \"ok\",\n \"detail\": \"7.1 \u00b7 /usr/bin/ffmpeg\", \"ms\": 4.1}]}\n</code></pre> <p>An instance can answer every request and still fail every download, because <code>mp4decrypt</code> is missing or a vault's credentials expired. This finds that before a job does.</p> <p><code>status</code> is <code>ok</code>, <code>degraded</code> (an optional dependency is missing) or <code>failing</code> (a required one is). Player binaries are not checked: a headless server never has one and it plays nothing. Each check is <code>ok</code>, <code>warn</code> or <code>fail</code>. Check ids are the binary names, <code>cdm</code>, <code>vault:&lt;name&gt;</code> (the vault's configured <code>name</code>, so two vaults of the same type stay apart), <code>bad_keys</code> and <code>proxies</code>. <code>bad_keys</code> warns when the vaults hold no <code>SQLite</code> entry, because only that backend stores the flag for a content key a remote client proved wrong; without it the server serves the same bad pair again.</p> <p>The server caches the result for 30 seconds and keeps every probe shallow: a vault answers one lookup that should miss, and no probe allocates anything. A failing probe's <code>detail</code> has the vault's password or token masked. This is a panel, not a liveness probe - do not poll it faster than the cache: every refresh that the cache does not answer costs one real lookup against each configured vault, which a vault that meters or rate limits its callers will count.</p> <p>An unreachable vault costs a slow, partial answer</p> <p>The probes run one after another, so a cold read takes as long as the probes that finish inside the deadline. The endpoint gives up after 15 seconds and answers with the checks that did complete, plus one <code>probe</code> check with the status <code>fail</code> naming how many finished. A database vault that accepts the connection and then stalls is what this deadline is for: its driver applies no timeout of its own, so without one the request would never answer.</p> <p>The probe that timed out keeps running in its thread until its driver returns, and the server caches the partial answer for the full 30 seconds, so callers cannot stack up more of them. A second caller waits behind the first, because the server shares one refresh rather than running it twice.</p> <p>Proxy providers are only checked at construction</p> <p>The proxy check builds each proxy provider but never asks it for a proxy, because for some proxy providers that allocates a connection. A proxy provider that only fails on its first real use still reads <code>ok</code>.</p>"},{"location":"dev/rest-api/dashboard/#counters-reset-on-restart","title":"Counters reset on restart","text":"<p>Stats, the log ring and the event history are all in memory. A restart drops every number to zero. <code>started_at</code> in the <code>stats</code> frame (with <code>version</code> and <code>code_hash</code>) is the signal: it arrives in the first frame after a reconnect, so a dashboard can tell a restart from a bug without any extra field.</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>. A slow response is not compressed.</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> <li>Remote services. A full-mode server can run a service through one of its own <code>remote_services</code> servers (see Remote sessions). <code>GET /api/config</code> lists their names in <code>remote_services</code>, and <code>GET /api/services?remote=&lt;name&gt;</code> lists that server's services, each with <code>remote</code> set to the name. Add <code>\"remote\": \"&lt;name&gt;\"</code> to <code>POST /api/search</code>, <code>/api/list-titles</code>, <code>/api/list-tracks</code> or <code>/api/download</code>, and the server opens a remote session with its own key for that server: the remote logs in and resolves titles, tracks and licences, and a download still runs, decrypts and muxes here. The tag may be any case or an alias, and your allowlist applies to it. An unknown name is <code>400 INVALID_PARAMETERS</code>, a server that does not answer is <code>SERVICE_UNAVAILABLE</code>, and a tag it does not offer is <code>INVALID_SERVICE</code>. List calls for the same title, profile, proxy and service options share one remote session, which closes after 120 seconds unused. An optional <code>client_name</code> names your client on the remote server's dashboard as <code>serve (&lt;client_name&gt;)</code>. A relayed search opens no remote session. The server sends its own credentials, cookies and cache for the <code>profile</code> with the search. A service that searches with no login gets none of them. A <code>--remote-only</code> server does not relay. A remote login that waits on you (a pair code or URL to approve on another device) cannot answer through a list call, so poll <code>GET /api/remote/logins</code> alongside it: each entry carries the login's <code>notice</code>, and its <code>prompt</code> when it asks a question (an OTP), which you answer with <code>POST /api/remote/logins/{id}/input</code> and <code>{\"response\": \"...\"}</code>. A remote download job shows the same text as its own <code>notice</code>, and asks a question (an OTP) through <code>input_prompt</code> as a local job does.</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>. The same middleware answers <code>429</code> in that shape when an API key goes over its rate limit. 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). <code>load_errors</code> lists the services the server skipped because they failed to import, at startup or after a service repository refresh; the server also writes each one to its log. An entry marked <code>pending_update</code> has newer code staged: it keeps its current code until its running or queued jobs and its live remote sessions finish.</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 \"geoblock\": [],\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 \"anonymous_search\": false,\n \"has_drm\": true,\n \"auth_methods\": [\"cookies\"]\n }\n ],\n \"load_errors\": []\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>geoblock</code> Region codes where the service refuses to work (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>anonymous_search</code> Whether <code>POST /api/search</code> operates with no login for this service. The server then ignores <code>credentials</code> and <code>cookies</code> on a search. <code>has_drm</code> Whether the service overrides a Widevine or PlayReady license hook. <code>pending_update</code> Set to <code>true</code> while a service repository refresh waits for this service's jobs to finish before it swaps in the new code. Absent otherwise. <code>server_accounts</code> Present when the server lends its own accounts for this service: <code>{regions: [\"ca\", \"gb\"], global: bool}</code>, the regions those accounts cover. A client sends no credentials, cookies, or cache for such a service. <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>422</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>For a service with <code>anonymous_search</code>, the server does not log in and ignores <code>credentials</code> and <code>cookies</code>. The server account check still applies.</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> Full proxy URI, a Control D resolver as <code>controld://&lt;resolver&gt;@dns.controld.com</code>, or a country code when the API key has <code>server_proxy</code>. <code>no_proxy</code> boolean no <code>false</code> Force-disable all proxy use. <code>credentials</code>, <code>cookies</code>, <code>cache</code> - no <code>null</code> Your own login material, on a <code>--remote-only</code> server only. See Client cache on a remote-only server. 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>422</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 Full proxy URI, a Control D resolver as <code>controld://&lt;resolver&gt;@dns.controld.com</code>, or a country code when the API key has <code>server_proxy</code>. <code>no_proxy</code> boolean no Force-disable proxy. <code>cdm_type</code> string no Preferred CDM type. <code>credentials</code>, <code>cookies</code>, <code>cache</code> - no Your own login material, on a <code>--remote-only</code> server only. See Client cache on a remote-only server. <p>You can also pass service-specific CLI options as additional keys.</p>"},{"location":"dev/rest-api/endpoints/#logins-that-need-the-user","title":"Logins that need the user","text":"<p><code>search</code>, <code>list-titles</code> and <code>list-tracks</code> have no channel to the user. A login that asks for input or waits for an approval on another device fails at once with <code>AUTH_FAILED</code> on these endpoints. Complete that login in a download job or a remote session, then send the saved login with the request.</p>"},{"location":"dev/rest-api/endpoints/#client-cache-on-a-remote-only-server","title":"Client cache on a remote-only server","text":"<p>A <code>--remote-only</code> server keeps nothing that a client sends. When the request does not use a server account, the server runs <code>search</code>, <code>list-titles</code> and <code>list-tracks</code> on a new service cache directory for that request only, and removes the directory when the request ends, on success and on error. A <code>--remote-only</code> server exposes only <code>search</code> of these three endpoints, so the rule applies to <code>list-titles</code> and <code>list-tracks</code> only if a later release exposes them in that mode.</p> <p><code>credentials</code> (<code>{username, password, extra?}</code>) and <code>cookies</code> (base64 of a zlib-compressed Netscape cookie file) are the same as on <code>POST /api/session/create</code>. <code>cache</code> is a map of cache files in the same form: each cache key is the file path relative to the service cache directory, with <code>/</code> separators and no <code>.json</code> suffix, and each value is base64 of the zlib-compressed file. The server writes these files into the request cache directory before the service authenticates.</p> <p>When you send <code>credentials</code>, <code>cookies</code> or <code>cache</code>, a successful response also has a <code>cache</code> field in the same form, with the updated files (for example a refreshed token), but no <code>titles_</code> files. Save them to send with the next request. A request that uses a server account, or a request to a full-mode server, uses the server's own cache and returns no <code>cache</code> field.</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>422</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>. <code>credentials</code>, <code>cookies</code>, <code>cache</code> - no As on <code>list-titles</code>. <code>dl_params</code> object no The <code>dl</code> track selection that the service reads from <code>ctx.parent.params</code>: <code>lang</code>, <code>v_lang</code>, <code>a_lang</code>, <code>s_lang</code>, <code>acodec</code>, <code>forced_subs</code> and <code>exact_lang</code>, as on <code>POST /api/session/create</code>. Some services select the manifests they fetch from these values. <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, \"bitrate_bps\": 8000000, \"width\": 3840, \"height\": 2160,\n \"resolution\": \"2160p\", \"fps\": \"24\", \"range\": \"HDR10\",\n \"range_display\": \"HDR10\", \"scan_type\": null, \"closed_captions\": [],\n \"dv_compatible_bitstream\": false, \"hdr10plus\": false, \"hdr10_base\": false, \"language\": \"en\",\n \"is_original_lang\": true,\n \"name\": null, \"track_name\": \"English\", \"needs_repack\": false, \"edition\": [], \"data\": null,\n \"drm\": [], \"descriptor\": \"DASH\"\n }\n ],\n \"audio\": [\n {\n \"id\": \"a-1\", \"codec\": \"EC3\", \"codec_display\": \"DD+\",\n \"bitrate\": 640, \"bitrate_bps\": 640000, \"channels\": \"5.1\", \"language\": \"en\",\n \"is_original\": true, \"is_original_lang\": true, \"atmos\": false, \"joc\": 0,\n \"descriptive\": false, \"name\": null, \"track_name\": \"English\", \"needs_repack\": false, \"edition\": [],\n \"data\": null, \"drm\": [], \"descriptor\": \"DASH\"\n }\n ],\n \"subtitles\": [\n { \"id\": \"s-1\", \"codec\": \"vtt\", \"language\": \"en\",\n \"forced\": false, \"sdh\": false, \"cc\": false, \"is_original_lang\": false,\n \"name\": null, \"track_name\": \"English\", \"needs_repack\": false, \"edition\": [], \"data\": null,\n \"drm\": [], \"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> <p>Every track carries the same fields as a local track: <code>is_original_lang</code>, <code>name</code>, <code>needs_repack</code>, <code>edition</code>, and <code>data</code>. <code>name</code> is the name the service set, or null. <code>track_name</code> is the name <code>--list</code> shows and the mux writes to an audio or subtitle track: <code>name</code> when the service set one, else the name of the language (English, or in the language itself when the server sets <code>muxing.track_names: native</code>, or no name when it sets <code>none</code>), then the server's <code>muxing.original_label</code> on an original-language track, then the SDH, CC, Forced or Descriptive label. <code>bitrate</code> is in kb/s, and <code>bitrate_bps</code> gives the exact bits/s. <code>data</code> holds the part of the service-set <code>track.data</code> that fits in JSON, without the <code>hls</code>, <code>dash</code>, and <code>ism</code> parser keys. Audio keeps <code>is_original</code> and <code>atmos</code> for clients that read them, and adds the exact <code>joc</code> object count.</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\": \"HEVC\",\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>latest_episodes</code> integer <code>null</code> Only the N newest episodes. A positive integer. When set, it overrides <code>latest_episode</code>. <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_subs_only</code> boolean <code>false</code> Download forced subtitles and no other subtitle; implies <code>forced_subs</code>. Not valid with <code>no_subs</code>, <code>video_only</code>, <code>audio_only</code> or <code>chapters_only</code>. <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> A language tag without a region never falls back to another variant. A tag with a region is always exact. <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> / <code>no_attachments</code> boolean <code>false</code> Skip a track type. <code>audio_description</code> boolean <code>false</code> Download audio description. <code>audio_description_only</code> boolean <code>false</code> Download audio description and no standard audio. Not valid with <code>no_audio</code>, <code>video_only</code>, <code>subs_only</code> or <code>chapters_only</code>. <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>all_drm</code> boolean <code>false</code> License each track with both Widevine and PlayReady. Needs a CDM for each DRM system. Key vaults are read first; <code>cdm_only: true</code> sends a challenge for each system. The server refuses it with <code>cdm</code>, which selects one device. <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> / <code>proxy_download</code> string / bool / bool / string <code>null</code> / <code>false</code> / <code>false</code> / <code>null</code> Proxy controls. <code>proxy</code> and <code>proxy_download</code> must be full proxy URIs unless the API key has <code>server_proxy</code>. A Control D resolver, <code>controld://&lt;resolver&gt;@dns.controld.com</code>, counts as a full proxy URI: the server runs a forwarder for it. <code>no_folder</code> / <code>no_source</code> / <code>no_mux</code> boolean <code>false</code> Output/mux controls. <code>sample</code> boolean/string <code>null</code> Download a short sample and write it with a <code>SAMPLE</code> tag on the filename in a <code>Sample</code> folder inside the output folder. <code>true</code> is 60 seconds from 2 minutes in; <code>\"0-60\"</code> is a window in seconds. <code>include_sample</code> boolean <code>false</code> Download the full title, then also cut a 60 second sample from each muxed file into a <code>Sample</code> folder next to it. <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. With <code>all_drm</code>, a DRM system that does not license is a warning. <code>generate_dv</code> boolean <code>false</code> With <code>HYBRID</code> in <code>range</code>, make Dolby Vision from the HDR10+ metadata when a title has no DV track. Needs <code>hdr10plus_tool</code> on the server. Without <code>HYBRID</code> in <code>range</code>, the request returns <code>400</code>. <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> Output directory, relative to the server's downloads directory. The server rejects a path that resolves outside it with <code>400</code>. <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>, <code>acodec</code> and <code>sub_format</code> take the same spellings as the CLI options of the same name (<code>unshackle dl --help</code> prints each list). The API and the CLI read one list, so they cannot disagree. <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>Service options. A service's own CLI options travel in the same body. Send them in a nested <code>service_params</code> object, or as flat top-level keys. <code>service_params</code> wins over a flat key of the same name. An option you leave out takes the default declared on the service's <code>cli</code> command, so the job matches the equivalent <code>dl</code> run. <code>profile</code> at the top level always means the credential profile, never a service's own <code>--profile</code> option.</p> Request <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 \"service_params\": {\"device\": \"chrome\", \"movie\": true}\n }'\n</code></pre> <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-scripts only in <code>unshackle.yaml</code>, where they still operate for API jobs. See Post-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. <code>403</code> <code>SERVER_CDM_CAPPED</code> The API key has a <code>server_cdm_max_height</code> for the service, and the job has no <code>quality</code> at or under it, sets <code>best_available</code>, or has <code>HYBRID</code> in <code>range</code>."},{"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 \"input_prompt\": null,\n \"notice\": null\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>, and <code>error_code</code>. When you start the server with <code>--debug-api</code>, each job also includes <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. <code>403</code> <code>SERVER_CDM_CAPPED</code> The job is no longer inside the <code>server_cdm_max_height</code> of the API key."},{"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/#post-apidownloadjobsjob_idinput","title":"<code>POST /api/download/jobs/{job_id}/input</code>","text":"<p>Answer the prompt that a running job waits on. A service can ask for input during a job, for example an OTP code, a PIN, or a device-code confirmation. The job then shows the prompt in its <code>input_prompt</code> field and in its <code>progress</code> events. Show the prompt to the user and send the answer here.</p> <p>A job that waits for an approval on another device, such as a pair code login, shows the message in its <code>notice</code> field instead. A notice needs no answer: show it to the user and keep polling.</p> RequestResponse <code>200</code> <pre><code>{ \"response\": \"123456\" }\n</code></pre> <pre><code>{ \"status\": \"accepted\" }\n</code></pre> Status Error code Meaning <code>200</code> - Answer sent to the job. The <code>input_prompt</code> field goes back to <code>null</code>. <code>400</code> <code>INVALID_INPUT</code> The body is not JSON, or it has no <code>response</code>. <code>404</code> <code>JOB_NOT_FOUND</code> No such job. <code>409</code> <code>CONFLICT</code> The job does not wait on a prompt. <p>Warning</p> <p>The job keeps its download slot while it waits. It fails with <code>AUTH_FAILED</code> if nobody answers the prompt within 10 minutes.</p>"},{"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 looks like a secret (<code>secret</code>, <code>password</code>, <code>passwd</code>, <code>token</code>, <code>api_key</code>, <code>credential</code>, <code>auth</code>, <code>cookie</code>, <code>bearer</code>, <code>private</code>) and any userinfo in proxy URLs. The <code>directories</code> block holds the server's absolute paths and reaches only an admin key (<code>admin: true</code> or the <code>api_secret</code>); a plain key gets the response without it.</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. Each API key sees only the jobs it submitted, plus entries written before the history recorded an owner. The same rule applies to <code>DELETE /api/history/{job_id}</code> and <code>POST /api/download/jobs/clear-finished</code>. 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. Both, and refresh-services, need <code>admin: true</code> on the API key or the <code>api_secret</code> itself; any other key gets <code>403 FORBIDDEN</code>. 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> and re-import the services that changed, without a restart. <code>refreshed</code> becomes <code>true</code> when all repos updated successfully, or when you configure no repository. <code>deferred</code> lists the services that have a running or queued job: they keep their current code until that job finishes, then swap. <code>load_errors</code> lists the services whose new code failed to import; the server drops them until the next successful refresh.</p> Response <code>200</code> <pre><code>{\n \"refreshed\": true,\n \"repos\": [\n {\n \"spec\": \"github.com/example/services\",\n \"updated\": true,\n \"changes\": [\"~EXAMPLE\", \"+EXAMPLE2\"],\n \"deferred\": [\"EXAMPLE\"],\n \"load_errors\": []\n }\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) without a request, 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}/segment_filter \u2192 HLS segments the service drops (ads, bumpers)\nPOST /api/session/{id}/samples \u2192 decrypt cbcs samples of a track on the server\nPOST /api/session/{id}/license \u2192 proxy or server-CDM DRM licensing\nPOST /api/session/{id}/keys/bad \u2192 report a server-vault content key that did not decrypt\nDELETE /api/session/{id} \u2192 tear down, harvest updated cache\n</code></pre>"},{"location":"dev/rest-api/endpoints/#slow-responses","title":"Slow responses","text":"<p>The <code>titles</code>, <code>tracks</code> and <code>license</code> routes can take minutes on a large catalogue. When the answer is not ready after 30 seconds, the route sends status <code>200</code> and the headers. It then sends a newline every 30 seconds until the JSON body is ready. JSON parsers ignore the leading newlines. This keeps the connection open through a reverse proxy that closes an idle request.</p> <p>A late failure has status <code>200</code></p> <p>The server sent the status before the work ended. A failure after the first 30 seconds arrives as the standard error body with status <code>200</code>. Check <code>status</code> in the body, not only the HTTP status. The body has no HTTP status field. Use <code>error_code</code> and <code>retryable</code> to decide what to do.</p> <p>A slow response is not gzip-compressed. Gzip output cannot start before the body is ready, and the newlines must go out at once.</p>"},{"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, keyed by the file path relative to the service cache directory with <code>/</code> separators and no <code>.json</code> suffix, so a nested key such as <code>session_web/&lt;sha1&gt;</code> lands in a subdirectory), <code>client_region</code>, <code>proxy_region</code>, <code>cdm_type</code>, <code>range_</code>, <code>vcodec</code>, <code>quality</code>, <code>best_available</code>, <code>dl_params</code>, <code>client</code>, and any service CLI options. <code>proxy_region</code> is the country code the client resolved <code>proxy</code> from; the server matches it against its own accounts. <code>client</code> is a freeform object the dashboard shows as sent (the CLI puts <code>version</code>, <code>code_hash</code>, <code>platform</code> and a redacted <code>argv</code> in it); the server ignores it above 4096 bytes of JSON.</p> <p><code>dl_params</code> is an object with the <code>dl</code> track selection: <code>lang</code>, <code>v_lang</code>, <code>a_lang</code> and <code>s_lang</code> (arrays of language strings), <code>acodec</code> (an array of audio codec names or <code>dl -a</code> aliases such as <code>ddp</code>), and <code>forced_subs</code> and <code>exact_lang</code> (booleans). The service reads these values from <code>ctx.parent.params</code>. The server uses the <code>dl</code> default for each absent or malformed value, and drops an unknown codec name.</p> <p>Service CLI options also travel in a nested <code>service_params</code> object, which wins over a flat key with the same name. <code>profile</code> at the top level always means the credentials profile, never a service's own <code>--profile</code> option.</p> <p>The <code>proxy</code> value must be a full proxy URI, unless the operator gives your API key <code>server_proxy</code> in the <code>serve.users</code> config. Without <code>server_proxy</code>, the server does not resolve country codes with its own proxy providers. It rejects the request with <code>INVALID_PROXY</code> when no <code>proxy</code> is set and the reported <code>client_region</code> differs from the server's region. A request that reports no <code>client_region</code> is not blocked. Pass <code>proxy</code> with your own proxy, or <code>no_proxy</code> to accept the server's own connection. With <code>server_proxy</code>, the server resolves a country code and picks a proxy for your <code>client_region</code> itself. A Control D resolver, <code>controld://&lt;resolver&gt;@dns.controld.com</code>, counts as a full proxy URI: the server runs a forwarder for it and needs no Control D configuration of its own.</p> Response <code>200</code> <pre><code>{\n \"session_id\": \"d4e5f6a7-...\",\n \"service\": \"EXAMPLE\",\n \"status\": \"authenticating\",\n \"server_account\": false\n}\n</code></pre> <p><code>server_account</code> is <code>true</code> when the server authenticated with one of its own accounts (<code>serve.server_accounts</code>). Otherwise the server uses only what the client sent, and never falls back to its own credentials. When the login succeeds and the remote session does not use a server account, the login belongs to the client, and the client gets cookies, auth headers, and the remote session cache back. A remote session on the server's device is the exception: the client gets its cookies back, but no auth headers and no cache. For a server-account remote session the tracks and segments responses carry no cookies and no auth headers. The server also drops secret-looking keys from track data, and the cache stays on the server. A server-account service also refuses a client proxy URI, because the server's login would pass through it.</p> 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_idlogs","title":"<code>GET /api/session/{session_id}/logs</code>","text":"<p>Drain the service's server-side log output for this remote session. The server mirrors every log call the service makes (<code>self.log.info</code>, warnings, errors) into a bounded per-session buffer, so a remote client can see why an auth, title, or license step failed. Pass <code>since=&lt;seq&gt;</code> to get only records newer than the last drained sequence number. Works in every auth state, including <code>failed</code>.</p> Response <code>200</code> <pre><code>{\n \"session_id\": \"a1b2c3\",\n \"logs\": [\n { \"seq\": 1, \"level\": \"INFO\", \"message\": \"Signed in as profile 'Main'\", \"ts\": 1724990000.1 },\n { \"seq\": 2, \"level\": \"WARNING\", \"message\": \" - ThePlatform returned no streams\", \"ts\": 1724990002.7 }\n ],\n \"last_seq\": 2\n}\n</code></pre> Status Error code Meaning <code>200</code> - Records returned (empty list when nothing new). <code>404</code> <code>SESSION_NOT_FOUND</code> No such session. <p>The buffer keeps the newest 500 records. Only the service instance's own logger is mirrored; core pipeline loggers stay on the server. A server-account session gets no log relay at all - auth-time service output can carry the operator account's identity, so it stays server-side.</p>"},{"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. A slow answer arrives as a slow response.</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. A slow answer arrives as a slow response.</p> <p><code>manifests</code> holds each served DASH/ISM manifest once. A service can build an AdaptationSet of its own that the served manifest does not contain. <code>track_manifests</code> holds a one-AdaptationSet MPD for each such track, and the client re-parses that in place of the whole manifest.</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 \"track_manifests\": [ { \"track_id\": \"s-1\", \"type\": \"dash\", \"url\": \"https://...\", \"data\": \"&lt;base64 zlib xml&gt;\" } ],\n \"session_headers\": { \"User-Agent\": \"...\" },\n \"session_cookies\": { \"sid\": \"...\" },\n \"session_cookie_jar\": [ { \"name\": \"sid\", \"value\": \"...\", \"domain\": \".example.com\", \"path\": \"/\", \"secure\": true } ],\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\": { ... }, \"cookie_jar\": [ ... ], \"data\": { ... } }\n }\n}\n</code></pre> <p><code>cookies</code> gives names and values only. <code>cookie_jar</code> gives the same cookies with their domain, path and <code>secure</code> flag, in the <code>session_cookie_jar</code> form of the tracks response.</p> 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_idsegment_filter","title":"<code>POST /api/session/{session_id}/segment_filter</code>","text":"<p>Get the HLS segments a service drops (ads, bumpers, dub cards). The server runs the service's own segment filter over the track's media playlist and returns only the URIs, so the client drops the same segments the service does. Body: <code>{ \"track_id\": \"v-1\" }</code> (required). <code>unwanted</code> is <code>null</code> when the track has no filter. The client keeps every segment when the server does not have this route.</p> Response <code>200</code> <pre><code>{ \"unwanted\": [\"https://cdn.example/hls/ad1.ts\"] }\n</code></pre> Status Error code Meaning <code>200</code> - Unwanted segment URIs, or <code>null</code>. <code>400</code> <code>INVALID_INPUT</code> Missing <code>track_id</code>. <code>404</code> <code>TRACK_NOT_FOUND</code> An unknown track ID was requested. <code>422</code> <code>SERVICE_ERROR</code> The playlist request or the filter failed."},{"location":"dev/rest-api/endpoints/#post-apisessionsession_idsamples","title":"<code>POST /api/session/{session_id}/samples</code>","text":"<p>Decrypt the samples of a track that the service decrypts itself after the download. The tracks response lists those track IDs in <code>sample_decrypt_tracks</code>. The client downloads the file, then sends each <code>stsd</code> sample entry's samples here, and writes the plaintexts back in place. The query string names the track and the 1-based entry: <code>?track_id=a-1&amp;entry=2</code>.</p> <ul> <li>An empty body asks how the entry decrypts. The JSON response is <code>{ \"key\": \"&lt;hex&gt;\" }</code>, which the client then uses itself, or <code>{ \"decrypter\": true }</code>.</li> <li>An <code>application/octet-stream</code> body is a sample frame: a big-endian <code>uint32</code> count, one <code>uint32</code> length per sample, then the samples. Each sample is a ciphertext cut to whole AES blocks. The response is a frame of the same shape with the plaintexts in the same order.</li> </ul> <p>The client sends at most 8 MiB of samples per request, and the route accepts a body of up to 16 MiB. Binary frames keep the upload the size of the samples, and the server does not compress them. The route needs the <code>server_cdm</code> grant for the service, because the decrypter can use a process or an account of the server.</p> Status Error code Meaning <code>200</code> - The content key, <code>decrypter</code>, or the plaintext frame. <code>400</code> <code>INVALID_INPUT</code> Missing <code>track_id</code>, a bad <code>entry</code>, a malformed frame, or a track the service does not decrypt. <code>413</code> - The body is larger than 16 MiB. <code>403</code> <code>FORBIDDEN</code> The API key has no <code>server_cdm</code> grant for the service. <code>404</code> <code>TRACK_NOT_FOUND</code> An unknown track ID was requested. <code>422</code> <code>SERVICE_ERROR</code> The service's decrypter failed."},{"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. A slow answer arrives as a slow response.</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;\" }, \"vault_keys\": [\"&lt;kid_hex&gt;\"], \"drm_type\": \"widevine\" }\n</code></pre> <pre><code>{ \"keys\": { \"v-1\": { \"&lt;kid_hex&gt;\": \"&lt;key_hex&gt;\" } }, \"vault_keys\": [\"&lt;kid_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>. In server-CDM mode the server's <code>cdm</code> mapping for the service decides the DRM system and the response <code>drm_type</code> names the system that licensed. The client's value decides only when the server has no mapping for the service. <code>mode</code> <code>proxy</code> (default) or <code>server_cdm</code>. <code>clear_tracks</code> (response) Requested track ids that carry no DRM, so they have no keys. Absent when every requested track is encrypted. <code>vault_keys</code> (response) KIDs whose content key came from a server vault, not the CDM. The client proves such a content key with a decode before it trusts it; the field is absent when every content key came from the CDM. 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>422</code> <code>SERVICE_ERROR</code> The service aborted during licensing."},{"location":"dev/rest-api/endpoints/#post-apisessionsession_idkeysbad","title":"<code>POST /api/session/{session_id}/keys/bad</code>","text":"<p>Report a content key from <code>vault_keys</code> that did not decrypt the track. The server flags the pair in its local vaults and reports it to the vault that served it, and the next licence for that KID reaches the CDM. When the CDM returns the same pair, the server removes the flag. The client never learns the server vault names.</p> <pre><code>{ \"kid\": \"&lt;kid_hex&gt;\", \"key\": \"&lt;key_hex&gt;\" }\n</code></pre> Status Error code Meaning <code>200</code> - <code>{\"flagged\": true}</code>: the pair is flagged. <code>{\"flagged\": false}</code>: the CDM licensed the pair, so it is not flagged. <code>400</code> <code>INVALID_INPUT</code> This remote session was not served that pair. <code>404</code> <code>SESSION_NOT_FOUND</code> Unknown remote session."},{"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\": \"&lt;base64 zlib bytes&gt;\", \"session_web/&lt;sha1&gt;\": \"&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 and the login belongs to the client. Each cache key is the file path relative to the session cache directory, with <code>/</code> separators and no <code>.json</code> suffix, so a file in a subdirectory keeps its place on the client. The server rejects a cache key with a drive letter, a root, a <code>..</code> segment, or an empty segment, and so does the client. <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>, <code>{\"status\": 401, \"message\": \"Secret Key is Invalid.\"}</code>, or <code>{\"status\": 429, \"message\": \"Rate limit exceeded.\"}</code> with a <code>Retry-After</code> header) with an integer <code>status</code> and no <code>error_code</code>, <code>timestamp</code>, or <code>details</code>. A <code>429</code> from the middleware therefore carries no <code>error_code</code>, unlike the <code>RATE_LIMITED</code> code below, which a handler raises for a rate limit the service imposed. 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":"<p>The error code catalogue gives the default HTTP status of each error code.</p> <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> (424, retryable), \"rate limit\" or \"429\" become <code>RATE_LIMITED</code> (429, retryable), and anything unrecognized collapses to <code>INTERNAL_ERROR</code> (422).</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, ... (ref 7f3a2c)\",\n \"ref\": \"7f3a2c\",\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, followed by <code>(ref &lt;ref&gt;)</code>. Wording may change between versions, so do not parse it. <code>ref</code> string Yes A short random reference for this one error. The server logs it with the request, so an operator can find the record from a user's report. <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/#find-an-error-from-its-ref","title":"Find an error from its <code>ref</code>","text":"<p>For each error response, the server logs one <code>WARNING</code> line on the <code>api</code> logger:</p> <pre><code>Error ref 7f3a2c: SERVICE_ERROR 422 POST /api/session/&lt;id&gt;/license service=EXAMPLE user=alice: Licence request failed: ...\n</code></pre> <p>Search the server log for <code>Error ref &lt;ref&gt;</code>. The handler's traceback, when there is one, is directly above that line. The developer dashboard log view also shows it.</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, but the defaults hold for the overwhelming majority of responses.</p> <p>The server never answers with a <code>5xx</code> status. A proxy such as Cloudflare can replace the body of a <code>5xx</code> with its own page, and the JSON error is then lost. Server-side failures use <code>422</code>, and the ones that a retry can fix use <code>424</code>. Read <code>error_code</code> to tell them apart. A <code>5xx</code> that a client receives comes from a proxy in front of the server, for example while the server restarts.</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, or the proxy failed the exit check. <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>SERVER_CDM_CAPPED</code> 403 The server CDM does not license live above the <code>server_cdm_max_height</code> of the API key. <code>details.reason</code> is <code>server_cdm_max_height</code> (with <code>details.max_height</code>), <code>client_device</code>, for a remote session where the client's own device licenses, or <code>server_device</code>, for a remote session that runs on the server's device. A remote client licenses the track with its own device, except for <code>server_device</code>: then only its own vaults can supply the key. <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>SERVER_DRAINING</code> 409 The server is about to restart and starts no new remote session or download job. Open work continues. Retryable after the restart. <code>SERVICE_ERROR</code> 422 The streaming service's API returned an error, or the service does not support the requested operation. <code>DRM_ERROR</code> 422 DRM or license acquisition failed. <code>RATE_LIMITED</code> 429 The streaming service is rate-limiting requests. Retryable. <p>Not every <code>429</code> is <code>RATE_LIMITED</code></p> <p>The server has a rate limit of its own. An API key over <code>serve.tiers.&lt;name&gt;.rate_limit</code> or <code>serve.users.&lt;key&gt;.rate_limit</code> gets a <code>429</code> from the authentication middleware, before any handler runs, so it carries no <code>error_code</code> and is not the <code>RATE_LIMITED</code> code above. It is the shape <code>{\"status\": 429, \"message\": \"Rate limit exceeded.\"}</code> with a <code>Retry-After</code> header. Read <code>Retry-After</code> and wait it out rather than retrying on a backoff of your own: the window is fixed, so an early retry only spends the next window. See Authentication.</p>"},{"location":"dev/rest-api/errors/#server-errors-422-and-424","title":"Server errors (422 and 424)","text":"Code Status Meaning <code>INTERNAL_ERROR</code> 422 An unexpected server-side error. This is the fallback for any exception the server could not categorise, and for an exception that no handler caught. <code>DOWNLOAD_ERROR</code> 422 The download process itself failed. <code>WORKER_ERROR</code> 422 The download worker subprocess errored out. <code>NETWORK_ERROR</code> 424 A network connectivity problem (connection, timeout, DNS, TLS). Retryable. <code>SERVICE_UNAVAILABLE</code> 424 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>422</code>. In practice every code above has an explicit mapping. A middleware in every server mode also changes any <code>5xx</code> answer, such as one from a CDM subapplication, to <code>422</code>.</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> (424) yes <code>geofence</code>, <code>geoblock</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> (422) no <code>service unavailable</code>, <code>503</code>, <code>maintenance</code>, <code>temporarily unavailable</code> <code>SERVICE_UNAVAILABLE</code> (424) 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> (422) 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/#late-failures-with-status-200","title":"Late failures with status <code>200</code>","text":"<p>The remote session <code>titles</code>, <code>tracks</code> and <code>license</code> routes send status <code>200</code> and the headers when the work takes longer than 30 seconds. They then send a newline every 30 seconds to keep the connection open. See Slow responses. A failure after that time arrives as the standard error body, but with status <code>200</code>. The body has no field for the HTTP status that the error would otherwise have. <code>error_code</code> and <code>retryable</code> stay in the body.</p> <p>Check the body on these routes</p> <p>On these routes a <code>200</code> does not always mean success. Parse the body and treat <code>\"status\": \"error\"</code> with an <code>error_code</code> as a failure.</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. 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, and a <code>200</code> body with <code>\"status\": \"error\"</code> and an <code>error_code</code> too: it logs <code>Server error [&lt;error_code&gt;]: &lt;message&gt;</code> and exits. It retries a request once, after one second, only when a <code>502</code>, <code>503</code> or <code>504</code> arrives with a body that is not JSON: that is a page from the proxy in front of the server, not an answer from the server. 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). <code>input_prompt</code> string or <code>null</code> The prompt the service waits on. Answer it with <code>POST /api/download/jobs/{job_id}/input</code>. <code>notice</code> string or <code>null</code> A message the service shows while it waits for an approval on another device, such as a pair code. It needs no answer. <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>, and <code>error_code</code>. With <code>--debug-api</code>, it also adds <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>The job worker has no terminal. When a service asks the user for input, the job worker writes the prompt to <code>progress.json</code> as <code>input_prompt</code> and waits. The answer from <code>POST /api/download/jobs/{job_id}/input</code> goes to the job worker on its stdin. When a service waits for an approval on another device, the job worker writes the message as <code>notice</code> and sets it back to <code>null</code> when the wait ends.</p> <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> <p>If you have no install yet, follow Installation. Then check your tools:</p> From a cloneInstalled as a uv tool <pre><code>uv run unshackle env check\n</code></pre> <pre><code>unshackle env check\n</code></pre> <p>This page uses the bare <code>unshackle</code> command. From a git clone, the recommended install, run each command as <code>uv run unshackle ...</code>.</p>"},{"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 \"geoblock\": [],\n \"title_regex\": null,\n \"url\": \"https://example.com\",\n \"help\": \"EXAMPLE service documentation...\",\n \"needs_auth\": true,\n \"has_search\": true,\n \"anonymous_search\": false,\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\": \"HEVC\",\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>SERVICE_ERROR</code> 422 The service raised an error <code>RATE_LIMITED</code> 429 Upstream throttling (retryable) <code>INTERNAL_ERROR</code> 422 Unexpected server-side failure <code>NETWORK_ERROR</code> 424 Connection/timeout reaching the service (retryable) <p>The error code catalogue lists every code.</p> <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 --remote 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 --remote --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/#making-a-service-remote-by-default","title":"Making a service remote by default","text":"<p>To run a service on the server without <code>--remote</code>, set <code>remote</code> in the <code>services</code> block, not in the <code>services</code> sub-dict of <code>remote_services</code>. Add <code>server</code> to select one of several servers:</p> unshackle.yaml (client)<pre><code>services:\n EXAMPLE:\n dl:\n remote: true\n server: my_server\n</code></pre> <p><code>unshackle dl EXAMPLE 0ABCDEF</code> and <code>unshackle search EXAMPLE \"query\"</code> then run on <code>my_server</code>. A <code>--server</code> on the command line overrides the configured server, and <code>--local</code> runs the local service code for that run. The global <code>dl: remote: true</code> makes every <code>dl</code> run remote, but it has no effect on <code>search</code>. The REST API ignores both settings: a job runs remote only when its request asks for it.</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. A client that reports no region is not blocked. The proxy must be a full proxy URI unless the operator gives your API key <code>server_proxy</code>. Without <code>server_proxy</code> the server does not resolve country codes with its own proxy providers, and it rejects the remote session when it sits in a different region from the reported one, asking the client to pass <code>--proxy</code> with its own proxy, or <code>--no-proxy</code> to accept the server's own connection. With <code>server_proxy</code> the server picks a proxy that matches the client region itself. For <code>--proxy controld:ca</code> the client points its Control D profile at the region and sends only the resolver, as <code>controld://&lt;resolver&gt;@dns.controld.com</code>. The server counts it as a full proxy URI and runs its own forwarder for it. A bare region skips Control D, because its proxy is a forwarder on the client. See Control D. The client also downloads playlists and segments through the same proxy, as a local run does. <code>--no-proxy-download</code> and <code>--proxy-download</code> change that for downloads only.</li> <li>A <code>--local-proxy</code> goes as <code>tunnel:&lt;id&gt;</code>. The client opens <code>GET /api/tunnel</code> first, and the server replaces the ID with a loopback SOCKS5 proxy that relays to the client's own connection. See Send the server's requests through your machine.</li> <li>Track-selection hints (<code>range_</code>, <code>vcodec</code>, <code>quality</code>, <code>best_available</code>, <code>generate_dv</code>) so the server fetches the right manifests</li> <li>Your language and audio codec selection (<code>-l</code>, <code>-vl</code>, <code>-al</code>, <code>-a</code>, <code>-fs</code>) in a <code>dl_params</code> object. Some services fetch one manifest for each audio language, and pick the languages from these values</li> <li>Your local per-service cache files (e.g. refreshed tokens), including files in subdirectories of the service cache directory, but only the files for the active profile. The client withholds a file whose path, in any directory or file name, embeds a hash of another credential or the name of another profile. One profile's tokens therefore never reach the server while you use a different profile. At worst, a withheld file makes the server authenticate again</li> </ul> <p>The server uses its own accounts only when the operator lists the service in <code>serve.server_accounts</code> and gives your API key <code>server_accounts</code> in <code>serve.users</code>. For any other service, a client that sends no credentials or cookies authenticates with nothing. For a listed service the client sends no credentials, cookies, or cache at all: the server picks one of its own accounts that works in your region and rotates through them. <code>--proxy ca</code> picks a <code>ca</code> account.</p> <p><code>GET /api/services</code> advertises the regions those accounts cover. When your own region is not one of them and you set no <code>--proxy</code>, the client resolves a proxy for the first advertised region itself, so both sides sit in a region the account works in. This is a bare region query, so it skips Control D. A server-account service does not accept a <code>controld://</code> resolver from the client.</p> <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>A client older than the <code>service_params</code> change sends service options as flat body keys only. A flat key that shares a name with a transport field (such as <code>profile</code>, which at the top level always means the credentials profile) no longer reaches the service; the server logs a warning naming the dropped key. Update the client to send service options under <code>service_params</code>.</p> <p>The server also mirrors the service's own log output (<code>self.log</code>) into a per-session buffer. The client drains it through <code>GET /api/session/{id}/logs</code> after each step and prints the records locally, so you see the server-side reason when a step fails.</p> <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. A service can build an AdaptationSet of its own that the served manifest does not contain. Each such track gets a one-AdaptationSet MPD in <code>track_manifests</code>, and the client re-parses that instead. Any <code>session_headers</code> and cookies the server used are merged into the client's local HTTP session. Each cookie in <code>session_cookie_jar</code> keeps its domain, path and <code>secure</code> flag, so it goes only to its own hosts. <code>session_cookies</code> carries the same cookies as names and values only, for older clients.</p> <p>The tracks response repeats the title. A service can rewrite title fields inside <code>get_tracks</code>, so the client takes this copy in place of the one from the title list. Each track carries the full local field set. After the manifest re-parse the client overlays the JSON-safe part of the service-set <code>track.data</code>, so a service value wins over the parser's. An attachment that the service wrote to a file on the server travels as base64, and the client writes it to its own temp directory.</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. While it works, it sends a keep-alive request to the remote session at an interval of one third of <code>session_ttl</code>, so a long download does not let the remote session expire. On completion, and also when <code>dl</code> exits early (<code>--list</code>, Ctrl+C, an error), it deletes the remote session. If the login belongs to the client, the <code>DELETE</code> request returns the updated cache files (for example a refreshed token) and the client saves them locally, so the next remote session can skip interactive authentication. The login belongs to the client when it succeeds and the remote session does not use a server account. This includes a pair code that the user approves on another device. A server-account login never does, and neither does a remote session on the server's device (see below). The client saves only the returned files that pass the same profile check it applies before it sends them, so a file for another profile cannot overwrite that profile's local file.</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> <li>Also used for a run with <code>dl --cdm &lt;name&gt;</code>, and for a service whose own entry in your <code>cdm</code> config named the loaded device. In each case the client sends <code>server_cdm: false</code> when it creates the remote session, and the server builds the service on your device even when the API key has the server CDM.</li> <li>A service option that the service lists in <code>SERVER_DEVICE_OPTIONS</code> keeps the server CDM. The server reads the option from <code>service_params</code>, then from the top level of the request. The create response gives the result in <code>server_cdm</code>, and the client shows a warning when the server did not apply its choice.</li> <li>The service on the server sees your device, not the server's: its DRM system, security level, system ID and device type. A CDM call that the service makes (for example a session-key exchange at login) goes to your client as a <code>cdm_call</code>, and your local CDM answers it. See Your own device identity.</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> <li>A content key the server took from its own vault is unproven. The response lists its KID in <code>vault_keys</code>, the client decrypts and checks that the output decodes, and a wrong pair goes back to <code>POST /api/session/{id}/keys/bad</code>. The server flags the pair in every local vault it holds, reports it to the vault that served it, and the next licence for that KID skips the pair and reaches the CDM. When the CDM returns the same pair, the server removes the flag, because then the client's check was wrong. A server with no local SQLite vault cannot store the flag. The server accepts a report only for a pair it served to that remote session, and does not flag a pair its CDM licensed. The client never learns the server vault names.</li> <li>A content key in the client's own vaults goes first, even when the server already answered. The client proves it, and a server key waits as the next candidate.</li> </ul> <p>A height limit on the server CDM</p> <p>An API key with <code>server_cdm_max_height</code> gets the server CDM only up to that height. The session create response tells the client who licenses the session in <code>server_cdm</code> and gives the limit in <code>server_cdm_max_height</code>. In a server CDM session, the batch licence response lists each track the server refused to license live under <code>capped_tracks</code>. A single-track server CDM licence answers <code>403 SERVER_CDM_CAPPED</code> for such a track. In both cases the client licenses those tracks in proxy mode with its own local CDM. See <code>server_cdm_max_height</code>.</p>"},{"location":"dev/rest-api/remote-sessions/#your-own-device-identity","title":"Your own device identity","text":"<p>A service can need more than a licence challenge from your device: an ESN, model keys, or a session-key exchange that runs on the CDM. The device never leaves your machine. Only these cross the wire:</p> <ul> <li>Device facts. When it creates the remote session, the client sends its DRM system, security level, system ID and device type. The service sees a stand-in with these facts.</li> <li>CDM calls. When the service calls the CDM, the server sends a <code>cdm_call</code> to the client and waits. The client makes the challenge, or parses the licence, on its own CDM. When the service closes a CDM session, the server sends a <code>close</code> call, because a CDM holds only a few sessions. The client polls for calls during login and while one of its own requests runs service code, so an idle remote session sends nothing extra.</li> <li>Session keys only. A <code>keys</code> call returns Widevine <code>OPERATOR_SESSION</code> and <code>SIGNING</code> keys. It never returns a content key, and the client refuses a PlayReady <code>keys</code> call. So a server cannot use your device to license titles for itself.</li> <li>Identity config. A service names the config keys a client may send (for example <code>esn</code>, <code>Kpe</code>, <code>Kph</code>, <code>esn_map</code>). The server lists them in the service listing as <code>client_config</code>. The client sends only those keys, from its own <code>services: &lt;TAG&gt;:</code> block in <code>unshackle.yaml</code>. When the client sends an identity, the server drops its own value for each of those keys, so the two identities never mix. A mapping (such as <code>esn_map</code>) merges the client's entries over the server's. A client entry replaces a server entry with the same key, also when the server's key is a number. The server keeps these values in the remote session's memory only.</li> </ul> <p>A service can also offer an option that builds the remote session on the server's own device and identity, for the quality that device reaches. The session then makes no live licence at all: each content key comes from the server vault or the client's own vaults, and a content key that no vault holds stops the download with an error. The create response sets <code>server_device</code> to <code>true</code> for such a remote session. The service then uses the server's own config: the client's identity values do not apply. The client reads the server vault only when the API key has the <code>server_vault</code> grant (or <code>server_cdm</code>); without it, the client reads only its own vaults. The login tokens of such a remote session hold the server's device identity, so the server keeps them: <code>DELETE</code> returns no cache files, and the HTTP session headers and <code>track.data</code> lose their secret-looking keys, as for a server login.</p> <p>The server vault in a session your device licenses</p> <p>With the <code>server_vault</code> grant (or <code>server_cdm</code>) on the API key, a remote session that your own device licenses still takes content keys from the server vault. The server tries the vault first. A track that no server vault holds goes back to your device. See <code>server_vault</code>.</p>"},{"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 and when a <code>titles</code> or <code>tracks</code> request ends. A remote session does not expire while a request works on it Max concurrent sessions 100 default Oldest (least recently used) is evicted when full. A remote session that a request works on goes last 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. A remote session that uses a server account (<code>serve.server_accounts</code>) gets a persistent per-account cache instead, so the account's tokens outlive the remote session. The server and the client both refuse a forwarded cache file that is not JSON or that names a type other than a date or time, and the service then authenticates again.</li> <li>A tunnel belongs to its API key. The server accepts <code>tunnel:&lt;id&gt;</code> only from the API key that opened the tunnel. Its SOCKS5 proxy listens on loopback only, and it needs a username and password for that tunnel, so a raw <code>socks5h://127.0.0.1:&lt;port&gt;</code> proxy from a client fails.</li> <li>Only the client dials. The server ignores a request from the client to open a connection, so a tunnel never gives a client access to the server's network.</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/tunnel</code> WebSocket that relays the connections of a <code>tunnel:&lt;id&gt;</code> proxy to the client; <code>?id=</code> reconnects <code>GET</code> <code>/api/tunnel/check?id=</code> Exit IP address and lookup time through the caller's tunnel, for <code>unshackle tunnel-test</code> <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}/segment_filter</code> Unwanted HLS segment URIs for one track (ads, bumpers) <code>POST</code> <code>/api/session/{id}/samples</code> Decrypt the cbcs samples of a track the service decrypts itself <code>POST</code> <code>/api/session/{id}/license</code> DRM licensing (proxy or server CDM) <code>POST</code> <code>/api/session/{id}/keys/bad</code> Report a server-vault content key that did not decrypt <code>GET</code> <code>/api/session/{id}/logs</code> Drain the service's server-side log output <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>server_cdm</code> (<code>false</code> when the user picked the local CDM), <code>cdm_type</code>, <code>cdm_security_level</code>, <code>cdm_relay</code> (<code>true</code> when the client answers CDM calls), <code>cdm_system_id</code> and <code>cdm_device_type</code> (Widevine only), <code>service_config</code> (the identity config keys the service lists in <code>client_config</code>), <code>client</code> (a freeform identity object the dashboard shows as sent), and the track-selection hints <code>range_</code>, <code>vcodec</code>, <code>quality</code>, <code>best_available</code>, <code>generate_dv</code>, plus arbitrary service CLI options (<code>additionalProperties: true</code>).</p> <p><code>dl_params</code> holds the <code>dl</code> track selection: <code>lang</code>, <code>v_lang</code>, <code>a_lang</code> and <code>s_lang</code> (arrays of language strings), <code>acodec</code> (an array of audio codec names, such as <code>EC3</code>), and <code>forced_subs</code> and <code>exact_lang</code> (booleans). The server gives these values to the service in <code>ctx.parent.params</code>, never as service options, so a service option with the same name, such as an own <code>--lang</code>, does not get them. The server uses the <code>dl</code> default for each absent or malformed value: <code>lang</code> is <code>[\"orig\"]</code>, <code>v_lang</code>, <code>a_lang</code> and <code>acodec</code> are <code>[]</code>, and <code>forced_subs</code> and <code>exact_lang</code> are <code>false</code>. The server drops an unknown codec name. An empty array is a valid value and stays empty.</p> <p>The server does not forward the <code>dl</code> mode flags: <code>video_only</code>, <code>audio_only</code>, <code>subs_only</code>, <code>chapters_only</code>, <code>list_</code>, <code>skip_dl</code>, <code>sub_format</code>, <code>no_attachments</code>, <code>audio_description</code>, <code>audio_description_only</code> and <code>forced_subs_only</code>. A service that reads one of them to skip work fetches more on the server, but the result is the same.</p> <p>In a client-login session (not a server account), the server gives the service the client's <code>profile</code> in <code>ctx.parent.params</code>, the same as a local run with that profile. The profile name keys the service's token cache, so the cache files the client sends and gets back belong to that profile. A service can also use the name to select per-profile entries in the server's service config, such as a per-profile ESN.</p> <p>The response returns before authentication finishes:</p> <pre><code>{ \"session_id\": \"...uuid4...\", \"service\": \"EXAMPLE\", \"status\": \"authenticating\",\n \"server_cdm\": false, \"server_cdm_max_height\": null, \"server_vault\": true, \"server_device\": false }\n</code></pre> <p><code>server_vault</code> tells the client that the server vault serves a remote session its own device licenses. <code>server_device</code> tells it that the service runs on the server's device, so every content key comes from a vault.</p> <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>A prompt after authentication (in <code>get_titles()</code>, <code>get_tracks()</code> or licensing) raises <code>RuntimeError</code> at once. The client polls for prompts only during authentication, so no answer can come.</li> <li>A CDM call (<code>InputBridge.request_cdm</code>) works during and after authentication, because the client also polls while its own requests run. A call that no client fetches within 10 seconds fails then, because no client is listening. A fetched call waits 60 seconds for its answer. The call leaves the auth status as it was. An answer never marks the remote session as client-authenticated.</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\": \"pending_input\", \"prompt\": \"...\", \"cdm_call\": { \"op\": \"challenge\", \"drm\": \"widevine\", \"init_data\": \"...\", \"license_type\": \"OFFLINE\", \"privacy_mode\": true, \"service_certificate\": \"...\" } }\n{ \"status\": \"failed\", \"error\": \"...message...\" }\n</code></pre> <p>A <code>cdm_call</code> comes first, in any auth state. The client answers it with a JSON object in <code>response</code>: <code>{\"session\": \"...\", \"challenge\": \"&lt;base64&gt;\"}</code> for <code>challenge</code>, <code>{\"keys\": [{\"kid\", \"type\", \"key\", \"permissions\"}]}</code> for <code>keys</code>, <code>{}</code> for <code>close</code>, or <code>{\"error\": \"...\"}</code> when its CDM refuses. An older client refuses <code>close</code>, and the server ignores that refusal. An answered call stops being pending at once, so a client that polls again straight away does not see it twice.</p> <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>, when the login belongs to the client (<code>client_auth</code>) and the remote session does not run on the server's device, the handler harvests updated cache files from the whole directory tree (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. Each cache key is the file path relative to that directory, with <code>/</code> separators and no <code>.json</code> suffix, which is the <code>Cacher</code> cache key the service reads it with:</p> <pre><code>{\n \"status\": \"ok\",\n \"cache\": {\n \"tokens\": \"...base64(zlib(bytes))...\",\n \"session_web/&lt;sha1&gt;\": \"...base64(zlib(bytes))...\"\n }\n}\n</code></pre> <p>Both sides reject a cache key with a drive letter, a root, a <code>..</code> segment, an empty segment, or more than 8 segments before it becomes a path, so a peer cannot write outside the cache directory. Both sides also refuse a <code>cache</code> map with more than 64 entries. The server skips a cache key it cannot write, such as one that names an existing file as a directory, and logs a warning.</p>"},{"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 the server's <code>timeout</code> from <code>remote_services</code> (default 120s) as the read timeout, 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>. A <code>200</code> body with <code>\"status\": \"error\"</code> is also fatal (see the heartbeat below).</li> <li>Heartbeat. The <code>titles</code>, <code>tracks</code> and <code>license</code> routes send a newline every 30s while the service works. The read timeout starts again at each byte, so a slow request stays open for as long as the server works on it, and a reverse proxy does not close it as idle. A route that answers within 30s sends the usual response. After 30s the status is already <code>200</code>, so a failure after that time arrives as the usual error body with status <code>200</code>. Your client must check <code>status</code> in the body. JSON parsers ignore the leading newlines. The server does not gzip-compress a heartbeat response, because gzip output cannot start before the body is ready.</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_cookie_jar</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 at ...\\\"</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>&lt;clone&gt;/unshackle/unshackle.yaml</code> (a <code>uv</code> tool install: <code>.../site-packages/unshackle/unshackle.yaml</code>) 2 The parent of the package folder <code>&lt;clone&gt;/unshackle.yaml</code> (a <code>uv</code> tool install: <code>.../site-packages/unshackle.yaml</code>) 3 Your OS user-config directory see the table below <p>Where the file belongs depends on how you installed unshackle:</p> <ul> <li>Git clone (recommended). Keep the file at <code>unshackle/unshackle.yaml</code> inside the clone, which is location 1. <code>unshackle setup</code> writes a new config there, and it stays with the clone when you update it.</li> <li><code>uv</code> tool install. Use location 3, your per-user config directory. A <code>uv</code> tool upgrade replaces the package folder, so a file at location 1 or 2 is lost. <code>unshackle setup</code> writes a new config there.</li> </ul> <p>The path of the per-user config directory 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-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> in the <code>unshackle</code> package folder (location 1 above):</p> <ul> <li>Git clone. That is <code>unshackle/unshackle.yaml</code> in the clone, which is the correct place.</li> <li><code>uv</code> tool install. A tool upgrade replaces the package folder and deletes that file. Run <code>unshackle setup</code> first, which writes the config to your user config directory, or make the file there yourself. Then <code>unshackle cfg</code> writes to it.</li> </ul> <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 the install script, the <code>unshackle setup</code> command, the Python version unshackle needs, and the external command-line tools it expects to find.</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/#install-from-a-git-clone-recommended","title":"Install from a git clone (recommended)","text":"<p>A git clone with the install script is the recommended way to install unshackle. A clone keeps unshackle, its external tools, its config, its data folders, and your services together in one folder that you can see.</p> <p>The repository has an install script for Linux (<code>install.sh</code>) and for Windows (<code>install.bat</code>). The script installs <code>uv</code> if it is not found, installs unshackle, and then runs <code>unshackle setup</code>.</p> LinuxWindows <pre><code>git clone https://github.com/unshackle-dl/unshackle.git\ncd unshackle\nsh install.sh\n</code></pre> <pre><code>git clone https://github.com/unshackle-dl/unshackle.git\ncd unshackle\n.\\install.bat\n</code></pre> <p>In a clone, the script runs <code>uv sync</code> and then <code>uv run unshackle setup</code>. The last lines of setup tell you to check your tools with <code>uv run unshackle env check</code>. Run unshackle from the clone with <code>uv run unshackle ...</code>.</p> <p>To install without a clone, see Advanced: install as a uv tool.</p>"},{"location":"getting-started/installation/#what-unshackle-setup-does","title":"What <code>unshackle setup</code> does","text":"<p><code>unshackle setup</code> prepares a new installation. The install script runs it for you, and you can run it yourself at any time:</p> From a cloneInstalled as a uv tool <pre><code>uv run unshackle setup\n</code></pre> <pre><code>unshackle setup\n</code></pre> <p>The command does these steps:</p> <ol> <li>It shows which external tools are missing, and where to get the ones that it cannot download.</li> <li>It asks once for each tool or group of tools to download. The required tools come first. shaka-packager and <code>mp4decrypt</code> share one DRM question, so <code>mp4decrypt</code> comes with the required tools, but <code>env check</code> still shows it as optional. The HDR and subtitle groups are optional. The prompts show the version that setup downloads. On Windows, the subtitle question also shows the download size of CCExtractor, which is much larger than the other tools. It puts the downloads in a <code>binaries</code> folder (see Where setup puts files).</li> <li>If no <code>unshackle.yaml</code> exists, it asks for a downloads folder and writes a minimal config file.</li> <li>It makes the data folders for cookies, WVDs, PRDs, and services.</li> <li>It asks for <code>.wvd</code> and <code>.prd</code> devices to import. You can give a file or a folder of devices, and it asks again until you give an empty answer. It validates each file, copies it into the WVDs or PRDs folder, and prints one line for each file. If setup wrote a new config in this run, it sets <code>cdm.default</code> to the imported device. If you imported more than one, it asks which one is the default.</li> <li>It prints a summary of the tools that it found. If it wrote a config, it gives the path of that config and a link to the configuration reference. Then it tells you to run <code>env check</code> next.</li> </ol> <p>You can run the command again. It skips the tools that it finds and never overwrites an existing config.</p> <p>Not every tool has a download</p> <p>Setup downloads tools only on Linux and Windows, and only when the tool has a portable build for your system. For other tools, setup prints where to get them, for example a package manager. On macOS, setup downloads nothing and prints these links for each missing tool.</p> <p>On Linux, setup cannot download MKVToolNix, which is a required tool. Install the <code>mkvtoolnix</code> package with your package manager (for example <code>apt</code>, <code>dnf</code>, or <code>pacman</code>).</p> <p>CCExtractor on Linux needs FUSE</p> <p>On Linux, setup downloads CCExtractor as an AppImage, which needs FUSE to run. Setup runs the AppImage once after the download. If it does not run, setup removes it and prints the manual install link. Install FUSE with your package manager and run setup again, or install the <code>ccextractor</code> package instead.</p>"},{"location":"getting-started/installation/#where-setup-puts-files","title":"Where setup puts files","text":"Item From a git clone From a <code>uv</code> tool install External tools <code>unshackle/binaries</code> in the clone <code>binaries</code> in the user data directory New config (<code>unshackle.yaml</code>) <code>unshackle/unshackle.yaml</code> in the clone The user config directory Data folders (cookies, WVDs, PRDs, cache, logs, services, temp) The default folders in the clone The user data directory Downloads The folder that you give at the prompt The folder that you give at the prompt <p>On Windows, CCExtractor and its libraries go into their own <code>ccextractor</code> subfolder of the tools folder.</p> <p>On Linux, the user data directory is usually <code>~/.local/share/unshackle</code> and the user config directory is usually <code>~/.config/unshackle</code>. On Windows, both are <code>%LOCALAPPDATA%\\unshackle</code>. Run <code>uv run unshackle env info</code> to see the paths that unshackle uses. Its <code>User_Binaries</code> row shows the <code>binaries</code> folder in the user data directory.</p> <p>Setup writes a new config only when it finds no <code>unshackle.yaml</code> in any of the config locations. It keeps an existing config where it is. In a clone, the new config sets only <code>directories.downloads</code>, so the data folders stay at their defaults in the clone.</p> <p>A <code>uv</code> tool upgrade replaces the package folder. For a <code>uv</code> tool install, setup puts the tools in the user data directory and writes a <code>directories</code> block that moves the data folders there, so an upgrade keeps them. If an existing config keeps data folders inside the package of a <code>uv</code> tool install, setup shows a warning and prints the <code>directories</code> lines to add.</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-by-hand","title":"Installing by hand","text":"<p>If you do not use the install script, install unshackle with <code>uv</code> and then run <code>unshackle setup</code>, or install the external tools yourself.</p>"},{"location":"getting-started/installation/#running-from-a-clone","title":"Running from a clone","text":"<p>Use <code>uv run</code> inside the clone. It keeps the project's virtual environment active for the duration of the command, so you do not have to activate it yourself. It also installs the dependencies on the first run.</p> Run from a git clone<pre><code>git clone https://github.com/unshackle-dl/unshackle.git\ncd unshackle\nuv run unshackle setup\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>"},{"location":"getting-started/installation/#advanced-install-as-a-uv-tool","title":"Advanced: install as a uv tool","text":"<p>This way is for users who know <code>uv</code> tools and want the <code>unshackle</code> command on their <code>PATH</code> without a clone.</p> <p>Where a uv tool install keeps files</p> <p><code>uv tool install</code> puts unshackle into the tool folder of <code>uv</code>, not into a folder that you choose. <code>unshackle setup</code> therefore puts the external tools, the config, and the data folders in your user data and config directories (see Where setup puts files). A git clone is the easier setup: its tools, config, data, and services stay in one folder that you can see. On the first run from a <code>uv</code> tool install, <code>unshackle setup</code> tells you this and asks if you want to continue.</p> <p>Install the tool and run setup:</p> Install as a uv tool<pre><code>uv tool install git+https://github.com/unshackle-dl/unshackle.git\nunshackle setup\n</code></pre> <p>The install scripts also do this when you run one alone, without a clone: when the script does not find the unshackle <code>pyproject.toml</code> next to it, it runs <code>uv tool install</code> and then <code>unshackle setup</code>. When it finishes, it tells you to open a new terminal, because the <code>PATH</code> change only applies to new terminals. Run <code>unshackle env check</code> there.</p> <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> <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, then in the <code>binaries</code> folder of your user data directory, and then on your system <code>PATH</code>. <code>unshackle setup</code> installs tools into the first folder in a clone and into the second for a <code>uv</code> tool install. Installing a tool system-wide or putting it into one of those folders both work.</p> <p><code>unshackle setup</code> installs the required tools and some optional ones for you. Use the tables below when you install a tool by hand.</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 MP4Box (GPAC) <code>MP4Box</code> Muxing DTS:X Profile 2 (DTS-UHD) and MPEG-H audio 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>, <code>ccextractorwin</code>, <code>ccextractorwinfull</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>MP4Box is only used for DTS:X Profile 2 and MPEG-H</p> <p>Titles with DTS:X Profile 2 (DTS-UHD) or MPEG-H audio mux to MP4; everything else muxes to MKV with <code>mkvmerge</code>. Install with <code>apt install gpac</code>.</p> <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 unshackle can see the tools it depends on.</p>"},{"location":"getting-started/installation/#examine-the-external-dependencies","title":"Examine the external dependencies","text":"<p>The <code>env check</code> subcommand is the first check. It inspects your environment and reports which tools it found:</p> From a cloneInstalled as a uv tool <pre><code>uv run unshackle env check\n</code></pre> <pre><code>unshackle env check\n</code></pre> <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> <p>If a required tool shows as missing, <code>env check</code> tells you to run <code>unshackle setup</code>. You can also install the tool by hand and put it on your <code>PATH</code> (or in one of the <code>binaries</code> folders), then re-run the check.</p> <p><code>unshackle</code> is not found after a uv tool install</p> <p>The bin directory of <code>uv</code> tools is probably not on your <code>PATH</code>. Run <code>uv tool update-shell</code> and open a new terminal.</p>"},{"location":"getting-started/installation/#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>uv run 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>), or let <code>unshackle setup</code> write a first one.</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 that you installed unshackle as Installation describes. The examples use the bare <code>unshackle</code> command. From a git clone, the recommended install, run each one as <code>uv run unshackle ...</code>, for example <code>uv run unshackle env check</code>.</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-run-setup","title":"1. Run setup","text":"<p>unshackle drives several external tools (FFmpeg, MKVToolNix, shaka-packager, and others) to decrypt, repack, and mux media, and it needs a config file. The <code>unshackle setup</code> command prepares both. If you used the install script, setup has already run. You can run it again at any time:</p> <pre><code>unshackle setup\n</code></pre> <p>Setup downloads the missing required tools and, if you agree, groups of optional tools. If no <code>unshackle.yaml</code> exists, it writes a minimal one with your downloads folder. It also makes the data folders and lets you import <code>.wvd</code> and <code>.prd</code> devices, one file or a whole folder at a time. Installation tells you what each step does and where the files go.</p> <p>Then make sure that unshackle finds the tools:</p> <pre><code>unshackle env check\n</code></pre> <p>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>Set up by hand</p> <p>To do these steps yourself, install the tools from the tables in Installation. Then run <code>unshackle env info</code> to see where unshackle looks for <code>unshackle.yaml</code>, and make the file in one of those locations. The configuration guide gives the details.</p>"},{"location":"getting-started/quickstart/#2-check-the-output-template","title":"2. Check the output template","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. The config that setup writes copies <code>tag</code> and <code>output_template</code> from the example config. 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>). If you imported devices during <code>unshackle setup</code>, they are already in place. If setup also wrote your config, it set <code>cdm.default</code> to the device that you chose. Otherwise, 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> <p>unshackle repairs the usual export damage in memory and does not change your file: a missing header line, a byte-order mark, spaces in place of tabs, and rows a text editor broke. unshackle refuses a JSON export. Export the cookies again in Netscape format.</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. A config from <code>unshackle setup</code> uses the folder that you gave at its prompt. Without that setting, the 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>setup</code>: install the external tools and make a first config.</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>Running commands from a clone</p> <p>This page uses the bare <code>unshackle</code> command. From a git clone, the recommended install, run each command as <code>uv run unshackle ...</code>.</p> <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>H264</code>, <code>HEVC</code>/<code>H.265</code>/<code>H265</code>, <code>VC1</code>/<code>VC-1</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>AC-4</code>, <code>OPUS</code>, <code>OGG</code>/<code>VORB</code>/<code>vorbis</code>, <code>DTS</code>, <code>DTSX</code>/<code>DTS-X</code>, <code>ALAC</code>, <code>FLAC</code>, <code>MP3</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>--generate-dv</code> off With <code>-r HYBRID</code>, make Dolby Vision from the HDR10+ metadata when a title has no Dolby Vision track. Needs <code>hdr10plus_tool</code>. See Dolby Vision from HDR10+. <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. With <code>--all-drm</code>, also when one DRM system does not license. <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>-fso</code>, <code>--forced-subs-only</code> off Keep only forced subtitle tracks; drop the other subtitles. Implies <code>-fs</code>. <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 A tag without a region selects only the variant it means and never falls back to another: <code>-l es</code> does not select <code>es-419</code>. A tag with a region, such as <code>es-419</code>, is always exact. 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>--latest-episodes N</code> Download only the N most recent episodes. <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.</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> <code>-nt</code>, <code>--no-attachments</code> (cover art, subtitle fonts, and files the service attaches) Flag Description <code>-ad</code>, <code>--audio-description</code> Include descriptive (audio-description) tracks. <code>-ado</code>, <code>--audio-description-only</code> Keep only descriptive (audio-description) tracks; drop the standard audio. Does not need <code>-ad</code>. <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 video tracks that share a height, range, and codec into one file, so only language varies inside a 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>--sample</code> Download a short sample and write it with a <code>SAMPLE</code> tag on the filename in a <code>Sample</code> folder inside the output folder. Bare <code>--sample</code> = 60 seconds from 2 minutes in; <code>--sample 0-60</code> = a custom window in seconds. <code>--include-sample</code> Download the full title, then also cut a 60 second sample from each muxed file into a <code>Sample</code> folder next to it. <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-scripts. <code>--no-postscript</code> Run no post-script for this run, neither the configured ones nor <code>--postscript</code>."},{"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>--cdm &lt;name&gt;</code> Use the named CDM device from the <code>cdm</code> config mapping for this run, ignoring the service/default mapping. Over <code>--remote</code>, that device licenses the remote session, not the server CDM. <code>--skip-dl</code> Skip the download but still retrieve keys. <code>--all-drm</code> License each track with both Widevine and PlayReady. Needs a CDM for each DRM system. Key Vaults are read first; <code>--cdm-only</code> sends a challenge for each system. Not for use with <code>--cdm</code>. <code>--export</code> Export track info and keys to a <code>mediaexport</code> 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 country or location 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>controld:yul</code>). <code>--local-proxy</code> With <code>--remote</code>, send the server's service requests through your machine's own connection. Works with no other proxy option. Check it first with <code>unshackle tunnel-test</code>. See Proxies &amp; VPN. <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>--proxy-download</code> Use a different proxy for all downloads, in the same forms as <code>--proxy</code> (manifest, licence, and auth stay on <code>--proxy</code>). <code>--remote</code> Use a remote unshackle server. <code>--local</code> Use the local service code, also when the config sets <code>remote: true</code>. <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. Also ignored when the service HTTP session carries state a child process cannot rebuild, such as a custom TLS adapter. <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> <p>unshackle logs in to the service before the search. A service that declares a search with no login is the exception: unshackle then reads no cookies and no credentials, and <code>--profile</code> has no effect.</p> Option Description <code>-p</code>, <code>--profile</code> Profile for credentials and cookies. <code>--proxy</code> Proxy URI, country or location code, or <code>provider:region</code> (e.g. <code>controld:ca</code>). <code>--local-proxy</code> With <code>--remote</code>, send the server's search requests through your machine's own connection. Works with no other proxy option. <code>--no-proxy</code> Force-disable all proxy use. <code>--remote</code> Search on a remote unshackle server. The server logs in to the service. unshackle sends it your credentials, cookies and cache for the profile, and saves the cache that the server sends back. A service that searches with no login gets none of them. <code>--local</code> Search with the local service code, also when the config sets <code>remote: true</code> for the service. <code>--server</code> Name a remote server from the <code>remote_services</code> config. <p>Example</p> <pre><code>unshackle search EXAMPLE \"My Show\"\nunshackle search -p myprofile EXAMPLE \"Another Show\"\nunshackle search --proxy nordvpn:ca SERVICE \"query\"\nunshackle search --remote --server my_server 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 can be a <code>mediaexport</code> file from <code>dl --export</code>, an export from an older version of unshackle, or an export from unidl. The file must name the service it came from.</p>"},{"location":"guide/cli-reference/#tunnel-test","title":"<code>tunnel-test</code>","text":"<p>Check <code>--local-proxy</code> before a real <code>--remote</code> run. The command finds the IP address that this machine exits from, opens a tunnel to the server, and makes the server look up its exit IP address through the tunnel. It stops at the first step that fails.</p> <pre><code>unshackle tunnel-test [--server NAME]\n</code></pre> Flag Description <code>--server</code> Name of the remote server from <code>remote_services</code> config, if you configure more than one. <p>See Proxies &amp; VPN.</p>"},{"location":"guide/cli-reference/#setup","title":"<code>setup</code>","text":"<p>Install the external tools and make a first config.</p> <pre><code>unshackle setup\n</code></pre> <p>The command takes no options and asks its questions at the prompt. It shows the missing external tools and downloads the ones you accept. It puts them in a <code>binaries</code> folder, in the package folder of a git clone or in your user data directory for a <code>uv</code> tool install. If no <code>unshackle.yaml</code> exists, it writes a first one: inside the clone, or to your user config directory for a <code>uv</code> tool install. It then makes the data folders and imports <code>.wvd</code> and <code>.prd</code> devices, one file or folder per answer, until you give an empty answer. It ends with a summary of the tools, the path of a config that it wrote, and a pointer to <code>env check</code>. You can run it again: it skips the tools it finds and never overwrites a config. Installation gives the full steps and where each file goes.</p> <p>Example</p> <pre><code>uv run unshackle setup # from a git clone\nunshackle setup # from a uv tool install\n</code></pre>"},{"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. If a config key is set twice in the same block, every command warns with the line numbers of the two copies and uses the later copy. <code>cfg</code> stops without a change.</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. If a required tool is missing, it tells you to run <code>unshackle setup</code>.</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>. This updates the clones on disk. A server that is already running reloads the changed services through <code>POST /api/maintenance/refresh-services</code> or <code>serve.services_refresh_interval</code> instead.</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>, <code>--latest-episodes</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>/<code>--latest-episodes</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>). unshackle applies the fallback to each range and codec on its own. A service that crops only its HDR10 tracks therefore keeps its <code>3840\u00d71920</code> HDR10 track, even when another range has an exact <code>2160</code> height match.</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, and with <code>--all-drm</code> a DRM system that does not license. <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> <code>LCEVC</code> <code>LCEVC</code> <p><code>H264</code> and <code>H265</code> are aliases of <code>AVC</code> and <code>HEVC</code>.</p> <p>An LCEVC (MPEG-5 Part 2) track only adds detail on top of its base video track and cannot play alone, so unshackle selects it only when you ask for it with <code>-v LCEVC</code>.</p> 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><code>--list</code> labels a track that carries a second format as <code>&lt;range&gt;+&lt;format&gt;</code>:</p> <ul> <li>The first part is the range that <code>-r</code> selects the track by.</li> <li>The second part is the format that the track also carries.</li> <li>The <code>+</code> only joins the two parts. unshackle writes HDR10+ as <code>HDR10P</code>, so <code>HDR10+DV</code> is HDR10 with Dolby Vision, not HDR10+ with Dolby Vision.</li> </ul> Label Track Selected by <code>DV+HDR10P</code> A Dolby Vision track that also carries HDR10+ <code>-r DV</code> <code>HDR10+DV</code> An HDR10 track whose frames also carry a Dolby Vision profile 8 RPU <code>-r HDR10</code> <code>HDR10P+DV</code> An HDR10+ track whose frames also carry a Dolby Vision profile 8 RPU <code>-r HDR10P</code> <p>The output file of a track with a Dolby Vision profile 8 RPU plays as Dolby Vision on a DV screen.</p> <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, the <code>binaries</code> folder of your user data directory, or your <code>PATH</code>. A hybrid needs a DV track plus an HDR10 or HDR10+ base. With no DV track, the title fails, unless you add <code>--generate-dv</code> (see below). When HDR10+ is present, unshackle prefers it over HDR10 as the base layer. The base must be HEVC; a title whose HDR10/HDR10+ tracks are all in another codec fails before it downloads. If the hybrid step fails for one resolution, unshackle logs an error, skips that resolution and goes on with the other resolutions of the title. When no hybrid file at all was made, the title fails.</p> <p>A track that is <code>DV+HDR10P</code>, <code>HDR10+DV</code> or <code>HDR10P+DV</code> in <code>--list</code> already carries Dolby Vision and an HDR10 or HDR10+ base, so it is already a hybrid. At a resolution that has one, <code>-r HYBRID</code> selects it and muxes it as it is, with no base track and no dovi_tool step. A track that carries HDR10+ comes first, then the highest bitrate (the lowest with <code>--worst</code>). The other resolutions get a hybrid that unshackle makes.</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/#dolby-vision-from-hdr10","title":"Dolby Vision from HDR10+","text":"<p>When a title has HDR10+ but no DV track, <code>-r HYBRID --generate-dv</code> makes a Dolby Vision Profile 8.1 track from the HDR10+ metadata. It needs <code>hdr10plus_tool</code> as well as <code>dovi_tool</code>. When a title has a DV track, unshackle uses that track and ignores the flag. When it has none, the flag also makes unshackle ask the service for its HDR10+ tracks. A track that the service labels HDR10 but that carries HDR10+ metadata also qualifies (see <code>hdr10plus_probe</code>).</p> Generate Dolby Vision from HDR10+, and keep the HDR10+ file too<pre><code>unshackle dl -q 2160 -r HYBRID,HDR10P --generate-dv EXAMPLE '...'\n</code></pre> <p>Each HDR10+ scene becomes one Dolby Vision shot, with its own scene cut and its own Level 1 brightness values (peak and average). unshackle calculates the average itself, as a PQ mean of the HDR10+ brightness distribution without the letterbox bars. A scene with no black pixels keeps its whole frame, so a title that changes aspect ratio is also correct. The <code>dovi_tool generate --hdr10plus-json</code> average makes most scenes too bright.</p> <p>The <code>generate_dv_mode</code> setting in <code>unshackle.yaml</code> changes how the average is set: <code>v29</code> (default), <code>v40</code> for the 10-nit floor of studio Dolby Vision, or <code>legacy</code> for the <code>dovi_tool</code> average.</p> <p>Generated Dolby Vision is not studio Dolby Vision</p> <ul> <li>There are no colourist trims (Level 2 and Level 8). The TV does all the tone mapping from the Level 1 values.</li> <li>Dolby Vision does not let the average go below about 2.4 nits (10 nits with <code>generate_dv_mode: v40</code>), so a very dark scene reads a little brighter than its pixels.</li> <li>The HDR10+ tone-mapping curve (Profile B) has no Dolby Vision equivalent. The HDR10+ metadata stays in the file, so an HDR10+ TV still reads it.</li> <li>The result can be no better than the HDR10+ metadata. Profile A metadata is often less reliable than Profile B, and unshackle shows a warning for Profile A.</li> <li>A TV or player that supports both formats almost always picks Dolby Vision. On such a TV, the generated Dolby Vision replaces the original HDR10+. To keep the original, also request <code>HDR10P</code>, as in the example above.</li> </ul> <p>An HDR10 track that a service labels HDR10 but that carries HDR10+ metadata does not convert. Only a track with the <code>HDR10P</code> range does.</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>DTSX</code> <code>DTS-X</code> DTS:X Profile 2 (DTS-UHD) <code>DTSHD</code> <code>DTS-HD</code> DTS-HD High Resolution, Master Audio and Express <code>MPEGH</code> <code>MPEG-H</code> MPEG-H 3D Audio <code>ALAC</code> <code>ALAC</code> Apple Lossless <code>FLAC</code> <code>FLAC</code> FLAC <code>MP3</code> <code>MP3</code> MPEG-1 Audio Layer III <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. An immersive layout such as <code>5.1.4</code> matches on its total number of channels, so <code>-c 10</code> selects it.</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>An exclusion without a region removes every regional form: <code>-es</code> removes <code>es-419</code> and <code>es-ES</code>. An exclusion with a region removes only that variant: <code>-es-419</code> removes only <code>es-419</code>. With <code>--exact-lang</code>, <code>-es</code> removes only the variant <code>es</code> means.</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>A tag without a region asks for the variant it means: <code>pt</code> is Brazilian Portuguese, <code>es</code> is Spanish from Spain, and <code>en</code> is US English. With <code>pt-PT</code> and <code>pt-BR</code> tracks, <code>-l pt</code> selects <code>pt-BR</code>. If the title has no such variant, the tag takes every regional form, so <code>-l es</code> on a title with only <code>es-419</code> selects <code>es-419</code>.</p> <p>A tag with a region asks for that variant only: <code>-l es-419</code> selects <code>es-419</code>, never <code>es-ES</code> or <code>es-MX</code>. If the service has no <code>es-419</code> track, unshackle reports <code>es-419 not found</code> and stops. With <code>--best-available</code>, it continues with the other languages.</p> <p>A track without a region matches only the region its language implies. <code>en</code> is US English and <code>pt</code> is Brazilian Portuguese, so <code>-l en-US</code> accepts a track tagged <code>en</code>, but <code>-l en-GB</code> and <code>-l pt-PT</code> do not accept <code>en</code> or <code>pt</code>. To take any English track, write <code>en</code>.</p> <p><code>--exact-lang</code> turns off that fallback: a tag without a region then selects only the variant it means, so <code>-l es</code> does not select <code>es-419</code>.</p> <p><code>orig</code> is the title language that the service gives. It selects that exact variant first, so a <code>fr-CA</code> title takes <code>fr-CA</code> audio over <code>fr-FR</code>. When the title has no track in that variant, <code>orig</code> takes the closest regional form, unless you pass <code>--exact-lang</code>.</p> <p>An exclusion without a region removes every regional form: <code>-es</code> drops <code>es-ES</code> and <code>es-419</code>. See the exclusion rules for <code>--exact-lang</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>-fso</code> / <code>--forced-subs-only</code>: keep only the forced subtitle tracks and drop every other subtitle (implies <code>-fs</code>). <code>--s-lang</code> and <code>-fsl</code> still select the languages.</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>--latest-episodes N</code> Download only the N most recent episodes. The newest episodes can come from more than one season. A split episode counts as one episode, and all its parts download. <code>--list-titles</code> List every title the service returned, then stop. <code>-w</code>, <code>--latest-episode</code> and <code>--latest-episodes</code> are not applied to this listing. <p>When <code>--latest-episode</code> or <code>--latest-episodes</code> is set, <code>-w</code> has no effect.</p> Grab just the newest episode<pre><code>unshackle dl --latest-episode EXAMPLE 81234567\n</code></pre> Grab the three newest episodes<pre><code>unshackle dl --latest-episodes 3 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> <li><code>-nt</code> / <code>--no-attachments</code> (cover art, subtitle fonts, and files the service attaches)</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>-ado</code> / <code>--audio-description-only</code>: keep only the descriptive tracks and drop the standard audio. It does not need <code>-ad</code>. Add <code>-A</code> to download no video or subtitles.</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> <p>The <code>-only</code> kind flags</p> <p><code>-ado</code> and <code>-fso</code> each keep one kind of track inside its track type. They do not drop the other track types: <code>-ado</code> still downloads the video, and <code>-fso</code> still downloads video and audio. Add <code>-A</code> or <code>-S</code> for that.</p> <ul> <li>The language flags still apply. With the default <code>-l orig</code>, <code>-ado</code> fails when the descriptive track is not in the original language. Select the language with <code>-al</code>.</li> <li>A flag that drops the same tracks is an error, for example <code>-ado</code> with <code>--no-audio</code> or <code>-fso</code> with <code>-A</code>.</li> <li>A title with no track of that kind stops a run of one title. A run of more than one title skips that title with a warning and continues.</li> <li>unshackle reads the kind from the manifest or from the service. A track that neither of them marks as descriptive or forced does not match.</li> </ul> Audio description only, in English<pre><code>unshackle dl -A -ado -al en EXAMPLE 81234567\n</code></pre> 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> and <code>--latest-episodes</code> are not applied to this listing. <code>--skip-dl</code> Skip downloading but still acquire the decryption keys. <code>--all-drm</code> License each track with both Widevine and PlayReady. See Widevine and PlayReady on the same title. 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>--sample</code> Download a short sample: 60 seconds from 2 minutes in, or <code>--sample START-END</code> for a window in seconds. - <code>--include-sample</code> Download the full title, then also cut a 60 second sample from each muxed file into a <code>Sample</code> folder. - <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><code>--sample</code> needs a segmented track</p> <p><code>--sample</code> downloads only the segments that hold the window, and <code>mkvmerge</code> cuts the output to the window. The cut starts at the first video keyframe in the window, so a sample can be some seconds short. unshackle downloads each subtitle track in full and then keeps only the cues of the window.</p> <p>The run stops before the download starts in two conditions: a service gives a video or audio track as one file with no segments and no segment index, or the title ends before the window starts.</p> <p>A sidecar subtitle file with <code>sidecar_format: original</code> is not trimmed. It holds the segments around the window, or the whole file when the track is one file.</p> <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> post-script operates under <code>--no-mux</code>, because that run writes no muxed output. A <code>failure</code> post-script 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><code>--no-postscript</code> operates the run with no post-script at all. It silences the <code>post_scripts</code> config and <code>--postscript</code> together, for every event and mode.</p> Skip the uploader for one run<pre><code>unshackle dl --no-postscript EXAMPLE 81234567\n</code></pre> <p>For post-scripts that continue across runs, for the <code>season</code> and <code>run</code> modes, for <code>failure</code> post-scripts and for the full variable list, see Post-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 country or location code (resolved through your configured proxy providers), or a <code>provider:region</code> form. See Proxies &amp; VPN for the exact grammar.</p> Proxy forms<pre><code>unshackle dl --proxy us EXAMPLE 81234567\nunshackle dl --proxy nordvpn:ca EXAMPLE 81234567\nunshackle dl --proxy controld:yul EXAMPLE 81234567\nunshackle dl --proxy 'http://user:pass@host:8080' EXAMPLE 81234567\n</code></pre> <p>Three 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> <li><code>--proxy-download</code>: use a different proxy for all downloads. The manifest, license, and authentication requests still go through <code>--proxy</code>. Takes the same forms as <code>--proxy</code>.</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 the per-track worker count at <code>--workers</code>, reduce it when the CDN returns errors, then raise it again while the extra workers add measured throughput. The count never goes above <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 a per-job budget, which extra processes cannot share, so the download stays in a single process. Also ignored when the service HTTP session carries state a child process cannot rebuild, such as a custom TLS adapter. The download stays in a single process instead of running with the wrong settings. 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). Over a <code>server_cdm</code> remote session the flag does not reach the server, whose vault shortcut still runs; it only skips the client's decode check on a server key.</li> <li><code>--cdm &lt;name&gt;</code>: use the named CDM device for this run, ignoring the <code>cdm</code> config mapping (including its quality and Widevine/PlayReady sub-entries). Over <code>--remote</code>, that device licenses the remote session, not the server CDM.</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 <code>mediaexport</code> JSON file into the configured exports directory. It holds the manifest, the DRM init data, the content keys, the KIDs of each track and the title metadata for each title. <code>unshackle import</code> reads it to reconstruct a download later, and gives each track only the content keys for its KIDs. The importer also reads the older unshackle <code>version: 2</code> files and unidl's own export files.</p> Export track info and keys<pre><code>unshackle dl --skip-dl --export EXAMPLE 81234567\n</code></pre> <p>Add <code>--all-drm</code> to get the content keys of each DRM system the title offers. The export then holds the DRM init data of both. A Key Vault that has a content key stops the challenge for its KID; add <code>--cdm-only</code> to send a challenge for each DRM system.</p> License with Widevine and PlayReady, no download<pre><code>unshackle dl --skip-dl --all-drm --export EXAMPLE 81234567\n</code></pre> <p>The file name tells what the file holds, in the form <code>{title}.{scope}.{resolutions}.{codecs}.{ranges}.{manifests}.{audio}-{SERVICE}.json</code>:</p> Export File name A movie <code>Example.Movie.2024.1080p.h264.sdr.hls.aac2.0-EXAMPLE.json</code> A whole season <code>Example.Show.S01.2160p.h265.sdr.hdr10.dash.dd5.1-EXAMPLE.json</code> Episodes 5 to 9 and 12 <code>Example.Show.S01E05-E09.S01E12.1080p.h264.sdr.dash.aac2.0-EXAMPLE.json</code> <ul> <li>A dot separates each part and each word of the title. The name has no spaces or underscores. It does not follow your <code>output_template</code>: a template with spaces does not change the export name.</li> <li>The scope is <code>S01</code> only when the file holds every episode the service lists for that season. Otherwise it names each run of episodes. Whole seasons in a row become <code>S01-S03</code>. After three parts, <code>+N</code> counts the parts left out. A movie has no scope.</li> <li>The quality parts come from the video and audio tracks selected for the titles in the file. Each value shows once.</li> <li>unshackle renames the file after each write, so the name always matches what the file holds. When a run stops early, the file is complete for the titles it holds.</li> <li>When another file already has the name, unshackle adds <code>-2</code>, <code>-3</code>, and so on. It never writes over another export.</li> </ul> <p>The run logs the file name at the first write, the track and content key counts for each title, and at the end the path and the total counts.</p> <p>The export holds a content key for each track your flags selected and no others. To make a file another person can use, select generously: for example <code>-a AAC,EC3</code> and every language you want them to have. An import can only pick tracks whose key is in the file. A track that another tool exported as a direct file URL is added next to the manifest's own tracks. An export with no manifest, for example a unidl export of whole media files, gets all of its tracks from those URLs. If such an export does not give the title a language, <code>orig</code> has no value: select the languages with <code>-l</code> and <code>-vl</code>.</p> <p>An import uses only the content keys in the file and in your vaults. It never gets a licence from a CDM. When a track needs a content key that neither has, the import stops and names the KID. To fix this, export the title again with that track selected.</p> <p>The export file is a secret</p> <p>It holds the content keys and usually a signed manifest URL. Hand it over on purpose, not by accident.</p> <p>The mediaexport package specifies the <code>mediaexport</code> format and is the reader and writer unshackle uses.</p> <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> <p>An HLS master playlist gives no language for a video track. When the export gives no title language, the video track takes the language of the default audio track. When the master playlist gives no audio language either, the import stops with a message.</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>--latest-episodes N</code> Only the N newest episodes. <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>--no-attachments</code> <code>-nv</code> / <code>-na</code> / <code>-ns</code> / <code>-nc</code> / <code>-nt</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> / <code>--no-postscript</code> Run a command after each output file, or run none. <code>--proxy</code> / <code>--no-proxy</code> / <code>--no-proxy-download</code> / <code>--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>--cdm &lt;name&gt;</code> Pin one CDM device, bypassing the <code>cdm</code> config mapping. <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 six 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 Blowfish stripe none The service gives the per-track key. No CDM, no license server. in-process Blowfish-CBC on every third 2048-byte chunk <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> <p>A pywidevine or pyplayready serve API can operate behind a reverse proxy or a CDN. Refer to Serve APIs behind a proxy.</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, L3 (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, the <code>binaries</code> folder of your user data 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/#license-both-systems-with-all-drm","title":"License both systems with <code>--all-drm</code>","text":"<p>By default a track licenses with one DRM system. <code>--all-drm</code> gets the content keys for Widevine and for PlayReady on each track that offers both. Use it with <code>--skip-dl</code> and <code>--export</code> to keep the content keys and the DRM init data of both systems. The two systems can list different sets of KIDs, and unshackle keeps the content keys of both.</p> <pre><code>unshackle dl --skip-dl --all-drm --export EXAMPLE 81234567\n</code></pre> <ul> <li>The <code>cdm</code> mapping must name a device for each system. A single device name, or <code>--cdm</code>, stops the run with an error that names the missing system.</li> <li>The order of the <code>widevine</code> and <code>playready</code> config keys in the <code>cdm</code> entry sets the order of the two systems, as in a run without the flag. Each track licenses first with the system of the first config key.</li> <li>A Key Vault is read first, as in a run without the flag. A DRM system sends a challenge only for a KID that no Key Vault and no earlier track of the run gave a content key for. When the first system returns all the KIDs of the second, the second sends no challenge.</li> <li>With <code>--cdm-only</code>, unshackle does not read the Key Vaults, and each DRM system sends one challenge for a set of KIDs in a run.</li> <li>A service with a Widevine licence function only gets the PlayReady challenge through that function. If its licence server refuses the challenge, that DRM system does not license.</li> <li>If one DRM system does not license, the title fails. With <code>--best-available</code> unshackle shows a warning and continues, if the other system gave the content key of the track. unshackle does not send the challenge again for the same KIDs in that run.</li> <li>A track gets its DRM systems from the manifest. For a DASH track or a direct URL, unshackle also reads the init segment for a system that the manifest does not carry.</li> <li>With <code>--cdm-only</code>, the service gets a challenge from each DRM system for each set of KIDs. A licence server that limits the request rate can answer <code>429</code>, and unshackle then tries again.</li> </ul> <p>Where <code>--all-drm</code> licenses one system only</p> <ul> <li>A service that gets a different manifest for each DRM system. unshackle shows a warning one time when a track offers one system only.</li> <li>A service that fetched its playback for one DRM system and refuses the other. That system does not license, so the title fails unless you use <code>--best-available</code>.</li> <li>An HLS playlist that changes its <code>EXT-X-KEY</code> entries part-way: only the first set licenses with the second system.</li> <li>A remote session that the server CDM licenses, and <code>unshackle import</code>. unshackle shows a warning and ignores the flag.</li> <li>A remote CDM that stores content keys can answer without a challenge to the service.</li> </ul>"},{"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. Over a <code>server_cdm</code> remote session the server still reads its own vaults; the flag only skips the client's decode check on the key it gets back. <code>--cdm &lt;name&gt;</code> Use the named CDM device for this run instead of the one the <code>cdm</code> config maps for the service. Over <code>--remote</code>, that device licenses the remote session, not the server CDM. <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, <code>.mp4</code> for DTS:X Profile 2 and MPEG-H audio. 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, and they compare languages with the same matching rules as <code>-l</code>: a rule condition of <code>en</code> matches <code>en-US</code>, <code>en-GB</code>, and any other <code>en-*</code> form, but <code>es-419</code> matches only <code>es-419</code>. 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>DTS-X</code> <code>audio_channels</code> Channel layout; bed.LFE.heights when the track has height channels <code>5.1</code>, <code>2.0</code>, <code>5.1.4</code> <code>audio_full</code> Codec + channels combined <code>DDP5.1</code>, <code>DTS-X.5.1.4</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> MP3 <code>.mp3</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>The embedded lyrics are plain text. A service can also save timed lyrics in a file beside the audio, for example <code>08.Get.Lucky.lrc</code> next to <code>08.Get.Lucky.m4a</code>. A music player reads the timed lines from that file. The file also comes back to the client from a remote server.</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>Height channels</p> <p>A track with height channels is named bed.LFE.heights, such as <code>5.1.4</code>.</p>"},{"location":"guide/output-and-naming/#track-names-and-language-tags","title":"Track names and language tags","text":"<p>When the service gives a track no name, unshackle names it with the English name of its language, such as <code>English</code>, <code>Portuguese (Portugal)</code> or <code>Spanish (Latin America)</code>. The name leaves out the region that is the default for the language, so <code>en-US</code> is <code>English</code> and <code>pt-BR</code> is <code>Portuguese</code>, but <code>en-GB</code> is <code>English (United Kingdom)</code>. A name from the service is kept as is. unshackle adds the SDH, CC, Forced or Descriptive label after either name.</p> <p>A subtitle in a language with more than one script gets the script from its region:</p> Service tag Tag in the file Track name <code>zh-TW</code> <code>zh-Hant-TW</code> Chinese (Traditional) <code>zh-HK</code> <code>zh-Hant-HK</code> Chinese (Traditional, Hong Kong) <code>zh-CN</code> <code>zh-Hans-CN</code> Chinese (Simplified) <code>sr-ME</code> <code>sr-Latn-ME</code> Serbian (Latin, Montenegro) <code>zh</code> <code>zh</code> Chinese <p>A tag without a region, such as <code>zh</code>, gets no script because the region is what tells the script. unshackle writes audio tags as the service gives them, because a script applies only to written text. Track selection, <code>--list</code> tags and file names use the service tag.</p> <p>Set <code>muxing.track_names</code> to <code>native</code> to name each track in its own language. The same rules apply to the script and the region:</p> unshackle.yaml<pre><code>muxing:\n track_names: native\n</code></pre> Service tag Track name <code>zh-TW</code> subtitle \u4e2d\u6587\uff08\u7e41\u9ad4\uff09 <code>zh-HK</code> subtitle \u4e2d\u6587\uff08\u7e41\u9ad4\uff0c\u9999\u6e2f\uff09 <code>pt-PT</code> Portugu\u00eas (Portugal) <code>es-419</code> Espa\u00f1ol (Latinoam\u00e9rica) <code>ja-JP</code> \u65e5\u672c\u8a9e <p>Set <code>muxing.track_names</code> to <code>none</code> to leave a track unnamed when the service gives it no name. An SDH, CC, Forced or Descriptive track then has only that label as its name.</p> <p>The option also changes the names in <code>--list</code> and in the <code>track_name</code> field of the REST API.</p> <p>Set <code>muxing.original_label</code> to add a label after the name of each audio and subtitle track in the title's original language. unshackle also sets the Matroska original flag on these tracks, but some players show only the name. MP4 output has no original flag, so there the label is the only marker:</p> unshackle.yaml<pre><code>muxing:\n original_label: \"[Original]\"\n</code></pre> Track Track name Japanese audio, original language Japanese [Original] Japanese SDH subtitle, original language Japanese [Original] (SDH) Korean subtitle Korean <p>The label can be any text, for example <code>\"| Original\"</code> or a label in another language. Put it in quotes: YAML reads an unquoted <code>[Original]</code> as a list, and an unquoted <code>| Original</code> stops the config from loading. unshackle ignores a value that is not text.</p> <p>The label also applies to a name that the service sets, and to audio that a service keeps inside the video file. unshackle does not add the label when the name already contains its words, so a service name <code>Original</code> or <code>Japanese (original)</code> stays as it is.</p> <p>Use an English label with Jellyfin 12</p> <p>Jellyfin 12 adds its own \"Original\" to an original-language audio track from the flag, unless the name already contains the word. It adds none to a subtitle. A label in another language, such as <code>[\uc6d0\uc5b4]</code>, then shows next to Jellyfin's \"Original\".</p> <p>Players that show the language next to the name</p> <p>Some players, such as Jellyfin, show the track name and the language name together. They leave out the language when the name already contains it, so an English name shows once. A native name such as <code>\u65e5\u672c\u8a9e</code> shows next to <code>Japanese</code> in an English interface.</p>"},{"location":"guide/output-and-naming/#dtsx-profile-2-and-mpeg-h-output","title":"DTS:X Profile 2 and MPEG-H output","text":"<p>A title whose audio holds a <code>dtsx</code> or <code>dtsy</code> sample entry (DTS:X Profile 2, DTS-UHD), or an MPEG-H sample entry (<code>mha1</code>, <code>mha2</code>, <code>mhm1</code>, <code>mhm2</code>), muxes to MP4 with MP4Box, because Matroska has no CodecID for it. Without MP4Box installed the mux stops.</p> <p>DTS:X Profile 1 is DTS-HD Master Audio and muxes to MKV as usual.</p> <p>An MP4 title loses:</p> <ul> <li>the forced, hearing-impaired and original track flags</li> <li>attachments, such as subtitle fonts</li> <li>SubStation Alpha (<code>.ass</code>) subtitles</li> <li>container tags (<code>mkvpropedit</code>)</li> </ul> <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/#sample-files","title":"Sample files","text":"<p><code>--sample</code> and <code>--include-sample</code> write a sample into a <code>Sample</code> folder inside the output folder of the title. The sample keeps the filename of the title, with a <code>SAMPLE</code> tag at the end. The tag uses the separator of the output template.</p> A movie with --include-sample<pre><code>Some.Movie.2026.1080p.EXAMPLE.WEB-DL.H.264-TAG/\n\u251c\u2500\u2500 Some.Movie.2026.1080p.EXAMPLE.WEB-DL.H.264-TAG.mkv\n\u2514\u2500\u2500 Sample/\n \u2514\u2500\u2500 Some.Movie.2026.1080p.EXAMPLE.WEB-DL.H.264-TAG.SAMPLE.mkv\n</code></pre> <p>With <code>--sample</code>, the <code>Sample</code> folder holds the only output file. If the run makes no title folder, the <code>Sample</code> folder is in the downloads directory.</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, with the vowel and tone marks of languages such as Thai, Hindi and Bengali. <p>With each value, unshackle first normalises the name to Unicode NFC. A title that a service sends in composed form and in decomposed form gives the same name.</p> <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, Control D, 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>Five 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>--local-proxy</code> With <code>--remote</code>, send the server's service requests through your machine's own connection. Works with no other proxy option. See Send the server's requests through your machine. <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. <code>--proxy-download</code> Use <code>--proxy</code> for the manifest, licence, and authentication, and a different proxy for the downloads. Takes the same forms as <code>--proxy</code>. 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/#-proxy-download","title":"<code>--proxy-download</code>","text":"<p><code>--proxy-download</code> is the middle ground: the manifest, licence, and authentication go through <code>--proxy</code>, and the downloads go through a second proxy. Use it when one proxy passes the geo-check and another one is faster for bulk traffic. The value takes the same forms as <code>--proxy</code>, so a country code or <code>provider:region</code> resolves against the same providers.</p> Manifest and licence over NordVPN, downloads over Windscribe<pre><code>unshackle dl --proxy nordvpn:us --proxy-download windscribevpn:us EXAMPLE 10a1234\n</code></pre> <p><code>--no-proxy</code> and <code>--no-proxy-download</code> both override <code>--proxy-download</code>. The same region warning applies: if the service ties segment delivery to the manifest region, keep both proxies in that region.</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. A <code>host:port</code> value such as <code>localhost:8080</code> is also an explicit proxy.</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>, or <code>us1234</code>. unshackle asks each loaded proxy provider in order and uses the first proxy any of them returns. A bare city query such as <code>us:seattle</code> does not work: unshackle reads <code>us</code> as a proxy provider name. Use the proxy provider prefix, for example <code>nordvpn:us:seattle</code>. If no proxy provider has a proxy for the query, unshackle stops with <code>No proxy provider had a proxy for &lt;query&gt;</code> and does not continue without a proxy.</li> </ol> <p>unshackle compares the query against a region grammar: a country or location code of two to four letters, with an optional <code>_code</code> part (<code>res_yyz</code>), then an optional server number and/or a <code>:city</code> or <code>-city</code> part, and an optional <code>@</code> network part (see Choose a server network). A <code>host:port</code> value never matches. It then lowercases the query and hands it to the proxy provider. Its section below gives the exact forms each proxy provider accepts.</p> <p>A Control D resolver, <code>controld://&lt;resolver&gt;@dns.controld.com</code>, is a fourth form. A <code>--remote</code> client sends it to a server in place of a proxy URI, and the server starts a forwarder for it. See Control D.</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. It uses that same order for bare-query resolution:</p> <ol> <li>Basic is always first, so your own proxies win.</li> <li>The other proxy providers follow in the order of their keys under <code>proxy_providers</code> in <code>unshackle.yaml</code>. Proxy providers that load without a config key, such as Hola, come after the listed ones in this default order: ExpressVPN \u2192 NordVPN \u2192 Proton VPN \u2192 Surfshark \u2192 Windscribe \u2192 Gluetun \u2192 Hola</li> <li>Control D is always last.</li> </ol> <p>So if you list <code>windscribevpn</code> above <code>nordvpn</code> and use <code>--proxy us</code>, a <code>us</code> entry in your Basic config answers first, then Windscribe. To skip ahead to a specific proxy provider, prefix the query (<code>--proxy nordvpn:us</code>).</p> <p>If a proxy provider cannot load, for example because its server list cannot be fetched or its config is not valid, unshackle logs a warning and continues with the other proxy providers. A bare query skips the proxy provider that did not load. A query that names it, such as <code>--proxy nordvpn:us</code>, fails and shows the reason it did not load.</p> <p>A bare region reaches Control D last</p> <p>unshackle asks Control D for a bare region such as <code>--proxy us</code> only when no other loaded proxy provider has a proxy for it. Hola loads automatically when the <code>hola-proxy</code> binary is on your <code>PATH</code>, and it comes before Control D. When Control D answers, it changes your Control D account: it points a profile at that country, and it can create an <code>unshackle-us</code> profile and endpoint. The geofence auto-proxy uses the same order. To use Control D directly, prefix the query (<code>--proxy controld: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>NordVPN and Windscribe name the server, its IP, and its network, for example <code>Using NordVPN Proxy fr1154.proxy.nordvpn.com (187.14.108.15, Datacamp Limited)</code>. Surfshark prints the same line when the query has an <code>@</code> part.</li> <li>Other proxy providers log the resolved proxy URL.</li> </ul>"},{"location":"guide/proxies-and-vpn/#choose-a-server-network","title":"Choose a server network","text":"<p>A VPN rents its servers from different hosting companies, and each hosting company has its own network. A service often blocks all the IPs of one network, so a random server in a country works on one run and fails on the next. NordVPN, Surfshark and Windscribe accept an <code>@</code> part after the query that keeps or skips a network, or one server IP:</p> Query Meaning <code>nordvpn:ca@datacamp</code> A random Canadian server on a network whose name contains <code>datacamp</code>. <code>nordvpn:ca@-datacamp</code> A random Canadian server on any other network. <code>windscribevpn:fr:paris@m247</code> A random Paris server on an M247 network. <code>nordvpn:fr@187.14.108.15</code> The French server with that IP. Any of the three proxy providers takes an IP. <code>surfsharkvpn:fr-bod@-195.86.24.103</code> A random Bordeaux server IP other than that one. <p>A network name matches without case, spaces or punctuation, and part of the name is enough. Read the name or IP to use from the connection line of an earlier run. To keep a server that works, run again with <code>@&lt;ip&gt;</code>. When a server is blocked, run again with <code>@-&lt;name&gt;</code> to skip its network.</p> <p>unshackle gets the network of each server IP from the Team Cymru whois service (<code>whois.cymru.com</code>, TCP port 43). The NordVPN and Windscribe connection line uses it too, on every run. If that port is blocked, a query with an <code>@</code> part fails, and the connection line shows no network name. unshackle tries the port once per run. An <code>@</code> part skips <code>server_map</code>, except on Surfshark, where it selects from the servers of the mapped cluster. A query that already names one server, such as <code>nordvpn:us1234</code>, does not accept an <code>@</code> part. An IP selector needs no whois lookup. On NordVPN it searches every server in the country, not only the recommended ones, so a pinned server still works when it is busy.</p> <p>To keep a selector for every run, put it in <code>server_map</code>. A value that starts with <code>-</code> or <code>@</code> applies to the region of its config key, and a value with <code>@</code> after a server name is a whole query. A selector in <code>--proxy</code> wins over one in <code>server_map</code>.</p> unshackle.yaml<pre><code>proxy_providers:\n nordvpn:\n server_map:\n ca: -datacamp # --proxy nordvpn:ca means nordvpn:ca@-datacamp\n windscribevpn:\n server_map:\n fr:paris: \"@m247\" # quote a value that starts with @\n surfsharkvpn:\n server_map:\n fr: fr-bod@195.86.24.103 # always this one server\n</code></pre> <p>Not every proxy provider</p> <p>Only NordVPN, Surfshark and Windscribe read the <code>@</code> part. With a bare query such as <code>--proxy fr@datacamp</code>, the other proxy providers have no proxy for it, so prefix the query to be sure which proxy provider answers.</p>"},{"location":"guide/proxies-and-vpn/#exit-check","title":"Exit check","text":"<p>Before the service sends a request, unshackle looks up the proxy exit IP through the proxy. The service stops with <code>Proxy check failed</code> in two cases:</p> <ul> <li>No IP lookup gets through the proxy. The proxy is down, or it refused the connection.</li> <li>The proxy exit IP is the same as your own IP, so traffic does not go through the proxy.</li> </ul> <p>unshackle tries each geolocation API in turn, and a 429 moves on to the next one. If at least one API answers through the proxy but none of them gives an IP, the proxy passes the check without the IP comparison. unshackle does not compare the exit country with the region you asked for, because geolocation data can be out of date.</p> <p>Over the REST API, the server returns this failure to the client as <code>INVALID_PROXY</code>.</p>"},{"location":"guide/proxies-and-vpn/#system-proxy-and-environment-variables","title":"System proxy and environment variables","text":"<p><code>--proxy</code> takes priority over the <code>HTTP_PROXY</code> and <code>HTTPS_PROXY</code> environment variables and over the Windows system proxy. unshackle still reads a <code>REQUESTS_CA_BUNDLE</code> or <code>CURL_CA_BUNDLE</code> certificate bundle, so a local debugging proxy with its own certificate authority continues to work. Without <code>--proxy</code>, unshackle uses the system proxy.</p>"},{"location":"guide/proxies-and-vpn/#requests-outside-the-proxy","title":"Requests outside the proxy","text":"<p>With a proxy active, unshackle logs a warning when service code sends a request that does not go through the proxy:</p> <pre><code>A request to api.example.com did not go through the proxy, so api.example.com sees your own IP (EXAMPLE/__init__.py:120)\n</code></pre> <p>The host in the message sees your own IP address, and a service can treat that as proxy detection. The request still goes: unshackle only warns. Report the message, with the file and line, to the service maintainer.</p> <p>A request to your own machine or to your local network gives no warning. This includes a private IP address such as <code>192.168.1.50</code>, and a <code>.local</code>, <code>.lan</code> or <code>.home.arpa</code> host name. A request to the <code>host</code> of a remote CDM in <code>remote_cdm</code> also gives no warning. The CDM API sees your own IP, but the service does not.</p> <p>A <code>socks5://</code> proxy makes the DNS lookup of each host on your machine and gives no warning. Use <code>socks5h://</code> to make the proxy do the DNS lookups too.</p>"},{"location":"guide/proxies-and-vpn/#send-the-servers-requests-through-your-machine","title":"Send the server's requests through your machine","text":"<p>With <code>--remote</code>, the server sends the service requests, and they leave from the server's own connection. Add <code>--local-proxy</code> to send them through your machine's connection instead:</p> <pre><code>unshackle dl --remote --local-proxy EXAMPLE 81234567\n</code></pre> <p>A VPN app that covers your whole machine then also covers the server's requests, so the service sees your VPN's IP address. <code>--local-proxy</code> needs <code>--remote</code> (or a service with <code>remote: true</code>), and it works with no other proxy option: unshackle stops if you also give <code>--proxy</code>, <code>--no-proxy</code>, <code>--proxy-download</code> or <code>--no-proxy-download</code>. A proxy option from the <code>dl</code> config defaults does not count: <code>--local-proxy</code> turns it off for the run.</p> <p>A <code>--proxy</code> on <code>localhost</code> or a loopback address, such as the local port of a VPN app, stops a <code>--remote</code> run with <code>That proxy is on your machine, so --remote cannot use it</code>. Connect the VPN app for the whole machine, then use <code>--local-proxy</code> without <code>--proxy</code>.</p>"},{"location":"guide/proxies-and-vpn/#test-it-first","title":"Test it first","text":"<p><code>unshackle tunnel-test</code> checks the route before a real run. Add <code>--server &lt;name&gt;</code> to test a server other than the default one:</p> <pre><code>unshackle tunnel-test\n</code></pre> <p>It does three steps, and it stops at the first one that fails:</p> <ol> <li>It looks up the IP address that your machine exits from.</li> <li>It opens a tunnel to the server.</li> <li>It makes the server look up its exit IP address through the tunnel. That address must be the same as in step 1, or in the same country when one lookup used IPv4 and the other IPv6. It fails when the lookup left from the server's own address. It also shows how long one lookup takes.</li> </ol>"},{"location":"guide/proxies-and-vpn/#how-the-tunnel-works","title":"How the tunnel works","text":"<ol> <li>The client opens a WebSocket on the server, on the same host and port as the other remote session requests. Only a client opens a tunnel. The server never connects to a host for a client, so a tunnel gives no access to the server's network.</li> <li>The server gives the service a SOCKS5 proxy on its loopback address, with a username and password for that tunnel only. Another API key cannot use it.</li> <li>The server sends each connection that the service opens through the tunnel. The client connects to the host and relays the bytes.</li> </ol> <p>The client logs <code>The server sends its requests through your connection on this machine</code>. You do not configure ports: the server picks a free one, and your machine opens none, because the client opens the connection to the server. A NAT router, a firewall, or a Cloudflare tunnel in front of the server does not stop it.</p> <p>The service traffic stays encrypted from the server to the service, so the client relays only encrypted bytes. The client refuses to connect to <code>localhost</code>, and to a host name that resolves only to an address on your machine or local network: loopback, private, link-local, CGNAT (<code>100.64.0.0/10</code>) or multicast. An IP address that the server sends must also be public, and the client closes a connection that reaches one of its own addresses. Other devices on your network that have a public IPv6 address, and your router's public address, are not blocked.</p> <p>Some VPN and proxy apps answer a host name with a synthetic address, for example fake-IP DNS in TUN mode (<code>198.18.0.0/15</code>), and map it back to the real host. The client accepts any such address for a host name, so <code>--local-proxy</code> works with these apps. The client cannot see the real address behind a synthetic one, so it cannot stop a host name that points into your local network.</p> <p>Each request crosses the tunnel twice</p> <p>A request from the server goes to your machine and then to the service, so it takes longer than a request that the server sends directly. The segments do not go through the tunnel: the client downloads them as before.</p> <p>A service that uses a server account does not work with <code>--local-proxy</code>, because the server logs in with its own account. If the tunnel drops, the client connects again, and a new request from the server waits up to 10 seconds for it. A request that was in progress when the tunnel dropped fails. The server closes a tunnel when its client has not connected for 60 seconds, and the client then stops with <code>The tunnel to the server closed</code>. An API key can have 4 tunnels open at once.</p>"},{"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/#control-d","title":"Control D","text":"<p>Control D is a DNS service, not a proxy. It answers the hostnames it redirects with the IP of a transparent proxy in the region you chose, and that proxy relays onwards by SNI. There is no proxy URI to hand to Requests, so this proxy provider runs a small forwarder on loopback: it resolves each connection through your Control D resolver and relays the bytes. Everything downstream (the service session, the downloads, <code>--proxy-download</code>) sees an ordinary HTTP proxy.</p> <p>unshackle picks the region itself, by pointing a profile's default rule at it. A profile holds one region at a time, so unshackle gives each region in use a profile of its own, each with its own endpoint and its own forwarder port. <code>--proxy controld:yyz --proxy-download controld:yul</code> therefore uses two profiles, when two are free: Toronto for the service and Montreal for the downloads. When no second profile is free, the second region moves the first profile (see step 5).</p> <p>Keep both locations in one country. Some CDNs also check the country of the download IP, and refuse a <code>--proxy-download</code> exit in another country with a 403. This applies to every proxy provider.</p> <p><code>unshackle search --proxy controld:ca</code> works the same way as <code>dl</code>.</p>"},{"location":"guide/proxies-and-vpn/#what-you-need","title":"What you need","text":"<ul> <li>A plan with traffic redirection. On the personal plans that is Full Control; Some Control has no redirection, and every redirect fails. The 14-day trial includes it. See Control D's plans for current prices.</li> <li>An API token of type Write. A Read token cannot change a profile's default rule. Create it in the dashboard under API. If you set Allowed IPs on the token, include the address of each machine that runs unshackle with it.</li> </ul> unshackle.yaml<pre><code>proxy_providers:\n controld:\n token: api.xxxxxxxxxxxx # a Write API token, from the Control D dashboard\n</code></pre> <pre><code>unshackle dl --proxy controld:ca EXAMPLE 81234567\n</code></pre> <p>The token is the only required key. You do not need to create a profile or an endpoint, or to give a <code>profile</code> and <code>resolver</code>: unshackle creates an <code>unshackle-&lt;region&gt;</code> profile and endpoint on your account the first time it needs one, and uses it again on the next run. Give <code>profile</code> and <code>resolver</code> only to use a profile that you made yourself (see How unshackle chooses a profile).</p> <p>The returned proxy is HTTP on loopback, <code>http://127.0.0.1:{port}</code>. The log shows the location and a masked resolver ID, for example <code>Using ControlD Proxy (YUL - Montreal): abcd***@dns.controld.com</code>. The locations themselves are read from Control D at startup (107 of them across 68 countries, at the time of writing), so there is nothing to list:</p> Query Meaning <code>ca</code> One of Control D's Canadian locations, at random. <code>yul</code> That exact location, by its code. <code>res_yyz</code> A residential location, by its code. A country pick never uses a residential location, so name it this way. <p>The configuration reference lists every <code>controld</code> config key.</p>"},{"location":"guide/proxies-and-vpn/#how-unshackle-chooses-a-profile","title":"How unshackle chooses a profile","text":"<p>Each region query gets a profile and an endpoint named after it: <code>--proxy controld:ca</code> uses <code>unshackle-ca</code>. For each region, unshackle uses the first match in this list:</p> <ol> <li>A profile that this process already pointed at that region.</li> <li>The endpoint named <code>unshackle-&lt;region&gt;</code> on your account, made by an earlier run.</li> <li> <p>A profile from your config that this process does not use yet. These are optional:</p> unshackle.yaml<pre><code>proxy_providers:\n controld:\n token: api.xxxxxxxxxxxx\n profile: abcd123 # a profile kept for unshackle, and nothing else\n resolver: efgh456 # the resolver ID of an endpoint using that profile\n profiles: # more pairs, in the same shape\n - profile: ijkl789\n resolver: mnop012\n max_profiles: 4 # the most profiles unshackle uses, yours included (default 4)\n</code></pre> <p>The resolver ID is the last part of the endpoint's DoH URL, <code>https://dns.controld.com/&lt;resolver&gt;</code>. You can also give the full URL.</p> </li> <li> <p>A new profile and endpoint named <code>unshackle-&lt;region&gt;</code>, while your config pairs plus the <code>unshackle-*</code> endpoints on the account are fewer than <code>max_profiles</code>. unshackle keeps them for the next run. <code>max_profiles</code> limits only this step: unshackle uses every pair in your config, even more than <code>max_profiles</code>.</p> </li> <li>When no profile is free, a profile moves to the new region, with everything that still uses it. unshackle first moves a profile that this process has not pointed at a region, which another process can still use. Next, it moves the profile that this process pointed at a region first. An <code>unshackle-*</code> profile that moves, and its endpoint, get the new region's name. unshackle logs <code>Every Control D profile is in use; moving profile \u2026 to \u2026</code>, and connections already open keep the old exit until they close.</li> </ol> <p>Because the names live on the account, every unshackle process agrees on them: two runs, or two jobs on a <code>serve</code> instance, that ask for <code>ca</code> both use <code>unshackle-ca</code>. Two processes can still move a profile under each other when they run out of profiles (step 5).</p> <p>unshackle changes only the profiles in your config and the profiles of <code>unshackle-*</code> endpoints. It skips an <code>unshackle-*</code> endpoint whose profile an endpoint without that name also uses, so unshackle never redirects a profile that serves your own devices. Leave the <code>unshackle-*</code> profiles empty: no services, no custom rules. unshackle sets their default rule to <code>REDIRECT</code>, and the Services and Custom Rules tabs stay at zero by design. To remove them, delete the endpoints and profiles in the dashboard. unshackle creates new ones when it next needs them.</p> <p>Business accounts pay per endpoint</p> <p>Personal plans allow an unlimited number of profiles and endpoints. Business plans bill each endpoint every month, so each <code>unshackle-&lt;country&gt;</code> endpoint adds to the bill. On a business account, configure your own pairs, as many as the countries you use at the same time, and set <code>max_profiles</code> to that number. unshackle then never creates a profile.</p> <p>Everything goes through the proxy, including the segments</p> <p>With the default rule redirecting, the whole download leaves through Control D's transparent proxy. Control D serves it on a best-effort basis. Pair it with <code>--no-proxy-download</code> to keep the geo-check on the manifest and the licence while pulling the files over your own connection.</p> <p>The switch is not instant</p> <p>unshackle drops its own DNS cache when it changes region, but Control D's edge may still serve the previous answer for the remainder of the record's TTL.</p> <p>Same machine, same IP, over IPv4</p> <p>Control D authorises its proxies by source IP: the address that queried DNS is the one allowed to use the proxy. The forwarder resolves and connects from the same host, so this holds. Control D also answers a redirected name only to a query over IPv4, so the forwarder asks over IPv4 even on a host with IPv6, and ignores <code>HTTPS_PROXY</code> for these queries.</p> <p>The forwarder refuses a connection to an IP address with a <code>502</code>, because an IP address skips Control D's DNS and connects from your own address. A request that names a host by IP address fails with this proxy provider.</p> <p>With <code>--remote</code>, the server resolves</p> <p>unshackle does not send your API token to a server. For <code>--proxy controld:ca</code> with <code>--remote</code>, unshackle points <code>unshackle-ca</code> at Canada with your token, then sends the server only that endpoint's resolver ID, as <code>controld://&lt;resolver&gt;@dns.controld.com</code>. The server runs its own forwarder with it, from its own address, and needs no Control D configuration. The resolver ID lets anyone who has it use that endpoint's proxy, so treat it as a secret: unshackle masks it in logs and in stored job parameters.</p> <p>The server must run a version of unshackle that knows <code>controld://</code>. An older server rejects it with <code>INVALID_PROXY</code>: <code>Proxy provider 'controld' not found</code> when your API key has <code>server_proxy</code>, else a message that asks for a full proxy URI. A bare region, such as <code>--proxy ca</code>, skips Control D with <code>--remote</code>, because the proxy it gives is on your machine. A service whose accounts the server manages does not accept a proxy from the client, and that includes a Control D resolver.</p>"},{"location":"guide/proxies-and-vpn/#troubleshooting-control-d","title":"Troubleshooting Control D","text":"<p>When the forwarder cannot connect to a host, it answers <code>502 Bad Gateway</code> and gives the reason in brackets. Python-Requests shows it as <code>Tunnel connection failed: 502 Bad Gateway (&lt;reason&gt;)</code>. The forwarder also logs each reason once as a warning, <code>Could not reach &lt;host&gt;:&lt;port&gt;: &lt;reason&gt;</code>, because some HTTP clients do not show the reason.</p> Symptom Cause and fix <code>Proxy check failed</code>, because the exit IP is your own IP. The profile does not redirect. Make sure that the plan includes traffic redirection (Full Control, not Some Control). After a region change, wait for the TTL of the previous answer to end. <code>502 Bad Gateway (Control D returned no A record for \u2026)</code> Control D gave no IPv4 address for that host. <code>502 Bad Gateway (an IP address skips Control D's DNS \u2026)</code> The request names the host by IP address. The forwarder refuses it. See the note on IPv4 above. <code>502 Bad Gateway (Control D sent \u2026 to \u2026, which did not answer: \u2026)</code> Control D gave an address for the host, but the connection to that address failed. This is usually a temporary fault on Control D's network. Try again, or use <code>--no-proxy-download</code> to download without the proxy. <code>502 Bad Gateway (Control D DNS timed out)</code>, <code>(Control D DNS could not be reached \u2026)</code> or <code>(Control D DNS answered HTTP \u2026)</code> unshackle got no answer from Control D's DNS at <code>dns.controld.com</code>. Check the network connection of this machine. An HTTP <code>401</code> or <code>403</code> from <code>api.controld.com</code>. The token is a Read token, or its Allowed IPs do not include this machine. Use a Write token. <code>Control D needs both a profile and a resolver</code> or <code>Control D needs max_profiles of 1 or more</code> at startup. The <code>controld</code> config is not valid. Give <code>profile</code> and <code>resolver</code> together, and a <code>max_profiles</code> of 1 or more. Every run fails until you correct it, also a run that does not use Control D. <code>Could not read Control D's locations</code>. unshackle could not get the location list. It tries again at the next Control D query. A <code>403</code> for the segments only, with <code>--proxy-download</code> in another country. The CDN checks the country of the download IP. Keep <code>--proxy-download</code> in the same country as <code>--proxy</code>."},{"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>Not available with <code>--remote</code></p> <p>Gluetun listens on your machine, so a server on another machine cannot reach it. With <code>--remote</code>, unshackle stops with an error for <code>--proxy gluetun:...</code>, and for any proxy that resolves to <code>localhost</code> or a loopback address, such as a region query that Gluetun answers. Give <code>--remote</code> a proxy the server can reach, or run the service locally. A server on this machine (a <code>remote_services</code> URL on <code>127.0.0.1</code>) can reach a local proxy, so it is exempt.</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. 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). Get both from the Windscribe WireGuard config generator.</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). Surfshark has no numbered servers, so map a Surfshark region to a server name such as <code>us-dal.prod.surfshark.com</code> in <code>server_hostnames</code>.</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, or to a selector (see Choose a server network). 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>nordvpn:us:seattle</code> A recommended server in Seattle. <code>228</code> A NordVPN numeric country ID. <code>nordvpn:us@-datacamp</code> A recommended US server that is not on a Datacamp network. See Choose a server network. <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> <p>The <code>hola-proxy</code> GitHub repository is no longer online, so build the binary with Go. The Go module proxy still has the source for version 1.18.2. <code>go install</code> puts the binary in <code>$(go env GOPATH)/bin</code>, which must be on your <code>PATH</code>.</p> Build hola-proxy, then query a country<pre><code>go install github.com/Snawoot/hola-proxy@v1.18.2\nunshackle 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. While a ban is active, <code>hola-proxy</code> does not stop, so unshackle waits 30 seconds and then reports the ban. 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: region -&gt; server name\n us: us-dal\n us:seattle: us-sea\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 a server per region, or holds a selector (see Choose a server network). Give the server name from Surfshark's server list, for example <code>us-dal</code>. A full hostname such as <code>us-dal.prod.surfshark.com</code> also works. Surfshark does not use numeric server IDs. unshackle ignores a numeric or empty value and logs a warning. A <code>us:seattle</code> entry applies only to that city query, and it does not fall back to the <code>us</code> entry.</p> <p>Query forms:</p> Query Meaning <code>surfsharkvpn:us</code> A random US server. <code>uk</code> and <code>gb</code> both give a UK server. <code>surfsharkvpn:us-bos</code> A specific server from Surfshark's server list. <code>surfsharkvpn:us:seattle</code> A random server in Seattle. <code>surfsharkvpn:fr-bod@datacamp</code> A random Bordeaux server IP on a Datacamp network. See Choose a server network. <code>surfsharkvpn:fr-bod@195.86.24.103</code> The server at that IP, in the <code>fr-bod</code> cluster. <p>unshackle ignores case, spaces, hyphens and accents in a city name, so <code>us:new-york</code> matches New York. A city also matches the start of a longer name: <code>de:frankfurt</code> matches Frankfurt am Main. A bare <code>us</code> also reaches Surfshark. A bare <code>us-bos</code> can stop at a proxy provider earlier in the order, and a bare <code>us:seattle</code> does not work, so use the <code>surfsharkvpn:</code> prefix for those forms.</p> <p>The returned proxy is HTTPS on port 443.</p> <p>A Surfshark server name such as <code>fr-bod</code> is a cluster: its DNS name points at many server IPs, and each connection can go to a different one. Surfshark publishes no name for each server, so unshackle lists the IPs of a cluster from its nameserver. With an <code>@</code> part, unshackle connects to one of those IPs through a local port on <code>127.0.0.1</code>. That port checks the server certificate against the cluster name, so your credentials go only to a real Surfshark server. The connection line shows the IP, so you can pin a server that works with <code>@&lt;ip&gt;</code>. Surfshark changes its server IPs from time to time, and a pinned IP can stop working.</p> <p>With <code>--remote</code>, the client sends a Surfshark query with an <code>@</code> part to the server as you typed it, because the local port is on your machine. The server then selects and pins the server with its own Surfshark configuration. This needs the <code>server_proxy</code> grant on your API key.</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 takes a selector (see Choose a server network), or 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>windscribevpn:us:seattle</code> A random server in Seattle. <code>windscribevpn:fr@-datacamp</code> A random French server that is not on a Datacamp network. See Choose a server network. <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>One resolution path (developers)</p> <p><code>dl</code>, <code>search</code>, the REST API handlers and the remote-service client all load proxy providers through <code>load_proxy_providers()</code> in <code>unshackle/core/proxies/resolve.py</code>. The REST API and the remote-service client call it through <code>initialize_proxy_providers()</code>, which leaves out Gluetun because Gluetun starts a local Docker container. All paths accept the same query grammar: a direct URI, a <code>provider:query</code>, a bare query tried against providers in order, or a <code>controld://</code> resolver.</p> <p>The remote-service client resolves <code>--proxy</code> with its own <code>resolve_remote_proxy_arg()</code>. It changes a <code>controld:</code> query to a <code>controld://</code> resolver for the server with <code>get_remote_proxy()</code>, and it removes Control D from a bare query, because a loopback forwarder is of no use to a server on another machine.</p> <p>Keeping service requests on the proxy (developers)</p> <p><code>unshackle/core/utils/run_proxy.py</code> holds the proxy rules for service traffic:</p> <ul> <li><code>pin(session)</code> stops environment and system proxies from overriding the proxy of a requests HTTP session, and keeps the environment CA bundle. Call it on each requests HTTP session that gets a proxy.</li> <li><code>fallback_session()</code> gives a core helper with no HTTP session (a manifest parser, a DRM class) a session on the proxy of the service that called it.</li> <li>An audit hook on <code>socket.getaddrinfo</code> and on <code>socket.connect</code> to a host name, and a check in <code>RnetSession.request</code>, warn about requests from service code that do not use the proxy. A service sets <code>proxy_exempt = True</code> on an HTTP session that goes direct on purpose.</li> </ul> <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>Cue markup normalisation: unshackle removes the WebVTT-only parts of a cue payload, so no player draws them as dialogue. See Cue markup.</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>-fso</code>, <code>--forced-subs-only</code> Keep only forced subtitle tracks and drop the other subtitles; implies <code>-fs</code>. <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> A tag without a region never falls back to another variant: <code>es</code> does not match <code>es-419</code>. <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>A tag without a region selects the variant it means, such as <code>en-US</code> for <code>en</code>, and every regional form only when the title has no such variant. A tag with a region matches only that variant:</p> Only Latin-American Spanish, no other Spanish variants<pre><code>unshackle dl --s-lang es-419 EXAMPLE 'https://www.example.com/...'\n</code></pre> <p>If a requested language is missing, unshackle stops with an error. With <code>--best-available</code>, it continues with the languages it found and tells you which ones it dropped. See exact vs fuzzy matching for the full rules.</p>"},{"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> <p>To download the forced tracks and no other subtitle, use <code>-fso</code> / <code>--forced-subs-only</code>. It implies <code>-fs</code>, and <code>--s-lang</code> and <code>-fsl</code> still select the languages:</p> Only the English forced track<pre><code>unshackle dl --s-lang en --forced-subs-only EXAMPLE 81234567\n</code></pre> <p><code>-fso</code> does not drop video or audio. Add <code>-S</code> for a subtitle-only download. A title with no forced track stops a run of one title. A run of more than one title skips that title with a warning.</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 uses the same matching rules as <code>--s-lang</code>. A plain track covers an SDH track only when it is the same variant: <code>en</code> and <code>en-US</code> cover each other, but a plain <code>en-GB</code> track does not stop a stripped <code>en</code> or <code>en-US</code> copy. When unshackle creates a stripped copy, it keeps the original SDH track 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>Every engine removes the same three things: bracketed sound effects (<code>[MUSIC PLAYING]</code>, <code>(door creaks)</code>), speaker labels (<code>MAN:</code>), and font tags. Every engine keeps plain dialogue and inline <code>&lt;i&gt;</code> styling. They differ on music and lyric lines:</p> <code>sdh_method</code> Engine that runs Lyric lines (<code>\u266a ... \u266a</code>) <code>auto</code> <code>subby</code> for an SRT track. SubtitleEdit for any other format when you install it, otherwise <code>filter-subs</code>. Kept, unless the fallback reaches <code>filter-subs</code>. <code>subby</code> <code>subby</code>, but only for a track that is already SRT. Any other format falls through to <code>filter-subs</code>. Kept for SRT, removed otherwise. <code>subtitleedit</code> SubtitleEdit when you install it, otherwise <code>filter-subs</code>. Kept with SubtitleEdit, removed without it. <code>filter-subs</code> <code>filter-subs</code> always. Removed. <p>Pick <code>filter-subs</code> when you want lyrics gone as well. Pick <code>subby</code> or install SubtitleEdit when you want to read along with the songs.</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>When unshackle converts SSA/ASS to a format that is not SSA/ASS, it writes the cues in start-time order. SSA/ASS files often list layered sign events out of time order. The SSA/ASS source file keeps its order, because the order of events on one layer sets the order in which they are drawn.</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>"},{"location":"guide/subtitles/#cue-markup-and-html-entities","title":"Cue markup and HTML entities","text":"<p>Styling is not the only thing a conversion has to handle. WebVTT carries markup that no other format understands, and a player that does not know a tag draws it as dialogue. unshackle removes that markup before any backend runs, so the result is the same for every <code>conversion_method</code>:</p> WebVTT markup Result <code>&lt;c.bg_transparent&gt;text&lt;/c&gt;</code> Tags removed, text kept. A class only selects a CSS <code>::cue</code> rule that no player ever receives, so it carries no styling. <code>&lt;i.loud&gt;</code>, <code>&lt;b.x&gt;</code>, <code>&lt;u.y&gt;</code> Class list removed, the styling tag kept. <code>&lt;v Bob&gt;</code>, <code>&lt;lang ja&gt;</code>, <code>&lt;ruby&gt;</code>, <code>&lt;rt&gt;</code> Tags removed, text kept. <code>&lt;00:00:02.000&gt;</code> Removed. These are karaoke timings that no subtitle player renders. <code>&amp;amp;</code>, <code>&amp;nbsp;</code>, <code>&amp;#39;</code> Decoded to real characters for SRT, SSA, and ASS output. Kept escaped for WebVTT and TTML, which need them. <p>A class list breaks more than you expect</p> <p>FFmpeg reads SubRip markup as a tag only while the tag name stays inside <code>[0-9a-zA-Z_/]</code>. The dot in <code>&lt;i.loud&gt;</code> fails that test, so FFmpeg prints the opening tag on screen and then closes an italic run that never opened. The FFmpeg WebVTT reader matches <code>i</code>, <code>b</code>, and <code>u</code> exactly, so there the same class silently loses the styling. mpv, VLC, Plex, and Jellyfin all use one of those two readers.</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."},{"location":"guide/subtitles/#which-settings-to-change","title":"Which settings to change","text":"<p>The defaults give a clean, player-safe file, so most people change nothing. Start here only when you want something the defaults do not do:</p> If you want Set Every original style kept, with no re-encode at all <code>--sub-format original</code>, and <code>sidecar_format: original</code> for sidecars The highest conversion fidelity, including colour Install SubtitleEdit. <code>conversion_method</code> stays <code>auto</code> Music and lyric lines stripped along with the sound effects <code>sdh_method: filter-subs</code> Lyric lines kept <code>sdh_method: subby</code>, or install SubtitleEdit No stripped copies made at all <code>strip_sdh: false</code> One backend for every conversion, whatever you install <code>conversion_method: &lt;backend&gt;</code> <p>Two keys read as if they control markup, and do not:</p> <ul> <li><code>preserve_formatting</code> decides whether unshackle re-encodes a WebVTT file after the repair pipeline. Left <code>true</code>, the cue text passes through as written. Set to <code>false</code>, unshackle re-encodes the file through pycaption, which merges identical cues and drops empty ones but also flattens styling. Neither setting leaves WebVTT-only markup in the file: cue markup normalisation runs either way.</li> <li><code>convert_before_strip</code> applies to SDH stripping, not to your output format. It converts the working copy to SRT so a non-SubtitleEdit engine can read it. Turning it off makes <code>subby</code> and <code>filter-subs</code> no-ops on anything that is not already SRT.</li> </ul> <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. Run <code>unshackle setup</code> to install it, or install it by hand, 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 vault served a wrong content key</p> <p>Symptom: a warning names a content key and the vault it came from, either <code>was bad, trying other vaults</code> (the decode check failed) or <code>is flagged bad, skipping</code> (an earlier run flagged it). The download stops with <code>The content key from the vault did not decrypt the track; run again</code>, <code>was bad and no other source has the key</code>, or <code>No vault or CDM produced a content key that decrypts the track</code> when no source is left to try.</p> <p>Inspect: while it decrypts a track whose content key came from a vault, unshackle keeps the ciphertext as a <code>.enc</code> sibling of the track file in the temp directory, and removes it afterwards; a leftover one is from a killed run and is safe to delete. Read the <code>bad_keys</code> table of your local SQLite vault to see which pairs are flagged and which vault each came from. See Wrong keys from a poisoned vault.</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>A segment download fails after every retry</p> <p>Symptom: the download stops with a line like <code>MaxRetriesError: GET &lt;host&gt; failed: RequestError (stream closed because of a broken pipe), gave up after 5 failed attempts over 30s</code>.</p> <p>Inspect: the connection to the CDN host dropped on every attempt. This is almost always the network, the VPN, or the proxy, not the service. Run the download again: unshackle keeps the segments it already has. Over HTTP/2, all segments share one connection, so one drop fails every segment in flight. Set <code>network.http1_only: true</code> (see Network &amp; proxy) to spread them over separate connections. Operate unshackle with <code>-d</code> to see each retry as a <code>segment_retry</code> entry in the JSON debug log.</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>unshackle pushes keys from every source, not only a local CDM. A run against a remote server that licenses with its own CDM (<code>--remote</code>) writes the keys the server returns, and <code>unshackle import</code> writes the keys it reads from an export file.</p>"},{"location":"guide/vaults/#wrong-keys-from-a-poisoned-vault","title":"Wrong keys from a poisoned vault","text":"<p>A public vault can return the right KID with a wrong content key. The decrypters accept a wrong content key and write noise. unshackle therefore trusts a content key from a vault only after FFmpeg decodes the decrypted track with strict error detection. For a fragmented MP4, unshackle reads from the encrypted file which fragments each KID encrypts, and FFmpeg decodes up to three windows of each KID: from its first, middle and last fragment on through the next fragments of that KID, for up to 4 seconds. A window never runs into a fragment of another KID or a clear fragment. A clear lead or a lead under another KID therefore cannot hide a wrong content key, and only the KID that fails is flagged. When every KID in the map has a content key, the map is complete, and a KID that is not in it does not encrypt this file. This file does not judge that KID; the file of its own track judges it. A file with no encrypted sample entry and no encrypted fragment, for example a clear audio track, judges no KID, so it neither flags nor copies a content key. A KID that is not in an incomplete map, for example one with an all-zero KID, and every KID of any other file, gets one check of the whole file. FFmpeg decodes the first seconds and the last seconds. A failure there flags each of those KIDs. When a mapped KID fails, the KIDs that are not in the map get no verdict from that pass; the retry with the replaced key judges them. Content keys from a licence skip this check. A file this FFmpeg build cannot judge counts as a pass, never as a wrong content key: a codec it has no decoder for, or a header it cannot read. A pass is not proof. A wrong content key for HEVC video can decode without an error for some seconds, most often at a low resolution, and that content key passes the check. Without FFmpeg there is no check at all.</p> <p>When the decode fails, unshackle:</p> <ol> <li>Flags the KID:KEY in the <code>bad_keys</code> table of every local SQLite vault, with the service and the name of the vault it came from. The pair also goes out of the service table, except in a vault marked <code>no_push</code>, where only the flag is written. A flagged pair cannot go back into a local vault from another vault, a later run, or <code>kv copy</code>. A licence that returns the pair clears the flag and stores it. An <code>API</code> vault that served the pair gets a report only when a different content key for that KID is accepted. When the CDM returns the same content key, that vault gets no report. <code>HTTP</code> and <code>MySQL</code> vaults have no report route. A pair from a local vault goes to no remote vault, even when a remote vault holds the same pair.</li> <li>Restores the ciphertext from a hard link it made before decryption, then asks for the content key again. Every vault lookup skips a flagged pair, so the request reaches the remaining vaults and then the CDM. A remote answer that arrived after the winning one is reused instead of queried again.</li> <li>Removes the flag when the CDM returns the same content key, because then the decode check was wrong, not the content key. A content key from another vault is checked in its turn, and flagged as well if it also fails.</li> </ol> <p>The download stops with an error instead of writing noise when no ciphertext is left to retry with, or when every vault and the CDM are used up. Without a local SQLite vault nothing remembers a flag, so the same vault serves the same pair again and the download stops there.</p> <p>Per-segment decryption gives up the retry. With <code>decrypt_segments</code> on, and always with MonaLisa, the plaintext replaces each segment as it arrives, so no ciphertext is left. A failed decode then flags the pair and stops the download. The next run skips the flagged pair.</p> <p>unshackle copies a content key from one vault to the others only after this check passes, so a content key that fails the check does not spread. Without FFmpeg, a content key from a vault is not copied at all. To see or clear the flags, open the SQLite file and read or delete rows in <code>bad_keys</code>.</p> <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. <code>MySQL</code> uses <code>vault_timeout</code> as its <code>connect_timeout</code> instead, and falls back to the pymysql default of 10 seconds when <code>vault_timeout</code> is <code>0</code>. To use a different connect timeout, set <code>connect_timeout</code> on the vault.</p> <p>unshackle pushes content keys to all vaults at the same time, so one slow or unreachable vault costs only its own timeout and does not delay the others.</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>One more table, <code>bad_keys</code>, is created on demand and holds every KID:KEY that failed the decode check described in Wrong keys from a poisoned vault, with the service, the vault it came from, and the time it was flagged. It is not a service table, and every command that walks the service tables skips it.</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>. Bulk writes (<code>kv copy</code>, <code>kv add</code>) first try <code>InsertKeys</code> with <code>params: {\"keys\": {kid: key, ...}, \"service\": ..., \"title\": ...}</code> (up to 500 content keys per call) and expect <code>{\"inserted\": &lt;count&gt;}</code> back. A server that answers HTTP 404 or <code>Unknown JSON-RPC method</code> to <code>InsertKeys</code> gets one <code>InsertKey</code> call per content key for the rest of the run instead. 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> <p>A pair the destination vault has flagged in <code>bad_keys</code> is left behind, so a copy does not undo a flag. <code>bad_keys</code> is never treated as a service, so its rows are never copied into a service table.</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. It runs <code>copy</code> between each pair, so it skips flagged pairs and the <code>bad_keys</code> table in the same way.</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.restore_bool_languages","title":"restore_bool_languages","text":"<pre><code>restore_bool_languages(data)\n</code></pre> <p>Put back the language tags <code>no</code> and <code>yes</code>, which YAML reads as booleans.</p>"},{"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.cdm_entry_names_device","title":"cdm_entry_names_device","text":"<pre><code>cdm_entry_names_device(entry, profile=None)\n</code></pre> <p>Whether a per-service <code>cdm</code> entry names a device when no quality is known.</p> <p>An entry that selects only by quality, or by a different profile, names none.</p>"},{"location":"reference/api/config/#unshackle.core.config.duplicate_key_lines","title":"duplicate_key_lines","text":"<pre><code>duplicate_key_lines(root)\n</code></pre> <p>Return (first line, repeat line), counted from 1, for each repeated scalar key in a PyYAML or ruamel node tree.</p> <p>Keys compare as written, so two spellings that load as the same key (yes and true, 1 and 0x1) are not found.</p>"},{"location":"reference/api/config/#unshackle.core.config.load_yaml","title":"load_yaml","text":"<pre><code>load_yaml(path)\n</code></pre> <p>yaml.safe_load a file, and warn with the lines of each duplicate key, which PyYAML takes silently.</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.BlowfishStripe","title":"BlowfishStripe","text":"<pre><code>BlowfishStripe(key)\n</code></pre> <p>Blowfish CBC stripe cipher: the service encrypts every third full 2048-byte chunk and leaves the rest clear.</p> <p>Each encrypted chunk is its own CBC run with a fixed IV. The service gives the content key, so there is no licence.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.BlowfishStripe.decrypt_chunk","title":"decrypt_chunk","text":"<pre><code>decrypt_chunk(chunk)\n</code></pre> <p>Decrypt one encrypted chunk.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.BlowfishStripe.decrypt","title":"decrypt","text":"<pre><code>decrypt(path)\n</code></pre> <p>Decrypt the file to a new file that then replaces it. A short trailing chunk stays clear.</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.mp4decrypt_key_args","title":"mp4decrypt_key_args","text":"<pre><code>mp4decrypt_key_args()\n</code></pre> <p>Build the mp4decrypt --key arguments for every content key.</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, device_path, tool_path=None, **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>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>device_path</code> <code>Path</code> <p>Path to the CDM device file (.mld).</p> required <code>tool_path</code> <code>Optional[Path]</code> <p>Optional path to an external decryption binary.</p> <code>None</code> <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.key_pair","title":"key_pair <code>property</code>","text":"<pre><code>key_pair\n</code></pre> <p>The formatted <code>KID:KEY</code> for CLI decryptors (32hex:32hex).</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.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, device_path, tool_path=None)\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>device_path</code> <code>Path</code> <p>Path to the CDM device file (.mld).</p> required <code>tool_path</code> <code>Optional[Path]</code> <p>Optional path to an external decryption binary.</p> <code>None</code> <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, output_path=None)\n</code></pre> <p>Decrypt an individual segment file using the configured CLI tool via subprocess.</p> <p>Parameters:</p> Name Type Description Default <code>segment_path</code> <code>Path</code> <p>Path to the segment file to decrypt.</p> required <code>output_path</code> <code>Optional[Path]</code> <p>Optional path for the decrypted output segment.</p> <code>None</code>"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.decrypt","title":"decrypt","text":"<pre><code>decrypt(path, output_path=None, *, is_segment=False)\n</code></pre> <p>Decrypt a media file (segment or track) using the configured CLI tool via subprocess.</p> <p>Parameters:</p> Name Type Description Default <code>path</code> <code>Path</code> <p>Path to the target file to decrypt.</p> required <code>output_path</code> <code>Optional[Path]</code> <p>Optional path for the decrypted output file.</p> <code>None</code> <code>is_segment</code> <code>bool</code> <p>Set True if this is an individual segment rather than a full track.</p> <code>False</code>"},{"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.from_pssh_b64","title":"from_pssh_b64 <code>classmethod</code>","text":"<pre><code>from_pssh_b64(pssh_b64, kid=None)\n</code></pre> <p>Load a base64 PSSH box or PlayReady Object, or a bare UTF-16LE WRMHEADER that some packagers emit.</p> <p>It wraps a bare WRMHEADER in a PlayReady Object and keeps that as <code>pssh_b64</code>, so remote CDMs and the REST API can parse it again.</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.header_kids","title":"header_kids <code>staticmethod</code>","text":"<pre><code>header_kids(header)\n</code></pre> <p>Return the KIDs one WRM header names, in header order.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.absorb","title":"absorb","text":"<pre><code>absorb(*others)\n</code></pre> <p>Fold sibling PlayReady objects into this one so their headers and KIDs get licensed too.</p> <p>A manifest can attach one PlayReady object per WRM header to the same track (ISM shares its Protection list across tracks; HLS emits one per EXT-X-KEY). The caller keeps this object's identity, which the decrypt path and drm_lock depend on.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.distinct_headers","title":"distinct_headers","text":"<pre><code>distinct_headers()\n</code></pre> <p>Return the WRM headers to license, deduplicated by the KID set each one names.</p> <p>Two headers naming the same KIDs (a v4.0 header beside its v4.3 twin, or one PRH per rendition for one content key) cost one challenge. A header with no readable KID is kept: it may still be the only route to a content key nothing else names.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.pro_b64_for","title":"pro_b64_for <code>staticmethod</code>","text":"<pre><code>pro_b64_for(header)\n</code></pre> <p>Build a base64 one-record PlayReady Object holding only this header.</p> <p>Remote CDMs send the value given to set_pssh_b64 rather than the header passed to get_license_challenge, so a per-header challenge needs a per-header PRO.</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.get_content_keys","title":"get_content_keys","text":"<pre><code>get_content_keys(cdm, certificate, licence)\n</code></pre> <p>License every distinct WRM header whose KIDs still lack a content key.</p> <p>A v4.2+ header may list several KIDs and one response may stack several licences, so one challenge often covers everything. Content that ships several headers (ISM with one ProtectionHeader per track type, HLS with one PRH per playlist) gets one challenge per header that is not yet covered. Headers are sent as-is: Microsoft lets the server ignore the header, so a merged header could ask for keys it never grants.</p> <p>A header that a round refused, or that yielded nothing, is not sent again by this object: every track of a title runs this method, and a repeat would only repeat the refusal.</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.own_kids","title":"own_kids","text":"<pre><code>own_kids()\n</code></pre> <p>Return the KIDs that identify this track's own content key.</p> <p>The KID given to the constructor (from the manifest or the init segment) names the track exactly. A PSSH can name the KIDs of other renditions too.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.mp4decrypt_key_args","title":"mp4decrypt_key_args","text":"<pre><code>mp4decrypt_key_args()\n</code></pre> <p>Build the mp4decrypt --key arguments for every content key and the zero-KID fallback.</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.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.own_kids","title":"own_kids","text":"<pre><code>own_kids()\n</code></pre> <p>Return the KIDs that identify this track's own content key.</p> <p>The KID given to the constructor (from the manifest or the init segment) names the track exactly. A PSSH can name the KIDs of other renditions too.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.mp4decrypt_key_args","title":"mp4decrypt_key_args","text":"<pre><code>mp4decrypt_key_args()\n</code></pre> <p>Build the mp4decrypt --key arguments for every content key and the zero-KID fallback.</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/drm/#unshackle.core.drm.real_kids","title":"real_kids","text":"<pre><code>real_kids(drm)\n</code></pre> <p>Return the KIDs a DRM object names, without the all-zero and test-pattern placeholders.</p>"},{"location":"reference/api/drm/#unshackle.core.drm.own_kids","title":"own_kids","text":"<pre><code>own_kids(drm)\n</code></pre> <p>Return the real KIDs that identify the track's own content key, as the DRM object knows them.</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 generate_dv=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 generate_dv = ctx.parent.params.get(\"generate_dv\", 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 generate_dv=bool(generate_dv),\n )\n\n whose = \"the server's\" if ctx.parent and ctx.parent.params.get(\"served\") else \"your\"\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 try:\n proxy_provider, proxy = pick_proxy(ctx.obj.proxy_providers, mapped_value, proxy_provider_name)\n self.log.info(\n f\"Using mapped proxy from {proxy_provider.__class__.__name__}: \"\n f\"{sanitize_proxy_for_log(proxy, mask_host=isinstance(proxy_provider, Basic))}\"\n )\n except ValueError:\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 or self.GEOBLOCK:\n try:\n current_region = (get_ip_info(self.session) or {}).get(\"country\", \"\").lower()\n if not current_region:\n self.log.warning(f\"Could not find {whose} region, so the region check does not run\")\n elif self.is_region_allowed(current_region):\n self.log.info(\"Service is not Geoblocked in your region\")\n elif not (fence_targets := [x for x in self.GEOFENCE if self.is_region_allowed(x)]):\n raise click.ClickException(\n f\"Service is not available in {whose} region ({current_region.upper()})\"\n )\n else:\n requested_proxy = fence_targets[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 try:\n proxy_provider, proxy = pick_proxy(ctx.obj.proxy_providers, requested_proxy)\n self.log.info(f\"Got Proxy from {proxy_provider.__class__.__name__}\")\n except ValueError:\n self.log.warning(f\"No proxy available for {requested_proxy}\")\n except click.ClickException:\n raise\n except Exception as e:\n self.log.warning(f\"Failed to check geofence: {e}\")\n else:\n self.log.info(\"Service has no region restrictions\")\n\n if proxy:\n self.session.proxies.update({\"all\": proxy})\n if isinstance(self.session, requests.Session):\n run_proxy.pin(self.session)\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 # Verify the proxy IP every time, because a proxy can change its exit node. A dead\n # proxy fails here, not after every service request has used up its retries.\n exit_region = verify_proxy_exit(self.session).get(\"country\")\n self.current_region = exit_region\n # Only GEOBLOCK applies here: an explicit --proxy outside GEOFENCE stays the user's call.\n if exit_region and any(x.lower() == exit_region.lower() for x in self.GEOBLOCK):\n raise click.ClickException(\n f\"Service is not available in {whose} proxy's region ({exit_region.upper()})\"\n )\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\n run_proxy.watch(type(self), run_proxy.proxy_of(self.session))\n</code></pre>"},{"location":"reference/api/service/#unshackle.core.service.Service.is_region_allowed","title":"is_region_allowed <code>classmethod</code>","text":"<pre><code>is_region_allowed(region)\n</code></pre> <p>True when an exit IP in <code>region</code> (two-letter region code, any case) can use the service.</p> <p>An unknown region (None or empty) is allowed, because there is nothing to compare.</p> Source code in <code>unshackle/core/service.py</code> <pre><code>@classmethod\ndef is_region_allowed(cls, region: Optional[str]) -&gt; bool:\n \"\"\"True when an exit IP in `region` (two-letter region code, any case) can use the service.\n\n An unknown region (None or empty) is allowed, because there is nothing to compare.\n \"\"\"\n if not region:\n return True\n region = region.lower()\n if any(x.lower() == region for x in cls.GEOBLOCK):\n return False\n return not cls.GEOFENCE or any(x.lower() == region for x in cls.GEOFENCE)\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>Video, audio and subtitles merge from every combo, so a track that only one manifest offers is kept. The helper skips a later track whose <code>Tracks.signature</code> matches a held one, because its ID can differ between manifests. Chapters and attachments come from the first combo only.</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 tracks into the HDR10 result. With no DV video and <code>generate_dv</code> requested, it merges the HDR10P tracks instead.</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 Video, audio and subtitles merge from every combo, so a track that only one manifest\n offers is kept. The helper skips a later track whose ``Tracks.signature`` matches a held\n one, because its ID can differ between manifests. Chapters and attachments come from the\n first combo only.\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 tracks into the HDR10 result. With no DV video and\n ``generate_dv`` requested, it merges the HDR10P tracks instead.\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 def merge(tracks: Tracks) -&gt; None:\n nonlocal first\n if first:\n all_tracks.add(tracks, warn_only=True)\n first = False\n return\n held = {Tracks.signature(track) for track in all_tracks}\n all_tracks.add([track for track in tracks if Tracks.signature(track) not in held], warn_only=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, then DV\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 merge(hdr_tracks)\n\n try:\n dv_tracks = fetch_fn(title, codec=codec_val, range_=Video.Range.DV)\n except (ValueError, SystemExit):\n self.log.info(\" - No DolbyVision manifest available for HYBRID\")\n dv_tracks = Tracks()\n merge(dv_tracks)\n has_hdr10p = any(v.range == Video.Range.HDR10P for v in all_tracks.videos)\n if not dv_tracks.videos and self.track_request.generate_dv and not has_hdr10p:\n # the HDR10 request may not return HDR10+, which the conversion needs as its base\n try:\n hdr10p_tracks = fetch_fn(title, codec=codec_val, range_=Video.Range.HDR10P)\n except (ValueError, SystemExit):\n self.log.info(\" - No HDR10+ manifest available for HYBRID\")\n else:\n merge(hdr10p_tracks)\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 merge(tracks)\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 retry_after_max=MAX_BACKOFF,\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.get_binaries","title":"get_binaries <code>staticmethod</code>","text":"<pre><code>get_binaries()\n</code></pre> <p>Declare custom binary dependencies required by this service. :returns: List of dicts, each with a <code>name</code> and optional <code>candidates</code> and <code>desc</code>.</p> Source code in <code>unshackle/core/service.py</code> <pre><code>@staticmethod\ndef get_binaries() -&gt; list[dict]:\n \"\"\"\n Declare custom binary dependencies required by this service.\n :returns: List of dicts, each with a ``name`` and optional ``candidates`` and ``desc``.\n \"\"\"\n return []\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. The one exception is a search on a Service that sets <code>ANONYMOUS_SEARCH</code>, which does not operate this method.</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. The one exception is a search on a\n Service that sets ``ANONYMOUS_SEARCH``, which does not operate this method.\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>Locally, prompts through the shared rich console so the prompt renders alongside Live progress. A remote-dl session relays it through its :class:<code>InputBridge</code>, and a REST download job relays it through <code>prompt_user</code> to the job's <code>input_prompt</code>.</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 Locally, prompts through the shared rich console so the prompt renders alongside\n Live progress. A remote-dl session relays it through its :class:`InputBridge`, and a\n REST download job relays it through ``prompt_user`` to the job's ``input_prompt``.\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.wait_for_approval","title":"wait_for_approval","text":"<pre><code>wait_for_approval(message, check, timeout, interval=3.0)\n</code></pre> <p>Show <code>message</code>, then call <code>check</code> until it returns a value.</p> <p>Use it for a login that the user approves on another device, such as a pair code. <code>check</code> returns None while the approval is pending, and must return within a few seconds. Raises TimeoutError after <code>timeout</code> seconds, and RuntimeError when the remote session no longer exists. A REST download job shows <code>message</code> as its <code>notice</code>.</p> Source code in <code>unshackle/core/service.py</code> <pre><code>def wait_for_approval(\n self, message: str, check: Callable[[], Optional[T]], timeout: float, interval: float = 3.0\n) -&gt; T:\n \"\"\"Show ``message``, then call ``check`` until it returns a value.\n\n Use it for a login that the user approves on another device, such as a pair code.\n ``check`` returns None while the approval is pending, and must return within a few\n seconds. Raises TimeoutError after ``timeout`` seconds, and RuntimeError when the\n remote session no longer exists. A REST download job shows ``message`` as its ``notice``.\n \"\"\"\n self.log.info(message)\n show_notice(message)\n deadline = time.monotonic() + timeout\n try:\n while True:\n if self._input_bridge is not None:\n self._input_bridge.ensure_active()\n result = check()\n if result is not None:\n return result\n if time.monotonic() + interval &gt;= deadline:\n raise TimeoutError(f\"No approval within {timeout:.0f}s\")\n time.sleep(interval)\n finally:\n show_notice(None)\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 service can then ban, revoke, disable, or downgrade that device.</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.\n The service can then ban, revoke, disable, or downgrade that device.\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 service can then ban, revoke, disable, or downgrade that device.</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.\n The service can then ban, revoke, disable, or downgrade that device.\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 # A service that implements Widevine licensing only still gets PlayReady, with the\n # arguments its own signature declares.\n return self.get_widevine_license(\n **declared_kwargs(self.get_widevine_license, {\"challenge\": challenge, \"title\": title, \"track\": track})\n )\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>signatures</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 `signatures` 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.decrypts_samples","title":"decrypts_samples","text":"<pre><code>decrypts_samples(track)\n</code></pre> <p>Whether this service decrypts the cbcs file of <code>track</code> after the download, through <code>get_sample_decrypter</code>.</p> Source code in <code>unshackle/core/service.py</code> <pre><code>def decrypts_samples(self, track: AnyTrack) -&gt; bool:\n \"\"\"Whether this service decrypts the cbcs file of `track` after the download, through `get_sample_decrypter`.\"\"\"\n return False\n</code></pre>"},{"location":"reference/api/service/#unshackle.core.service.Service.get_sample_decrypter","title":"get_sample_decrypter","text":"<pre><code>get_sample_decrypter(track, entry)\n</code></pre> <p>The content key, or a <code>cbcs.SampleDecrypter</code>, for <code>stsd</code> entry <code>entry</code> (1-based) of <code>track</code>.</p> <p>unshackle calls this only for a track <code>decrypts_samples</code> names. A remote session runs it on the server, so a decrypter that needs a local process works for remote clients too.</p> Source code in <code>unshackle/core/service.py</code> <pre><code>def get_sample_decrypter(self, track: AnyTrack, entry: int) -&gt; Union[bytes, \"SampleDecrypter\"]:\n \"\"\"The content key, or a `cbcs.SampleDecrypter`, for `stsd` entry `entry` (1-based) of `track`.\n\n unshackle calls this only for a track `decrypts_samples` names. A remote session runs it on the\n server, so a decrypter that needs a local process works for remote clients too.\n \"\"\"\n raise NotImplementedError(f\"{self.__class__.__name__} does not decrypt samples\")\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. None for DASH and ISM tracks and for an HLS track that merged during the download (merge_segments).</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. None for DASH and ISM tracks and\n for an HLS track that merged during the download (merge_segments).\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: the rebuild 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> <p>Every mounted adapter grows in place, through its own <code>init_poolmanager</code>. A service can mount an :class:<code>HTTPAdapter</code> subclass, such as <code>SSLCiphers</code>, on any prefix. Mounting a new adapter over it would drop that subclass state, and its TLS context with 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: the rebuild 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 Every mounted adapter grows in place, through its own ``init_poolmanager``. A service can\n mount an :class:`HTTPAdapter` subclass, such as ``SSLCiphers``, on any prefix. Mounting a new\n adapter over it would drop that subclass state, and its TLS context with it.\n \"\"\"\n if not isinstance(session, requests.Session):\n return\n for adapter in {id(a): a for a in session.adapters.values()}.values():\n if not isinstance(adapter, HTTPAdapter) or getattr(adapter, \"_pool_maxsize\", 0) &gt;= size:\n continue\n adapter.init_poolmanager(size, size, block=True)\n adapter.proxy_manager.clear()\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, mask_host=False)\n</code></pre> <p>Sanitise a proxy URI for logs by masking any embedded userinfo (username/password).</p> <p><code>serve</code> sends these log lines to the client of a remote session, so the mask is unconditional and debug mode never lifts it. <code>mask_host</code> hides the hostname as well, for a proxy that came from the user-supplied <code>Basic</code> proxy provider.</p> Source code in <code>unshackle/core/service.py</code> <pre><code>def sanitize_proxy_for_log(uri: Optional[str], mask_host: bool = False) -&gt; Optional[str]:\n \"\"\"\n Sanitise a proxy URI for logs by masking any embedded userinfo (username/password).\n\n ``serve`` sends these log lines to the client of a remote session, so the mask is\n unconditional and debug mode never lifts it. ``mask_host`` hides the hostname as\n well, for a proxy that came from the user-supplied ``Basic`` proxy provider.\n \"\"\"\n if uri is None:\n return None\n if not isinstance(uri, str):\n return str(uri)\n return mask_proxy(uri, mask_host=mask_host, allow_debug=False)\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 synced_lyrics=None,\n lyrics_suffix=None,\n)\n</code></pre> <p> Bases: <code>Title</code></p> <p><code>lyrics</code> is the plain text the tagger embeds.</p> <p><code>synced_lyrics</code> (timed LRC or TTML) is saved beside the audio file with <code>lyrics_suffix</code> (\".lrc\", \".ttml\").</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(\n session=None,\n *,\n no_proxy_download=False,\n proxy_download=None,\n)\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.delete","title":"delete","text":"<pre><code>delete()\n</code></pre> <p>Delete the file only if it is in the temp directory. Files in other locations belong to the user.</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>An immersive layout names its height channels in a third figure, e.g. \"5.1.4\", which no float can hold, so it stays the string it came as. Use channel_total for arithmetic on either form.</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.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Audio.channel_total","title":"channel_total <code>staticmethod</code>","text":"<pre><code>channel_total(channels)\n</code></pre> <p>Total number of channels in either channel form, so a caller can compare both.</p> <p>A float layout keeps its own value, because a caller compares those by rounding the sub channel up, e.g. 5.1 and 6.0 both match. An immersive layout has no such float, so this adds its figures: \"5.1.4\" -&gt; 10.0.</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(crop)\n</code></pre> <p>Write the active area of the HDR10 track, as (left, top, right, bottom), to Level 5.</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.detect_active_area","title":"detect_active_area","text":"<pre><code>detect_active_area(input_video)\n</code></pre> <p>The picture's crop as (left, top, right, bottom) and its share of the frame, or None.</p> <p>None also when the picture is under 40% of the frame: cropdetect on dark samples can report a tiny picture, which would be wrong in L5 and would divide the HDR10+ conversion's mean by a tiny share.</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(active_fraction=1.0)\n</code></pre> <p>Generate a Dolby Vision RPU with one shot per HDR10+ scene.</p> <p>By default unshackle builds the L1 of each shot itself (see hdr10plus_shots), because dovi_tool's --hdr10plus-json sets L1 avg from the linear AverageMaxRGB and so makes most scenes too bright. config.generate_dv_mode picks the L1 avg floor: v29 (about 2.4 nits, closest to the pixels) or v40 (about 10 nits, as in studio CM v4.0 RPUs). legacy hands the HDR10+ JSON to dovi_tool instead.</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.mux_language","title":"mux_language <code>property</code>","text":"<pre><code>mux_language\n</code></pre> <p>The language tag written to the output file, with the script its region implies.</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_cue_classes","title":"strip_webvtt_cue_classes <code>staticmethod</code>","text":"<pre><code>strip_webvtt_cue_classes(text)\n</code></pre> <p>Reduce a cue payload to the markup every target format shares: <code>&lt;i&gt;</code>, <code>&lt;b&gt;</code> and <code>&lt;u&gt;</code> without their class list. It removes class spans (<code>&lt;c.foo&gt;</code>), <code>&lt;v&gt;</code>, <code>&lt;lang&gt;</code>, <code>&lt;ruby&gt;</code>/<code>&lt;rt&gt;</code> and karaoke timestamps (<code>&lt;00:00:01.000&gt;</code>).</p> <p>A class only selects a CSS <code>::cue</code> rule that no player receives, so it never carries styling, but it does break rendering. FFmpeg's SubRip reader treats a tag name as a tag only while it matches <code>[0-9a-zA-Z_/]</code>. The dot fails that test, so FFmpeg prints <code>&lt;i.loud&gt;</code> as cue text and then emits the closing italic-off with nothing opened. FFmpeg's WebVTT reader matches <code>i</code>/<code>b</code>/<code>u</code> exactly and drops the rest, so there a class silently loses the styling instead. The tags this method removes outright are the ones both readers already discard, and that libass would draw as text if a conversion carried them into ASS.</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.sample_slice","title":"sample_slice","text":"<pre><code>sample_slice(starts, timescale=1, window=None)\n</code></pre> <p>Return the segments of <code>window</code> plus one segment on each side.</p> <p>Cue times in a segment are absolute, so <code>sample_start</code> stays zero and <code>trim</code> makes the cut. A track that ends before the window keeps only its last segment.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.trim","title":"trim","text":"<pre><code>trim(start, end)\n</code></pre> <p>Keep the cues between <code>start</code> and <code>end</code> seconds and move them to start at zero.</p> <p>Returns False and leaves the file whole when pysubs2 cannot read or write its format.</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.language","title":"language <code>property</code> <code>writable</code>","text":"<pre><code>language\n</code></pre> <p>The language the service tagged, parsed even when a service assigns a string or None later.</p>"},{"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.drm_preference","title":"drm_preference <code>property</code> <code>writable</code>","text":"<pre><code>drm_preference\n</code></pre> <p>DRM system this track must license with, one of the names in DRM_PREFERENCE_TYPES.</p> <p>None (the default) lets the loaded CDM choose. Set it when the manifest advertises more than one DRM system but only one of them licenses this track.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.mux_language","title":"mux_language <code>property</code>","text":"<pre><code>mux_language\n</code></pre> <p>The language tag written to the output file.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.sample_slice","title":"sample_slice","text":"<pre><code>sample_slice(starts, timescale=1, window=None)\n</code></pre> <p>Return the slice of segments that hold <code>window</code>, from the start time of each segment.</p> <p>Sets <code>sample_start</code> to the start time of the first kept segment, in seconds. A video keeps <code>sample_tail</code> segments after the window: mkvmerge ends the cut only at a video keyframe, and with no such keyframe the audio and the subtitles continue to their own end.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.sample_byte_range","title":"sample_byte_range","text":"<pre><code>sample_byte_range(session)\n</code></pre> <p>Find the bytes of a one-file track that hold the sample window.</p> <p>Reads the start of the file for a <code>sidx</code> box. Returns the bytes before that box, which hold the init data, and the byte range of the window. Returns None when the file has no such index.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.can_sample","title":"can_sample","text":"<pre><code>can_sample(session)\n</code></pre> <p>Return False when a sample cannot cut this track, because it is one file with no segment index.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.add_init_drm","title":"add_init_drm","text":"<pre><code>add_init_drm(init_data, cdm)\n</code></pre> <p>Add the Widevine and PlayReady DRM that the init segment carries and the track does not have.</p> <p>A track with a different DRM type stays as it is. The DRM system that agrees with the CDM comes first.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.prefers_playready","title":"prefers_playready","text":"<pre><code>prefers_playready(cdm)\n</code></pre> <p>Whether to try PlayReady before Widevine. The track's preference wins over the loaded CDM.</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 proxy_download=None,\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.embedded_audio_name","title":"embedded_audio_name","text":"<pre><code>embedded_audio_name()\n</code></pre> <p>Name the audio a service keeps inside this track's file, by its language when the service set none.</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, or the name of its language when the service set none.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.with_original_label","title":"with_original_label","text":"<pre><code>with_original_label(name)\n</code></pre> <p>Add <code>muxing.original_label</code> to the name of a track in the title's original language, unless the name already contains the label's words.</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.sample_base","title":"sample_base <code>property</code>","text":"<pre><code>sample_base\n</code></pre> <p>The earliest <code>sample_start</code> of the video and audio tracks, which a sample mux uses as time zero.</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.signature","title":"signature <code>staticmethod</code>","text":"<pre><code>signature(track)\n</code></pre> <p>The attributes that listing and selection read. Two tracks with one signature look and select the same.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.dedupe","title":"dedupe","text":"<pre><code>dedupe()\n</code></pre> <p>Drop each video, audio or subtitle track whose signature matches an earlier track.</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. A <code>native_hybrid</code> track is the hybrid itself, so it stays unflagged too.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.select_hybrid","title":"select_hybrid","text":"<pre><code>select_hybrid(\n tracks, quality, worst=False, generate_dv=False\n)\n</code></pre> <p>A filter for the hybrid ingredients of each resolution. It sets <code>native_hybrid</code> on every track.</p> <p>A track that already carries DV and an HDR10 or HDR10+ base (DV+HDR10P, HDR10+DV, HDR10P+DV) is a finished hybrid, so its resolution takes that track and no base. One that carries HDR10+ comes first. The other resolutions get a base only when a DV track can give it an RPU, or with <code>generate_dv</code>.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.first_match_index","title":"first_match_index <code>staticmethod</code>","text":"<pre><code>first_match_index(tracks, language)\n</code></pre> <p>The index of the first track that <code>language</code> asks for, matched against every track at once.</p> <p>Matching the whole list lets the RFC 4647 string preference pick en-US over en.</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 hdr10plus=False,\n hdr10_base=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> <code>hdr10plus</code> <code>bool</code> <p>The DV track also carries HDR10+ metadata. The HDR10+ probe sets it.</p> <code>False</code> <code>hdr10_base</code> <code>bool</code> <p>The DV track has an HDR10 base layer, as DV profile 8.1 does.</p> <code>False</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.carries_hdr10plus","title":"carries_hdr10plus <code>property</code>","text":"<pre><code>carries_hdr10plus\n</code></pre> <p>Whether the track carries HDR10+, as its range or, on a DV track, found by the HDR10+ probe.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.finished_hybrid","title":"finished_hybrid <code>property</code>","text":"<pre><code>finished_hybrid\n</code></pre> <p>Whether the track already carries DV and an HDR10 or HDR10+ base, so <code>-r HYBRID</code> needs no build.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.range_label","title":"range_label <code>property</code>","text":"<pre><code>range_label\n</code></pre> <p>The range that <code>-r</code> selects the track by, then any second format it carries: HDR10+DV, DV+HDR10, DV+HDR10P.</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.dv_fourccs","title":"dv_fourccs <code>staticmethod</code>","text":"<pre><code>dv_fourccs(codecs)\n</code></pre> <p>The Dolby Vision fourccs in a codecs list (comma or space separated, <code>/brand</code> suffixes allowed).</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.has_dv_codec","title":"has_dv_codec <code>staticmethod</code>","text":"<pre><code>has_dv_codec(codecs)\n</code></pre> <p>Whether a codecs list names a Dolby Vision codec.</p>"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.is_dv_composite","title":"is_dv_composite <code>staticmethod</code>","text":"<pre><code>is_dv_composite(codec, codecs, supplemental_codecs)\n</code></pre> <p>Whether an HEVC track names DV only in its supplemental codecs: DV profile 8 on an HDR10, SDR or HLG base.</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>, <code>services_repo_force</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>merge_segments</code>, <code>subtitle</code>, <code>audio</code>, <code>muxing</code>, <code>language_tags</code>, <code>dual_multi_mode</code>, <code>generate_dv_mode</code>, <code>hdr10plus_probe</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-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>), Python bytecode (<code>.pyc</code>, <code>.pyo</code>, also when the repo commits it) and <code>.DS_Store</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>Set <code>services_repo_force: true</code> to make the automatic 24 h refresh behave like <code>refresh-services</code>. When a refresh is due, the run fetches and hard-resets every clone, and discards any local edits in <code>_repos/</code>. Runs between refreshes do not touch the network. Use it on unattended hosts where nobody edits the clones by hand.</p> <pre><code>services_repo_force: true\n</code></pre> <p>Refresh inside <code>serve</code></p> <p>A running server does not restart to pick up a refresh. Both the periodic refresh (<code>serve.services_refresh_interval</code>, see serve) and the manual <code>POST /api/maintenance/refresh-services</code> endpoint hard-reset the clones and then re-import only the services that changed. A service with a running or queued download job keeps its current code until that job finishes, then swaps; <code>GET /api/services</code> marks it with <code>pending_update</code> in the meantime.</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>forced_subs_only</code> bool <code>false</code> Keep only forced subtitle tracks; implies <code>forced_subs</code>. <code>audio_description</code> bool <code>false</code> Include descriptive (audio-description) tracks. <code>audio_description_only</code> bool <code>false</code> Keep only descriptive (audio-description) tracks. <code>no_subs</code> / <code>no_audio</code> / <code>no_chapters</code> / <code>no_attachments</code> bool <code>false</code> Skip that track type. <code>no_attachments</code> also skips attaching subtitle fonts. <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, or when one DRM system does not license under <code>--all-drm</code>. The CLI flag is <code>--best-available</code>, also spelled <code>--warn-only</code>. <code>generate_dv</code> bool <code>false</code> With <code>-r HYBRID</code>, make Dolby Vision from the HDR10+ metadata when a title has no DV track. Needs <code>hdr10plus_tool</code>. See Dolby Vision from HDR10+. <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. <p><code>no</code> and <code>yes</code> are language tags</p> <p>YAML reads a bare <code>no</code> as <code>false</code> and a bare <code>yes</code> as <code>true</code>. unshackle puts both back to the tags <code>no</code> (Norwegian) and <code>yes</code> (Nyankpa) in every config key that takes a language: <code>lang</code>, <code>v_lang</code>, <code>a_lang</code>, <code>s_lang</code>, <code>forced_s_lang</code>, <code>require_audio</code>, <code>require_video</code>, <code>require_subs</code>, <code>language_priority</code>, <code>muxing.default_language</code> and the <code>language_tags</code> rules. Quotes (<code>lang: \"no\"</code>) work as well.</p> 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 keeps the segments of a failed track in a <code>resume</code> directory inside the temp directory, and the next download of the same track takes them back from there. It removes a kept entry after 7 days, and <code>unshackle env clear temp</code> removes them all. A process that is killed, or a job cancelled over the REST API, keeps nothing.</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> <li>A track downloaded with <code>merge_segments</code> or <code>decrypt_segments</code> never resumes. Both options consume or rewrite the segment files during the download.</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/#merge_segments","title":"<code>merge_segments</code>","text":"<ul> <li>Type: <code>bool</code> \u00a0\u00b7\u00a0 Default: <code>false</code></li> </ul> <p>Appends each segment to the output file as soon as it and every segment before it have arrived, instead of joining all the segment files after the last one lands. The join runs during the download, so the \"Merging\" step after the last segment goes away. The output file is the same either way.</p> <p>Segments arrive out of order because the workers run in parallel. unshackle keeps a cursor on the next segment it needs and appends every segment that is ready in order, then deletes the segment file. With <code>decrypt_segments</code> also on, each segment is appended after its decryption completes, never before.</p> <p>This option is off by default because it disables resume, and because its cost during the download is not measured. The append reads each segment straight after a worker wrote it, so the read usually comes from the page cache. On a hard disk, the append to one file while the workers write many segment files can still make the head seek. If a download gets slower with the option on, turn it off.</p> <p>This applies to video and audio tracks from DASH, ISM, and HLS. An HLS track qualifies only when every segment shares one init segment and one <code>EXT-X-KEY</code>, with no <code>EXT-X-DISCONTINUITY</code>, and the DRM is Widevine, PlayReady, or none. AES-128 tracks, tracks with content key rotation or discontinuities, and subtitle tracks keep the merge after the download.</p> <p>No resume</p> <p>A track that merges segment by segment always downloads from the start. <code>continue_downloads</code> cannot reuse its segments, because unshackle deletes each segment after it appends it.</p> <pre><code>merge_segments: 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> Pass WebVTT cue text through as written. <code>false</code> re-encodes it through pycaption, which merges identical cues but flattens styling. unshackle removes WebVTT-only cue markup either way. <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 puts the variant it means first and its other regional forms after it, so <code>en</code> sorts <code>en-US</code> and then <code>en-GB</code>, but <code>zh</code> does not cover <code>zh-Hant</code>, which you must name. A tag with a region sorts only that variant, so <code>[en-US]</code> puts <code>en-US</code> before <code>en-GB</code>. 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 the variant it means, and <code>en-GB</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>. A tag with a region, such as <code>en-US</code>, matches only that variant. <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>track_names</code> str <code>english</code> The language of the name unshackle gives a track that the service left unnamed: <code>english</code> (<code>Chinese (Traditional)</code>), <code>native</code>, the name in the language itself (<code>\u4e2d\u6587\uff08\u7e41\u9ad4\uff09</code>), or <code>none</code>, which leaves the track unnamed. Read Track names and language tags. <code>original_label</code> str unset Text that unshackle adds after the name of an audio or subtitle track in the title's original language, such as <code>[Original]</code>. Read Track names and language tags. <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> At least one audio language matches. <code>subs_contain</code> At least one subtitle language matches. <code>subs_contain_all</code> Every listed language must be present. <code>dual</code> / <code>multi</code> / <code>dubbed</code> <code>true</code> matches when that filename variable is set, <code>false</code> when it is not. <p>Each language condition takes one language tag or a list of them. A list matches when any entry matches, except <code>subs_contain_all</code>, which needs them all. An entry that is not a valid language tag (for example <code>japanese</code>) never matches. A tag with a region matches only that variant, so <code>audio: es-419</code> does not match <code>es-ES</code> audio. <code>dual</code>, <code>multi</code> and <code>dubbed</code> take a bare <code>true</code> or <code>false</code>, not a quoted string. unshackle skips a rule with a condition name it does not know, or with any other value in a boolean condition. It logs a warning in each of these cases and tries the next rule.</p> <p><code>dual</code>, <code>multi</code> and <code>dubbed</code> carry the same meaning as the filename variables of those names. Pair one with a language to name a release yourself, in place of the fixed <code>DUAL</code>, <code>MULTi</code> and <code>DUBBED</code> text. A rule that names <code>dubbed: true</code> and a language tags a localized dub without tagging a native release the same way.</p> <pre><code>language_tags:\n rules:\n - audio: [ja]\n subs_contain: [en]\n tag: \"SUBBED\"\n - audio: th\n dubbed: true\n tag: \"THAIDUB\"\n - audio: th\n dual: true\n tag: \"THAIDUAL\"\n</code></pre> <p>Put <code>{lang_tag}</code> where you want the name</p> <p>These rules fill <code>{lang_tag}</code>. To use your own name in place of the fixed text, keep <code>{lang_tag?}</code> in the template and leave out <code>{dual?}</code>, <code>{multi?}</code> and <code>{dubbed?}</code>.</p>"},{"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/download/#hdr10plus_probe","title":"<code>hdr10plus_probe</code>","text":"<ul> <li>Type: <code>bool</code> \u00a0\u00b7\u00a0 Default: <code>true</code></li> </ul> <p>Find the HDR10+ tracks that a service labels as HDR10. Before unshackle lists or selects tracks, it reads the first fragment of HEVC HDR10 tracks from DASH, HLS fMP4 and one-file sources. A track whose first frame carries HDR10+ (SMPTE ST 2094-40) metadata becomes <code>HDR10P</code>. Then <code>-r HDR10P</code>, <code>--list</code> and <code>--generate-dv</code> use it.</p> <p>unshackle also probes HEVC Dolby Vision tracks. A DV track that carries HDR10+ keeps its <code>DV</code> range, so <code>-r DV</code> selects it, and <code>--list</code> shows it as <code>DV+HDR10P</code>. <code>-r HYBRID</code> uses it as the hybrid of its resolution, with no base track. The HDR10 tracks and the DV tracks of a title are sampled as two separate sets.</p> <p>When two HDR10 tracks have the same resolution, they can be an HDR10 encode and an HDR10+ encode side by side, so unshackle probes every track. When each track has its own resolution, unshackle probes the two highest and the two lowest bitrates first:</p> Result Action All four carry HDR10+ Every HDR10 track of the title becomes <code>HDR10P</code>. Some carry HDR10+ The title has HDR10 and HDR10+ encodes side by side, so unshackle probes every track. None carry HDR10+ Every track stays <code>HDR10</code>. <p>A probe that fails, or a fragment whose metadata is encrypted, keeps the label from the service. unshackle does not probe ISM tracks. Each probe makes one to three small requests: the 64 KiB fragment, plus the playlist of an HLS track or the header of a one-file track. The probes run in parallel, with no more at a time than <code>--workers</code> (or <code>dl.workers</code>) sets for a track download.</p> <pre><code>hdr10plus_probe: true\n</code></pre> <p>A remote server probes its tracks before it sends them, so the setting on the server applies to remote downloads and to the REST API.</p>"},{"location":"reference/configuration/download/#generate_dv_mode","title":"<code>generate_dv_mode</code>","text":"<ul> <li>Type: <code>str</code> \u00a0\u00b7\u00a0 Default: <code>v29</code></li> </ul> <p>How <code>--generate-dv</code> sets the Level 1 brightness values of the Dolby Vision it makes from HDR10+. All modes make one shot per HDR10+ scene and keep the same peak and letterbox area. They differ in the scene average, which the TV uses to tone-map.</p> Mode Scene average <code>v29</code> (default) unshackle's average from the HDR10+ brightness distribution, at least about 2.4 nits. Closest to the pixels. <code>v40</code> The same average, at least about 10 nits, as in studio Dolby Vision (CM v4.0). Dark scenes read brighter than <code>v29</code>. <code>legacy</code> The <code>dovi_tool generate --hdr10plus-json</code> average. Most scenes read brighter than the pixels. <pre><code>generate_dv_mode: v29\n</code></pre> <p>The setting applies on the machine that runs the hybrid step: the client for a remote download, the server for a REST API job.</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: an override (<code>dl --cdm &lt;name&gt;</code>, or the <code>cdm</code> field of an API job) wins, then the per-service entry, then <code>default</code>. An override pins one device for the whole run and skips any quality or Widevine/PlayReady sub-entries.</p> <p>Over <code>--remote</code>, an override also makes your device license the remote session, not the server CDM. A per-service entry does the same when it names a device without a quality: a device name, a <code>widevine</code> or <code>playready</code> sub-entry, or a profile or <code>default</code> sub-entry. A per-service entry that selects only by quality, or only for a different profile, loads no device when the run starts. unshackle then shows a warning, and the server decides who licenses the remote session. With only the top-level <code>default</code> entry, the server CDM licenses when the API key has it. See <code>remote_services</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>When an entry holds <code>widevine</code> and <code>playready</code>, their order sets which device unshackle loads first. A track that offers the two DRM systems licenses with that system. A track that offers only the other system uses the other device. A <code>widevine</code> / <code>playready</code> dict in a quality key does not set the order. The server CDM of a remote session follows the same order.</p> <p>A quality key can also hold a dict of <code>widevine</code> / <code>playready</code> devices, and so can the top-level <code>default</code> entry:</p> <pre><code>cdm:\n default:\n widevine: chromecdm_l3\n playready: sl2000\n EXAMPLE1:\n \"&gt;=1080\": { widevine: android_l1, playready: sl3000 }\n \"&lt;1080\": { widevine: chromecdm_l3, playready: sl2000 }\n</code></pre> <p>A quality key that holds one device name applies to both DRM systems. When a track needs the other system, unshackle uses the <code>widevine</code> / <code>playready</code> config key of the entry. <code>dl --all-drm</code> needs a device for each system from one of these shapes.</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>Serve APIs behind a proxy</p> <p>unshackle does not send upstream's <code>HEAD</code> request or examine the <code>Server</code> response header, so the server can operate behind a reverse proxy or a CDN that removes or changes that header. Thus a <code>host</code> that is not a serve API fails at the first licence request, not when unshackle loads the CDM. On a redirect to a different host or port, unshackle removes the <code>secret</code> from the request.</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>, <code>L3</code> (Widevine) or <code>SL2</code>, <code>SL3</code> (PlayReady). The host decides which of these names it serves. <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/drm/#decrypt_segments","title":"<code>decrypt_segments</code>","text":"<ul> <li>Type: <code>bool</code> \u00a0\u00b7\u00a0 Default: <code>false</code></li> </ul> <p>Decrypts each fragmented MP4 segment as it arrives, instead of decrypting the whole track after the download ends. The decryption runs during the download, so the wait after the last segment goes away. The output file is the same either way.</p> <p>This works with <code>mp4decrypt</code> only. Set <code>decryption</code> to <code>mp4decrypt</code> for the service (or as the default); with <code>shaka</code> the option has no effect, because shaka-packager cannot decrypt a segment without its init segment. It applies to DASH tracks and to HLS tracks that use one init segment, one <code>EXT-X-KEY</code> and no <code>EXT-X-DISCONTINUITY</code>. Every other track keeps the whole-file decryption.</p> <p>No resume</p> <p>A track that decrypts segment by segment always downloads from the start. <code>continue_downloads</code> cannot reuse its segments, because a reused segment is already decrypted.</p> <pre><code>decrypt_segments: true\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. A bare <code>--proxy</code> query tries Basic first, then the other proxy providers in the order of their sub-keys, and Control D last (see Provider load order). 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 Control D <code>controld</code> Write API token (profile/resolver pairs optional) <code>http://127.0.0.1:{port}</code> (local forwarder) 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>"},{"location":"reference/configuration/network/#controld","title":"<code>controld</code>","text":"<p>Config keys of the Control D proxy provider. See Control D for how unshackle uses them.</p> Key Type Default Meaning <code>token</code> <code>str</code> required A Control D API token of type Write. <code>profile</code> <code>str</code> none Optional. The ID of a profile you made for unshackle. Give it together with <code>resolver</code>. Without it, unshackle creates <code>unshackle-&lt;region&gt;</code> profiles itself. <code>resolver</code> <code>str</code> none Optional. The resolver ID of an endpoint that uses <code>profile</code>, or its DoH URL <code>https://dns.controld.com/&lt;resolver&gt;</code>. <code>profiles</code> <code>list</code> <code>[]</code> Optional. More pairs, each a mapping with <code>profile</code> and <code>resolver</code>. <code>max_profiles</code> <code>int</code> <code>4</code> The most profiles unshackle uses: your pairs plus the <code>unshackle-*</code> endpoints on the account. It must be 1 or more. unshackle creates an <code>unshackle-&lt;region&gt;</code> profile and endpoint only while the total is lower. <p>Provider loading differs between CLI and REST server</p> <p>The <code>dl</code> CLI loads all providers, including <code>gluetun</code>. The REST API / remote-client path does not load <code>gluetun</code>, because it starts a local Docker container. 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-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 <code>wait</code> <code>false</code> <code>true</code> makes unshackle wait for the script to exit before carrying on. See Waiting for a script <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>By default, 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, set <code>wait: true</code>, queue the work inside the script, or use <code>mode: season</code>.</p>"},{"location":"reference/configuration/post-scripts/#wait","title":"Waiting for a script","text":"unshackle.yaml<pre><code>post_scripts:\n - command: \"python /opt/upload.py --file={filepath}\"\n wait: true\n</code></pre> <p>With <code>wait: true</code>, unshackle waits until the script exits, then writes the exit code to the debug log and carries on. Because the <code>file</code> post-script runs between titles, unshackle runs one script at a time over a season pack instead of starting them all at once. unshackle only logs the exit code: a failing script does not fail the download or change unshackle's own exit code. <code>--postscript</code> entries never wait.</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>{part}</code> Part number of a split episode as a plain number (<code>1</code> for <code>Part.1</code>). Empty when the episode has no part <code>{season_episode}</code> <code>{absolute}</code> <code>{date}</code> As in the filename template: <code>{season_episode}</code> keeps the part suffix (<code>S01E05.Part.1</code>) while <code>{episode}</code> drops it <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>, <code>{episode}</code> or <code>{part}</code>, and music has none of them.</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 post-script is a <code>failure</code> one. A failed download has no output file to read metadata from, so everything that comes from the output file 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 post-script gets the release fields instead of the season and episode ones. <code>{season}</code>, <code>{episode}</code>, <code>{part}</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> post-script <code>{title}</code> is the track name. See Modes for what an album post-script 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 dispatches the post-script, and not at the start of the run. The title search inside the download loop finds an episode's TMDB ID, so a post-script 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 post-script 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> post-script fires when the last title this run queued for that season finishes. With <code>-w S01-S02</code> the S01 post-script runs while S02 is still downloading. It says nothing about whether the season is complete on disk. Downloading a single episode fires the post-script 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> post-script for that title and then returns. It downloads no further title, and no <code>season</code> or <code>run</code> post-script fires after that point. This applies to every title type. If one episode of S01 fails, the S01 post-script does not fire at all.</p> <p>unshackle attaches the post-script 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> post-script 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> post-script <code>{title}</code> and <code>{title_raw}</code> are the track name. In an album post-script 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 post-script.</p> <p>An album post-script obeys the same rule as a season post-script. 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 post-script as soon as that track lands. If a track fails, the run stops there, so the album post-script 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> post-script 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> post-script 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>{part}</code>, <code>{season_episode}</code>, <code>{absolute}</code>, <code>{date}</code>, <code>{episode_name}</code>, the music release fields such as <code>{artist}</code> and <code>{album}</code>, <code>{service}</code>, the tagging IDs and <code>{error}</code>. Everything that comes from the output file, such as <code>{quality}</code>, <code>{hdr}</code>, <code>{vcodec}</code> and <code>{acodec}</code>, is empty.</p> <p>A resumed <code>--continue-downloads</code> download that finishes runs <code>success</code> as usual. unshackle sees your script's exit code only when that entry sets <code>wait: true</code>, and even then it only writes the code to the debug log. Nothing else reports a failing script. Your script owns its own error handling and logging.</p> <p>A <code>success</code> post-script 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/#-no-postscript","title":"<code>--no-postscript</code>","text":"<p><code>dl --no-postscript</code> operates the run with no post-script. It silences every configured entry and every <code>--postscript</code> command, for each event and mode. Use it to skip an uploader or a notifier for one run without an edit to <code>unshackle.yaml</code>.</p> <pre><code>$ unshackle dl --no-postscript SERVICE TITLE_ID\n</code></pre>"},{"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 post-script 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> post-script operates under <code>--no-mux</code> or <code>--skip-dl</code>, because neither writes a muxed output. A <code>failure</code> post-script still runs under <code>--no-mux</code> if the download itself fails.</li> <li><code>failure</code> post-scripts 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. Set <code>remote: true</code> to send the <code>dl</code> and <code>search</code> runs of that service to a remote server without <code>--remote</code>. Add <code>server</code> to select one of several servers. On the command line, <code>--local</code> and <code>--server</code> override these keys. A REST API job ignores both keys. A REST API job takes the other keys that it accepts as download parameters as its defaults, above the <code>serve</code> defaults and below the values that the request sends. See making a service remote by default.</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, an optional <code>timeout</code> in seconds, and an optional <code>services</code> sub-dict of per-service local overrides such as <code>title_map</code>.</p> <p>Leave <code>server_cdm</code> unset and the client follows the server: it uses the server CDM for each service the API key has it on, and the local CDM for the others. <code>true</code> asks for the server CDM and falls back to the local CDM when the server refuses; <code>false</code> always uses the local CDM. <code>dl --cdm &lt;name&gt;</code> on a remote run has the same effect as <code>false</code> for that run: the device you name licenses the remote session. A <code>cdm</code> entry for the service has the same effect for that service when it names the device that unshackle loaded. Both take priority over <code>server_cdm: true</code>. Remove the entry to use the server CDM for that service. The <code>default</code> entry does not count.</p> <p>The server has the last word. When it keeps the server CDM for a remote session that your device was to license, unshackle shows a warning. This occurs with a server that does not read your choice, and with a service option that runs the remote session on the server's device.</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 unshackle always appends as fallbacks. It 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><code>timeout</code> is the time in seconds that the client waits for data from the server. The default is <code>120</code>. The server sends a heartbeat every 30 seconds while it gets titles, tracks or licences, so a slow service does not cause a timeout. Increase <code>timeout</code> only when the server runs an older version that sends no heartbeat. Give a number of seconds. With a value below 30 the client can time out before the first heartbeat. <code>0</code> means the default.</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. Service names resolve against the server's tags and aliases, not your local services. If the server does not offer a name to your API key, unshackle rejects the name and lists the tags it does offer. 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 the server accepts in the <code>X-Secret-Key</code> header. Required unless you start the server with <code>--no-key</code>. <code>users</code> dict <code>{}</code> Per-user API keys and their allowlists (see below). <code>tiers</code> dict <code>{}</code> Named settings that <code>users</code> entries reference by name (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>dashboard</code> dict (unset) Developer dashboard: <code>key</code> is the API key for the read-only <code>/api/dashboard/</code> endpoints (status, remote sessions, remote session logs, jobs, keys, services, health, logs, SSE events). Unset leaves those routes unregistered. See dashboard endpoints. <code>session_ttl</code> int (s) <code>300</code> Seconds a remote session can stay idle before it expires. A remote client sends keep-alive requests to its remote session during a download, so the remote session does not expire during a long download. <code>max_sessions</code> int or null <code>100</code> Maximum concurrent remote sessions; at the cap the server evicts the oldest. Set it to <code>null</code> or <code>0</code> for no limit, which is also what <code>/api/dashboard/status</code> then reports, so a dashboard can tell \"no cap\" from a cap that happens to sit at the default. <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>services_refresh_interval</code> int (s) <code>0</code> How often the server pulls the git-backed service repositories in <code>directories.services</code> and hot-reloads the services that changed. <code>0</code> turns it off. A service with a running or queued job, or a live remote session, is staged and swaps to the new code as soon as its last job and session finish. <code>services_staged_max_age</code> int (s) <code>0</code> How long a staged service waits for its jobs and sessions before the server swaps it in anyway. <code>0</code> waits forever. Set it on a server whose popular services never have a quiet moment. A session that is live at the swap keeps the old code until it ends; a running job keeps its old code too. <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>). Each download job gets an equal share: the cap divided by the number of download job slots (2 by default, see job lifecycle). A job that runs alone still gets only its share. The server ignores per-job speed limits 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>server_accounts</code> dict <code>{}</code> Services whose remote sessions use the server's own <code>credentials</code> and cookie files instead of the client's (see below). <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>Reload <code>serve</code> settings without a restart</p> <p>Send <code>SIGHUP</code> to a running server (<code>systemctl reload</code> with <code>ExecReload=kill -HUP $MAINPID</code> in the unit) after you edit the file. The server reads the whole file again, globs the device directories again, and swaps in the new <code>users</code>, <code>tiers</code>, <code>services</code> and device lists in one step. Open CDM sessions and remote sessions continue; an API key you removed gets <code>401</code> on its next request. A file that does not parse or validate keeps the running settings and logs the reason. A change to <code>remote_only</code>, <code>services_refresh_interval</code>, the first PlayReady device, or any command-line flag needs a restart, and the log says so. A new <code>global_speed_limit</code> applies to jobs that start after the reload; running jobs keep their share. Windows has no <code>SIGHUP</code>: restart the server there.</p> <p><code>server_cdm</code> decides whether the server runs the CDM licensing for that API key. Set it to <code>true</code> to enable every service, or to a list of service tags to enable only those. It is <code>false</code> unless the entry sets it. For a service the API key does not cover, the server tells a remote client configured with <code>server_cdm: true</code> 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> for that service 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> <p>A remote client that picks its own device licenses the remote session with that device. It picks with <code>dl --cdm</code>, with a <code>cdm</code> entry for the service, or with <code>server_cdm: false</code> in its <code>remote_services</code> entry. The server CDM makes no licence for that remote session, with or without a limit. A service option that runs the remote session on the server's device, such as a server-identity flag, keeps the server CDM.</p> <p><code>server_cdm_max_height</code> limits the live licences the server's device makes for that API key. Set it to a height in pixels for every service, or to a map of service tag to height with an optional <code>default</code> entry. A service the map does not name or sets to <code>null</code> gets the <code>default</code>, and with no <code>default</code> it has no limit. The server compares the limit with the lowest <code>-q</code> that selects the track: the track height, or the 16:9 height from the width when that is lower. The server reads the remote client's <code>-q</code> when the remote session starts:</p> <ul> <li>With no <code>-q</code>, or a <code>-q</code> at or below the limit, the server CDM licenses the remote session. The server refuses a live licence for a video track taller than the limit, and the client licenses that track with its own local CDM.</li> <li>With a <code>-q</code> above the limit, the client's own local CDM licenses every track of the remote session. The service sees the DRM system and security level of the client's device. A client with no local CDM gets a <code>SERVER_CDM_CAPPED</code> error.</li> <li>A download job must pass a <code>quality</code> at or below the limit, and must not set <code>best_available</code> or a <code>HYBRID</code> range. <code>HYBRID</code> can keep the lowest Dolby Vision track, at any quality. A job with no <code>quality</code>, with a higher one, with <code>best_available</code>, or with <code>HYBRID</code> gets a <code>SERVER_CDM_CAPPED</code> error. The server checks the values the job runs with, after it applies the service defaults and the <code>serve:</code> download defaults.</li> </ul> <p>The limit protects the server's device, not the content keys. For a Widevine track, a server vault still supplies a content key at every height. A PlayReady track never reads the vault, so above the limit it always goes to the client's device. A licence for a lower track can carry the content key of a higher track when the service shares one content key between them. With server accounts enabled, a client that reports a stronger device than it holds makes the server's account request those manifests; the licence server still refuses its challenge.</p> <p><code>server_vault</code> lets a remote session that the client's own device licenses take content keys from the server vault. Set it to <code>true</code> for every service, or to a list of service tags. It is <code>false</code> unless the entry sets it, and <code>server_cdm</code> for a service implies it. The server looks up every KID of the track in its vault and makes no live licence. A track that the vault does not hold goes back to the client's device. When the service runs the remote session on the server's own device (a service option, such as a server-identity flag), the client's own vaults, and the server vault with this grant, are the only source, and a missing content key stops the download.</p> <p><code>admin</code> is a boolean that lets the API key run the maintenance endpoints (clear-cache, clear-temp, refresh-services). It is <code>false</code> unless the entry sets it. Keys that have no <code>users</code> entry, such as <code>api_secret</code>, keep that access.</p> <p>A <code>tier</code> names an entry under <code>serve.tiers</code>, which holds the settings that several API keys share. Today a tier carries <code>rate_limit</code>, the requests per hour that API key may make; an API key can also set its own <code>rate_limit</code>, which wins over its tier's. An API key with neither has no limit. Going over the limit answers <code>429</code> with a <code>Retry-After</code> header. The server keeps a fixed window rather than a sliding one: it opens on the first request and resets an hour later. A <code>tier</code> that names no entry under <code>serve.tiers</code>, or a <code>rate_limit</code> that is not a positive whole number, stops the server at startup, because the alternative is an API key that silently gets no limit. The rate limit never applies to the dashboard key, and never to <code>/api/health</code>.</p> <p><code>server_accounts</code> lists, per service, the accounts the server lends to remote sessions. A remote session for a listed service ignores the credentials, cookies, and cache the client sends and uses one of the server's own profiles from <code>credentials</code>. For a service that is not listed the server never uses its own accounts: a client that sends nothing authenticates with nothing.</p> <pre><code>credentials:\n EXAMPLE1:\n ca_main: user1@example.com:pw1\n eu_box: user2@example.com:pw2\n shared: user3@example.com:pw3\n\nserve:\n server_accounts:\n EXAMPLE1:\n ca_main: ca # one country\n eu_box: [gb, fr, de] # a list of countries\n shared: global # any region\n EXAMPLE2: true # every profile (or the single credential), any region\n</code></pre> <p>Each entry under a service names a profile from <code>credentials</code>, or a cookie file <code>cookies/&lt;TAG&gt;/&lt;profile&gt;.txt</code> for a service that has no credentials. Its value is the region or regions that account works in: a two-letter country code, a list of them, or <code>global</code>. Quote <code>no</code> (Norway), because YAML reads the bare word as <code>false</code>.</p> <p>The region of a remote session is the country the client asked for with <code>--proxy</code> (<code>ca</code>, <code>ca1</code>, <code>provider:ca</code>), the server's own region with <code>--no-proxy</code>, or the client's own region otherwise. A full proxy URI carries no country, so with one only a <code>global</code> account matches. The server picks the profiles that cover that region (or are <code>global</code>) and rotates through them round-robin, one account per remote session. With no matching account it rejects the remote session. These services ignore the client's <code>-p/--profile</code>.</p> <p>Cookies come only from the profile's own file (<code>cookies/EXAMPLE1/ca_main.txt</code>; the server does not read a bare <code>cookies/EXAMPLE1.txt</code>), and each account keeps its own persistent cache under <code>cache/_accounts/EXAMPLE1/&lt;profile&gt;/</code>, so refreshed tokens survive the remote session but never cross accounts. <code>serve</code> refuses to start when a listed profile has neither an entry under <code>credentials</code> nor a cookie file. <code>/api/search</code>, <code>/api/list-titles</code> and <code>/api/list-tracks</code> use the same pool, matched on the client's reported region, and return <code>FORBIDDEN</code> to an API key without the opt-in. Rotation is per process and does not track which accounts are in use, so concurrent remote sessions can share one account.</p> <p>A <code>users</code> entry opts in to those accounts with <code>server_accounts: true</code> (every listed service) or a list of service tags. It is off unless set: an API key without it authenticates with the credentials the client sends, as for any other service, and <code>/api/services</code> does not advertise the server's accounts to it. API keys with no <code>users</code> entry, such as <code>api_secret</code>, keep access.</p> <p><code>server_proxy</code> decides whether that API key may use the proxy providers the server has configured. There is no implicit access: only the boolean <code>true</code> on the API key's <code>users</code> entry grants it, and an API key without a <code>users</code> entry has no access either. Without the opt-in the server never spends its own proxy subscriptions on a remote client: not to resolve a country code in <code>proxy</code>, not to match the client's region, and not for a service geofence. This applies to remote sessions, search, title lists, and <code>/api/download</code> jobs alike. Such a client must send a full proxy URI, or <code>no_proxy</code> to accept the server's own connection. Set <code>server_proxy: true</code> to let that API key send a country code or a <code>provider:country</code> value, and to let the server pick a proxy for the client's region and for a service geofence. The client reports its own region; a client that reports none is not blocked.</p> <pre><code>serve:\n api_secret: change-me\n remote_only: true\n services: [EXAMPLE1, EXAMPLE2]\n services_refresh_interval: 3600 # pull the service repositories hourly and reload what changed\n # server-wide download defaults (same keys as the `dl:` block)\n downloads: 3\n best_available: true\n tiers:\n bot: { rate_limit: 600 } # requests per hour, for every key on this tier\n users:\n a1b2c3d4: # this user's API key\n services: [EXAMPLE1] # may only use EXAMPLE1\n tier: bot # 600 requests/hour; 429 with Retry-After once over\n e5f6a7b8:\n server_cdm: true # this key may have the server do the licensing\n server_cdm_max_height: 1080 # above 1080p the client licenses with its own device\n c9d0e1f2:\n services: [EXAMPLE1, EXAMPLE2]\n server_cdm: [EXAMPLE1] # the server licenses only EXAMPLE1; EXAMPLE2 needs a local CDM\n server_accounts: [EXAMPLE1] # may authenticate EXAMPLE1 with one of the server's own accounts\n server_proxy: true # this key may also use the server's proxy providers\n f3a4b5c6:\n services: [EXAMPLE1]\n server_vault: [EXAMPLE1] # the client's device licenses; the server vault still serves keys\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>connect_timeout</code> defaults to <code>vault_timeout</code>. <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> <p>Bad content keys</p> <p>A content key from a vault is proven by short FFmpeg decodes of the decrypted output, with windows inside the fragments of each KID in a fragmented MP4. A content key that fails the decode is written to the <code>bad_keys</code> table of every <code>SQLite</code> vault with the name of the vault that supplied it, and every vault lookup skips a flagged pair from then on. A <code>SQLite</code> vault also refuses to store a flagged pair again. Only the <code>SQLite</code> backend stores flags; an <code>API</code> vault that supplied the pair gets a report. A <code>serve</code> instance with <code>server_cdm</code> flags a pair the same way when a remote client reports it, so a server whose <code>key_vaults</code> hold no <code>SQLite</code> entry cannot remember a bad content key.</p>"},{"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). The <code>MySQL</code> backend uses it as the default <code>connect_timeout</code>.</p> <p>The <code>API</code> and <code>HTTP</code> backends send a request again up to 3 times when the vault answers <code>429 Too Many Requests</code>. They wait the <code>Retry-After</code> time, but never longer than this timeout. A connection failure or a timeout is not tried again. The run does not use a vault again after a connection failure, a timeout, or a <code>429</code> that continues after the retries, so a vault that is down costs one timeout per run.</p>"}]}