diff --git a/dev/rest-api/endpoints/index.html b/dev/rest-api/endpoints/index.html index 75a8f4f0..7cbcb261 100644 --- a/dev/rest-api/endpoints/index.html +++ b/dev/rest-api/endpoints/index.html @@ -3654,7 +3654,7 @@ ignore it safely. See Split e
dl_paramsdl track selection that the service reads from ctx.parent.params: lang, v_lang, a_lang, acodec and forced_subs, as on POST /api/session/create. Some services select the manifests they fetch from these values.dl track selection that the service reads from ctx.parent.params: lang, v_lang, a_lang, acodec, forced_subs and exact_lang, as on POST /api/session/create. Some services select the manifests they fetch from these values.error_code and retryable to decide what to do.
the newlines must go out at once.
POST /api/session/create¶Make a remote session for a service and title. Authentication runs asynchronously in the background. This call returns immediately with status: "authenticating", and you then poll the prompt endpoint. The body accepts service and title_id (both required). It also accepts a broad set of optional keys, because the body allows additionalProperties. These are credentials ({username, password, extra?}), cookies (base64 of zlib-compressed Netscape cookie file), proxy, no_proxy, profile, cache (map of forwarded cache files, keyed by the file path relative to the service cache directory with / separators and no .json suffix, so a nested key such as session_web/<sha1> lands in a subdirectory), client_region, proxy_region, cdm_type, range_, vcodec, quality, best_available, dl_params, client, and any service CLI options. proxy_region is the country code the client resolved proxy from; the server matches it against its own accounts. client is a freeform object the dashboard shows as sent (the CLI puts version, code_hash, platform and a redacted argv in it); the server ignores it above 4096 bytes of JSON.
dl_params is an object with the dl track selection: lang, v_lang and a_lang (arrays of language strings), acodec (an array of audio codec names or dl -a aliases such as ddp) and forced_subs (boolean). The service reads these values from ctx.parent.params. The server uses the dl default for each absent or malformed value, and drops an unknown codec name.
dl_params is an object with the dl track selection: lang, v_lang and a_lang (arrays of language strings), acodec (an array of audio codec names or dl -a aliases such as ddp), and forced_subs and exact_lang (booleans). The service reads these values from ctx.parent.params. The server uses the dl default for each absent or malformed value, and drops an unknown codec name.
Service CLI options also travel in a nested service_params object, which wins over a flat key with the same name. profile at the top level always means the credentials profile, never a service's own --profile option.
The proxy value must be a full proxy URI, unless the operator gives your API key server_proxy in the serve.users config. Without server_proxy, the server does not resolve country codes with its own proxy providers. It rejects the request with INVALID_PROXY when no proxy is set and the reported client_region differs from the server's region. A request that reports no client_region is not blocked. Pass proxy with your own proxy, or no_proxy to accept the server's own connection. With server_proxy, the server resolves a country code and picks a proxy for your client_region itself. A Control D resolver, controld://<resolver>@dns.controld.com, counts as a full proxy URI: the server runs a forwarder for it and needs no Control D configuration of its own.
range_<
(additionalProperties: true).
dl_params holds the dl track selection: lang, v_lang and a_lang
(arrays of language strings), acodec (an array of audio codec names, such as
-EC3), and forced_subs (boolean). The server gives these values to the
+EC3), and forced_subs and exact_lang (booleans). The server gives these values to the
service in ctx.parent.params, never as service options, so a service option
with the same name, such as an own --lang, does not get them. The server uses
the dl default for each absent or malformed value: lang is ["orig"],
-v_lang, a_lang and acodec are [], and forced_subs is false. The
+v_lang, a_lang and acodec are [], and forced_subs and exact_lang are false. The
server drops an unknown codec name. An empty array is a valid value and stays
empty.
The server does not forward the dl mode flags: video_only, audio_only,
diff --git a/search/search_index.json b/search/search_index.json
index 9762841b..28854aba 100644
--- a/search/search_index.json
+++ b/search/search_index.json
@@ -1 +1 @@
-{"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":"
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.
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.
Use responsibly
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.
"},{"location":"#what-it-does","title":"What it does","text":"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:
- Fetch the title metadata (movies, full series, seasons, episodes, albums, tracks).
- Parse the streaming manifest: DASH, HLS, or Smooth Streaming (ISM).
- Select the tracks you asked for by resolution, codec, bitrate, range, language, and channel layout.
- 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.
- Decrypt, extract closed captions, repack, and mux the result into a Matroska (
.mkv) file with correct language, forced, and default flags. - Tag and name the output using configurable filename templates.
"},{"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; 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":"A git clone with the install script is the recommended way to install unshackle.
Linux (recommended)Windows (recommended)Advanced: uv tool git clone https://github.com/unshackle-dl/unshackle.git\ncd unshackle\nsh install.sh\nuv run unshackle env check\n
git clone https://github.com/unshackle-dl/unshackle.git\ncd unshackle\n.\\install.bat\nuv run unshackle env check\n
uv tool install git+https://github.com/unshackle-dl/unshackle.git\nunshackle setup\n
This installs unshackle into the tool folder of uv, not a folder that you choose. unshackle setup then puts the tools, config, and data in your user data and config directories.
The install script installs uv and unshackle, then runs unshackle setup. In a clone, run every command as uv run unshackle .... The examples on this site use the bare unshackle command.
External tools
unshackle shells out to FFmpeg, MKVToolNix, shaka-packager, Bento4, and dovi_tool for decryption, repacking, muxing, and Dolby Vision work. unshackle setup downloads them when a portable build exists for your system. See Installation for the full list and recommended versions.
"},{"location":"#a-first-download","title":"A first download","text":"Every download is three parts: the dl command, a service tag, and the service's title argument (a URL, ID, or slug).
Download a 1080p title with English audiounshackle dl -q 1080 -l en EXAMPLE 81234567\n
The dl command carries all the quality, language, and output flags. The service tag (EXAMPLE 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.
"},{"location":"#where-to-go-next","title":"Where to go next","text":" - Installation. Install unshackle and the external tools it depends on.
- Quickstart. Configure
unshackle.yaml and do your first download. - Downloading. The full
dl command guide: quality, codecs, languages, track selection, and output. - Configuration. Where
unshackle.yaml lives, the directory layout, and how to edit values. Full config key list in the Configuration Reference. - REST API. Operate the
serve HTTP server and drive downloads programmatically.
Getting help
Operate unshackle --help or unshackle dl --help at any time. The community Discord is the fastest place to ask questions.
"},{"location":"dev/creating-a-service/","title":"Creating a Service","text":"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).
Who this page is for
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.
unshackle ships two reference services. EXAMPLE, at unshackle/services/EXAMPLE/, 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 unshackle/services/MUSIC_EXAMPLE/, is the same kind of showcase for a music service. If your platform has songs, read that one too.
"},{"location":"dev/creating-a-service/#how-unshackle-finds-a-service","title":"How unshackle finds a service","text":"At startup unshackle scans every path in the directories.services config key (a list). Each entry is either a local directory of services or a remote repo spec (a git URL or owner/repo shorthand, which unshackle clones for you). The default is the bundled unshackle/services directory.
Within a services directory, every subfolder that contains an __init__.py is a service, and the folder name is the service tag:
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
Two rules the loader enforces:
- The class name must match the folder/tag name exactly. Folder
EXAMPLE must define class EXAMPLE. A mismatch raises a RuntimeError. - 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.
After installation, you call a service as a subcommand of dl:
unshackle dl EXAMPLE 20914\nunshackle dl EX 20914 # via an ALIAS\n
Config lives next to the code
A service's own settings go in config.yaml inside the service folder (directories.services/<TAG>/config.yaml). This is separate from the global unshackle.yaml. Access it in code as self.config[...]. Never hardcode URLs, user agents, or certificates. Put them here.
config.yaml is shared: keep secrets out of it
Treat config.yaml 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 unshackle.yaml under services.<TAG>, which is merged into self.config at runtime. That checked-in-defaults / per-user-overrides split is exactly why every URL lives in config.yaml with {}/{name} placeholders while the secrets that fill them stay out of it. Both halves read back through the same self.config[...].
Split across files? Use relative imports
If your service grows beyond a single __init__.py, import your own modules relatively:
from .helpers import parse_manifest # correct\nfrom unshackle.services.TAG.helpers import parse_manifest # breaks from a repo\n
A service loaded from a remote repo lives outside the unshackle package, so Python cannot find the absolute unshackle.services.<TAG>.* path and the import fails with no known parent package. Relative imports work both locally and from a cloned repo.
"},{"location":"dev/creating-a-service/#the-service-base-class","title":"The Service base class","text":"Every service subclasses unshackle.core.service.Service. The minimum is a Click cli entry point plus three abstract methods.
"},{"location":"dev/creating-a-service/#class-variables","title":"Class variables","text":"Declared at class level to configure framework behaviour:
Variable Type Purpose ALIASES tuple[str, ...] Extra tags that resolve to this service (e.g. (\"EX\", \"DOMAIN\")). Case does not matter. Default (). GEOFENCE tuple[str, ...] IP region codes the service requires. Empty = no geofence. unshackle treats the first entry as the main region for auto-proxy. GEOBLOCK tuple[str, ...] IP region codes where the service refuses to work. Every other region is allowed. Default (). VAULT_TAG Optional[str] Overrides the key-vault namespace so sibling services can share one vault. Default None (use the service's own tag). AUTH_METHODS Optional[tuple[str, ...]] Auth methods accepted (\"cookies\" / \"credentials\"). When None, the REST /services endpoint infers them from authenticate(). ANONYMOUS_SEARCH bool Set True when search() needs no login and no state from authenticate(). A search then skips the cookie load, authenticate() and the cookie save. Default False. NO_SUBTITLES bool Set True on a service with no subtitle tracks to skip subtitle handling entirely. ANIME bool Set True when the catalogue is anime, so metadata lookups prefer AniList. A title's own anime flag overrides it. DAILY bool Set True when the catalogue is daily/date-based (talk shows, news, sports), so unshackle names episodes by air date. A title's own daily flag overrides it. NO_SUBTITLES is a convention, not a base-class attribute
dl.py uses hasattr to find NO_SUBTITLES, and the Service base class deliberately does not declare it, so it only exists if your service defines it. Setting NO_SUBTITLES = True is what makes the pipeline skip subtitle work for services that never carry subtitles. Leave it off otherwise.
GEOFENCE drives an automatic proxy: on startup, if you did not pass an explicit --proxy, the base class does a live IP check and, if your region is blocked, fetches a proxy to GEOFENCE[0] from your configured proxy providers.
GEOBLOCK is the negative form: the service works everywhere except the listed regions. With no GEOFENCE to name a main region, a GEOBLOCK hit stops the run with a \"not available in your region\" error; pass --proxy yourself.
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
"},{"location":"dev/creating-a-service/#what-service__init__-wires-up","title":"What Service.__init__ wires up","text":"When you call super().__init__(ctx), the base class sets up the attributes you will use throughout the service:
Attribute What it is self.config This service's config.yaml contents (a dict), or None if absent. self.log A logging.Logger named after your class. self.session A prepared requests.Session with config headers and a retry adapter (5 retries, backoff 0.2, retries on 429/500/502/503/504). self.cache A Cacher for arbitrary key/value data, for example authentication tokens. self.title_cache A region/account-aware TitleCacher used by get_titles_cached. self.cache_dir config.directories.cache / <ClassName>. self.track_request A TrackRequest built from the CLI --vcodec / --range / --best-available flags. self.credential None until authenticate() runs. self.current_region The two-letter region resolved from proxy/IP. self.track_request is a small dataclass you can read and rewrite before fetching tracks:
@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
Read the request, don't second-guess the user
Services may narrow track_request 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 get_tracks returns.
Override get_session() to defeat TLS-fingerprint bot detection
The base get_session() returns a plain requests.Session (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 session(\"Chrome131\") (any rnet.Impersonate preset). RnetSession is a drop-in requests.Session replacement (same .get/.post/cookie-jar interface), so nothing else in the service changes. If instead you need specific SSL cipher behaviour, mount unshackle.core.utils.sslciphers.SSLCiphers onto a plain requests.Session.
"},{"location":"dev/creating-a-service/#the-methods-you-write","title":"The methods you write","text":"unshackle calls the methods in the order shown. Only the three abstract ones are mandatory.
graph LR\n A[cli] --> B[__init__] --> C[authenticate] --> D[get_titles] --> E[get_tracks] --> F[get_chapters]
"},{"location":"dev/creating-a-service/#cli-the-click-entry-point","title":"cli: the Click entry point","text":"A static method decorated as a Click command. It defines the CLI arguments and returns an instance of your service. Keep the command name= matching the tag.
name= is cosmetic: the directory name is what resolves the command
unshackle chooses the command from the folder/class name, not from the name= in @click.command. A mismatched name= still loads and runs. It only produces confusing --help/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.
@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) -> 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
Your docstring becomes the CLI --help text (help=__doc__), so document the accepted URL/ID formats and options there.
CDM-aware behaviour
The resolved CDM is on ctx.obj.cdm (may be None for DRM-free runs). Use is_widevine_cdm() / is_playready_cdm() from unshackle.core.cdm.detect to classify it. These work correctly for local and remote CDMs, so never hand-roll an isinstance check. Services often pick a device profile or manifest endpoint based on which DRM the CDM speaks.
"},{"location":"dev/creating-a-service/#authenticate-optional-login","title":"authenticate: optional login","text":"Override to log in with cookies and/or credentials. Call super().authenticate() first: the base implementation loads the cookie jar into self.session.cookies and stores self.credential. Do all token fetching here. It runs before get_titles.
def authenticate(self, cookies=None, credential=None) -> 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) > 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
Cookies come from files under directories.cookies. Credentials come from the credentials map in unshackle.yaml. For interactive prompts (OTP, captcha) use self.request_input(prompt), never a bare input(). Under serve mode there is no local terminal, so a bare input() would hang the server waiting on stdin that never arrives. request_input instead relays the prompt to the client: a remote-dl session gets it through the attached InputBridge, and a REST download job shows it as input_prompt. Locally it routes through the shared Rich console (prompt_user) so the prompt renders correctly alongside progress and log output.
For a login that the user approves on another device (a pair code, a QR code), use self.wait_for_approval(message, check, timeout), never a hand-written loop. It shows the message, then calls check at each interval until check returns a value. check returns None while the approval is pending.
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
It raises TimeoutError after timeout seconds. Under serve 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 notice field until the wait ends.
The wait sees a cancel only between two check calls, so check must return within a few seconds. A check that reads a socket keeps the socket open across calls and returns None after each short idle wait.
Make each token cache entry unique
The cache above uses tokens_{device}_{profile} on purpose. A token cache must include every dimension that changes the token (device, profile, or credential.sha1), 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.
Use the credential carefully
Use the Credential only inside authenticate() to get tokens. Do not stash it or the raw cookie jar elsewhere. The base class already caches identity for you.
"},{"location":"dev/creating-a-service/#get_titles-required","title":"get_titles: required","text":"Return a titles collection for the given ID. The return type depends on the kind of title:
Return Contains Use for Movies Movie objects Films Series Episode objects Shows (flatten seasons into episodes) Album Song objects Music Every title carries a language (its original recorded language) and an arbitrary data 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.
def get_titles(self) -> 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
Common constructor fields:
MovieEpisodeSong Movie(id_, service, name, year=None, language=None, data=None, description=None)\n
Episode(id_, service, title, season, number, name=None, year=None,\n language=None, data=None, description=None, air_date=None,\n part=None)\n
Pass air_date for daily and sports titles to name by date instead of SxxExx. Return a Series([...]) of episodes. Pass part only when the service splits one episode into several videos, see Split episodes.
Song(id_, service, name, artist, album, track, disc=1, year=None,\n language=None, data=None, ...)\n
Return an Album([...]) of songs. disc defaults to 1 and year is optional. Optional metadata keywords such as album_artist, genre, isrc, label, lyrics and artwork_url feed the tagger and the naming templates. Read the class for the current list.
From get_tracks(), give one Audio track for each codec and bitrate you offer for the song. The framework then selects one with its usual audio options. A Song skips the muxer, so restore the real container suffix on the track path in on_track_downloaded. The MUSIC_EXAMPLE service shows the full music surface.
The ID must be unique and stable
id_ must be truthy and, if it has a length, at least 4 characters, to avoid clashes. Use the service's own stable IDs.
Title caching
You can call self.get_titles_cached() instead of get_titles() 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 title_map config.
"},{"location":"dev/creating-a-service/#split-episodes","title":"Split episodes","text":"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). Episode.number stays an int. The optional part carries the index.
Episode(..., season=1, number=1, part=1, name=\"The Reckoning\")\nEpisode(..., season=1, number=1, part=2, name=\"The Reckoning\")\n
part counts from 1, contiguous. unshackle rejects part=0, and -w can only address parts up to 99. - Every part of one episode shares the same
season and number. - Each part is a separate
Episode with its own unique id_. - Unsplit episode: leave
part unset. Never pass part=1 for a whole episode. - Do not put the part in
name or number. Pass a clean name (or None) and set part. part 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.
part accepts an int or a digit string. A value that is not an integer raises TypeError. A value of 0 or less raises ValueError.
The framework never infers a part from the episode name
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 part argument.
Clean the part out of the name
Episode discards any name that starts with Episode <number>, so a raw \"Episode 1 (Part 2): The Reckoning\" leaves you with no episode name at all. Remove the prefix before you pass it, or pass None.
Once part is set, the filename gains a part token (S01E01.Part.2, see Output & naming), -w S01E01.2 selects a single part while a bare -w S01E01 selects them all, and the --list-titles tree labels the episode 01.2. The REST API reports it as an extra part field on the serialized title, described in Endpoints.
Opt-in and additive
Leaving part unset costs you nothing: filenames, sort order, -w matching and the API JSON are identical to a plain episode, so a service that does not split episodes has nothing to adopt.
"},{"location":"dev/creating-a-service/#get_tracks-required","title":"get_tracks: required","text":"Given one title, return a Tracks object holding Video, Audio, and Subtitle tracks. In almost all cases you assemble these by parsing a manifest, not by hand.
The manifest parsers live in unshackle.core.manifests:
from unshackle.core.manifests import DASH, HLS, ISM\n
Each exposes from_url(url, session=...) (or from_text(text, url)) and then .to_tracks(language=...):
DASH (.mpd)HLS (.m3u8)ISM (Smooth Streaming) def get_tracks(self, title: Title_T) -> Tracks:\n return DASH.from_url(manifest_url, session=self.session) \\\n .to_tracks(language=title.language)\n
def get_tracks(self, title: Title_T) -> Tracks:\n return HLS.from_url(manifest_url, session=self.session) \\\n .to_tracks(language=title.language)\n
The URL must be a variant (master) playlist, not a media playlist.
def get_tracks(self, title: Title_T) -> Tracks:\n return ISM.from_url(manifest_url, session=self.session) \\\n .to_tracks(language=title.language)\n
Always pass language=
Pass the title's original language to to_tracks(language=...). For DASH and HLS this is required as a fallback. If to_tracks cannot derive a track's language and you gave no valid fallback, it raises ValueError. It is also what lets the parser flag is_original_lang on each track (through is_close_match), which drives -l best/all selection and the filename language token.
Some services deliver a separate manifest per codec/range. The base class provides get_tracks_for_variants(title, fetch_fn) to fan out over every codec\u00d7range in the TrackRequest, including HYBRID (fetch HDR10 + DV and merge) and --best-available skip-on-error handling:
def get_tracks(self, title: Title_T) -> Tracks:\n def fetch_variant(title, codec, range_) -> 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
After parsing, you may correct track metadata the manifest gets wrong: stamp the real video.range, fix odd audio channel counts, mark descriptive audio, add hand-built subtitles or an Attachment (e.g. cover art). Do not filter for resolution/bitrate. See fetch_dash_manifest in the EXAMPLE service for a thorough demonstration.
Flip HDR10 \u2192 HDR10+ by hand when you know the platform embeds it
HDR10+ is a bitstream (SEI) feature. The HLS parser intentionally does not sniff it from the bitstream, so a manifest that embeds HDR10+ SEI but labels the variant plain HDR10 will parse as HDR10. The label is the only signal the parser has, and it is wrong. Only the service author knows the platform embeds HDR10+, so it is on you to correct video.range to HDR10+ here for those services.
get_tracks is your only chance to capture license inputs
The license callbacks (get_widevine_license and the others) fire much later, in the download/decrypt step, long after get_tracks has returned, and they receive only challenge, title, and track. Nothing else from the manifest response reaches them. So you must stash anything a license call needs (the license URL, dt-custom-data, a session token) now, during get_tracks, onto self.license_data or title.data. This is a lifecycle-timing consequence you cannot infer from the callback signatures.
Give the KID if you cheaply can
If you can get a track's Key ID (32-char hex) without downloading the track data, set track.kid. It speeds up the decryption and key-lookup path. And be sure encrypted tracks carry the correct drm so the core licenses them.
"},{"location":"dev/creating-a-service/#get_chapters-required","title":"get_chapters: required","text":"Return a Chapters object of 0 or more Chapters. It sorts by timestamp, numbers the chapters at mux time, and adds a 00:00:00.000 chapter if none exists. Timestamps take \"HH:MM:SS[.mmm]\", int milliseconds, or float seconds.
def get_chapters(self, title: Title_T) -> 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
Sort by timestamp before you build the Chapters
Chapters.add() adds its own unnamed Chapter(0) once you add a chapter that is not at 0, and a duplicate timestamp raises ValueError. Sort first, so yours lands before it.
You never need to add Chapter(0). An API chapter at 0 keeps its name. Drop duplicate timestamps.
Close a named range with an unnamed chapter
An unnamed Chapter ends the range before it: Chapter(name=\"Intro\") at the start, an unnamed one where the intro ends.
Don't invent chapter names
Never write \"Chapter 1\"; leave unnamed chapters unnamed. Users set chapter_fallback_name in their config (for example, \"Chapter {i:02}\").
"},{"location":"dev/creating-a-service/#handling-drm","title":"Handling DRM","text":"The core drives licensing. Your job is to answer the license challenges the CDM produces. Mark encrypted tracks with the right DRM in get_tracks (the manifest parsers do this automatically for PSSH/EXT-X-KEY found in the manifest), then write the license callbacks you need. Each receives the challenge plus the current title and track:
Method For Returns get_widevine_service_certificate Widevine privacy mode The service certificate (bytes or base64 str), or None. get_widevine_license Widevine The raw license response (bytes or base64 str), unmodified. get_playready_license PlayReady The license response. Defaults to delegating to get_widevine_license. get_clearkey_license DASH org.w3.clearkey The JWK Set (dict/JSON/bytes), or None to let the framework POST the challenge to the manifest's Laurl. 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
Return the license untouched
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.
ClearKeyCENC (org.w3.clearkey) has three escalating integration levels
Pick the lowest level that works for the platform:
- The manifest carries a
<Laurl>: write nothing. The framework POSTs the challenge to that URL itself. - Your service needs a custom endpoint or extra headers: override
get_clearkey_license to do the POST yourself. - Keys arrive obfuscated or through a bespoke channel: fetch and unwrap the content key in
get_tracks and pre-populate drm.content_keys[kid] = key_hex on the track's ClearKeyCENC. The non-obvious payoff: when every KID is already keyed, the framework skips the license round-trip entirely.
Things the service does not do:
- HLS AES-128 (
ClearKey) tracks and DRM-free tracks have no license callback. The content key comes from the manifest, and unshackle applies it directly. - Key vaults cache
KID:KEY pairs across runs, so repeat downloads skip the license round-trip entirely. - Decryption tooling (shaka-packager or mp4decrypt) and the choice of local vs remote CDM are user configuration, not service concerns.
See the DRM & CDM reference for the full picture.
"},{"location":"dev/creating-a-service/#optional-event-hooks","title":"Optional event hooks","text":"Override any of these to react to pipeline stages (all no-ops by default): on_segment_downloaded, on_track_downloaded, on_track_decrypted, on_track_repacked, on_track_multiplex. Also override search() to yield SearchResult objects for unshackle search.
Set ANONYMOUS_SEARCH only for a search that needs no account
With ANONYMOUS_SEARCH = True, search() operates on an HTTP session with no cookies, and authenticate() does not run. Set it only when the search results do not depend on the account, and when search() does its own setup. A search() that reads a token, a header or a region from authenticate() fails or gives results for the wrong region.
def search(self) -> 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
"},{"location":"dev/creating-a-service/#minimal-service-skeleton","title":"Minimal service skeleton","text":"A complete, minimal single-manifest service. Save as services/MYSVC/__init__.py (class name MYSVC), with an optional services/MYSVC/config.yaml beside it.
services/MYSVC/__init__.pyfrom __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 <title-id-or-url>\n \"\"\"\n\n ALIASES = (\"MY\",)\n GEOFENCE = (\"US\",)\n TITLE_RE = r\"^(?:https?://myservice\\.com/watch/)?(?P<id>[\\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) -> \"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) -> None:\n super().authenticate(cookies, credential)\n # obtain any tokens here, e.g. self.token = ...\n\n def get_titles(self) -> 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) -> 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) -> 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
services/MYSVC/config.yamlendpoints:\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
Try it with:
unshackle dl MYSVC https://myservice.com/watch/abc123\n
"},{"location":"dev/creating-a-service/#checklist","title":"Checklist","text":" - Folder name, class name, and Click
name= all match the tag exactly. -
cli is a @staticmethod that returns an instance. __init__ calls super().__init__(ctx). -
get_titles, get_tracks and get_chapters written. Titles carry the original language. - Tracks come from a manifest parser with
to_tracks(language=title.language). No filtering by quality or language. - Encrypted tracks carry their DRM. The license callbacks you need return responses unmodified.
- URLs, user agents, and certificates live in
config.yaml, read through self.config[...]. - Multi-file services import their own modules relatively (
from .helpers import x), so they work when loaded from a repo.
Read unshackle/services/EXAMPLE/ end to end. It annotates every feature touched above in one place. For a music service, read unshackle/services/MUSIC_EXAMPLE/ too.
"},{"location":"dev/service-architecture/","title":"Service Architecture","text":"This page is the conceptual map of the internal object model that a service author works against. It ties together the moving parts: the Service base class, the Title hierarchy a service returns, the Track 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.
Who this page is for
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.
"},{"location":"dev/service-architecture/#the-shape-of-a-download","title":"The shape of a download","text":"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 dl command drives the whole flow and only ever calls three required methods on your service, in order:
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
get_titles() returns a Titles collection: the movies, episodes, or songs the platform exposes for the requested ID. get_tracks(title) returns a Tracks object for a single chosen title. In practice this means fetching a manifest and handing it to a parser, which builds the Video/Audio/Subtitle objects. get_chapters(title) returns any chapter markers.
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 Title and Track objects. The framework does the rest.
"},{"location":"dev/service-architecture/#the-service-base-class","title":"The Service base class","text":"Every service subclasses unshackle.core.service.Service, an abstract base class. Two kinds of members matter: class variables that give the details of the service, and methods that the pipeline calls.
"},{"location":"dev/service-architecture/#class-variables","title":"Class variables","text":"Declared at the top of your service class, these are static descriptors:
Class variable Type Purpose ALIASES tuple[str, ...] Alternate tags the service answers to, in any case (resolved by Services.get_tag). GEOFENCE tuple[str, ...] ISO region codes the service requires; empty means no geofence. unshackle treats the first entry as the \"main region\" for automatic proxy selection. GEOBLOCK tuple[str, ...] 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. VAULT_TAG Optional[str] Overrides the key-vault namespace; defaults to the service's own tag. AUTH_METHODS Optional[tuple[str, ...]] Accepted auth methods (\"cookies\" / \"credentials\"). When None, the REST /services endpoint infers them from authenticate(). ANONYMOUS_SEARCH bool search() needs no login and no state from authenticate(). A search then skips the cookie load, authenticate() and the cookie save. Default False. ANIME bool The catalogue is anime, so metadata lookups prefer AniList. A title's own anime flag overrides it. DAILY bool The catalogue is daily/date-based, so unshackle names episodes by air date. A title's own daily flag overrides it."},{"location":"dev/service-architecture/#required-methods","title":"Required methods","text":"These are abstract. A service will not load unless it defines all three:
get_titles() -> Titles_T: find the title collection for the requested ID. get_tracks(title) -> Tracks: assemble the track set for one title. get_chapters(title) -> Chapters: return chapter markers (may be empty).
"},{"location":"dev/service-architecture/#optional-methods-and-hooks","title":"Optional methods and hooks","text":" authenticate(cookies=None, credential=None): the base implementation loads a CookieJar into self.session.cookies and stores self.credential. Override it to do a real login handshake. search(): raises NotImplementedError by default. Write it so that the search command can operate. unshackle calls authenticate() first, unless the service sets ANONYMOUS_SEARCH. - DRM license hooks:
get_widevine_service_certificate, get_widevine_license, get_playready_license (delegates to Widevine by default), and get_clearkey_license (returns None by default). See DRM hooks below. request_input(prompt): prompts the user. It goes through the remote-dl input bridge, the REST download job relay, or the rich console. wait_for_approval(message, check, timeout, interval=3.0): shows a message, then calls check 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 notice. - Event callbacks:
on_segment_downloaded, on_track_downloaded, on_track_decrypted, on_track_repacked, on_track_multiplex let a service react to pipeline events (for example, MonaLisa decrypts each segment in on_segment_downloaded). resolve_server_keys(title): 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 Service base class at all: dl.py probes for it with hasattr 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.
"},{"location":"dev/service-architecture/#what-__init__-wires-up-for-you","title":"What __init__ wires up for you","text":"You rarely override __init__. The base constructor takes the Click context and sets up the objects your methods rely on:
Attribute What it is self.config The per-service config slice (see Request and HTTP session objects). self.log A logging.Logger named after your class. self.session A ready-to-use HTTP session (headers, retries, and proxy applied). self.cache A generic key/value Cacher namespaced to the service. self.title_cache A region- and account-aware TitleCacher. self.cache_dir config.directories.cache / <ServiceName>. self.credential The active Credential, or None until authenticated. self.track_request A TrackRequest describing the requested codecs, ranges, and best-available flag (see below). The constructor also resolves proxies: it reads --proxy and the proxy_query and proxy_provider context params that dl derives from it, consults the per-service proxy_map, and, if GEOFENCE is set and you did not give an explicit proxy, does a live IP check and auto-fetches a proxy to GEOFENCE[0] when it detects a geoblock. A GEOBLOCK hit with no GEOFENCE stops the run with a \"not available in your region\" error, because there is no main region to fetch a proxy for; pass --proxy yourself. A proxy whose exit is in a GEOBLOCK region stops the run the same way. See Proxies and VPN.
TrackRequest
self.track_request is a small dataclass built from the CLI: codecs (from --vcodec, empty means \"accept any\"), ranges (from --range, default [Video.Range.SDR]), and best_available. Use it in get_tracks to decide which variants to fetch.
"},{"location":"dev/service-architecture/#titles-and-the-title-hierarchy","title":"Titles and the Title hierarchy","text":"get_titles() returns a title collection, one of the Titles_T types. Each collection holds one or more Title objects (Title_T). There are three parallel families, one per media kind:
Media kind Item (Title_T) Collection (Titles_T) Movies Movie Movies TV Episode Series Music Song Album, and Music (the base collection) All items subclass Title, which carries the shared identity: a unique id, the originating service class, an optional original language, arbitrary data, and a freshly-constructed self.tracks = Tracks() that get_tracks will fill. Collections use sorted lists, so titles stay in a stable order.
The unique ID is validated
Title.__init__ rejects a falsy id_, and rejects any ID shorter than 4 characters (\"The unique ID is not large enough, clash likely.\"). Pick a stable, sufficiently unique identifier from the platform.
"},{"location":"dev/service-architecture/#constructors-at-a-glance","title":"Constructors at a glance","text":"Each subclass adds its own required fields on top of id_ and service:
MovieEpisodeSong Movie(id_, service, name, year=None, language=None, data=None, description=None)\n
You must give name. year is optional, but it must be a positive integer if you give it.
Episode(id_, service, title, season, number,\n name=None, year=None, language=None, data=None,\n description=None, air_date=None)\n
title is the show name. You must give season and number, and 0 is a valid value. unshackle converts an air_date to a date so the {date} naming token stays clean, and it discards a placeholder episode name like \"Episode 4\" automatically.
Song(id_, service, name, artist, album, track, disc=1, year=None,\n language=None, data=None, ...)\n
You must give name, artist, album, and track, and unshackle validates them. disc defaults to 1, and year is optional. A single therefore needs no disc, and an undated release needs no year.
A Song also takes optional metadata keywords that the tagger and the naming templates read: album_artist, release_type, total_tracks, total_discs, genre, explicit, isrc, upc, copyright, label, lyrics, and artwork_url. Read the class for the current list.
The tagger also falls back to Song.data 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 metadata sub-dict, with the nested keys winning, so either shape works.
From get_tracks(), a music service gives one Audio track for each codec and bitrate it offers for a Song. The framework then selects one with its usual audio options, -a/--acodec and --abitrate, and its usual audio sorting. A movie or an episode uses the same options. -q/--quality sets the video height only and does not apply to music. Audio has no bit_depth or sample_rate field. Therefore bitrate separates a hi-res FLAC from a CD FLAC, and the audio sort already ranks it.
A Song is an ordinary Title on the one generic download path. unshackle has no music-specific service API and no separate music download loop. The GROUP_AUDIO_DOWNLOADS flag, get_music_track_options and get_music_collection_label no longer exist, and a music service does not need them.
Restore the container in on_track_downloaded
Every track downloads to a temp file named Audio_<id>.mp4 whatever it holds, and the final move keeps that suffix. A Song 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 on_track_downloaded, or a FLAC lands as an untaggable .mp4. The event fires twice, once before decryption and once at the end, so wait until track.drm is clear before you rename.
The MUSIC_EXAMPLE reference service, at unshackle/services/MUSIC_EXAMPLE/, shows the full music surface.
"},{"location":"dev/service-architecture/#title-remapping","title":"Title remapping","text":"After the service fetches the titles (and after any cache), the framework applies remap_titles(titles, title_map) with the per-service title_map config. This does an exact-string rename (it compares Episodes on their show title, and Movies and Songs on their name), so you can change a platform's odd naming to what your library expects. get_titles_cached() also cache-wraps the titles, and it is region- and account-aware. See the TitleCacher notes.
The ordering here is deliberate on both sides. The framework applies title_map after the title cache so that editing the map takes effect immediately, without forcing a cache reset, and before metadata enrichment (--enrich) so that an explicit enrich override still wins over a mapped name.
"},{"location":"dev/service-architecture/#tracks-and-the-track-model","title":"Tracks and the Track model","text":"A Tracks object is the container get_tracks returns. It has typed buckets (videos, audio, subtitles, chapters, and attachments) plus a manifest_url. Iterating a Tracks 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.
Track IDs must be deterministic
Tracks.add 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 add will raise.
"},{"location":"dev/service-architecture/#the-base-track","title":"The base Track","text":"Track is the base for Video, Audio, and Subtitle. (Chapter, Chapters, and Attachment are standalone classes, not Track subclasses.) Every track records its delivery method in Track.Descriptor, which tells unshackle how to download it:
Descriptor Delivery URL A single direct URL. HLS HTTP Live Streaming. DASH Dynamic Adaptive Streaming over HTTP. ISM Smooth Streaming. The main attributes include url (a string or list of strings), language (a langcodes.Language), drm (an optional iterable of DRM objects), needs_repack, and descriptor-specific state stashed in track.data[\"hls\"] / track.data[\"dash\"]. If you do not give a name, unshackle derives a human-readable name from the language.
"},{"location":"dev/service-architecture/#video","title":"Video","text":"Video adds codec, range, bitrate, width, height, fps, scan_type, and closed-caption descriptors. The relevant enums:
Video.Codec: AVC (H.264), HEVC (H.265), VC1, VP8, VP9, AV1. Video.Range: SDR, HLG, HDR10, HDR10P (HDR10+), DV (Dolby Vision), and HYBRID. HYBRID 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 dovi_tool (see Dolby Vision hybrid).
Bitrate units
Both Video and Audio store bitrate in bits per second (rounded up). The string form displays kb/s, and --vbitrate and --abitrate compare in kb/s.
"},{"location":"dev/service-architecture/#audio","title":"Audio","text":"Audio adds bitrate, channels, joc (Joint Object Coding, the Atmos indicator), and descriptive. Audio.Codec covers AAC, AC3 (DD), EC3 (DD+), AC4, OPUS, OGG (Vorbis), DTS, DTSX, ALAC, and FLAC. The atmos property is True when joc is set (or when extra flags it).
"},{"location":"dev/service-architecture/#subtitle","title":"Subtitle","text":"Subtitle adds three mutually-constrained flags: cc (closed captions), sdh (subtitles for the deaf and hard-of-hearing), and forced. A track cannot be both cc and sdh, and forced cannot combine with either. Subtitle.Codec includes SubRip (SRT), WebVTT (VTT), SubStationAlpha/SubStationAlphav4 (SSA/ASS), TimedTextMarkupLang (TTML), SAMI, and the box-encapsulated DASH formats fTTML (STPP) and fVTT (WVTT). Subtitles receive post-download normalization (segment merging, WebVTT sanitization, format conversion, and optional SDH stripping), all documented for users in Subtitles.
"},{"location":"dev/service-architecture/#chapters-and-attachments","title":"Chapters and attachments","text":" Chapter(timestamp, name=None): a single marker. The timestamp accepts HH:MM:SS[.mmm], integer milliseconds, or float seconds. Chapters: a sorted collection that auto-inserts a 00:00:00.000 chapter and reads/writes OGM Simple format. Attachment: a font or image attached to the mux (for example, fonts an ASS subtitle references), built from a local path or a url.
"},{"location":"dev/service-architecture/#selection-sorting-and-muxing","title":"Selection, sorting, and muxing","text":"Tracks is also the selection engine the dl command uses. It offers sort_videos / sort_audio / sort_subtitles (P2P-standard ordering), predicate-based select_* filters, by_resolutions, and by_language. When downloads finish, the same object multiplexes everything: Tracks.mux(title, ...) builds and runs an mkvmerge command, applying language, default-track, forced, and hearing-impaired flags, attaching chapters and fonts, and writing a .muxed.mkv (or .mka / .mks for audio- or subtitle-only sets). As a service author you never call mux yourself. You only return correct tracks.
"},{"location":"dev/service-architecture/#manifest-parsers","title":"Manifest parsers","text":"Most services do not assemble tracks by hand. They give a manifest to one of three parsers in unshackle.core.manifests. Each parser has the same three-part contract:
Format Class Notes MPEG-DASH (.mpd) DASH Parses <MPD>; enumerates tracks from the first content period. HLS (.m3u8) HLS Requires a variant (master) playlist, not a media playlist. Smooth Streaming (.ism) ISM Synthesizes init segments from CodecPrivateData."},{"location":"dev/service-architecture/#the-parser-contract","title":"The parser contract","text":" - Construct:
DASH.from_url(url, session=...) or DASH.from_text(text, url) (and likewise for HLS / ISM). Always pass a url, even to from_text, because the parser needs it to make relative segment paths absolute. to_tracks(...): parses the manifest into a Tracks container of Video, Audio, and Subtitle objects, each carrying descriptor-specific state. download_track(...): 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.
A typical get_tracks therefore looks like fetching the manifest text with self.session and returning DASH.from_text(mpd, url).to_tracks(language=title.language).
Pass the original language
DASH and HLS to_tracks raise ValueError if they cannot derive a track's language and you gave no valid fallback. Always pass the title's original recorded language. For HLS, to_tracks uses this fallback directly for the primary track, because HLS variants carry no language.
"},{"location":"dev/service-architecture/#segment-filtering-hooks","title":"Segment-filtering hooks","text":" - HLS: set
track.OnSegmentFilter(segment) to drop unwanted segments (ads/bumpers). A dropped segment is invisible to the whole download: unshackle ignores its EXT-X-KEY and its EXT-X-DISCONTINUITY, so a clear ad break inside an encrypted track does not disturb decryption. - DASH: pass a
period_filter callable to to_tracks to drop whole periods. unshackle automatically drops the caching-breadth periods that some services send, and the non-content segment types.
"},{"location":"dev/service-architecture/#format-gotchas-worth-knowing","title":"Format gotchas worth knowing","text":" - DASH enumerates tracks from only the first content period, but downloads segments from all content periods matching the representation. The parser reads
SegmentTemplate, SegmentList, and SegmentBase addressing, and $Number%0Nd$ padding. - HLS re-fetches the media playlist at download time, recovers
SUPPLEMENTAL-CODECS 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. - ISM has no list of segments and no init segments: the parser synthesizes segment URLs from the
<c> fragment timeline, and rebuilds a moov/ftyp init box from CodecPrivateData (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: Tracks.add no longer reads the second manifest's tracks as duplicates of the first.
"},{"location":"dev/service-architecture/#drm-hooks","title":"DRM hooks","text":"If a track carries DRM, the framework licenses and decrypts it, but it needs your service to talk to the platform's license server. unshackle recognizes five DRM systems:
DRM class System License flow Widevine Widevine CDM challenge \u2192 license server \u2192 content keys (.wvd device) PlayReady PlayReady CDM challenge (WRM header) \u2192 license server \u2192 content keys (.prd device) ClearKeyCENC W3C org.w3.clearkey over CENC JSON KID request \u2192 JWK set; no CDM ClearKey HLS AES-128 content key fetched directly from a URI; no CDM, no challenge MonaLisa Proprietary WASM DRM keys extracted locally; no license server ClearKey vs ClearKeyCENC
Despite the shared prefix these are entirely different systems. ClearKey is HLS AES-128, decrypted in-process. ClearKeyCENC is the W3C EME JWK flow over MPEG-CENC, decrypted with shaka-packager or mp4decrypt like Widevine.
"},{"location":"dev/service-architecture/#the-service-side-hooks","title":"The service-side hooks","text":"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:
Hook Return Purpose get_widevine_service_certificate(title, track, challenge) cert bytes Optional privacy-mode service certificate. get_widevine_license(title, track, challenge) license bytes POST the Widevine challenge to the license server, return the response. get_playready_license(title, track, challenge) license Same for PlayReady; defaults to delegating to Widevine. get_clearkey_license(title, track, challenge) dict / str / bytes / None For ClearKeyCENC; return None to let the framework POST to the manifest Laurl. You do not open CDM sessions or operate shaka-packager yourself. The Widevine/PlayReady classes drive the CDM handshake and call the decryption backend. Your hook is only the \"send this challenge, give me back the license\" step.
"},{"location":"dev/service-architecture/#how-unshackle-chooses-a-cdm-and-finds-keys","title":"How unshackle chooses a CDM and finds keys","text":"CDM selection is config-driven: the cdm map resolves a service tag (and optionally the track quality or DRM type) to a device name, which load_cdm instantiates as a local .wvd/.prd 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.
"},{"location":"dev/service-architecture/#dolby-vision-and-hybrid","title":"Dolby Vision and hybrid","text":"Two DV mechanisms sit on top of the track model. DV fixup re-exposes DV signalling on HLS streams that carry a valid DV RPU but advertise plain HEVC (dv_compatible_bitstream). Hybrid processing (Video.Range.HYBRID) selects an HDR10(+) base and a DV donor, extracts the RPU with dovi_tool, 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.
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.
"},{"location":"dev/service-architecture/#request-and-http-session-objects","title":"Request and HTTP session objects","text":"Everything a service does over the network flows through objects the base constructor prepared, all derived from the Click context (ctx) that dl passes in.
self.config: your service's slice of unshackle.yaml, i.e. config.services[<ServiceName>]. This is a plain dict. Use it for per-service settings like base URLs, an API key, or a title_map. See Configuration. self.session: a requests.Session with config.headers applied, a retry policy (total=5, 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 session() factory uses and that the network config key configures.) self.credential: the active Credential (username:password[:extra]), populated by authenticate. unshackle uses its sha1 as the account hash for cache keys. self.cache: a generic Cacher: JSON key/value storage under the service's cache dir, with CRC32 integrity checks, versioning, and optional expiry (auto-derived from a JWT exp claim when present). Good for auth tokens and API responses. self.title_cache: a TitleCacher that wraps get_titles results, keyed by title ID, region, and account hash. It serves fresh data within title_cache_time, falls back to stale data within title_cache_max_retention when an API call fails, and --no-cache bypasses it. self.track_request: the TrackRequest describing what the user asked for (codecs, ranges, best-available), for use inside get_tracks.
A minimal service skeleton
services/EXMP/__init__.pyfrom 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) -> 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) -> \"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
The directory name (EXMP) must match the class name exactly. That stem is the service tag. Put your service in one of the directories.services paths.
"},{"location":"dev/service-architecture/#where-to-go-next","title":"Where to go next","text":" - Creating a Service: a guided walkthrough that builds on this model.
- Service API: exact signatures for the
Service base class. - Titles API and Tracks API: the full object reference.
- DRM API: the DRM and CDM classes in detail.
- Downloading: how the flags a user passes map onto track selection.
"},{"location":"dev/rest-api/","title":"REST API Overview","text":"unshackle ships with a built-in HTTP server. Alongside the command-line tool, you can operate unshackle serve 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.
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.
Who this section is for
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.
"},{"location":"dev/rest-api/#what-the-api-is-for","title":"What the API is for","text":"The server exposes the same capabilities as the dl command, but as discrete HTTP calls you can script against:
- Discovery: show the services available on the server, use a service's search, and enumerate the titles and tracks behind a title ID.
- 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.
- 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.
- 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.
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.
"},{"location":"dev/rest-api/#running-the-server","title":"Running the server","text":"Start the server with the serve command:
Start the REST API on the default host and portunshackle serve\n
By default the server binds to 127.0.0.1:8786 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.
An API key is required by default
Unless you pass --no-key, the server needs an API secret configured under the serve section of your config. If none is set, unshackle serve refuses to start. See Authentication for how to set api_secret and how the X-Secret-Key header works.
"},{"location":"dev/rest-api/#common-options","title":"Common options","text":"The serve command accepts the following flags:
Option Default Effect -h, --host 127.0.0.1 Address to bind to. Use 0.0.0.0 to accept connections from other machines. -p, --port 8786 Port to bind to. --api-only off Serve only the REST API, without the Widevine/PlayReady CDM HTTP endpoints. --cdm-only off Serve only the Widevine/PlayReady CDM HTTP endpoints, plus /api/health and the dashboard. No REST API, no remote sessions, no Swagger UI. Cannot be combined with --api-only or --remote-only. --no-widevine off Disable the Widevine CDM endpoints. Cannot be combined with --api-only. --no-playready off Disable the PlayReady CDM endpoints. Cannot be combined with --api-only. --no-key off Disable API-key authentication entirely; every request is allowed. --remote-only off Expose only the remote-session subset of routes. Implies --api-only. --debug-api off Include tracebacks and worker stderr in error responses. --debug off Enable debug-level logging. --caddy off Also launch Caddy as a reverse proxy, using the Caddyfile in your user-config directory. Serve the REST API only, on all interfacesunshackle serve --api-only --host 0.0.0.0 --port 8786\n
Binding to a public interface
--no-key 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 127.0.0.1, or keep the default key-based auth when binding to 0.0.0.0. Put a TLS-terminating reverse proxy (Caddy, nginx) in front for anything internet-facing.
"},{"location":"dev/rest-api/#server-modes","title":"Server modes","text":"The routes the server mounts depend on how you start the server:
Default (CDM + REST)--api-only--remote-only--cdm-only The server mounts both the pywidevine/pyplayready CDM endpoints and the full REST API. This is the mode you get when you operate unshackle serve with no mode flags.
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 --no-key).
The server mounts only the remote-session subset of routes (health, services, search, and everything under /api/session/*). This mode implies --api-only, and the interactive Swagger UI is not mounted.
The server mounts only the pywidevine and pyplayready CDM endpoints. Under /api/ it answers /api/health and, when serve.dashboard.key 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.
"},{"location":"dev/rest-api/#base-url","title":"Base URL","text":"All REST endpoints live under the /api prefix. With the default bind address the base URL is:
http://127.0.0.1:8786/api\n
Every path in this documentation is relative to the host and port. For example, the health check is GET http://127.0.0.1:8786/api/health.
Interactive API docs
Unless you started the server with --remote-only, an interactive Swagger UI is available at /api/docs/. The server generates it from the same route table it serves, so it always matches the version you operate. Note that in --api-only mode the docs page is itself behind the API key. Only /api/health is exempt from authentication.
A quick smoke test that needs no API key:
Confirm the server is upcurl http://127.0.0.1:8786/api/health\n
Response{\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
"},{"location":"dev/rest-api/#endpoint-map","title":"Endpoint map","text":"Every REST path uses JSON request and response bodies and lives under /api. The table below is a map of the surface. The Endpoints page gives each request and response in full.
"},{"location":"dev/rest-api/#discovery","title":"Discovery","text":"Method Path Purpose GET /api/health Liveness and version check. Never requires an API key. GET /api/services List the services available on this server. POST /api/search Run a service's search for a query. POST /api/list-titles List the titles behind a service title ID. POST /api/list-tracks 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 POST /api/download Queue a download; returns a job_id. GET /api/download/jobs List jobs, with filtering and sorting. POST /api/download/jobs/clear-finished Remove all finished jobs. GET /api/download/jobs/{job_id} Full detail for one job. GET /api/download/jobs/{job_id}/events Stream one job's progress as Server-Sent Events. DELETE /api/download/jobs/{job_id} Cancel a running job, or remove a finished one. POST /api/download/jobs/{job_id}/retry Re-queue a finished job's parameters as a new job. POST /api/download/jobs/{job_id}/priority Move a queued job to the front. POST /api/download/jobs/{job_id}/input 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 GET /api/history Read the persisted log of finished jobs. DELETE /api/history/{job_id} Delete a history entry. GET /api/profiles Named credential profiles per service. GET /api/config The server's effective, redacted configuration. GET /api/env/check Presence and versions of external tools."},{"location":"dev/rest-api/#maintenance","title":"Maintenance","text":"Method Path Purpose POST /api/maintenance/clear-cache Clear the cache directory. POST /api/maintenance/clear-temp Clear the temp directory. POST /api/maintenance/refresh-services git pull 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 POST /api/session/create Start a server-side, authenticated service session. GET /api/session/{session_id} Remote session info and time-to-live. DELETE /api/session/{session_id} Tear down a session. GET /api/session/{session_id}/titles Titles for the session's title ID. POST /api/session/{session_id}/tracks Tracks (with URLs) for a chosen title. POST /api/session/{session_id}/segments Per-track segment/download details. POST /api/session/{session_id}/segment_filter Server-side HLS segment filter results for one track. POST /api/session/{session_id}/license Proxy or server-side DRM licensing. POST /api/session/{session_id}/keys/bad Report a server-vault content key that did not decrypt. GET /api/session/{session_id}/logs Drain the service's server-side log output. GET /api/session/{session_id}/prompt Poll for interactive auth status/prompt. POST /api/session/{session_id}/prompt Submit an answer to an auth prompt. Remote-only routes
The health, services, search, and /api/session/* routes are the ones exposed when the server runs with --remote-only. Everything else (downloads, jobs, history, config, maintenance) is only available in the full or --api-only modes.
"},{"location":"dev/rest-api/#authentication-in-one-line","title":"Authentication in one line","text":"With the default configuration, send your API secret in the X-Secret-Key header on every request except /api/health:
An authenticated requestcurl -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
A missing or unknown API key returns 401. Authentication gives the full model, including per-key service allowlists.
"},{"location":"dev/rest-api/#where-to-go-next","title":"Where to go next","text":" - Quick Start: start the server, set an API key, and operate your first end-to-end download over the API.
- Authentication: the
X-Secret-Key header, --no-key, per-key service allowlists, and CORS. - Endpoints: every request body, query parameter, and response shape, endpoint by endpoint.
- Job Lifecycle: how a download moves from
queued to a terminal state, live progress, cancellation, and retries. - Remote Sessions: the
/api/session/* flow for driving a service from a thin remote client. - Error Responses: the standard error envelope, error codes, and their HTTP statuses.
"},{"location":"dev/rest-api/authentication/","title":"REST API Authentication","text":"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.
You start the API with the unshackle serve command. Authentication is on by default: if you start the server without an API key configured, it refuses to launch.
Which server am I running?
unshackle serve can operate in two shapes, and each uses a slightly different piece of code to examine your API key:
- The integrated server (the default) exposes the REST API and the pywidevine / pyplayready CDM HTTP endpoints.
- The API-only server (
--api-only, also implied by --remote-only) exposes only the REST API.
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.
"},{"location":"dev/rest-api/authentication/#the-short-version","title":"The short version","text":" - Add an
api_secret to the serve section of your unshackle.yaml. - Start the server with
unshackle serve. - Send that secret in the
X-Secret-Key header on every request except GET /api/health.
A minimal authenticated requestcurl -H \"X-Secret-Key: your-secret-key-here\" \\\n http://127.0.0.1:8786/api/services\n
"},{"location":"dev/rest-api/authentication/#configuring-authentication","title":"Configuring authentication","text":"All authentication settings live under the serve section of your unshackle config file (unshackle.yaml).
"},{"location":"dev/rest-api/authentication/#a-single-api-key","title":"A single API key","text":"The simplest setup defines one shared secret with api_secret:
unshackle.yamlserve:\n api_secret: \"a-long-random-secret-string\"\n
This value becomes the one and only API key that the server accepts. The server allows requests that present it in the X-Secret-Key header. The server rejects everything else.
The server will not start without a key
If you start unshackle serve with no api_secret configured, and you have not passed --no-key, the command fails immediately with:
API secret key is not configured. Please add 'api_secret' to the 'serve' section in your config.\n
Choose a long, unpredictable value. The API key is the only thing standing between the internet and your CDM and download endpoints.
"},{"location":"dev/rest-api/authentication/#multiple-keys-with-users","title":"Multiple keys with users","text":"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:
unshackle.yamlserve:\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
The config key of each entry under users (for example a-secret-key-for-alice) is the secret that client sends in X-Secret-Key. The username is a human-readable label used in logs and in job/history metadata.
How api_secret and users combine (integrated server)
On the integrated server, the server automatically adds the configured api_secret as an extra accepted API key alongside everyone in users. It gives that API key access to all loaded Widevine and PlayReady devices, and labels it api_user. So api_secret behaves as an admin-level API key in addition to any named users you define.
On the API-only server, the server accepts only api_secret: the single-key model. (See the developer notes for the exact difference.)
"},{"location":"dev/rest-api/authentication/#cdm-device-access-per-api-key","title":"CDM device access per API key","text":"Under the integrated server, an API key can do DRM licensing only through a CDM device that its user entry lists:
Config key Grants access to devices Widevine .wvd devices, by name playready_devices PlayReady .prd devices, by name PlayReady access is opt-in per user
If a user entry omits playready_devices, 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.
Grants decide whether the server returns content keys
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 (KID:KEY) for a remote session. server_cdm lets the server license with those devices. server_vault 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 serve for both grants.
"},{"location":"dev/rest-api/authentication/#disabling-authentication","title":"Disabling authentication","text":"The --no-key flag turns authentication off entirely. The server allows every request, ignores X-Secret-Key, and needs no API key in your configuration.
unshackle serve --no-key\n
Only use --no-key on a trusted, isolated network
With --no-key, any client that can reach the port can show your services, start downloads, and use your CDM devices. Never put a --no-key server on an untrusted network.
"},{"location":"dev/rest-api/authentication/#how-clients-present-credentials","title":"How clients present credentials","text":"Clients authenticate by sending the secret in a single HTTP request header on every call:
X-Secret-Key: <your-secret>\n
The value must match one of the configured API keys exactly (api_secret, or one of the keys under users). 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.
One route also accepts the key as a query parameter
The job event stream, GET /api/download/jobs/{job_id}/events, also accepts the API key in a secret_key query parameter. This is for browsers: the EventSource API cannot set request headers. The exception applies to that one route only, and it works in both server modes.
new EventSource(`http://127.0.0.1:8786/api/download/jobs/${jobId}/events?secret_key=${key}`);\n
The header always wins. If the request has an X-Secret-Key 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.
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.
curlPython (requests)JavaScript (fetch) curl -H \"X-Secret-Key: your-secret-key-here\" \\\n http://127.0.0.1:8786/api/services\n
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
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
The reference client sets it for you
unshackle's own remote download client (RemoteService) sends X-Secret-Key automatically, reading the API key from your remote_services config. It also sends a User-Agent of unshackle/<version>. You only deal with the header directly when writing your own client.
"},{"location":"dev/rest-api/authentication/#the-health-check-is-always-open","title":"The health check is always open","text":"One endpoint is exempt from authentication: GET /api/health. It never requires an API key, so you can use it for liveness and version probes without embedding a secret in your monitoring:
No key neededcurl http://127.0.0.1:8786/api/health\n
Response{\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
Every other endpoint (including the Swagger UI at /api/docs/ on the API-only server) requires a valid API key.
"},{"location":"dev/rest-api/authentication/#authentication-failures","title":"Authentication failures","text":"When the server rejects a request for authentication reasons, the response has an HTTP 401 Unauthorized status and a small JSON body.
Missing headerWrong key Sending a request with no X-Secret-Key header:
{\n \"status\": 401,\n \"message\": \"Secret Key is Empty.\"\n}\n
Sending an API key that is not in your config:
{\n \"status\": 401,\n \"message\": \"Secret Key is Invalid.\"\n}\n
Auth errors use a different JSON shape than other errors (developer note)
The rest of the API reports errors with a structured body containing error_code, message, timestamp, and other fields (see Errors). The authentication middleware is different: it returns {\"status\": 401, \"message\": \"...\"}, where status is an integer, and there is no error_code or timestamp.
In your client, treat any 401 as an authentication problem and parse both shapes, because the standard error body is not always present.
"},{"location":"dev/rest-api/authentication/#rate-limit-rejections","title":"Rate limit rejections","text":"An API key that carries a rate limit gets 429 Too Many Requests once it goes over, from the same middleware and in the same shape as the 401 bodies above, with a Retry-After header in seconds:
{\n \"status\": 429,\n \"message\": \"Rate limit exceeded.\"\n}\n
A limit comes from serve.tiers.<name>.rate_limit or from the API key's own serve.users.<key>.rate_limit, in requests per hour. An API key with neither has no limit, and GET /api/health is never limited. See dashboard rate limits for the config and the counters, and services configuration for the keys themselves.
429 is not the RATE_LIMITED error body
RATE_LIMITED in Errors is a service rate limit that a handler raises, and it arrives in the standard envelope with an error_code. The 429 here comes from the middleware before any handler runs, and has the integer-status shape shown above. A client that reads error_code to classify a 429 must cope with it being absent.
"},{"location":"dev/rest-api/authentication/#access-controls-on-top-of-the-api-key","title":"Access controls on top of the API key","text":"After the server authenticates a request, several additional controls decide what that specific API key can do.
"},{"location":"dev/rest-api/authentication/#per-key-service-allowlists","title":"Per-key service allowlists","text":"You can restrict which services an API key may use. Two layers combine:
- Global allowlist:
serve.services, applied to every API key. - Per-key allowlist:
services inside that key's users entry.
The effective allowlist for a request is:
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 servicesserve:\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
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.
"},{"location":"dev/rest-api/authentication/#cdm-overrides-and-per-job-credentials","title":"CDM overrides and per-job credentials","text":"The server config gates two download-time capabilities. Unless you enable them, the server refuses them with 403 Forbidden, even for an authenticated API key:
Config key Default Controls serve.cdm_overrides off Whether a request may pick a specific CDM device via the cdm field. Set to true to allow any, or to a list/set of device names to allow only those. serve.allow_job_credentials off Whether a request may pass its own credential / credentials login details for a download job. Opting in to per-request CDM and credentialsserve:\n api_secret: \"admin-key\"\n cdm_overrides: [\"my_widevine_device\"] # or true to allow any configured device\n allow_job_credentials: true\n
When to enable these gates
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 403, 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.
Client-supplied credentials get isolated token caches
When you enable allow_job_credentials and a download job supplies its own credential / credentials, 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.
See Downloads for how the download endpoint uses these fields.
"},{"location":"dev/rest-api/authentication/#session-ip-binding-remote-sessions","title":"Session IP binding (remote sessions)","text":"The remote-download session endpoints (/api/session/*) 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 403 Forbidden. Thus the server binds a remote session both to the API key that created it and to the address it came from.
"},{"location":"dev/rest-api/authentication/#transport-security-https","title":"Transport security (HTTPS)","text":"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 serve command can launch Caddy for you:
unshackle serve --caddy\n
With --caddy, unshackle also starts caddy run using the Caddyfile 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 Caddyfile.
"},{"location":"dev/rest-api/authentication/#quick-reference","title":"Quick reference","text":"Item Value Auth header X-Secret-Key Query-parameter alternative ?secret_key= on GET /api/download/jobs/{job_id}/events only Default bind address 127.0.0.1:8786 Exempt endpoint GET /api/health Failure status 401 Unauthorized, or 429 Too Many Requests for a key over its rate limit Missing-header body {\"status\": 401, \"message\": \"Secret Key is Empty.\"} Invalid-key body {\"status\": 401, \"message\": \"Secret Key is Invalid.\"} Over-limit body {\"status\": 429, \"message\": \"Rate limit exceeded.\"}, plus a Retry-After header Rate limit config serve.tiers.<name>.rate_limit, overridden by serve.users.<key>.rate_limit Disable auth --no-key (all requests allowed) Config location serve.api_secret and serve.users in unshackle.yaml"},{"location":"dev/rest-api/authentication/#developer-notes-how-the-server-does-the-check","title":"Developer notes: how the server does the check","text":"This section is for people writing or debugging the server, not for API consumers.
"},{"location":"dev/rest-api/authentication/#two-middlewares-one-header","title":"Two middlewares, one header","text":"The header and config are identical between modes, but the code that enforces them differs:
-
API-only server (--api-only, or --remote-only which forces API-only). An api_key_authentication middleware runs on every request. It lets GET /api/health through unconditionally, then reads X-Secret-Key. 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 api_secret (labelled api_user, with no devices) plus every key under serve.users. A per-user key therefore authenticates here exactly as it does on the integrated server, and that user's services allowlist applies as usual. With --no-key, this middleware is not installed and the users map is empty.
-
Integrated server (default). A serve_authentication middleware wraps pywidevine's authentication (and pyplayready's for /playready* paths), and the REST routes live in the same application, guarded by the same check. Here the accepted-keys map is your full serve config: api_secret (auto-added with access to all loaded devices) plus every entry under users, each with its declared devices / playready_devices.
Because the API-only middleware guards all non-health paths, the Swagger UI at /api/docs/ is also behind X-Secret-Key there. In --remote-only mode the Swagger UI is not mounted at all.
Both middlewares read the caller's API key through the shared request_secret_key() helper in unshackle/core/api/handlers.py. That helper returns the X-Secret-Key header, and falls back to the secret_key query parameter only when the matched route is the job event stream. The integrated server needs one extra branch for this. pywidevine's authentication is header-only. So serve_authentication 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.
"},{"location":"dev/rest-api/authentication/#cors-and-the-authorization-header","title":"CORS and the Authorization header","text":"A cors_middleware runs on every response in both modes (and answers OPTIONS preflight requests with an empty response). It emits:
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
The REST API authenticates with X-Secret-Key. The middleware advertises Authorization because the co-hosted pywidevine / pyplayready CDM endpoints use it. PUT appears in the allowed-methods list, but no REST route uses it. Only GET, POST, and DELETE have routes.
"},{"location":"dev/rest-api/authentication/#where-device-access-is-read","title":"Where device access is read","text":"The map of accepted API keys lives at request.app[\"config\"][\"users\"]. For DRM operations, an API key's permitted Widevine devices come from its devices list, and PlayReady devices from playready_devices. The server uses the first configured device when a request does not (or may not) override it. A server-wide config.cdm[<service>] mapping, if present, takes precedence over the API key's device list when the server chooses which device to use.
"},{"location":"dev/rest-api/dashboard/","title":"Developer Dashboard","text":"The dashboard endpoints show the operator of a serve 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 (serve --quiet) from a web page instead of a terminal.
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.
"},{"location":"dev/rest-api/dashboard/#enable","title":"Enable","text":"Set a dashboard key under serve.dashboard in unshackle.yaml:
serve:\n api_secret: ...\n dashboard:\n key: a-long-random-string\n
Without dashboard.key the server does not register the routes, and they answer 404. serve --no-key turns off user authentication only; the dashboard key stays required. Once the dashboard key is set, every /api/dashboard/ request must carry it in X-Secret-Key. Every other endpoint refuses the dashboard key, and the dashboard refuses user keys. The routes are available in --remote-only mode too.
Run the server headless with --quiet: no banner, no Rich output, one plain log line per event on stderr, and api.* loggers stay at INFO so remote session activity reaches the log ring. Add --debug to raise the level to DEBUG and also write the full log to directories.logs as unshackle_serve_<time>.log. 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.
unshackle serve --remote-only --quiet\n
"},{"location":"dev/rest-api/dashboard/#endpoints","title":"Endpoints","text":"All are GET.
Path Returns /api/dashboard/status Version, code_hash, bind host and port, mode (full, api_only, remote_only), uptime, requests_total, requests_rejected (401s), requests_by_key (label \u2192 count), configured service count (the same services as /api/dashboard/services), session count, max_sessions (null when the operator configured no limit), session_ttl, job counts by status. The service count includes services that failed to import - use /api/dashboard/services for the number that loaded. /api/dashboard/sessions Every live remote session: id, owner (username or masked key), creator_ip, service, title_id, titles, tracks, title (the display name of the title the client is on: the last one it asked tracks for, else the first resolved title), auth_status, auth_error, server_account (the server profile lent to the remote session, else null), server_cdm (false when the client's own device licenses the remote session), server_cdm_max_height (the tallest video the server CDM licenses live, else null), client, actions, created_at and last_accessed (ISO 8601) with created_ts and last_accessed_ts (Unix epoch, the same clock as log ts), age_seconds, idle_seconds, log_seq. client is whatever the remote client sent as client in its session create request. The CLI sends version, code_hash (the commit the client runs, null when its source cannot be read), platform and argv. argv is the command line the user ran: proxy and URL userinfo, secret query parameters and credential values become ***, 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 {}. log_seq is the last sequence number in the remote session's service log - poll /api/dashboard/sessions/{id}/logs when it changes. actions is the session's request log, newest last, capped at 500: ts, method, action (titles, tracks, segments, license, prompt, \u2026), query, status, ms, bytes_in, bytes_out. /api/dashboard/jobs Every download job with full detail, regardless of owner. Empty in --remote-only mode. /api/dashboard/logs {\"seq\": N, \"records\": [...]}: the last 1000 log records. ?since=<seq> returns only newer records; ?level=WARNING sets the minimum level; ?logger=serve keeps one logger and its children (aiohttp.access is the noisiest). ts is a Unix epoch in seconds. /api/dashboard/cdm-logs {\"seq\": N, \"records\": [...], \"sessions\": [...]}: the last 5000 calls to the Widevine and PlayReady CDM device routes, and the open sessions of each device. ?since=<seq> returns only newer records. See CDM calls. /api/dashboard/sessions/{id}/logs One remote session's service log: {\"session_id\", \"last_seq\", \"records\": [...]}. Each record has seq, ts, level, message. ?since=<seq> returns only newer records. 404 when the remote session is unknown. /api/dashboard/keys Every configured API key: what it may do and what it has done. One row per key in serve.users, plus serve.api_secret when it is set. /api/dashboard/services Every service configured on this server and its load state, including the ones that failed to import. See Services for what configured means. /api/dashboard/health Preflight: whether this instance could finish a download. Cached 30 seconds. /api/dashboard/events Server-Sent Events stream. With ?since=<seq> it returns {\"seq\", \"stats\", \"events\": [...]} instead: every event after seq (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. requests_rejected counts 401 responses; those never appear in requests_by_key. The label is the username from the users entry when one is set, else the first four characters of the API key.
"},{"location":"dev/rest-api/dashboard/#event-stream","title":"Event stream","text":"/api/dashboard/events sends a stats event (the same body as /status) on connect and then every 5 seconds, so the connection stays alive and the counters stay current. Between those it sends:
Event Data log One log record: seq, ts, level, logger, msg. session action (create, update on every request the session makes and when titles or tracks load, or delete) plus the full remote session summary, so each event is a complete snapshot. A delete also carries reason: closed (the client ended it), expired (TTL sweep) or evicted (max_sessions reached). A session opened by --skip-dl can live only a few seconds, so a UI that wants history must keep its own record of these events. job event (queued, progress, status, or the terminal status) plus the full job object. service action (staged, applied or failed) and tags, the services it applies to. A failed action carries errors and an empty tags. Refetch /api/dashboard/services when one arrives, instead of polling for a reload. Every frame carries an id: (the event seq). After a dropped connection an EventSource reconnects with Last-Event-ID and the server replays the events it missed. The connection never closes on its own.
A browser EventSource cannot set headers, so this route also accepts the dashboard key as ?secret_key=. The dashboard key then appears in proxy and access logs and in browser history, so use the query parameter only for /events and send the header everywhere else.
const es = new EventSource(`${server}/api/dashboard/events?secret_key=${key}`);\nes.addEventListener(\"log\", (e) => console.log(JSON.parse(e.data).msg));\n
CORS is open (Access-Control-Allow-Origin: *), so a dashboard page served from another origin works without a proxy.
"},{"location":"dev/rest-api/dashboard/#remote-session-logs","title":"Remote session logs","text":"A remote session mirrors the service's own self.log into a 500-record buffer at INFO, whatever level the server prints at. The remote session summary carries only a truncated auth_error; the buffer holds the real reason a login failed.
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
The field name is records, the same one /api/dashboard/logs uses, so one dashboard reads both logs the same way. Each record has the shape the client route /api/session/{id}/logs returns. last_seq is the buffer's own last sequence number, so an empty page still reports the true value.
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.
log_seq is a poll trigger, not a push
A remote session summary reaches the dashboard only when something publishes a session event - a request the remote session makes, or an auth transition. A log line on its own publishes nothing. Poll this route when log_seq changes, and on a timer while a drawer is open.
"},{"location":"dev/rest-api/dashboard/#cdm-calls","title":"CDM calls","text":"A server in full mode also mounts the Widevine CDM device routes at /{device}/... and the PlayReady ones at /playready/{device}/.... The server records each call to these routes in a 5000-record buffer of its own, apart from the log records of /api/dashboard/logs.
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
since and seq work as they do for /api/dashboard/logs: records holds the calls with a seq above since, oldest first. seq starts again at 1 when the server restarts, so a seq below your cursor means a restart: read again from 0.
Field Meaning ts Unix epoch in seconds, when the call arrived. drm widevine, or playready for a route below /playready/. op open, close, set_service_certificate, get_service_certificate, get_license_challenge, parse_license or get_keys. The licence type or content key type that follows in the path is not part of it. device The device name from the path, cut at 255 characters. key_id, user The id and label of the caller's row in /api/dashboard/keys. Both are anonymous when the API key is missing or unknown. session_id The CDM session, lowercase hexadecimal, so the calls of one licence exchange group together. null when there is none, for example a refused open. status, ok The HTTP status of the reply. ok is true below 400. error null when ok. Otherwise the message of the reply, cut at 300 characters. A handler that raised an error gives the error's class name only. ms Time the server took to answer, in milliseconds. A record never holds the API key, init_data, 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.
sessions 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: open is the number of sessions open now, and max 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 open. The list is [] until the first open, and on a server that mounts no CDM device routes.
Polled only
The event stream does not carry these records. One licence exchange is five calls, and that volume would push session events out of the stream's history.
"},{"location":"dev/rest-api/dashboard/#keys","title":"Keys","text":"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
id is a hash of the API key, so it stays stable across restarts and carries no key material. Two API keys with no username merge into one label in requests_by_key but stay separate here, so use id as the identity and label only for display.
Field Meaning role Which key this is: user (a serve.users entry), admin (serve.api_secret) or dashboard (serve.dashboard.key). Identity, not capability - read the grant fields for what the API key may do. services The effective allowlist, the global list intersected with the API key's. null means unrestricted; [] means the API key reaches no service route at all. server_cdm, server_accounts false, true, or the list of service tags the grant covers. server_cdm_max_height The configured limit on live server CDM licences: a height, a map of service tag to height, or null for no limit. server_proxy Boolean. Only a literal true grants it, and an API key with no users entry does not get it. rate_limit Requests per hour, from the API key's own value or its tier's. null means no limit. window_used Requests counted in the current hourly window. rejected Responses of 400 or worse that the server attributes to this API key, 429s included. The global requests_rejected stays 401-only. bytes_out Response bodies only. An event stream reports no body length, so it counts as zero. last_seen null until the API key makes its first request. Only a configured API key gets a row of counters. A request on an open route such as /api/health with an unknown key counts as anonymous, so an unauthenticated caller cannot grow the table.
Every API key the server counts has a row here, the dashboard key included, so a requests_by_key bucket other than anonymous always matches one. A \"traffic by key\" panel reads the rows here, which are unambiguous, and takes anonymous from requests_by_key. Read role before you draw the bars: the dashboard row is the panel measuring its own polling.
The dashboard key gets services: [] and no grants unless the operator also gave it a serve.users entry, because it reaches nothing outside /api/dashboard/. An API key listed in more than one place still gets exactly one row.
"},{"location":"dev/rest-api/dashboard/#rate-limits","title":"Rate limits","text":"An API key over its limit gets 429 with a Retry-After header:
serve:\n tiers:\n bot: { rate_limit: 600 } # requests per hour\n users:\n \"<api key>\":\n username: bot-relay\n tier: bot\n # rate_limit: 900 # optional, wins over the tier\n
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 tier that names no entry under serve.tiers, or a rate_limit 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 /api/health.
"},{"location":"dev/rest-api/dashboard/#services","title":"Services","text":"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
The list holds only the services configured on this server:
- The global
serve.services list, when it is set. - Else, the union of the
services lists of all keys in serve.users. - Else, every installed service.
The union does not show what every API key can reach
An API key with no services list can use every service, but it does not add to the union. The api_secret API key is the same. So with k1: {services: [A]} and a k2 with no list, the list shows only A. To list every service, remove the services lists or set serve.services.
GET /api/dashboard/services?all=1 lists every installed service. /status always counts only the configured services.
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.
state is loaded, staged or failed. A service that failed to import keeps its error here instead of disappearing, and /status still counts it in the service total - count the state values here for the number that loaded.
A staged service has an update on disk that a busy service blocks from the import: the repo pull already happened, so commit (what runs now) and staged_commit (what waits) differ. It swaps in when the last job and the last remote session for that tag finish. Both commits are null for a service from a plain local directory rather than a git repo.
Watch the service event rather than polling for the swap.
"},{"location":"dev/rest-api/dashboard/#health","title":"Health","text":"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
An instance can answer every request and still fail every download, because mp4decrypt is missing or a vault's credentials expired. This finds that before a job does.
status is ok, degraded (an optional dependency is missing) or failing (a required one is). Player binaries are not checked: a headless server never has one and it plays nothing. Each check is ok, warn or fail. Check ids are the binary names, cdm, vault:<name> (the vault's configured name, so two vaults of the same type stay apart), bad_keys and proxies. bad_keys warns when the vaults hold no SQLite 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.
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 detail 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.
An unreachable vault costs a slow, partial answer
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 probe check with the status fail 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.
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.
Proxy providers are only checked at construction
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 ok.
"},{"location":"dev/rest-api/dashboard/#counters-reset-on-restart","title":"Counters reset on restart","text":"Stats, the log ring and the event history are all in memory. A restart drops every number to zero. started_at in the stats frame (with version and code_hash) 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.
"},{"location":"dev/rest-api/endpoints/","title":"REST API Endpoints","text":"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.
Start the server with unshackle serve. By default it binds to 127.0.0.1:8786, and every route lives under the /api/ prefix. The Authentication page gives authentication, server modes, and the X-Secret-Key header in detail. Read that first if you have not already. For an end-to-end walkthrough, see the Quickstart.
Base URL
All examples below assume a base URL of http://127.0.0.1:8786. Replace the host and port so that they match your own unshackle serve -h <host> -p <port> invocation.
Interactive docs
The server mounts a live Swagger UI at /api/docs/ whenever it does not operate in --remote-only 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 X-Secret-Key. Only /api/health is exempt.
"},{"location":"dev/rest-api/endpoints/#conventions","title":"Conventions","text":" - Authentication. Every request except
GET /api/health requires the X-Secret-Key header when you configure an API key. --no-key disables the check entirely. See Authentication. - Content type. Request bodies are JSON (
Content-Type: application/json). All success responses are JSON unless this page documents a 204 No Content. - CORS. Every response carries permissive CORS headers, and the server answers
OPTIONS preflight requests automatically. - Compression. JSON responses of 256 bytes or more are gzip-compressed when the client sends
Accept-Encoding: gzip. A slow response is not compressed. - Service allowlist. The effective allowlist for your API key filters the service-facing endpoints (the intersection of the global
serve.services list and your per-key list). The server treats services you cannot use as unknown.
Error responses have two shapes
Structured application errors (raised inside a handler) return {\"status\": \"error\", \"error_code\": \"...\", \"message\": \"...\", \"timestamp\": \"...\"}. The authentication middleware, however, returns a different shape: {\"status\": 401, \"message\": \"...\"} with an integer status and no error_code. The same middleware answers 429 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.
"},{"location":"dev/rest-api/endpoints/#general-endpoints","title":"General endpoints","text":"These endpoints report server state and enumerate what is available. GET /api/health, GET /api/services, and POST /api/search are also exposed in --remote-only mode.
"},{"location":"dev/rest-api/endpoints/#get-apihealth","title":"GET /api/health","text":"Health check. This is the only route exempt from authentication: you can call it without an X-Secret-Key header. It reports the running version and a best-effort update check.
RequestResponse 200 curl http://127.0.0.1:8786/api/health\n
{\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_hash 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 unshackle/core, unshackle/commands, unshackle/utils, or unshackle/vaults. Service modules are not included. unshackle sets the value to null only when it cannot read the source files.
If the update check fails (for example, no network), update_available and latest_version are null while current_version still reports the installed version.
Status Meaning 200 Server is healthy."},{"location":"dev/rest-api/endpoints/#get-apiservices","title":"GET /api/services","text":"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). load_errors 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 pending_update has newer code staged: it keeps its current code until its running or queued jobs and its live remote sessions finish.
RequestResponse 200 curl -H \"X-Secret-Key: $KEY\" http://127.0.0.1:8786/api/services\n
{\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
Field notes:
Field Description tag Canonical service tag; use this as the service value on other endpoints. aliases Alternate tags the service also answers to. geofence Region codes the service is geofenced to (may be empty). geoblock Region codes where the service refuses to work (may be empty). title_regex URL/ID pattern the service matches, as a string or list of strings (or null). url Service URL, taken from the service's CLI short help. help The service module's docstring. cli_params Array of parameter descriptors. Arguments have {name, kind: \"argument\", required}; options have {name, kind: \"option\", opts, is_flag, default, help, type, multiple} and, for choice options, a choices list. needs_auth Whether the service overrides authenticate(). has_search Whether the service supports POST /api/search. anonymous_search Whether POST /api/search operates with no login for this service. The server then ignores credentials and cookies on a search. has_drm Whether the service overrides a Widevine or PlayReady license hook. pending_update Set to true while a service repository refresh waits for this service's jobs to finish before it swaps in the new code. Absent otherwise. server_accounts Present when the server lends its own accounts for this service: {regions: [\"ca\", \"gb\"], global: bool}, the regions those accounts cover. A client sends no credentials, cookies, or cache for such a service. auth_methods Declared or inferred auth methods, e.g. [\"cookies\"], [\"credentials\"]. Status Meaning 200 Service list returned. 500 Unexpected server error (INTERNAL_ERROR)."},{"location":"dev/rest-api/endpoints/#post-apisearch","title":"POST /api/search","text":"Find titles in a service by query string. The service must have a search() method (see has_search above).
For a service with anonymous_search, the server does not log in and ignores credentials and cookies. The server account check still applies.
Request body
Field Type Required Default Description service string yes - Service tag. query string yes - Search query. profile string no null Credential/cookie profile to use. proxy string no null Full proxy URI, a Control D resolver as controld://<resolver>@dns.controld.com, or a country code when the API key has server_proxy. no_proxy boolean no false Force-disable all proxy use. credentials, cookies, cache - no null Your own login material, on a --remote-only server only. See Client cache on a remote-only server. RequestResponse 200 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
{\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
Status Error code Meaning 200 - Search completed. 400 INVALID_PARAMETERS Missing query. 400 INVALID_SERVICE Unknown or disallowed service. 400 INVALID_PROXY Proxy could not be resolved. 502 SERVICE_ERROR Service failed to initialise, or does not support search."},{"location":"dev/rest-api/endpoints/#post-apilist-titles","title":"POST /api/list-titles","text":"Get the list of titles behind a title ID, for example episodes or a movie, without downloading anything.
Request body
Field Type Required Description service string yes Service tag. title_id string yes Title identifier. profile string no Credential/cookie profile. proxy string no Full proxy URI, a Control D resolver as controld://<resolver>@dns.controld.com, or a country code when the API key has server_proxy. no_proxy boolean no Force-disable proxy. cdm_type string no Preferred CDM type. credentials, cookies, cache - no Your own login material, on a --remote-only server only. See Client cache on a remote-only server. You can also pass service-specific CLI options as additional keys.
"},{"location":"dev/rest-api/endpoints/#logins-that-need-the-user","title":"Logins that need the user","text":"search, list-titles and list-tracks have no channel to the user. A login that asks for input or waits for an approval on another device fails at once with AUTH_FAILED on these endpoints. Complete that login in a download job or a remote session, then send the saved login with the request.
"},{"location":"dev/rest-api/endpoints/#client-cache-on-a-remote-only-server","title":"Client cache on a remote-only server","text":"A --remote-only server keeps nothing that a client sends. When the request does not use a server account, the server runs search, list-titles and list-tracks on a new service cache directory for that request only, and removes the directory when the request ends, on success and on error. A --remote-only server exposes only search of these three endpoints, so the rule applies to list-titles and list-tracks only if a later release exposes them in that mode.
credentials ({username, password, extra?}) and cookies (base64 of a zlib-compressed Netscape cookie file) are the same as on POST /api/session/create. cache is a map of cache files in the same form: each cache key is the file path relative to the service cache directory, with / separators and no .json 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.
When you send credentials, cookies or cache, a successful response also has a cache field in the same form, with the updated files (for example a refreshed token), but no titles_ 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 cache field.
RequestResponse 200 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
{\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
Each serialized title carries type (\"episode\", \"movie\", or \"other\"), name, id, language, description, date, and cover_url. Episodes and movies add year. Episodes also add series_title, season, and number.
A song serializes as \"other\"
A song has no type of its own. The server sends it as \"other\", and the response carries none of its music fields: no artist, no album, no track or disc number, and no year. name holds the song name. To read the disc and track numbers of a release, operate the CLI with --list-titles. You can still select songs over the API, through the wanted parameter.
These keys are sent only when the title carries them, so a title without them serializes exactly as before:
Key Type On Meaning part integer episode Part index of a split episode, counting from 1. air_date string episode ISO air date of daily and date-based content. unshackle names the episode by date instead of SxxExx. absolute integer episode Absolute episode number across all seasons. daily boolean episode The episode is daily/date-based. Set from the title, or from the service's DAILY class attribute. anime boolean episode, movie The title is anime, so metadata lookups prefer AniList. Set from the title, or from the service's ANIME class attribute. part on a split episode
A service that splits one episode into several separately playable videos reports each one as its own episode. Those titles share a season and number and add a part integer counting from 1. No other title carries the part field, so a client can ignore it safely. See Split episodes.
Status Error code Meaning 200 - Titles returned. 400 INVALID_INPUT Missing service or title_id. 400 INVALID_SERVICE Unknown or disallowed service. 401 AUTH_FAILED Authentication with the service failed. 404 NOT_FOUND Title not found. 500 INTERNAL_ERROR Unexpected error."},{"location":"dev/rest-api/endpoints/#post-apilist-tracks","title":"POST /api/list-tracks","text":"Show the video, audio, and subtitle tracks for a title. For series, you can scope to specific episodes.
Spotting the original-language audio
Each audio track carries is_original, which marks the track the default lang of orig 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 (pt marks pt-BR rather than pt-PT). Services need not report a title's language, so every track can legitimately come back false.
Request body
Field Type Required Description service string yes Service tag. title_id string yes Title identifier. wanted string / string[] no Episode/season range (e.g. \"S01E01-S01E03\"), or a song selector (e.g. \"1-5\", \"1,3,7\", or \"2x3\" for disc 2 track 3). A list of selectors is accepted too. season int/string no Season number (combined with episode). episode int/string no Episode number (combined with season). part int/string no Part index of a split episode (combined with season and episode). profile, proxy, no_proxy, cdm_type - no As on list-titles. credentials, cookies, cache - no As on list-titles. dl_params object no The dl track selection that the service reads from ctx.parent.params: lang, v_lang, a_lang, acodec and forced_subs, as on POST /api/session/create. Some services select the manifests they fetch from these values. When you give both season and episode, the server combines them into a \"{season}x{episode}\" selector. part narrows that to \"{season}x{episode}.{part}\", one part of a split episode. Without part you get every part of the episode. The server reads part only when you give both season and episode, and wanted takes precedence over all three. To scope a part by range, put it in wanted instead (\"S01E01.2\").
Single title / movie: Response 200Multiple episodes: Response 200 {\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, \"language\": \"en\", \"is_original_lang\": true,\n \"name\": null, \"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, \"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, \"needs_repack\": false, \"edition\": [], \"data\": null,\n \"drm\": [], \"descriptor\": \"DASH\" }\n ]\n}\n
{\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
The server sorts tracks by bitrate, descending. Episodes the server cannot get go into unavailable_episodes, rather than failing the whole request. Track objects here do not include a download url. Only the remote session endpoints give segment URLs.
The drm array on a track is a list of {type, pssh?, kids?, content_keys?, license_url?} objects.
Every track carries the same fields as a local track: is_original_lang, name, needs_repack, edition, and data. bitrate is in kb/s, and bitrate_bps gives the exact bits/s. data holds the part of the service-set track.data that fits in JSON, without the hls, dash, and ism parser keys. Audio keeps is_original and atmos for clients that read them, and adds the exact joc object count.
Status Error code Meaning 200 - Tracks returned. 400 INVALID_INPUT Missing service or title_id. 400 INVALID_PARAMETERS Invalid wanted range. 400 INVALID_SERVICE Unknown or disallowed service. 404 NO_CONTENT No matching episodes, or all matches failed."},{"location":"dev/rest-api/endpoints/#download-jobs","title":"Download jobs","text":"Downloads are asynchronous. POST /api/download enqueues a job and returns immediately with a job_id. The server runs each job in a background job worker subprocess. You then poll the job endpoints for progress and results.
Job states
A job moves through queued \u2192 downloading \u2192 one of the terminal states completed, failed, or cancelled. You can prioritise only queued jobs. You can retry or remove only terminal jobs.
"},{"location":"dev/rest-api/endpoints/#post-apidownload","title":"POST /api/download","text":"Make a download job. It requires service and title_id. Every other field is an optional download parameter with a server-side default. On success this returns 202 Accepted, not 200.
RequestResponse 202 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
{\n \"job_id\": \"b0f7c8e2-4a1d-4e9c-9b7e-2f3a1c0d5e6f\",\n \"status\": \"queued\",\n \"created_time\": \"2026-07-03T12:00:00+00:00\"\n}\n
Common parameters (all optional). These mirror the dl command flags:
Field Type Default Notes profile string null Credential/cookie profile. quality int[] [] Target resolution(s); best available if empty. vcodec string/string[] null Video codec filter. acodec string/string[] null Audio codec filter. vbitrate / abitrate int null Video / audio bitrate in kbps (positive). vbitrate_range / abitrate_range string null \"MIN-MAX\" bitrate window. range string[] [\"SDR\"] Dynamic range(s). channels number null Audio channel layout. no_atmos boolean false Exclude Atmos tracks. wanted string / string[] [] Episode/season selectors, as a list or as one comma-separated string. Accepts the part form, \"S01E01.2\", and the air-date form, \"2026-08-11\" or \"2026-08-01:2026-08-31\". For a music release, a selector is a track number, \"1-5\" or \"1,3,7\", or \"{disc}x{track}\" such as \"2x3\". latest_episode boolean false Only the newest episode. latest_episodes integer null Only the N newest episodes. A positive integer. When set, it overrides latest_episode. lang / v_lang / a_lang / s_lang string[] [\"orig\"] / [] / [] / [\"all\"] Language filters. require_audio string[] [] Audio languages that must exist. The job fails if one is missing, even with best_available. require_video string[] [] Video languages that must exist. The job fails if one is missing, even with best_available. require_subs string[] [] Subtitle languages that must exist. The job fails if one is missing. s_lang still decides what to keep. forced_subs boolean false Include forced subtitles. forced_subs_only boolean false Download forced subtitles and no other subtitle; implies forced_subs. Not valid with no_subs, video_only, audio_only or chapters_only. forced_s_lang string[] [] Forced subtitle language(s); implies forced_subs. exact_lang boolean false Exact language matching. sub_format string null Output subtitle format. video_only / audio_only / subs_only / chapters_only boolean false Track-type restriction (at most one). no_subs / no_audio / no_chapters / no_video / no_attachments boolean false Skip a track type. audio_description boolean false Download audio description. audio_description_only boolean false Download audio description and no standard audio. Not valid with no_audio, video_only, subs_only or chapters_only. slow boolean/string null Randomized delay between downloads. split_audio boolean null Separate files per audio codec. skip_dl boolean false Only fetch keys, do not download. all_drm boolean false License each track with both Widevine and PlayReady. Needs a CDM for each DRM system. Key vaults are read first; cdm_only: true sends a challenge for each system. The server refuses it with cdm, which selects one device. export boolean false Export manifest/keys/subs to JSON. cdm_only boolean null Force CDM-only (true) or vault-only (false) key retrieval. proxy / no_proxy / no_proxy_download / proxy_download string / bool / bool / string null / false / false / null Proxy controls. proxy and proxy_download must be full proxy URIs unless the API key has server_proxy. A Control D resolver, controld://<resolver>@dns.controld.com, counts as a full proxy URI: the server runs a forwarder for it. no_folder / no_source / no_mux boolean false Output/mux controls. sample boolean/string null Download a short sample and write it with a SAMPLE tag on the filename in a Sample folder inside the output folder. true is 60 seconds from 2 minutes in; \"0-60\" is a window in seconds. include_sample boolean false Download the full title, then also cut a 60 second sample from each muxed file into a Sample folder next to it. workers int null Threads per track. adaptive_workers boolean false Scale segment workers to measured CDN throughput, up to the workers cap. download_processes int 1 Split a track's segments across this many processes. Only engages for large batches. downloads int 1 Concurrent tracks. worst boolean false Lowest bitrate within quality. best_available boolean false Fall back to best available. With all_drm, a DRM system that does not license is a warning. repack boolean false Add REPACK tag. tag string null Release group tag. tmdb_id / imdb_id / tvdb_id / anilist_id - null External ID overrides. Each resolves its metadata directly instead of by a title search, and is used for tagging. Set enrich to also take the title, year and original language. Give at most one of tmdb_id, imdb_id and tvdb_id, since unshackle resolves the others from it. Sending two returns 400. anilist_id still combines with one of them. tmdb_id and tvdb_id must be positive integers, imdb_id must look like tt1375666, and anilist_id must be a positive integer or a string like mal:12345, or the request returns 400. An ID whose provider is unconfigured, such as tmdb_id with no tmdb_api_key, fails the job rather than returning 400. anilist_id needs no API key. tvdb_order official, dvd, absolute, alternate, regional null Renumber episodes to a TVDB season order. Falls back to the tvdb_order config option. enrich boolean false Overwrite title, year and original language with the external source's. Needs one of tmdb_id, imdb_id, tvdb_id or anilist_id. Without one the job fails instead of returning 400. daily boolean false Treat the title as daily/date-based content and fill missing episode air dates from TVDB. The fill needs enrich and a TVDB ID. An air date the service already set is kept. output_dir string null Output directory, relative to the server's downloads directory. The server rejects a path that resolves outside it with 400. no_cache / reset_cache boolean false Title cache controls. Validation. Invalid values return 400 INVALID_PARAMETERS. vcodec, acodec and sub_format take the same spellings as the CLI options of the same name (unshackle dl --help prints each list). The API and the CLI read one list, so they cannot disagree. range must be one of SDR/HDR10/HDR10P/DV/HLG/HYBRID, and HDR10+ is also valid. The bitrate, download worker, and download counts must be positive integers. You may set at most one of the *_only flags. You cannot combine no_subs with subs_only, or no_audio with audio_only.
Service options. A service's own CLI options travel in the same body. Send them in a nested service_params object, or as flat top-level keys. service_params wins over a flat key of the same name. An option you leave out takes the default declared on the service's cli command, so the job matches the equivalent dl run. profile at the top level always means the credential profile, never a service's own --profile option.
Request 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
Rejected parameters
postscript, post_script and post_scripts are never accepted. A body containing any of them gets 400 INVALID_PARAMETERS, because a command string that arrives from an HTTP caller would be remote code execution. You configure post-scripts only in unshackle.yaml, where they still operate for API jobs. See Post-scripts.
Gated parameters (developer)
The server accepts a few keys, but permits them only when the server config opts in. Otherwise the server rejects the request with 403 FORBIDDEN:
cdm (per-request CDM device name): allowed only if serve.cdm_overrides is true or a list containing that device name. credential (\"user:pass\") and credentials (a map): allowed only if serve.allow_job_credentials is truthy (off by default).
On the server, unshackle merges the effective parameters in this order: defaults \u2192 serve: config overrides \u2192 service-specific defaults \u2192 your request body.
Status Error code Meaning 202 - Job queued. 400 INVALID_INPUT Missing service/title_id or malformed JSON. 400 INVALID_PARAMETERS A parameter failed validation. 400 INVALID_SERVICE Unknown or disallowed service. 403 FORBIDDEN A gated parameter is not permitted. 403 SERVER_CDM_CAPPED The API key has a server_cdm_max_height for the service, and the job has no quality at or under it, sets best_available, or has HYBRID in range."},{"location":"dev/rest-api/endpoints/#get-apidownloadjobs","title":"GET /api/download/jobs","text":"Show download jobs, with optional filtering and sorting.
Query parameters
Param Values Default Description status queued, downloading, completed, failed, cancelled - Filter by status. service service tag - Filter by service. sort_by created_time, started_time, completed_time, progress, status, service created_time Sort field. sort_order asc, desc desc Sort direction. full true, false false Include full per-job details. RequestResponse 200 curl -H \"X-Secret-Key: $KEY\" \\\n \"http://127.0.0.1:8786/api/download/jobs?status=downloading&sort_by=progress&sort_order=desc\"\n
{\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
With full=true, each job additionally includes parameters (with secrets redacted), started_time, completed_time, output_files, error_message, error_details, and error_code. When you start the server with --debug-api, each job also includes error_traceback and worker_stderr.
Status Error code Meaning 200 - Jobs returned. 400 INVALID_PARAMETERS Invalid sort_by or sort_order."},{"location":"dev/rest-api/endpoints/#get-apidownloadjobsjob_id","title":"GET /api/download/jobs/{job_id}","text":"Fetch a single job with full details (equivalent to a full=true list entry).
Status Error code Meaning 200 - Job returned. 404 JOB_NOT_FOUND No such job."},{"location":"dev/rest-api/endpoints/#get-apidownloadjobsjob_idevents","title":"GET /api/download/jobs/{job_id}/events","text":"Stream the job's progress as Server-Sent Events. Use this instead of polling GET /api/download/jobs/{job_id}.
The response has the content type text/event-stream. Each event has this format:
event: <name>\ndata: <job JSON>\n
The data field of every event is the same job object that GET /api/download/jobs/{job_id} returns.
Event When it is sent snapshot Immediately, as the first event. Gives the job's current state. status The job leaves the queue and starts to download. progress 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. completed The job finished. The server then closes the event stream. failed The job failed. The server then closes the event stream. cancelled The job was cancelled. The server then closes the event stream. The server sends a : keep-alive comment each 15 seconds while the job is quiet, to keep proxies from closing an idle connection. Ignore these lines.
If the job is already in a terminal state, the server sends the snapshot event, then the terminal event, and closes the event stream immediately.
Authentication from a browser
EventSource cannot set headers. For this endpoint only, the server also accepts the API key in the secret_key query parameter. This works in both server modes, the default integrated server and --api-only:
const events = new EventSource(\n `http://127.0.0.1:8786/api/download/jobs/${jobId}/events?secret_key=${key}`\n);\nevents.addEventListener(\"progress\", (e) => console.log(JSON.parse(e.data).progress));\nevents.addEventListener(\"completed\", () => events.close());\n
The header always wins. Send the API key in the query parameter or in the header, not both. If an X-Secret-Key header is present, the server examines that header and ignores the query parameter. See Authentication.
RequestResponse 200 curl -N -H \"X-Secret-Key: $KEY\" \\\n \"http://127.0.0.1:8786/api/download/jobs/b0f7c8e2-.../events\"\n
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
Status Error code Meaning 200 - Event stream started. 404 JOB_NOT_FOUND No such job."},{"location":"dev/rest-api/endpoints/#delete-apidownloadjobsjob_id","title":"DELETE /api/download/jobs/{job_id}","text":"Cancel or remove a job. The behaviour depends on the job's current state:
- Terminal job (completed/failed/cancelled): removed from the manager, returning
204 No Content with an empty body. - Queued or downloading job: cancelled, returning
200 {\"status\": \"success\", \"message\": \"Job cancelled\"}.
Warning
A 204 response has no body. Do not try to parse JSON from it.
Status Error code Meaning 200 - Job cancelled. 204 - Terminal job removed (empty body). 400 INVALID_PARAMETERS Job is in a state that cannot be cancelled. 404 JOB_NOT_FOUND No such job."},{"location":"dev/rest-api/endpoints/#post-apidownloadjobsclear-finished","title":"POST /api/download/jobs/clear-finished","text":"Remove every terminal (completed/failed/cancelled) job from the manager. No request body.
Response 200 { \"removed\": 3 }\n
"},{"location":"dev/rest-api/endpoints/#post-apidownloadjobsjob_idretry","title":"POST /api/download/jobs/{job_id}/retry","text":"Enqueue a new job that reuses a terminal job's service, title, and parameters. The service allowlist and parameter gates are re-checked. Returns 202 with the new job's ID.
Retry reuses the original, unredacted parameters
A retry replays the finished job's stored parameters exactly as the original client submitted them, including any secrets such as credential/credentials. It does not use the redacted parameters view that GET /api/download/jobs and GET /api/history 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.
Response 202 {\n \"job_id\": \"9c1e2f3a-...\",\n \"status\": \"queued\",\n \"created_time\": \"2026-07-03T12:05:00+00:00\"\n}\n
Status Error code Meaning 202 - New job queued. 404 JOB_NOT_FOUND No such job. 409 CONFLICT Job is not in a terminal state. 400 INVALID_SERVICE Service is no longer allowed. 403 FORBIDDEN A gated parameter is no longer permitted. 403 SERVER_CDM_CAPPED The job is no longer inside the server_cdm_max_height of the API key."},{"location":"dev/rest-api/endpoints/#post-apidownloadjobsjob_idpriority","title":"POST /api/download/jobs/{job_id}/priority","text":"Move a queued job to the front of the download queue.
Response 200 { \"job_id\": \"b0f7c8e2-...\", \"position\": \"front\" }\n
Status Error code Meaning 200 - Job moved to front. 404 JOB_NOT_FOUND No such job. 409 CONFLICT Job is not queued."},{"location":"dev/rest-api/endpoints/#post-apidownloadjobsjob_idinput","title":"POST /api/download/jobs/{job_id}/input","text":"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 input_prompt field and in its progress events. Show the prompt to the user and send the answer here.
A job that waits for an approval on another device, such as a pair code login, shows the message in its notice field instead. A notice needs no answer: show it to the user and keep polling.
RequestResponse 200 { \"response\": \"123456\" }\n
{ \"status\": \"accepted\" }\n
Status Error code Meaning 200 - Answer sent to the job. The input_prompt field goes back to null. 400 INVALID_INPUT The body is not JSON, or it has no response. 404 JOB_NOT_FOUND No such job. 409 CONFLICT The job does not wait on a prompt. Warning
The job keeps its download slot while it waits. It fails with AUTH_FAILED if nobody answers the prompt within 10 minutes.
"},{"location":"dev/rest-api/endpoints/#server-management","title":"Server management","text":"Endpoints for profiles, effective configuration, download history, environment checks, and maintenance actions.
"},{"location":"dev/rest-api/endpoints/#get-apiprofiles","title":"GET /api/profiles","text":"Show the named credential profiles configured per service (usable as the profile 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.
Response 200 {\n \"profiles\": {\n \"EXAMPLE\": [\"default\", \"premium\"],\n \"OTHER\": [\"us-account\"]\n }\n}\n
"},{"location":"dev/rest-api/endpoints/#get-apiconfig","title":"GET /api/config","text":"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 (secret, password, passwd, token, api_key, credential, auth, cookie, bearer, private) and any userinfo in proxy URLs. The directories block holds the server's absolute paths and reaches only an admin key (admin: true or the api_secret); a plain key gets the response without it.
Response 200 {\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
"},{"location":"dev/rest-api/endpoints/#get-apihistory","title":"GET /api/history","text":"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 DELETE /api/history/{job_id} and POST /api/download/jobs/clear-finished. unshackle stores the history in api_history.jsonl in the cache directory. It skips corrupt lines, and a missing file yields an empty list.
Query parameters
Param Type Default Description limit int (\u2265 1) 100 Maximum entries to return. service string - Case-insensitive service filter. Response 200 {\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
Status Error code Meaning 200 - History returned. 400 INVALID_PARAMETERS Invalid limit."},{"location":"dev/rest-api/endpoints/#delete-apihistoryjob_id","title":"DELETE /api/history/{job_id}","text":"Remove a single persisted history entry. Returns 204 No Content (empty body) on success.
Status Error code Meaning 204 - Entry removed (empty body). 404 NOT_FOUND No such entry (or outside your allowlist)."},{"location":"dev/rest-api/endpoints/#post-apimaintenanceclear-cache-and-post-apimaintenanceclear-temp","title":"POST /api/maintenance/clear-cache and POST /api/maintenance/clear-temp","text":"Delete and recreate the cache or temp directory. Both, and refresh-services, need admin: true on the API key or the api_secret itself; any other key gets 403 FORBIDDEN. Neither takes a request body. The server blocks both with 409 CONFLICT if any job is currently downloading (the details include the offending active_jobs).
The 409 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.
clear-cache also wipes download history
The persistent history read by GET /api/history lives in api_history.jsonl 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 DELETE /api/history/{job_id} instead.
Response 200 { \"cleared\": true, \"freed_bytes\": 1048576 }\n
Status Error code Meaning 200 - Directory cleared. 409 CONFLICT A download is currently active."},{"location":"dev/rest-api/endpoints/#post-apimaintenancerefresh-services","title":"POST /api/maintenance/refresh-services","text":"git-pull every service repository configured under directories.services and re-import the services that changed, without a restart. refreshed becomes true when all repos updated successfully, or when you configure no repository. deferred lists the services that have a running or queued job: they keep their current code until that job finishes, then swap. load_errors lists the services whose new code failed to import; the server drops them until the next successful refresh.
Response 200 {\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
"},{"location":"dev/rest-api/endpoints/#get-apienvcheck","title":"GET /api/env/check","text":"Report the install status of the external binaries unshackle depends on (the same set unshackle env check inspects), with best-effort version detection.
Response 200 {\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
"},{"location":"dev/rest-api/endpoints/#remote-dl-sessions","title":"Remote-dl sessions","text":"Developer feature
The /api/session/* 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 --remote-only mode, and they are what the built-in RemoteService client drives. Most end users never call them directly.
The server holds remote sessions in memory. They expire after serve.session_ttl (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 403 FORBIDDEN.
"},{"location":"dev/rest-api/endpoints/#remote-session-lifecycle-overview","title":"Remote session lifecycle overview","text":"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}/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
"},{"location":"dev/rest-api/endpoints/#slow-responses","title":"Slow responses","text":"The titles, tracks and license routes can take minutes on a large catalogue. When the answer is not ready after 30 seconds, the route sends status 200 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.
A late failure has status 200
The server sent the status before the work ended. A failure after the first 30 seconds arrives as the standard error body with status 200. Check status in the body, not only the HTTP status. The body has no HTTP status field. Use error_code and retryable to decide what to do.
A slow response is not gzip-compressed. Gzip output cannot start before the body is ready, and the newlines must go out at once.
"},{"location":"dev/rest-api/endpoints/#post-apisessioncreate","title":"POST /api/session/create","text":"Make a remote session for a service and title. Authentication runs asynchronously in the background. This call returns immediately with status: \"authenticating\", and you then poll the prompt endpoint. The body accepts service and title_id (both required). It also accepts a broad set of optional keys, because the body allows additionalProperties. These are credentials ({username, password, extra?}), cookies (base64 of zlib-compressed Netscape cookie file), proxy, no_proxy, profile, cache (map of forwarded cache files, keyed by the file path relative to the service cache directory with / separators and no .json suffix, so a nested key such as session_web/<sha1> lands in a subdirectory), client_region, proxy_region, cdm_type, range_, vcodec, quality, best_available, dl_params, client, and any service CLI options. proxy_region is the country code the client resolved proxy from; the server matches it against its own accounts. client is a freeform object the dashboard shows as sent (the CLI puts version, code_hash, platform and a redacted argv in it); the server ignores it above 4096 bytes of JSON.
dl_params is an object with the dl track selection: lang, v_lang and a_lang (arrays of language strings), acodec (an array of audio codec names or dl -a aliases such as ddp) and forced_subs (boolean). The service reads these values from ctx.parent.params. The server uses the dl default for each absent or malformed value, and drops an unknown codec name.
Service CLI options also travel in a nested service_params object, which wins over a flat key with the same name. profile at the top level always means the credentials profile, never a service's own --profile option.
The proxy value must be a full proxy URI, unless the operator gives your API key server_proxy in the serve.users config. Without server_proxy, the server does not resolve country codes with its own proxy providers. It rejects the request with INVALID_PROXY when no proxy is set and the reported client_region differs from the server's region. A request that reports no client_region is not blocked. Pass proxy with your own proxy, or no_proxy to accept the server's own connection. With server_proxy, the server resolves a country code and picks a proxy for your client_region itself. A Control D resolver, controld://<resolver>@dns.controld.com, counts as a full proxy URI: the server runs a forwarder for it and needs no Control D configuration of its own.
Response 200 {\n \"session_id\": \"d4e5f6a7-...\",\n \"service\": \"EXAMPLE\",\n \"status\": \"authenticating\",\n \"server_account\": false\n}\n
server_account is true when the server authenticated with one of its own accounts (serve.server_accounts). 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.
Status Error code Meaning 200 - Session created; authentication in progress. 400 INVALID_INPUT Missing service or title_id. 400 INVALID_SERVICE Unknown or disallowed service."},{"location":"dev/rest-api/endpoints/#get-apisessionsession_idprompt","title":"GET /api/session/{session_id}/prompt","text":"Poll for the authentication status and any pending interactive prompt (OTP, PIN, device code). Response variants:
AuthenticatingPending inputAuthenticatedFailed { \"status\": \"authenticating\" }\n
{ \"status\": \"pending_input\", \"prompt\": \"Enter the code sent to your email:\" }\n
{ \"status\": \"authenticated\" }\n
{ \"status\": \"failed\", \"error\": \"Invalid credentials\" }\n
Status Error code Meaning 200 - Status returned. 403 FORBIDDEN Request IP differs from the remote session creator. 404 SESSION_NOT_FOUND No such session."},{"location":"dev/rest-api/endpoints/#post-apisessionsession_idprompt","title":"POST /api/session/{session_id}/prompt","text":"Submit a response to a pending prompt. Body: { \"response\": \"...\" } (required).
Response 200 { \"status\": \"accepted\" }\n
Status Error code Meaning 200 - Response accepted. 400 INVALID_INPUT Missing response, or no prompt is pending. 404 SESSION_NOT_FOUND No such session."},{"location":"dev/rest-api/endpoints/#get-apisessionsession_idlogs","title":"GET /api/session/{session_id}/logs","text":"Drain the service's server-side log output for this remote session. The server mirrors every log call the service makes (self.log.info, warnings, errors) into a bounded per-session buffer, so a remote client can see why an auth, title, or license step failed. Pass since=<seq> to get only records newer than the last drained sequence number. Works in every auth state, including failed.
Response 200 {\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
Status Error code Meaning 200 - Records returned (empty list when nothing new). 404 SESSION_NOT_FOUND No such session. 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.
"},{"location":"dev/rest-api/endpoints/#get-apisessionsession_idtitles","title":"GET /api/session/{session_id}/titles","text":"Fetch the titles for an authenticated remote session. A slow answer arrives as a slow response.
Response 200 {\n \"session_id\": \"d4e5f6a7-...\",\n \"titles\": [ { \"type\": \"episode\", \"name\": \"Pilot\", \"id\": \"ep-1\" } ]\n}\n
Requires an authenticated remote session. Otherwise it returns 404 SESSION_NOT_FOUND.
"},{"location":"dev/rest-api/endpoints/#post-apisessionsession_idtracks","title":"POST /api/session/{session_id}/tracks","text":"Get tracks and chapters for a specific title within the remote session. Body: { \"title_id\": \"...\" } (required). Unlike list-tracks, 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.
manifests holds each served DASH/ISM manifest once. A service can build an AdaptationSet of its own that the served manifest does not contain. track_manifests holds a one-AdaptationSet MPD for each such track, and the client re-parses that in place of the whole manifest.
Response 200 {\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\": \"<base64 zlib xml>\" } ],\n \"track_manifests\": [ { \"track_id\": \"s-1\", \"type\": \"dash\", \"url\": \"https://...\", \"data\": \"<base64 zlib xml>\" } ],\n \"session_headers\": { \"User-Agent\": \"...\" },\n \"session_cookies\": { \"sid\": \"...\" },\n \"server_cdm_type\": \"widevine\"\n}\n
Status Error code Meaning 200 - Tracks returned. 400 INVALID_INPUT Missing or unknown title_id. 404 SESSION_NOT_FOUND No such session."},{"location":"dev/rest-api/endpoints/#post-apisessionsession_idsegments","title":"POST /api/session/{session_id}/segments","text":"Get the download URL, DRM info, headers, cookies, and raw track data for the selected tracks. Body: { \"track_ids\": [\"v-1\", \"a-1\"] } (required).
Response 200 {\n \"tracks\": {\n \"v-1\": { \"descriptor\": \"DASH\", \"url\": \"https://...\", \"drm\": [ ... ], \"headers\": { ... }, \"cookies\": { ... }, \"data\": { ... } }\n }\n}\n
Status Error code Meaning 200 - Segment info returned. 400 INVALID_INPUT Missing track_ids. 404 TRACK_NOT_FOUND An unknown track ID was requested."},{"location":"dev/rest-api/endpoints/#post-apisessionsession_idsegment_filter","title":"POST /api/session/{session_id}/segment_filter","text":"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: { \"track_id\": \"v-1\" } (required). unwanted is null when the track has no filter. The client keeps every segment when the server does not have this route.
Response 200 { \"unwanted\": [\"https://cdn.example/hls/ad1.ts\"] }\n
Status Error code Meaning 200 - Unwanted segment URIs, or null. 400 INVALID_INPUT Missing track_id. 404 TRACK_NOT_FOUND An unknown track ID was requested. 500 SERVICE_ERROR The playlist request or the filter failed."},{"location":"dev/rest-api/endpoints/#post-apisessionsession_idlicense","title":"POST /api/session/{session_id}/license","text":"Get the content keys for the DRM. The mode field selects one of two modes. A slow answer arrives as a slow response.
Proxy mode (mode: \"proxy\", the default) forwards the client's CDM challenge to the service's license endpoint and returns the raw license bytes:
RequestResponse 200 { \"track_id\": \"v-1\", \"challenge\": \"<base64 CDM challenge>\", \"drm_type\": \"widevine\" }\n
{ \"license\": \"<base64 license bytes>\" }\n
Server-CDM mode (mode: \"server_cdm\") runs the full CDM flow on the server using the device configured for your API key, returning content keys directly. Use track_id for a single track or track_ids for a batch:
Single: Response 200Batch: Response 200 { \"keys\": { \"<kid_hex>\": \"<key_hex>\" }, \"vault_keys\": [\"<kid_hex>\"], \"drm_type\": \"widevine\" }\n
{ \"keys\": { \"v-1\": { \"<kid_hex>\": \"<key_hex>\" } }, \"vault_keys\": [\"<kid_hex>\"], \"drm_type\": \"widevine\" }\n
Field Description track_id / track_ids Single track, or a batch of tracks. challenge Base64 CDM challenge (proxy mode). pssh Base64 PSSH (server-CDM mode). drm_type widevine (default) or playready. In server-CDM mode the server's cdm mapping for the service decides the DRM system and the response drm_type names the system that licensed. The client's value decides only when the server has no mapping for the service. mode proxy (default) or server_cdm. clear_tracks (response) Requested track ids that carry no DRM, so they have no keys. Absent when every requested track is encrypted. vault_keys (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 200 - License/keys returned. 400 INVALID_INPUT Missing challenge/PSSH, or no CDM device configured for the API key. 400 INVALID_PARAMETERS Unsupported drm_type. 404 TRACK_NOT_FOUND Unknown track ID. 404 NO_CONTENT Server CDM produced no keys. 502 SERVICE_ERROR The service aborted during licensing."},{"location":"dev/rest-api/endpoints/#post-apisessionsession_idkeysbad","title":"POST /api/session/{session_id}/keys/bad","text":"Report a content key from vault_keys 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. The client never learns the server vault names.
{ \"kid\": \"<kid_hex>\", \"key\": \"<key_hex>\" }\n
Status Error code Meaning 200 - The pair is flagged. 400 INVALID_INPUT This remote session was not served that pair. 404 SESSION_NOT_FOUND Unknown remote session."},{"location":"dev/rest-api/endpoints/#get-apisessionsession_id","title":"GET /api/session/{session_id}","text":"Return remote session metadata and validity.
Response 200 {\n \"session_id\": \"d4e5f6a7-...\",\n \"service\": \"EXAMPLE\",\n \"valid\": true,\n \"expires_in\": 300,\n \"track_count\": 4,\n \"title_count\": 10\n}\n
404 SESSION_NOT_FOUND if the remote session does not exist or has expired.
"},{"location":"dev/rest-api/endpoints/#delete-apisessionsession_id","title":"DELETE /api/session/{session_id}","text":"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.
Response 200 {\n \"status\": \"ok\",\n \"cache\": { \"tokens\": \"<base64 zlib bytes>\", \"session_web/<sha1>\": \"<base64 zlib bytes>\" }\n}\n
The cache 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 / separators and no .json 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 .. segment, or an empty segment, and so does the client. 404 SESSION_NOT_FOUND if the remote session does not exist.
"},{"location":"dev/rest-api/endpoints/#error-responses","title":"Error responses","text":"The server serialises every structured error raised inside a handler to the same JSON envelope:
{\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
details appears only when non-empty. retryable appears only when the error is retryable (e.g. network errors, rate limiting). debug_info appears only when you start the server with --debug-api.
Authentication errors differ
Errors raised by the API-key middleware use a distinct shape ({\"status\": 401, \"message\": \"Secret Key is Empty.\"}, {\"status\": 401, \"message\": \"Secret Key is Invalid.\"}, or {\"status\": 429, \"message\": \"Rate limit exceeded.\"} with a Retry-After header) with an integer status and no error_code, timestamp, or details. A 429 from the middleware therefore carries no error_code, unlike the RATE_LIMITED 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 error_code: \"INVALID_INPUT\".
"},{"location":"dev/rest-api/endpoints/#error-codes-and-default-status","title":"Error codes and default status","text":"Error code HTTP status INVALID_INPUT 400 INVALID_SERVICE 400 INVALID_PROXY 400 INVALID_PARAMETERS 400 AUTH_FAILED 401 FORBIDDEN 403 SERVER_CDM_CAPPED 403 GEOFENCE 403 NOT_FOUND 404 NO_CONTENT 404 JOB_NOT_FOUND 404 SESSION_NOT_FOUND 404 TRACK_NOT_FOUND 404 CONFLICT 409 RATE_LIMITED 429 INTERNAL_ERROR 500 DOWNLOAD_ERROR 500 WORKER_ERROR 500 SERVICE_ERROR 502 DRM_ERROR 502 NETWORK_ERROR 503 SERVICE_UNAVAILABLE 503 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 NETWORK_ERROR (503, retryable), \"rate limit\" or \"429\" become RATE_LIMITED (429, retryable), and anything unrecognized collapses to INTERNAL_ERROR (500).
"},{"location":"dev/rest-api/endpoints/#see-also","title":"See also","text":" - REST API overview. What the server is and when to use it.
- Authentication. Keys, server modes, and the
X-Secret-Key header. - Quickstart. A first end-to-end request walkthrough.
- Downloading. The
dl flags mirrored by POST /api/download.
"},{"location":"dev/rest-api/errors/","title":"Error Responses","text":"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.
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.
Where this comes from
unshackle/core/api/errors.py defines the error format, and the wrapper that turns raised errors into responses lives in unshackle/core/api/routes.py. Nothing on this page is invented. It reflects the actual server behaviour.
"},{"location":"dev/rest-api/errors/#the-standard-error-shape","title":"The standard error shape","text":"A structured error is always a JSON object with status set to the literal string \"error\". The full set of fields:
Error response body{\n \"status\": \"error\",\n \"error_code\": \"INVALID_PARAMETERS\",\n \"message\": \"vcodec must be one of: H264, H265, ...\",\n \"timestamp\": \"2026-07-03T12:34:56.789012+00:00\",\n \"details\": { \"field\": \"vcodec\" },\n \"retryable\": true,\n \"debug_info\": {\n \"exception_type\": \"APIError\",\n \"traceback\": \"...\"\n }\n}\n
Field Type Always present? Meaning status string Yes Always the literal \"error\". Lets a client distinguish an error body from a success body at a glance. error_code string Yes A stable, machine-readable code from the catalogue below. Match on this, not on message. message string Yes A human-readable description of what went wrong. Wording may change between versions, so do not parse it. timestamp string Yes ISO 8601 timestamp (UTC) of when the error response was built. details 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). retryable boolean Only when true Present and set to true when retrying the same request may succeed later (network blips, rate limiting, transient outages). Absent otherwise. debug_info object Only with --debug-api Technical diagnostics; see Debug information. Match on error_code, branch on HTTP status
Treat error_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.
"},{"location":"dev/rest-api/errors/#the-details-object","title":"The details object","text":"When present, details carries extra context specific to the error. It is only included when it is non-empty, so a client must treat a missing details as \"no extra information\". Some concrete examples you may encounter:
- A validation failure may include the offending field or the list of valid values.
- A \"title not found\" error on a remote session includes
available_titles. - A maintenance conflict includes
active_jobs, the jobs blocking the operation. - Categorised exceptions add a
reason tag, such as \"network_connectivity\" or \"geofence_restriction\".
"},{"location":"dev/rest-api/errors/#the-retryable-hint","title":"The retryable hint","text":"The retryable field appears only when it is true. 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.
A retryable network error
{\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
"},{"location":"dev/rest-api/errors/#error-code-catalogue","title":"Error code catalogue","text":"Every code below is a member of the APIErrorCode enumeration. The Status column is the default HTTP status the server returns for that code. A handler can override the status in special cases (for example, a network error is always forced to 503), but the defaults hold for the overwhelming majority of responses.
"},{"location":"dev/rest-api/errors/#client-errors-4xx","title":"Client errors (4xx)","text":"Code Status Meaning INVALID_INPUT 400 A required field is missing, or the request body could not be parsed. Also used as the generic \"your input was malformed\" code. INVALID_SERVICE 400 The named service is unknown, or is not permitted for your API key. INVALID_PROXY 400 The supplied proxy specification could not be resolved or is malformed, or the proxy failed the exit check. INVALID_PARAMETERS 400 One or more download or query parameters failed validation (bad codec, bitrate, sort field, and so on). AUTH_FAILED 401 Authentication with the streaming service failed (bad credentials or cookies). FORBIDDEN 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. SERVER_CDM_CAPPED 403 The server CDM does not license live above the server_cdm_max_height of the API key. details.reason is server_cdm_max_height (with details.max_height), client_device, for a remote session where the client's own device licenses, or server_device, for a remote session that runs on the server's device. A remote client licenses the track with its own device, except for server_device: then only its own vaults can supply the key. GEOFENCE 403 The title is not available in the applicable region. NOT_FOUND 404 A requested resource (title, history entry, and so on) does not exist. NO_CONTENT 404 The request was valid but produced nothing: no matching titles, tracks, episodes, or keys. JOB_NOT_FOUND 404 The referenced download job does not exist. SESSION_NOT_FOUND 404 The remote-dl session does not exist or has expired. TRACK_NOT_FOUND 404 A referenced track ID is not present in the remote session. CONFLICT 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). RATE_LIMITED 429 The streaming service is rate-limiting requests. Retryable. Not every 429 is RATE_LIMITED
The server has a rate limit of its own. An API key over serve.tiers.<name>.rate_limit or serve.users.<key>.rate_limit gets a 429 from the authentication middleware, before any handler runs, so it carries no error_code and is not the RATE_LIMITED code above. It is the shape {\"status\": 429, \"message\": \"Rate limit exceeded.\"} with a Retry-After header. Read Retry-After 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.
"},{"location":"dev/rest-api/errors/#server-errors-5xx","title":"Server errors (5xx)","text":"Code Status Meaning INTERNAL_ERROR 500 An unexpected server-side error. This is the fallback for any exception the server could not categorise. DOWNLOAD_ERROR 500 The download process itself failed. WORKER_ERROR 500 The download worker subprocess errored out. SERVICE_ERROR 502 The streaming service's API returned an error, or the service does not support the requested operation. DRM_ERROR 502 DRM or license acquisition failed. Retryable. NETWORK_ERROR 503 A network connectivity problem (connection, timeout, DNS, TLS). Retryable. SERVICE_UNAVAILABLE 503 The service is temporarily unavailable or under maintenance. Retryable. Fallback status
If a code is ever emitted without a mapped status, the server falls back to 500. In practice every code above has an explicit mapping.
"},{"location":"dev/rest-api/errors/#how-the-server-produces-errors","title":"How the server produces errors","text":"Understanding where an error comes from helps interpret it.
Explicitly raised errors. Most endpoints raise a structured APIError directly. For example, a missing service field yields INVALID_INPUT, and a disallowed service yields INVALID_SERVICE. These carry a precise code, message, and often a populated details object.
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:
If the error mentions... It becomes Retryable auth, login, credential, unauthorized, forbidden, token AUTH_FAILED (401) no connection, timeout, network, unreachable, socket, dns, resolve (or ConnectionError, TimeoutError, URLError, SSLError) NETWORK_ERROR (503) yes geofence, geoblock, region, not available in, territory GEOFENCE (403) no not found, 404, does not exist, invalid id NOT_FOUND (404) no rate limit, too many requests, 429, throttle RATE_LIMITED (429) yes drm, license, widevine, playready, decrypt DRM_ERROR (502) no service unavailable, 503, maintenance, temporarily unavailable SERVICE_UNAVAILABLE (503) yes invalid, malformed, validation (or ValueError, ValidationError) INVALID_INPUT (400) no anything else INTERNAL_ERROR (500) no Categorised errors include a reason tag inside details (such as \"network_connectivity\" or \"drm_failure\") so a client can react without parsing the message text.
Invalid JSON bodies. If a POST endpoint receives a body that is not valid JSON, the server returns INVALID_INPUT (400) with the parse error in details.error:
Malformed request body{\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
"},{"location":"dev/rest-api/errors/#the-authentication-error-exception","title":"The authentication error exception","text":"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 X-Secret-Key header, the middleware short-circuits with a legacy body that uses an integer status and no error_code or timestamp.
Missing keyInvalid key { \"status\": 401, \"message\": \"Secret Key is Empty.\" }\n
{ \"status\": 401, \"message\": \"Secret Key is Invalid.\" }\n
Handle both shapes
A client must expect two error formats: the standard structured error (string status of \"error\", with error_code), and this authentication error (integer status, no error_code). The GET /api/health endpoint is exempt from authentication, so it never returns the key-error shape.
"},{"location":"dev/rest-api/errors/#late-failures-with-status-200","title":"Late failures with status 200","text":"The remote session titles, tracks and license routes send status 200 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 200. The body has no field for the HTTP status that the error would otherwise have. error_code and retryable stay in the body.
Check the body on these routes
On these routes a 200 does not always mean success. Parse the body and treat \"status\": \"error\" with an error_code as a failure.
"},{"location":"dev/rest-api/errors/#responses-with-no-body","title":"Responses with no body","text":"Not every failure or completion has a JSON body. Some endpoints answer with 204 No Content and an empty body, notably deleting a terminal download job and deleting a history entry.
Do not parse 204 bodies
A 204 response has no body. Clients must examine the status code before they decode JSON, or the decode will fail on an empty string.
"},{"location":"dev/rest-api/errors/#debug-information","title":"Debug information","text":"By default, error responses never include tracebacks or internal diagnostics. If you start the server with the --debug-api flag, every structured error gains a debug_info object:
Error with --debug-api enabled{\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
The debug_info object always carries exception_type and, for exception-derived errors, a formatted traceback. Some endpoints add extra diagnostics such as captured job worker stderr.
Developer use only
--debug-api exposes internal tracebacks in responses. Enable it only for local debugging, never on a server reachable by untrusted clients.
"},{"location":"dev/rest-api/errors/#client-handling-recommendations","title":"Client handling recommendations","text":"For anyone writing a consumer of the API, a durable strategy is:
- Read the HTTP status first. It tells you the broad class of outcome, and it lets you find the
204/no-body and authentication-error cases before you read the body. - Branch on
error_code. For structured errors, this is the stable identifier to switch on. Do not use message as the identifier. - Respect
retryable. When it is true, back off and try the request again. The reference client retries 429, 500, 502, 503, and 504 with exponential backoff. When absent, fix the request rather than repeating it. - Fall back gracefully. For an unrecognised code, show the
message and the HTTP status.
Reference consumer
unshackle's own remote-download client treats any status of 400 or above as fatal, and a 200 body with \"status\": \"error\" and an error_code too: it logs Server error [<error_code>]: <message> and exits. It also wraps requests in a retry adapter (five attempts, backing off on 429, 500, 502, 503, and 504). This is a reasonable template for your own client's error handling.
"},{"location":"dev/rest-api/job-lifecycle/","title":"Download Job Lifecycle","text":"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.
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.
Who this page is for
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.
For the full request and response shape of each endpoint, see Endpoints. For how the server reports errors, see Error Responses.
"},{"location":"dev/rest-api/job-lifecycle/#the-five-states","title":"The five states","text":"A job is always in exactly one of five states, exposed as the status field:
Status Meaning queued Created and waiting for a free job worker. No download has started yet. downloading A job worker has picked the job up and the download is in progress. completed The download finished successfully; output_files lists the results. failed The download stopped with an error; error_message and error_code explain why. cancelled The job was cancelled before it could finish, from either the queued or downloading state. The last three (completed, failed, and cancelled) 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.
"},{"location":"dev/rest-api/job-lifecycle/#how-a-job-moves-between-states","title":"How a job moves between states","text":"stateDiagram-v2\n [*] --> queued: POST /api/download\n queued --> downloading: a worker picks it up\n queued --> cancelled: DELETE (while queued)\n downloading --> completed: download succeeds\n downloading --> failed: download errors\n downloading --> cancelled: DELETE (while downloading)\n completed --> [*]\n failed --> [*]\n cancelled --> [*]\n\n completed --> queued: POST .../retry (as a NEW job)\n failed --> queued: POST .../retry (as a NEW job)\n cancelled --> queued: POST .../retry (as a NEW job)
The transitions in prose:
queued \u2192 downloading 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. downloading \u2192 completed is the happy path: the download engine wrote all the requested files and reported success. downloading \u2192 failed is any error during the download: a service failure, a network problem, a DRM error, and so on. The job records what went wrong. queued/downloading \u2192 cancelled happens when you send a DELETE for a job that has not finished (see Cancelling a job). - Retry does not move a terminal job back to
queued. 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).
Priority does not change status
Moving a job to the front of the queue with the priority endpoint reorders when it will start, but it stays queued until a job worker picks it up. It is not a state change.
"},{"location":"dev/rest-api/job-lifecycle/#creating-a-job","title":"Creating a job","text":"You queue a download with POST /api/download. The request needs at least a service and a title_id, plus any download options you want to set. On success the server replies with 202 Accepted and the new job's identity:
Queue a downloadcurl -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
202 Accepted{\n \"job_id\": \"b1e6c7de-6d0a-4f2f-9d1e-3a2b4c5d6e7f\",\n \"status\": \"queued\",\n \"created_time\": \"2026-07-03T12:00:00.000000\"\n}\n
The job starts in queued. The job workers auto-start on the first job you submit, so you switch nothing else on. Keep the job_id. Every later call uses it.
The full parameter set
POST /api/download accepts the same download options as the dl command (quality, codecs, language selection, wanted 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.
"},{"location":"dev/rest-api/job-lifecycle/#reading-a-jobs-status-and-progress","title":"Reading a job's status and progress","text":"There are two ways to look at jobs.
One job in fullAll jobs (summaries) GET /api/download/jobs/{job_id} returns the complete detail for a single job, including parameters (with secrets redacted), timing, output files, and error information if it failed.
curl http://127.0.0.1:8786/api/download/jobs/b1e6c7de-6d0a-4f2f-9d1e-3a2b4c5d6e7f \\\n -H \"X-Secret-Key: your-api-secret\"\n
GET /api/download/jobs lists every job the manager currently holds. By default each entry is a summary. Pass full=true to get the same full detail as the single-job endpoint for every job.
curl \"http://127.0.0.1:8786/api/download/jobs?status=downloading&sort_by=progress&sort_order=desc\" \\\n -H \"X-Secret-Key: your-api-secret\"\n
You can filter the list by status and service, and order it with sort_by (created_time, started_time, completed_time, progress, status, or service) and sort_order (asc / desc). See Endpoints for the query-parameter reference.
"},{"location":"dev/rest-api/job-lifecycle/#the-progress-fields","title":"The progress fields","text":"While a job is downloading, 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:
Field Type Meaning progress number 0 to 100 Overall percent complete. phase string Human-readable phase, e.g. downloading video 1080p HDR10, audio en 5.1. title string Title being processed. current_title string The specific episode/movie in progress (for a batch). completed_tracks int Number of tracks finished so far. total_tracks int Total tracks selected for the download. active_tracks list of strings Labels of the tracks downloading right now. track_progress list Per-active-track {label, progress, speed} entries. segments_done number Segments downloaded for the track in progress. segments_total number Total segments for the track in progress. speed string Transfer speed of the track in progress, e.g. 4.20 MB/s. skipped_subtitles list Subtitles that were skipped as non-fatal failures (when skip_subtitle_errors is set). input_prompt string or null The prompt the service waits on. Answer it with POST /api/download/jobs/{job_id}/input. notice string or null A message the service shows while it waits for an approval on another device, such as a pair code. It needs no answer. The full detail adds started_time, completed_time, output_files, the redacted parameters, and, for failed jobs, error_message, error_details, and error_code. With --debug-api, it also adds error_traceback and worker_stderr.
A typical polling loop
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
Or subscribe instead of polling
GET /api/download/jobs/{job_id}/events pushes the same job object as Server-Sent Events, and closes the event stream when the job ends. See Endpoints.
What the percentage means
progress climbs from 0 toward 90 while tracks download, then the final stretch to 100 covers post-download work such as decryption cleanup, repackaging, and muxing. A job that has finished downloading but is still muxing can sit near 90 for a moment before completing. On success the manager sets it to exactly 100.
For a batch, progress is per-episode, not whole-batch
A multi-episode request (a wanted range) is a single job that processes its episodes sequentially. As each new episode begins, progress and the track counts (completed_tracks / total_tracks) 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 output_files array against parameters.wanted rather than trusting progress.
"},{"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":"A completed job has its output_files populated with the paths of the muxed results, and progress is 100. This is the state you want.
"},{"location":"dev/rest-api/job-lifecycle/#failed","title":"Failed","text":"A failed job carries the error. error_message is the short human message, error_code is one of the API's structured error codes (for example NETWORK_ERROR, DRM_ERROR, AUTH_FAILED, or DOWNLOAD_ERROR), and error_details gives more context. When you start the server with --debug-api, error_traceback and worker_stderr are also filled in, to help you find the cause.
Secrets are scrubbed from error text
A service can echo a credential or a proxy URL into its output. The server masks any known secret values out of error_message, error_details, error_traceback, and worker_stderr before returning them, so it is safe to log these fields.
The error-code catalogue and how each maps to an HTTP status is on the Error Responses page.
"},{"location":"dev/rest-api/job-lifecycle/#cancelled","title":"Cancelled","text":"The server stopped a cancelled job on request, before it finished. It may have partial output, but it is not considered complete. See below.
"},{"location":"dev/rest-api/job-lifecycle/#cancelling-a-job","title":"Cancelling a job","text":"Send DELETE /api/download/jobs/{job_id}. The behaviour depends on the job's current state, and this is important because the response differs:
Job state when you DELETE What happens Response queued or downloading The job is cancelled. A running download's worker process is terminated. 200 with {\"status\": \"success\", \"message\": \"Job cancelled\"} completed, failed, or cancelled (terminal) The job is removed from the manager entirely. 204 No Content, empty body Not found - 404 with error code JOB_NOT_FOUND In other words, DELETE on a live job cancels it, while DELETE 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.
Do not parse the body of a 204
Removing a terminal job returns 204 No Content with an empty body. A client must not try to decode JSON from it. Examine the status code first.
Cancel a running jobcurl -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
To remove all terminal jobs at once, use POST /api/download/jobs/clear-finished, which returns {\"removed\": <count>}.
"},{"location":"dev/rest-api/job-lifecycle/#retrying-a-job","title":"Retrying a job","text":"POST /api/download/jobs/{job_id}/retry 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 202.
- You can retry only terminal jobs. A retry of a
queued or downloading job returns 409 with error code CONFLICT. - A missing job returns
404 (JOB_NOT_FOUND). - 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
INVALID_SERVICE or FORBIDDEN if permissions changed.
202 Accepted, a fresh job{\n \"job_id\": \"c2f7d8ef-7e1b-5a3a-ae2f-4b3c5d6e7f80\",\n \"status\": \"queued\",\n \"created_time\": \"2026-07-03T12:30:00.000000\"\n}\n
"},{"location":"dev/rest-api/job-lifecycle/#prioritising-a-job","title":"Prioritising a job","text":"POST /api/download/jobs/{job_id}/priority moves a queued job to the front of the line, so it will be the next one a free job worker picks up.
- The job must be
queued. Prioritising a job in any other state returns 409 (CONFLICT). A missing job returns 404. - On success the response is
{\"job_id\": \"<id>\", \"position\": \"front\"}.
This only reorders the queue. The job's status stays queued until a job worker starts it.
"},{"location":"dev/rest-api/job-lifecycle/#history-and-retention","title":"History and retention","text":"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.
- Read it with
GET /api/history (newest first, with limit and service filters). - Delete a single entry with
DELETE /api/history/{job_id} (returns 204).
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.
Why the history file lives under the cache directory
unshackle puts api_history.jsonl 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.
"},{"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":"Developer section
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.
"},{"location":"dev/rest-api/job-lifecycle/#the-manager-and-its-queue","title":"The manager and its queue","text":"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.
- Concurrency:
max_concurrent_downloads (default 2) caps it. That many jobs can be in downloading at once. The rest wait in queued. - Retention:
job_retention_hours (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.
Two concurrency knobs that are easy to conflate
max_concurrent_downloads caps how many separate download jobs operate at once. The separate serve.downloads setting controls how many tracks download in parallel within a single job. They are independent, and raising one does not affect the other.
Concurrency and retention config keys
The manager reads these as top-level config attributes (config.max_concurrent_downloads and config.download_job_retention_hours). Those keys are not part of the standard config schema, so in practice the built-in defaults of 2 and 24 apply. GET /api/config gives the live values. The related serve.history_limit (default 100) instead controls how many entries the on-disk history file keeps.
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 downloading, stamps started_time, does the download, and on finish stamps completed_time and records history.
"},{"location":"dev/rest-api/job-lifecycle/#each-job-runs-in-its-own-subprocess","title":"Each job runs in its own subprocess","text":"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:
python -m unshackle.core.api.download_worker <payload.json> <result.json> <progress.json>\n
Three temporary files bridge the parent and the job worker:
payload.json: the manager writes it before launch. It contains the job ID, service, title ID, and merged parameters. progress.json: the job worker writes it continuously as the download proceeds. result.json: the job worker writes it at the end.
The job worker has no terminal. When a service asks the user for input, the job worker writes the prompt to progress.json as input_prompt and waits. The answer from POST /api/download/jobs/{job_id}/input 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 notice and sets it back to null when the wait ends.
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.
The job worker's exit codes are 0 for success, 1 for a download error, and 2 for bad arguments. Its result.json is either {\"status\": \"success\", \"output_files\": [...]} or {\"status\": \"error\", \"message\", \"error_details\", \"error_code\", \"traceback\"}. If the process exits non-zero, or the result is missing or not a success, the parent marks the job failed and adopts the job worker's error_code (or derives one by categorising the exception).
"},{"location":"dev/rest-api/job-lifecycle/#how-progress-reaches-the-api","title":"How progress reaches the API","text":"While the job worker operates, the manager polls progress.json every 0.5 s and copies the fields it finds onto the live DownloadJob. That is what the GET endpoints return.
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 0 to 90. The download engine drives the remaining 90 to 100 as it repackages and muxes. A track counts as done when it reaches a terminal state such as Downloaded, Decrypted, or a skipped subtitle.
"},{"location":"dev/rest-api/job-lifecycle/#how-cancellation-works","title":"How cancellation works","text":"Each job carries a cancellation event. When you DELETE a live job:
- If it is
queued, it flips straight to cancelled, 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. - If it is
downloading, the manager sets the cancellation event and flips the job to cancelled. The polling loop notices the event, terminate()s the job worker subprocess (escalating to kill() 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.
"},{"location":"dev/rest-api/job-lifecycle/#secret-handling-in-serialized-jobs","title":"Secret handling in serialized jobs","text":"Job parameters may carry secrets: a raw user:pass 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 (credential, credentials, password, token, api_key) and strips userinfo from proxy URLs. The manager also scrubs free-text fields that a service might have leaked a secret into (error_message, error_details, error_traceback, worker_stderr, 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.
"},{"location":"dev/rest-api/job-lifecycle/#see-also","title":"See also","text":" - Endpoints: the full request/response reference for every job endpoint.
- Error Responses: the error envelope, codes, and HTTP statuses a failed job reports.
- Authentication: the
X-Secret-Key header and per-key service allowlists that gate job creation and retry. - Downloading: the equivalent options on the
dl command line.
"},{"location":"dev/rest-api/quickstart/","title":"REST API Quick Start","text":"Unshackle ships with a built-in REST API that exposes the same download engine you drive from the command line. The unshackle serve command serves it and lets you queue downloads, poll their progress, browse services, and manage history over HTTP instead of the terminal.
The full loop runs end to end: start the server, authenticate, submit a download job, and poll it to completion. The curl commands here come directly from the API routes.
Who this page is for
This is a developer guide. It assumes you are comfortable with HTTP, JSON, and a tool like curl. 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.
"},{"location":"dev/rest-api/quickstart/#before-you-begin","title":"Before you begin","text":"You need a working unshackle install with services and CDM devices already configured, exactly as you would for a normal command-line download. If unshackle dl works for you, the API will too, since it runs the identical download pipeline.
If you have no install yet, follow Installation. Then check your tools:
From a cloneInstalled as a uv tool uv run unshackle env check\n
unshackle env check\n
This page uses the bare unshackle command. From a git clone, the recommended install, run each command as uv run unshackle ....
"},{"location":"dev/rest-api/quickstart/#step-1-configure-an-api-secret","title":"Step 1: Configure an API secret","text":"The server authenticates every request (except the health check) with an API key that you send in the X-Secret-Key header. The server reads this API key from the serve section of your unshackle.yaml config.
At minimum you must set api_secret:
unshackle.yamlserve:\n api_secret: \"choose-a-long-random-secret\"\n
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 serve.users, keyed by the secret:
unshackle.yamlserve:\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
The secret must exist
If api_secret is not set and you do not pass --no-key, unshackle serve refuses to start and raises an error. Treat the secret like a password. Anyone who has it can queue downloads on your machine.
Disabling auth for local testing
--no-key turns authentication off entirely: the server allows every request and ignores the X-Secret-Key header. This is convenient for a throwaway local test, but never put a --no-key server on a network you do not fully trust.
"},{"location":"dev/rest-api/quickstart/#step-2-start-the-server","title":"Step 2: Start the server","text":"Start the REST API with the serve command:
unshackle serve --api-only\n
By default the server binds to 127.0.0.1:8786. The --api-only flag serves only the REST API and omits the Widevine/PlayReady CDM HTTP endpoints. Drop it when you also want those endpoints.
Common options:
Option Default Effect -h, --host 127.0.0.1 Address to bind to -p, --port 8786 Port to bind to --api-only off Serve only the REST API, no CDM endpoints --no-key off Disable API-key authentication (allow all requests) --debug-api off Include tracebacks and stderr in error responses --debug off Enable DEBUG-level logging --remote-only off Expose only the remote-session subset of routes --caddy off Also launch Caddy as a reverse proxy (for HTTPS) Once it is up you will see the API mounted under /api/ and, unless you started in remote-only mode, an interactive Swagger UI:
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
Swagger UI is also behind auth
In --api-only mode (without --no-key), the Swagger UI at /api/docs/ requires the X-Secret-Key header, the same as every other route. Only /api/health is exempt from authentication.
For the rest of this page we will assume the server is reachable at http://127.0.0.1:8786 and store the secret in an environment variable:
export SECRET=\"choose-a-long-random-secret\"\nexport BASE=\"http://127.0.0.1:8786\"\n
"},{"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":"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:
curl \"$BASE/api/health\"\n
200 OK{\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
The update_check block is best effort. If unshackle cannot reach the update source, update_available and latest_version come back as null rather than failing the request.
"},{"location":"dev/rest-api/quickstart/#step-4-authenticate-a-real-request","title":"Step 4: Authenticate a real request","text":"Every other endpoint needs the X-Secret-Key header. A quick way to prove your API key works is to show the services the server can see:
curl \"$BASE/api/services\" \\\n -H \"X-Secret-Key: $SECRET\"\n
200 OK (truncated){\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
If the API key is missing or wrong, you get a 401 with a plain body:
401 Unauthorized{ \"status\": 401, \"message\": \"Secret Key is Invalid.\" }\n
Two error shapes exist
The authentication middleware returns the short {\"status\": 401, \"message\": \"...\"} shape shown above. Every other error the API produces uses the richer structured shape (error_code, timestamp, details, ...) described in Error handling. Parse both shapes in your client.
The tag value for the service you want is the identifier you pass as service in the calls below.
"},{"location":"dev/rest-api/quickstart/#step-5-submit-a-download-job","title":"Step 5: Submit a download job","text":"Downloads are asynchronous. You POST a job to /api/download, the server immediately hands back a job_id, and the actual download runs in the background so your request never blocks.
The only required fields are service and title_id. Everything else mirrors the flags of the dl command and has a sensible default, so a minimal job looks like this:
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
A more realistic job pins the quality and codecs and asks for specific episodes:
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
On success the server responds with 202 Accepted and the identifier you will poll:
202 Accepted{\n \"job_id\": \"3f9c1e0a-8d2b-4e6f-9a1c-77b0f2a1c4d5\",\n \"status\": \"queued\",\n \"created_time\": \"2026-07-03T12:00:00.000000+00:00\"\n}\n
Capture the job_id for the next step:
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
"},{"location":"dev/rest-api/quickstart/#frequently-used-download-fields","title":"Frequently used download fields","text":"The request body accepts the full download parameter set. A few of the most useful:
Field Default Meaning service - Service tag (required) title_id - Title identifier (required) profile null Named credential/cookie profile to use quality [] Resolution(s), e.g. [1080]; empty means best available vcodec null Video codec, e.g. \"H265\" acodec null Audio codec, e.g. \"EC3\" range [\"SDR\"] Dynamic range: SDR, HDR10, HDR10+, DV, HLG, HYBRID wanted [] Episodes to fetch, e.g. [\"S01E01\"], or music tracks, e.g. [\"1-5\"]. Empty means all lang [\"orig\"] Video/audio language(s) s_lang [\"all\"] Subtitle language(s) downloads 1 Number of tracks to download concurrently proxy null Proxy URI or country code Validation is strict: invalid codecs, subtitle formats, dynamic-range names, non-positive counts, or mutually exclusive flags (for example both video_only and audio_only) come back as 400 with error code INVALID_PARAMETERS. See the full reference on the download reference page for every accepted field.
Gated fields
The server refuses a per-request CDM (cdm) or inline credentials (credential / credentials) with 403 FORBIDDEN, unless the server operator has explicitly opted in with serve.cdm_overrides and serve.allow_job_credentials. Both are off by default.
"},{"location":"dev/rest-api/quickstart/#step-6-poll-the-job-to-completion","title":"Step 6: Poll the job to completion","text":"A job moves through these states:
queued \u2192 downloading \u2192 completed | failed | cancelled\n
The last three are terminal. Poll the job detail endpoint until you reach one of them. This endpoint always returns the full job record:
curl \"$BASE/api/download/jobs/$JOB\" \\\n -H \"X-Secret-Key: $SECRET\"\n
While the download runs you will see status: \"downloading\" and a progress value climbing from 0 toward 100:
200 OK (in progress){\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
When it finishes you will see status: \"completed\" and the produced files under output_files:
200 OK (completed){\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
A simple polling loop in shell:
poll.shwhile 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
Polling cadence
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.
Or let the server push the updates
GET /api/download/jobs/{job_id}/events 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.
curl -N \"$BASE/api/download/jobs/$JOB/events\" \\\n -H \"X-Secret-Key: $SECRET\"\n
If a job ends in failed, the full record includes error_message, error_code, and (when you start the server with --debug-api) error_traceback and worker_stderr to help you find the cause. The server scrubs sensitive values in these fields before it returns them.
"},{"location":"dev/rest-api/quickstart/#step-7-clean-up","title":"Step 7: Clean up","text":"Once you have collected the output you can remove the finished job. DELETE on a job has two behaviors depending on its state:
curl -X DELETE \"$BASE/api/download/jobs/$JOB\" \\\n -H \"X-Secret-Key: $SECRET\"\n
- If the job is terminal (completed/failed/cancelled), the manager removes it. You get
204 No Content with an empty body. - If the job is still queued or downloading, the manager cancels it instead. You get
200 with {\"status\": \"success\", \"message\": \"Job cancelled\"}.
Do not parse JSON on 204
A 204 response has no body. This applies to terminal-job removal here and to deleting history entries. Examine the status code before you decode JSON.
To clear every finished job at once instead of one at a time:
curl -X POST \"$BASE/api/download/jobs/clear-finished\" \\\n -H \"X-Secret-Key: $SECRET\"\n
200 OK{ \"removed\": 3 }\n
"},{"location":"dev/rest-api/quickstart/#managing-the-queue","title":"Managing the queue","text":"A handful of endpoints round out job control. All require the X-Secret-Key header.
Method Path Purpose GET /api/download/jobs List all jobs, with optional filtering and sorting GET /api/download/jobs/{job_id} Full detail for one job DELETE /api/download/jobs/{job_id} Cancel a running job, or remove a terminal one POST /api/download/jobs/{job_id}/retry Re-queue a new job from a terminal one POST /api/download/jobs/{job_id}/priority Move a queued job to the front of the queue POST /api/download/jobs/clear-finished Remove all terminal jobs Listing supports query parameters for filtering by status or service, sorting with sort_by (created_time, started_time, completed_time, progress, status, service) and sort_order (asc / desc), and requesting full per-job detail with full=true:
curl \"$BASE/api/download/jobs?status=downloading&sort_by=progress&sort_order=desc\" \\\n -H \"X-Secret-Key: $SECRET\"\n
200 OK{\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
A retry reuses the original job's service, title, and parameters to enqueue a brand new job, and returns 202 with a fresh job_id. A retry works only on terminal jobs, and returns 409 CONFLICT otherwise. A priority change works only on jobs still in the queued state.
"},{"location":"dev/rest-api/quickstart/#beyond-a-single-download","title":"Beyond a single download","text":"The download loop above is the core of the API, but the same server exposes more:
- Discovery:
POST /api/search finds titles by query, and POST /api/list-titles / POST /api/list-tracks inspect what a title offers before you commit to downloading it. See titles and tracks. - History:
GET /api/history reads a persisted log of jobs that reached a terminal state (newest first), and DELETE /api/history/{job_id} removes a single entry. See history. - Introspection:
GET /api/profiles lists configured credential profiles per service, GET /api/config returns a redacted view of the effective server config, and GET /api/env/check reports which external binaries the machine has. - Maintenance:
POST /api/maintenance/clear-cache, .../clear-temp, and .../refresh-services do housekeeping (the server blocks the cache and temp clears with 409 while a download is active). - Remote sessions: the
/api/session/* endpoints drive the thin-client \"remote download\" flow, where the server authenticates and licenses on behalf of a local client. See remote sessions.
The interactive Swagger UI at /api/docs/ documents every route and lets you try them in the browser (send your X-Secret-Key there too).
"},{"location":"dev/rest-api/quickstart/#error-handling","title":"Error handling","text":"Apart from the auth middleware's short form, every error the API returns uses a single structured envelope:
{\n \"status\": \"error\",\n \"error_code\": \"INVALID_PARAMETERS\",\n \"message\": \"Human-readable description\",\n \"timestamp\": \"2026-07-03T12:00:00Z\",\n \"details\": { }\n}\n
details appears only when the server has more to add. retryable: true appears only for transient failures. The server includes a debug_info block (exception type and traceback) only when it runs with --debug-api.
The error_code maps to an HTTP status. The ones you will meet most often:
Error code HTTP Typical cause INVALID_INPUT 400 Malformed JSON body or missing required field INVALID_SERVICE 400 Unknown or disallowed service tag INVALID_PARAMETERS 400 A download field failed validation AUTH_FAILED 401 Service login/credential failure FORBIDDEN 403 A gated field was used without server opt-in NOT_FOUND 404 Title or resource does not exist JOB_NOT_FOUND 404 No job with that job_id CONFLICT 409 Illegal state transition (e.g. retry a running job) RATE_LIMITED 429 Upstream throttling (retryable) INTERNAL_ERROR 500 Unexpected server-side failure SERVICE_ERROR 502 The service raised an error NETWORK_ERROR 503 Connection/timeout reaching the service (retryable) Retry politely
Codes marked retryable (NETWORK_ERROR, RATE_LIMITED, SERVICE_UNAVAILABLE) reflect transient conditions. Back off and retry rather than hammering the server.
"},{"location":"dev/rest-api/remote-sessions/","title":"Remote Service Sessions","text":"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.
This is the mechanism behind unshackle's client/server \"remote download\" workflow. A thin local client (RemoteService) talks to an unshackle serve 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.
Why you'd use this
- The server has service accounts, cookies, or a CDM you do not want to copy to every machine.
- You want to do downloads on a fast/local machine but keep credentials and licensing centralised.
- A service is region-locked to where the server lives, and the client is not.
"},{"location":"dev/rest-api/remote-sessions/#the-big-picture","title":"The big picture","text":"\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
The client implements the same interface dl 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.
Migration: remote_dl is gone
The RemoteService adapter lives inside the ordinary dl command and replaces the old standalone remote_dl command. If you have prior scripts or docs that invoke remote_dl, use dl with a configured remote server instead. The functionality now rides on dl through RemoteService.
For the auth-facing endpoints, header format, and error shapes referenced below, see Authentication and the endpoint reference in the REST API index.
"},{"location":"dev/rest-api/remote-sessions/#configuring-a-remote-server-client-side","title":"Configuring a remote server (client side)","text":"On the client, add a remote_services block to your unshackle.yaml. Each entry names a server and provides its URL and API key.
unshackle.yaml (client)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
Key Required Meaning url yes Base URL of the unshackle serve instance (no trailing slash needed) api_key no Sent as the X-Secret-Key header on every request server_cdm no When true, DRM keys are resolved by the server's CDM rather than a local device (default false) services no Per-service local config overrides, keyed by service tag Port default
The unshackle serve default port is 8786 (not 8080). Use the port your server binds. Some older example snippets show 8080, which is not the default.
"},{"location":"dev/rest-api/remote-sessions/#selecting-a-server","title":"Selecting a server","text":"If you configure exactly one server, unshackle uses it implicitly:
unshackle dl EXAMPLE 0ABCDEF\n
If you configure more than one server, you must pick one with --server:
unshackle dl --server my_server EXAMPLE 0ABCDEF\n
With no remote_services configured at all, unshackle raises a clear error telling you to add the block shown above.
"},{"location":"dev/rest-api/remote-sessions/#what-happens-during-a-download","title":"What happens during a download","text":"From your point of view the command looks like an ordinary download. Under the hood the client walks a remote session through its lifecycle.
1. Create + authenticate2. Interactive prompts (if needed)3. Titles + tracks4. Licensing5. Download + close The client calls POST /api/session/create, forwarding whatever it can so the server does not have to prompt:
- Local credentials for the service/profile (
{username, password, extra?}) - Local cookies, compressed and base64-encoded
- 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
server_proxy. Without server_proxy 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 --proxy with its own proxy, or --no-proxy to accept the server's own connection. With server_proxy the server picks a proxy that matches the client region itself. For --proxy controld:ca the client points its Control D profile at the region and sends only the resolver, as controld://<resolver>@dns.controld.com. 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. --no-proxy-download and --proxy-download change that for downloads only. - Track-selection hints (
range_, vcodec, quality, best_available) so the server fetches the right manifests - Your language and audio codec selection (
-l, -vl, -al, -a, -fs) in a dl_params object. Some services fetch one manifest for each audio language, and pick the languages from these values - 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
The server uses its own accounts only when the operator lists the service in serve.server_accounts and gives your API key server_accounts in serve.users. 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. --proxy ca picks a ca account.
GET /api/services advertises the regions those accounts cover. When your own region is not one of them and you set no --proxy, 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 controld:// resolver from the client.
The server responds immediately with a session ID and a status. Authentication runs in the background on the server.
Some services need a one-time code, PIN, or device confirmation. When the server's auth flow asks for input, the remote session enters pending_input. 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.
Enter the 6-digit code sent to your email: 483920\n
A client older than the service_params change sends service options as flat body keys only. A flat key that shares a name with a transport field (such as profile, 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 service_params.
The server also mirrors the service's own log output (self.log) into a per-session buffer. The client drains it through GET /api/session/{id}/logs after each step and prints the records locally, so you see the server-side reason when a step fails.
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 track_manifests, and the client re-parses that instead. Any session_headers / session_cookies the server used are merged into the client's local HTTP session.
The tracks response repeats the title. A service can rewrite title fields inside get_tracks, 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 track.data, 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.
For a DRM-protected title the client either proxies its CDM challenge through the server, or, if server_cdm: true, asks the server to do the full CDM flow and return the content keys directly. See Server-side vs. proxied CDM below.
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 session_ttl, so a long download does not let the remote session expire. On completion, and also when dl exits early (--list, Ctrl+C, an error), it deletes the remote session. If the login belongs to the client, the DELETE 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.
Renaming remote titles locally
You can rename titles for a remote service you do not have installed locally by adding a title_map under that service in your client remote_services.<name>.services config. The server sends raw titles. Your local map wins.
This is deliberate: the server does no title_map 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.
"},{"location":"dev/rest-api/remote-sessions/#server-side-vs-proxied-cdm","title":"Server-side vs. proxied CDM","text":"There are two ways DRM keys get resolved, chosen by the client's server_cdm flag.
Proxied CDM (default)Server-side CDM (server_cdm: true) Your local CDM builds the license challenge. The client sends that challenge to POST /api/session/{id}/license, the server forwards it to the service, and the raw license bytes come back for your local CDM to parse.
- Keeps your CDM local. The server only relays the license request.
- Used when
server_cdm is false (the default). - Also used for a run with
dl --cdm <name>, and for a service whose own entry in your cdm config named the loaded device. In each case the client sends server_cdm: false when it creates the remote session, and the server builds the service on your device even when the API key has the server CDM. - A service option that the service lists in
SERVER_DEVICE_OPTIONS keeps the server CDM. The server reads the option from service_params, then from the top level of the request. The create response gives the result in server_cdm, and the client shows a warning when the server did not apply its choice. - 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
cdm_call, and your local CDM answers it. See Your own device identity.
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 KID:KEY pairs directly. The client needs no CDM.
- Enable with
server_cdm: true in the server entry. - The server tells the client which DRM type it used (
widevine or playready). - A content key the server took from its own vault is unproven. The response lists its KID in
vault_keys, the client decrypts and checks that the output decodes, and a wrong pair goes back to POST /api/session/{id}/keys/bad. 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. 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. The client never learns the server vault names. - 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.
A height limit on the server CDM
An API key with server_cdm_max_height gets the server CDM only up to that height. The session create response tells the client who licenses the session in server_cdm and gives the limit in server_cdm_max_height. In a server CDM session, the batch licence response lists each track the server refused to license live under capped_tracks. A single-track server CDM licence answers 403 SERVER_CDM_CAPPED for such a track. In both cases the client licenses those tracks in proxy mode with its own local CDM. See server_cdm_max_height.
"},{"location":"dev/rest-api/remote-sessions/#your-own-device-identity","title":"Your own device identity","text":"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:
- 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.
- CDM calls. When the service calls the CDM, the server sends a
cdm_call 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 close 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. - Session keys only. A
keys call returns Widevine OPERATOR_SESSION and SIGNING keys. It never returns a content key, and the client refuses a PlayReady keys call. So a server cannot use your device to license titles for itself. - Identity config. A service names the config keys a client may send (for example
esn, Kpe, Kph, esn_map). The server lists them in the service listing as client_config. The client sends only those keys, from its own services: <TAG>: block in unshackle.yaml. 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 esn_map) 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.
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 server_device to true 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 server_vault grant (or server_cdm); 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: DELETE returns no cache files, and the HTTP session headers and track.data lose their secret-looking keys, as for a server login.
The server vault in a session your device licenses
With the server_vault grant (or server_cdm) 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 server_vault.
"},{"location":"dev/rest-api/remote-sessions/#remote-session-lifecycle-and-expiry","title":"Remote session lifecycle and expiry","text":"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.
Behavior Value Notes Idle session TTL 300s (5 min) default Refreshed on every request to the session and when a titles or tracks 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 Auth is never rushed
A remote session that is still authenticating or waiting on pending_input 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.
The TTL and max-session limits are read from server config:
unshackle.yaml (server)serve:\n session_ttl: 300 # seconds a session may sit idle\n max_sessions: 100 # cap on concurrent sessions\n
"},{"location":"dev/rest-api/remote-sessions/#security-properties-worth-knowing","title":"Security properties worth knowing","text":" - API key required. Every remote session request carries
X-Secret-Key. The server rejects requests without a valid API key (health check aside). See Authentication. - 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
403 FORBIDDEN. Remote sessions are not portable between hosts. - 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 (
serve.server_accounts) gets a persistent per-account cache instead, so the account's tokens outlive the remote session. - The server redacts secrets in logs. It redacts remote session IDs, service tags, and other user values before it writes them to the log.
"},{"location":"dev/rest-api/remote-sessions/#developer-reference","title":"Developer reference","text":"This section is for developers
The material below documents the server-side implementation and the HTTP contract. End users configuring a client can stop at the sections above.
"},{"location":"dev/rest-api/remote-sessions/#remote-session-endpoints","title":"Remote session endpoints","text":"The server mounts all these routes, even in --remote-only mode. Paths use the session_id that create returns.
Why --remote-only exists
--remote-only 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 --api-only 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.
Method Path Purpose POST /api/session/create Build + authenticate a service instance; returns a session ID immediately GET /api/session/{id}/titles Fetch and cache the title list POST /api/session/{id}/tracks Resolve tracks, manifests, chapters, headers/cookies for a title POST /api/session/{id}/segments Resolve per-segment/track download descriptors POST /api/session/{id}/segment_filter Unwanted HLS segment URIs for one track (ads, bumpers) POST /api/session/{id}/license DRM licensing (proxy or server CDM) POST /api/session/{id}/keys/bad Report a server-vault content key that did not decrypt GET /api/session/{id}/logs Drain the service's server-side log output GET /api/session/{id}/prompt Poll interactive auth status / pending prompt POST /api/session/{id}/prompt Submit an answer to a pending prompt GET /api/session/{id} Session info (validity, TTL, counts) DELETE /api/session/{id} 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":"POST /api/session/create requires service and title_id. It also accepts credentials, cookies (base64 of zlib-compressed Netscape cookie file), proxy, no_proxy, profile, cache (a map of filename \u2192 base64(zlib(bytes))), client_region, server_cdm (false when the user picked the local CDM), cdm_type, cdm_security_level, cdm_relay (true when the client answers CDM calls), cdm_system_id and cdm_device_type (Widevine only), service_config (the identity config keys the service lists in client_config), client (a freeform identity object the dashboard shows as sent), and the track-selection hints range_, vcodec, quality, best_available, plus arbitrary service CLI options (additionalProperties: true).
dl_params holds the dl track selection: lang, v_lang and a_lang (arrays of language strings), acodec (an array of audio codec names, such as EC3), and forced_subs (boolean). The server gives these values to the service in ctx.parent.params, never as service options, so a service option with the same name, such as an own --lang, does not get them. The server uses the dl default for each absent or malformed value: lang is [\"orig\"], v_lang, a_lang and acodec are [], and forced_subs is false. The server drops an unknown codec name. An empty array is a valid value and stays empty.
The server does not forward the dl mode flags: video_only, audio_only, subs_only, chapters_only, list_, skip_dl, sub_format, no_attachments, audio_description, audio_description_only and forced_subs_only. A service that reads one of them to skip work fetches more on the server, but the result is the same.
In a client-login session (not a server account), the server gives the service the client's profile in ctx.parent.params, 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.
The response returns before authentication finishes:
{ \"session_id\": \"...uuid4...\", \"service\": \"EXAMPLE\", \"status\": \"authenticating\",\n \"server_cdm\": false, \"server_cdm_max_height\": null, \"server_vault\": true, \"server_device\": false }\n
server_vault tells the client that the server vault serves a remote session its own device licenses. server_device tells it that the service runs on the server's device, so every content key comes from a vault.
Authentication runs on a background thread (asyncio.to_thread(authenticate, ...)). The remote session starts in AUTHENTICATING. The client must poll the prompt endpoint until it reaches authenticated (or failed).
"},{"location":"dev/rest-api/remote-sessions/#interactive-auth-the-inputbridge","title":"Interactive auth: the InputBridge","text":"When the service calls its input function during authenticate() on the server thread, an InputBridge pauses that thread and exposes the prompt to the HTTP layer.
AuthStatus values: authenticating, pending_input, authenticated, failed. InputBridge.request_input(prompt, timeout=600) blocks the sync auth thread on a threading.Event until submit_response() or cancel() fires. - A timeout raises
TimeoutError and marks the remote session FAILED. - A prompt after authentication (in
get_titles(), get_tracks() or licensing) raises RuntimeError at once. The client polls for prompts only during authentication, so no answer can come. - A CDM call (
InputBridge.request_cdm) 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. AUTH_INPUT_TIMEOUT = 600.0 seconds. This is also the TTL granted to AUTHENTICATING / PENDING_INPUT sessions in the store.
GET /api/session/{id}/prompt returns one of:
{ \"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
A cdm_call comes first, in any auth state. The client answers it with a JSON object in response: {\"session\": \"...\", \"challenge\": \"<base64>\"} for challenge, {\"keys\": [{\"kid\", \"type\", \"key\", \"permissions\"}]} for keys, {} for close, or {\"error\": \"...\"} when its CDM refuses. An older client refuses close, 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.
A missing remote session returns 404 SESSION_NOT_FOUND. An IP mismatch returns 403 FORBIDDEN. POST /api/session/{id}/prompt takes { \"response\": \"...\" } and returns { \"status\": \"accepted\" }. A post with no pending prompt is an INVALID_INPUT error.
"},{"location":"dev/rest-api/remote-sessions/#sessionstore-internals","title":"SessionStore internals","text":"Source: unshackle/core/api/session_store.py. A singleton you get from get_session_store().
- Config-driven limits.
serve.session_ttl (default 300) and serve.max_sessions (default 100) are read as properties, so config changes take effect without recreating the store. create() evicts the least-recently-accessed remote session when at capacity, then stores a new SessionEntry. It defaults auth_status to AUTHENTICATED, and the create handler overrides it to AUTHENTICATING. get() refreshes last_accessed through touch(). It returns None (and deletes the entry) if an authenticated remote session has been idle longer than the TTL. Remote sessions in AUTHENTICATING / PENDING_INPUT are exempt from TTL expiry. cleanup_expired() runs every 60s: authenticated remote sessions expire at ttl, in-flight-auth remote sessions expire at AUTH_INPUT_TIMEOUT. The removal of a remote session cancels its InputBridge and deletes its cache directory (pruning empty parent dirs up to, but not including, the cache root). - The server calls
cancel_all_bridges() on shutdown, to unblock any waiting auth threads.
SessionEntry fields:
Field Description session_id UUID4 string service_tag Normalized service tag service_instance The authenticated service object kept alive between calls titles / title_map Result of get_titles() and a title_id \u2192 Title map tracks / tracks_by_title / chapters_by_title Cached resolved tracks and chapters creator_ip IP recorded at create time for IP-binding checks cache_tag Per-session cache directory tag input_bridge InputBridge for interactive auth, if any auth_status / auth_error Current AuthStatus and last error message created_at / last_accessed Timestamps; last_accessed drives TTL and LRU eviction"},{"location":"dev/rest-api/remote-sessions/#per-session-cache-namespacing","title":"Per-session cache namespacing","text":"The create handler builds a Cacher namespaced as:
_sessions/<pbkdf2_hmac(sha256, X-Secret-Key, \"unshackle-session-ns\", 100000)[:12]>/<session_id>/<service>\n
The handler writes forwarded cache files into that directory before authentication. On DELETE, when the login belongs to the client (client_auth) 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 titles_* files) and returns them under a cache field, so the client can keep refreshed tokens. Each cache key is the file path relative to that directory, with / separators and no .json suffix, which is the Cacher cache key the service reads it with:
{\n \"status\": \"ok\",\n \"cache\": {\n \"tokens\": \"...base64(zlib(bytes))...\",\n \"session_web/<sha1>\": \"...base64(zlib(bytes))...\"\n }\n}\n
Both sides reject a cache key with a drive letter, a root, a .. 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 cache 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.
"},{"location":"dev/rest-api/remote-sessions/#remote-session-info-response","title":"Remote session info response","text":"GET /api/session/{id}:
{\n \"session_id\": \"...\",\n \"service\": \"EXAMPLE\",\n \"valid\": true,\n \"expires_in\": 300,\n \"track_count\": 12,\n \"title_count\": 40\n}\n
expires_in is the configured TTL, not time remaining
The expires_in value reports the store's configured session_ttl, not the seconds left before this specific remote session expires.
"},{"location":"dev/rest-api/remote-sessions/#reference-client-remoteservice","title":"Reference client: RemoteService","text":"Source: unshackle/core/remote_service.py. This is the canonical consumer of the remote session API and a good template for any client.
RemoteClient.request sets X-Secret-Key and User-Agent: unshackle/<version>, uses the server's timeout from remote_services (default 120s) as the read timeout, and treats any status_code >= 400 as fatal: it logs Server error [<error_code>]: <message> and raises SystemExit(1). A 200 body with \"status\": \"error\" is also fatal (see the heartbeat below). - Heartbeat. The
titles, tracks and license 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 200, so a failure after that time arrives as the usual error body with status 200. Your client must check status 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. - Retries. The download-side HTTP session mounts an adapter with
Retry(total=5, backoff_factor=0.2, status_forcelist=[429, 500, 502, 503, 504]). - Flow.
authenticate() \u2192 create (+ poll prompt every 2s up to a 600s deadline, answering pending_input prompts. With stdin closed the client logs an error and raises SystemExit(1) instead of posting an empty answer) \u2192 get_titles() \u2192 get_tracks() (merging returned session_headers/session_cookies, re-parsing manifests) \u2192 get the licence in proxy mode or server_cdm mode \u2192 close() (DELETE, saving any returned cache). - Server resolution.
resolve_server() reads config.remote_services.<name> into {url, api_key, services, server_cdm}, injecting the server_cdm flag into the services map as _server_cdm.
"},{"location":"dev/rest-api/remote-sessions/#troubleshooting","title":"Troubleshooting","text":"\\\"Could not connect to remote server ... Is it running?\\\"
The client could not reach the URL. Make sure that unshackle serve operates on the server, the url/port in remote_services are correct (default port 8786), and any firewall or reverse proxy allows the connection.
403 FORBIDDEN mid-download
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.
Auth times out or the prompt never resolves
Interactive auth allows up to 600s. If you miss that window, the server marks the remote session failed 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.
\\\"Multiple remote services configured. Use --server ...\\\"
You have more than one entry under remote_services. Pass --server <name> to pick one.
"},{"location":"getting-started/configuration-file/","title":"The Configuration File","text":"A single configuration file named unshackle.yaml 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.
Where the exhaustive key list lives
This page is an overview. For the complete, key-by-key breakdown of every setting, its type, and its default, see the Configuration Reference.
"},{"location":"getting-started/configuration-file/#the-config-filename","title":"The config filename","text":"The main configuration file is always named unshackle.yaml. It uses plain YAML. You can open and edit it in any text editor, or manage individual values with the unshackle cfg command.
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.
"},{"location":"getting-started/configuration-file/#where-the-config-file-lives","title":"Where the config file lives","text":"When unshackle starts, it searches a fixed list of locations and uses the first one that exists. In order of priority:
# Location Typical path 1 The unshackle package folder <clone>/unshackle/unshackle.yaml (a uv tool install: .../site-packages/unshackle/unshackle.yaml) 2 The parent of the package folder <clone>/unshackle.yaml (a uv tool install: .../site-packages/unshackle.yaml) 3 Your OS user-config directory see the table below Where the file belongs depends on how you installed unshackle:
- Git clone (recommended). Keep the file at
unshackle/unshackle.yaml inside the clone, which is location 1. unshackle setup writes a new config there, and it stays with the clone when you update it. uv tool install. Use location 3, your per-user config directory. A uv tool upgrade replaces the package folder, so a file at location 1 or 2 is lost. unshackle setup writes a new config there.
The path of the per-user config directory depends on your operating system:
LinuxWindowsmacOS ~/.config/unshackle/unshackle.yaml\n
%LOCALAPPDATA%\\unshackle\\unshackle.yaml\n
~/Library/Application Support/unshackle/unshackle.yaml\n
Not sure which file is being used?
Operate unshackle env info. It prints the path unshackle loaded the config from, or tells you that it found none. It also prints every directory unshackle currently uses.
The config is read exactly once, when unshackle starts. If you edit the file, the change takes effect on the next command.
"},{"location":"getting-started/configuration-file/#top-level-structure","title":"Top-level structure","text":"unshackle.yaml 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.
Here is a small, realistic example that sets a download location, a release tag, a default CDM, and one service's credentials:
unshackle.yaml# 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 -> \"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
The top-level keys group loosely into these areas:
Area Example keys Downloading & DRM dl, cdm, remote_cdm, decryption Networking network, headers Credentials & cookies credentials, firefox_cookies Tracks & muxing subtitle, audio, muxing, language_tags Key vaults key_vaults, vault_timeout Proxies & remote proxy_providers, remote_services, serve, services Naming & tagging tag, output_template, chapter_fallback_name External API keys tmdb_api_key, tvdb_api_key, simkl_client_id, ipinfo_api_key, metadata_providers Behaviour & logging update_checks, redact_paths, debug, unicode_filenames Post-scripts post_scripts Paths directories, filenames For the full list with types and defaults, see the Configuration Reference.
Unknown keys are silently ignored
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.
"},{"location":"getting-started/configuration-file/#setting-download-defaults-dl","title":"Setting download defaults (dl:)","text":"If you always pass the same dl flags (a language, a resolution, a codec), put them under a dl: 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 (--best-available \u2192 best_available).
unshackle.yamldl:\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
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 dl: block under it:
Per-service defaultsdl:\n lang: [en] # default for everything\nservices:\n EXAMPLE:\n dl:\n lang: [en, ja] # Example downloads English + Japanese\n
A few keys are named after the flag's internal name
Most keys are obvious, but set these exact ones: range (-r), list (--list), tmdb_id (--tmdb), imdb_id (--imdb), tvdb_id (--tvdb), no_atmos (--noatmos), and output_dir (-o). The Configuration Reference has the full list and every available config key.
"},{"location":"getting-started/configuration-file/#the-directory-layout","title":"The directory layout","text":"The directories 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 ~ for your home directory.
unshackle.yamldirectories:\n downloads: ~/Videos/unshackle\n temp: /mnt/fast/unshackle-temp\n cache: ~/.cache/unshackle\n
The directories unshackle uses:
Name Purpose Overridable downloads Default output folder for finished downloads Yes temp Temporary working files during a download Yes cache Cache store (title cache, update checks, service caches) Yes cookies Per-service cookie files Yes logs Log files Yes exports Export JSONs Yes wvds Widevine devices (.wvd files) Yes prds PlayReady devices (.prd files) Yes dcsl DCSL data Yes services Search paths for service code (see below) Yes commands CLI command modules Yes vaults Vault modules Yes fonts Bundled fonts Yes Some directories cannot be moved
unshackle protects five internal entries: app_dirs, core_dir, namespace_dir, user_configs, and data. If you write any of them under directories, unshackle ignores the override. This is intentional. Those paths come from the package location and your OS user directories.
"},{"location":"getting-started/configuration-file/#the-services-directory-is-special","title":"The services directory is special","text":"Unlike the other entries, services 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:
unshackle.yamldirectories:\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
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.
"},{"location":"getting-started/configuration-file/#the-filenames-config-key","title":"The filenames config key","text":"Alongside directories, the filenames 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.
"},{"location":"getting-started/configuration-file/#editing-the-config-with-unshackle-cfg","title":"Editing the config with unshackle cfg","text":"You do not have to edit unshackle.yaml by hand. The unshackle cfg command reads and writes individual values for you, creating the config file (and its parent directory) if it does not exist yet.
Read a single value by passing its config key. Nested config keys use dot notation:
$ unshackle cfg tag\n$ unshackle cfg cdm.default\n
Set a value by passing a config key and a value:
$ unshackle cfg tag MYGRP\n$ unshackle cfg cdm.default my_device_l3\n
unshackle parses the value as a Python literal, so write booleans as True/False and quote the strings inside a list (\"['en']\"). unshackle stores anything that is not valid Python literal syntax as a plain string:
$ unshackle cfg update_checks False\n$ unshackle cfg vault_timeout 30\n
Remove a value with --unset:
$ unshackle cfg cdm.default --unset\n
Show everything currently set with --list:
$ unshackle cfg --list\n
When it writes, unshackle cfg targets the config file that unshackle loaded. If none exists yet, it makes unshackle.yaml in the unshackle package folder (location 1 above):
- Git clone. That is
unshackle/unshackle.yaml in the clone, which is the correct place. uv tool install. A tool upgrade replaces the package folder and deletes that file. Run unshackle setup first, which writes the config to your user config directory, or make the file there yourself. Then unshackle cfg writes to it.
Editing with cfg strips comments
Because unshackle cfg rewrites the whole file when it saves, a write removes any comments in unshackle.yaml. If you keep important notes as comments, edit the file by hand instead, or keep those notes elsewhere.
"},{"location":"getting-started/configuration-file/#next-steps","title":"Next steps","text":" - Browse the Configuration Reference for every config key and default.
- Set up your first download in Downloading.
- Learn how unshackle discovers and updates services in Creating a Service.
"},{"location":"getting-started/installation/","title":"Installation","text":"unshackle is a modular archival tool for movies, TV, and music. It ships as a single Python package named unshackle that installs one console command, also called unshackle. This page covers the install script, the unshackle setup command, the Python version unshackle needs, and the external command-line tools it expects to find.
What you get
Installing the package registers a single entry point, the unshackle command. It covers everything: downloading, key-vault management, device provisioning, the REST server, and the helper utilities.
"},{"location":"getting-started/installation/#install-from-a-git-clone-recommended","title":"Install from a git clone (recommended)","text":"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.
The repository has an install script for Linux (install.sh) and for Windows (install.bat). The script installs uv if it is not found, installs unshackle, and then runs unshackle setup.
LinuxWindows git clone https://github.com/unshackle-dl/unshackle.git\ncd unshackle\nsh install.sh\n
git clone https://github.com/unshackle-dl/unshackle.git\ncd unshackle\n.\\install.bat\n
In a clone, the script runs uv sync and then uv run unshackle setup. The last lines of setup tell you to check your tools with uv run unshackle env check. Run unshackle from the clone with uv run unshackle ....
To install without a clone, see Advanced: install as a uv tool.
"},{"location":"getting-started/installation/#what-unshackle-setup-does","title":"What unshackle setup does","text":"unshackle setup prepares a new installation. The install script runs it for you, and you can run it yourself at any time:
From a cloneInstalled as a uv tool uv run unshackle setup\n
unshackle setup\n
The command does these steps:
- It shows which external tools are missing, and where to get the ones that it cannot download.
- It asks once for each tool or group of tools to download. The required tools come first. shaka-packager and
mp4decrypt share one DRM question, so mp4decrypt comes with the required tools, but env check 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 binaries folder (see Where setup puts files). - If no
unshackle.yaml exists, it asks for a downloads folder and writes a minimal config file. - It makes the data folders for cookies, WVDs, PRDs, and services.
- It asks for
.wvd and .prd 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 cdm.default to the imported device. If you imported more than one, it asks which one is the default. - 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
env check next.
You can run the command again. It skips the tools that it finds and never overwrites an existing config.
Not every tool has a download
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.
On Linux, setup cannot download MKVToolNix, which is a required tool. Install the mkvtoolnix package with your package manager (for example apt, dnf, or pacman).
CCExtractor on Linux needs FUSE
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 ccextractor package instead.
"},{"location":"getting-started/installation/#where-setup-puts-files","title":"Where setup puts files","text":"Item From a git clone From a uv tool install External tools unshackle/binaries in the clone binaries in the user data directory New config (unshackle.yaml) unshackle/unshackle.yaml 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 On Windows, CCExtractor and its libraries go into their own ccextractor subfolder of the tools folder.
On Linux, the user data directory is usually ~/.local/share/unshackle and the user config directory is usually ~/.config/unshackle. On Windows, both are %LOCALAPPDATA%\\unshackle. Run uv run unshackle env info to see the paths that unshackle uses. Its User_Binaries row shows the binaries folder in the user data directory.
Setup writes a new config only when it finds no unshackle.yaml in any of the config locations. It keeps an existing config where it is. In a clone, the new config sets only directories.downloads, so the data folders stay at their defaults in the clone.
A uv tool upgrade replaces the package folder. For a uv tool install, setup puts the tools in the user data directory and writes a directories block that moves the data folders there, so an upgrade keeps them. If an existing config keeps data folders inside the package of a uv tool install, setup shows a warning and prints the directories lines to add.
"},{"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 (mp4decrypt) dovi_tool \u2265 2.1 Dolby Vision handling SubtitleEdit \u2265 5.0 Subtitle conversion (optional) The sections below tell you about each of these, and how to make sure that your setup is complete.
"},{"location":"getting-started/installation/#python-versions","title":"Python versions","text":"unshackle requires Python 3.11 or newer, up to and including 3.14 (requires-python = \">=3.11,<3.15\"). Anything older than 3.11 or 3.15 and later is unsupported, and the installer refuses to assemble the environment.
You do not usually need to install a matching Python interpreter by hand, since uv can download and manage one for you. If you work inside an existing virtual environment, make sure that it is on a supported version.
"},{"location":"getting-started/installation/#installing-by-hand","title":"Installing by hand","text":"If you do not use the install script, install unshackle with uv and then run unshackle setup, or install the external tools yourself.
"},{"location":"getting-started/installation/#running-from-a-clone","title":"Running from a clone","text":"Use uv run 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.
Run from a git clonegit clone https://github.com/unshackle-dl/unshackle.git\ncd unshackle\nuv run unshackle setup\n
Every command shown elsewhere in these docs works the same way from a clone. Prefix it with uv run:
uv run unshackle env check\n
"},{"location":"getting-started/installation/#advanced-install-as-a-uv-tool","title":"Advanced: install as a uv tool","text":"This way is for users who know uv tools and want the unshackle command on their PATH without a clone.
Where a uv tool install keeps files
uv tool install puts unshackle into the tool folder of uv, not into a folder that you choose. unshackle setup 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 uv tool install, unshackle setup tells you this and asks if you want to continue.
Install the tool and run setup:
Install as a uv tooluv tool install git+https://github.com/unshackle-dl/unshackle.git\nunshackle setup\n
The install scripts also do this when you run one alone, without a clone: when the script does not find the unshackle pyproject.toml next to it, it runs uv tool install and then unshackle setup. When it finishes, it tells you to open a new terminal, because the PATH change only applies to new terminals. Run unshackle env check there.
Upgrading and removing
Because you installed it from a git URL, re-run the same uv tool install command (uv will update in place) to get a newer version, and use uv tool uninstall unshackle to remove it.
Developer note
Contributors will also want the development and test dependency groups. The project defines dev (linters, type checkers) and test (pytest and friends) groups in pyproject.toml. Install them with uv sync --group dev --group test inside the clone. End users can ignore these entirely.
"},{"location":"getting-started/installation/#external-tools-on-your-path","title":"External tools on your PATH","text":"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 binaries/ folder inside the installed package, then in the binaries folder of your user data directory, and then on your system PATH. unshackle setup installs tools into the first folder in a clone and into the second for a uv tool install. Installing a tool system-wide or putting it into one of those folders both work.
unshackle setup installs the required tools and some optional ones for you. Use the tables below when you install a tool by hand.
"},{"location":"getting-started/installation/#required-tools","title":"Required tools","text":"These must be present for core downloading, decryption, and muxing to work:
Tool Binary looked up Why it is needed FFmpeg ffmpeg Media processing: remuxing, conversion, track handling FFprobe ffprobe Media analysis: inspecting tracks and container details MKVToolNix mkvmerge Muxing downloaded tracks into a final MKV mkvpropedit mkvpropedit Editing MKV metadata after muxing shaka-packager shaka-packager / packager Decrypting DRM-protected content (the default decryptor) shaka-packager is the default decryptor
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 decryption config key if you want to switch to mp4decrypt.
Do not use shaka-packager 3.0 through 3.9.x
These versions stop with a segmentation fault on a single-track MP4 whose internal track_id is 2 or more. A track that unshackle downloads from a DASH or HLS manifest usually has such a track_id.
"},{"location":"getting-started/installation/#recommended-and-optional-tools","title":"Recommended and optional tools","text":"These extend unshackle's capabilities. Install the ones relevant to what you download. For example, dovi_tool only matters if you download Dolby Vision video.
Tool Binary looked up Why it is needed Bento4 (mp4decrypt) mp4decrypt Alternative DRM decryptor to shaka-packager MP4Box (GPAC) MP4Box Muxing DTS:X Profile 2 (DTS-UHD) audio dovi_tool dovi_tool Dolby Vision metadata handling HDR10Plus_tool hdr10plus_tool HDR10+ metadata handling SubtitleEdit seconv, SubtitleEdit Subtitle conversion (the SeConv CLI from 5.x) CCExtractor ccextractor, ccextractorwin, ccextractorwinfull Extracting closed captions FFplay ffplay Simple preview player MPV mpv Advanced preview player (used by util crop/util range previews) HolaProxy hola-proxy Hola proxy provider support Caddy caddy Optional reverse proxy for unshackle serve --caddy Docker docker Gluetun VPN proxy support Git git Fetching and updating remote service repositories MP4Box is only used for DTS:X Profile 2
Titles with DTS:X Profile 2 (DTS-UHD) audio mux to MP4; everything else muxes to MKV with mkvmerge. Install with apt install gpac.
SubtitleEdit specifics
unshackle looks for seconv first, the batch CLI shipped with SubtitleEdit 5.x, before falling back to a SubtitleEdit (4.x) binary. The 5.0 GUI has no batch mode, so the SeConv CLI is what you want for automated subtitle conversion.
"},{"location":"getting-started/installation/#verifying-your-installation","title":"Verifying your installation","text":"After installation, make sure that unshackle can see the tools it depends on.
"},{"location":"getting-started/installation/#examine-the-external-dependencies","title":"Examine the external dependencies","text":"The env check subcommand is the first check. It inspects your environment and reports which tools it found:
From a cloneInstalled as a uv tool uv run unshackle env check\n
unshackle env check\n
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 All required tools installed \u2713 or Missing required: <names>.
If a required tool shows as missing, env check tells you to run unshackle setup. You can also install the tool by hand and put it on your PATH (or in one of the binaries folders), then re-run the check.
unshackle is not found after a uv tool install
The bin directory of uv tools is probably not on your PATH. Run uv tool update-shell and open a new terminal.
"},{"location":"getting-started/installation/#inspect-environment-paths","title":"Inspect environment paths","text":"To see where unshackle will read its configuration from and where it stores downloads, caches, cookies, and devices, use:
uv run unshackle env info\n
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.
"},{"location":"getting-started/installation/#next-steps","title":"Next steps","text":" - Set up your configuration file (
unshackle.yaml), or let unshackle setup write a first one. - Start downloading titles when
env check finds every required tool.
"},{"location":"getting-started/quickstart/","title":"Quick Start","text":"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 unshackle dl command, and learn where the finished file lands.
Before you start
This guide assumes that you installed unshackle as Installation describes. The examples use the bare unshackle command. From a git clone, the recommended install, run each one as uv run unshackle ..., for example uv run unshackle env check.
unshackle includes no services
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). EXAMPLE in this guide stands in for the tag you give yours.
"},{"location":"getting-started/quickstart/#1-run-setup","title":"1. Run setup","text":"unshackle drives several external tools (FFmpeg, MKVToolNix, shaka-packager, and others) to decrypt, repack, and mux media, and it needs a config file. The unshackle setup command prepares both. If you used the install script, setup has already run. You can run it again at any time:
unshackle setup\n
Setup downloads the missing required tools and, if you agree, groups of optional tools. If no unshackle.yaml exists, it writes a minimal one with your downloads folder. It also makes the data folders and lets you import .wvd and .prd devices, one file or a whole folder at a time. Installation tells you what each step does and where the files go.
Then make sure that unshackle finds the tools:
unshackle env check\n
The required tools (FFmpeg, FFprobe, MKVToolNix, mkvpropedit, and shaka-packager) must show a green check. Optional tools such as dovi_tool (Dolby Vision) and CCExtractor (closed captions) only matter for the features that use them.
Set up by hand
To do these steps yourself, install the tools from the tables in Installation. Then run unshackle env info to see where unshackle looks for unshackle.yaml, and make the file in one of those locations. The configuration guide gives the details.
"},{"location":"getting-started/quickstart/#2-check-the-output-template","title":"2. Check the output template","text":"unshackle refuses to start a download unless it knows how to name the output file. That means output_template is the one setting a first run genuinely requires. Everything else has a sensible default. The config that setup writes copies tag and output_template from the example config. A minimal, working config looks like this:
unshackle.yamloutput_template:\n movies: \"{title} ({year}) {quality} {source}\"\n series: \"{title} {season_episode} {episode_name?} {quality} {source}\"\n
unshackle fills in each {variable} from the title and the tracks you downloaded. Output and Naming gives the full set of valid variables, including resolution, video, audio, hdr, edition, tag, and more.
Spaces or dots?
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 Title.S01E01.1080p names. Write the template in the style you want the filenames to look.
Editing config from the CLI strips comments
You can read and set keys with unshackle cfg (for example unshackle cfg tag MYGROUP or unshackle cfg --list), 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.
"},{"location":"getting-started/quickstart/#3-write-a-service","title":"3. Write a service","text":"The service tag you pass to dl (like EXAMPLE) 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.
Put the finished module in your directories.services folder (unshackle env info shows the path). The tag then works with dl, search, and the other service commands.
"},{"location":"getting-started/quickstart/#4-add-a-cdm-for-drm","title":"4. Add a CDM for DRM","text":"Most streaming services encrypt their titles. To fetch content keys, unshackle needs a CDM, a Widevine device (.wvd) or a PlayReady device (.prd). If you imported devices during unshackle setup, they are already in place. If setup also wrote your config, it set cdm.default to the device that you chose. Otherwise, add a Widevine device you already have with:
unshackle wvd add /path/to/device.wvd\n
This validates the file and moves it into your WVDs directory. Then point services at it in your config. The cdm map uses the service tag as its config key, with a default that covers everything else:
unshackle.yamlcdm:\n default: my_device # the .wvd file's name, without the extension\n EXAMPLE: my_other_device # override for a specific service\n
PlayReady works the same way with .prd files created and managed by the prd command. If a title is DRM-free, unshackle needs no CDM.
Tip
Operate unshackle wvd parse my_device to inspect a device's security level and contents, and unshackle env info to show where unshackle stores WVDs and PRDs.
"},{"location":"getting-started/quickstart/#5-supply-authentication","title":"5. Supply authentication","text":"Services that require a login read either cookies or credentials.
-
Cookies: export the service's cookies to a Netscape-format text file and place it in your cookies directory. unshackle looks for, in order: cookies/{SERVICE}.txt, then cookies/{SERVICE}/{profile}.txt, then cookies/{SERVICE}/default.txt. So unshackle finds a file at cookies/EXAMPLE.txt automatically for the EXAMPLE service.
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.
-
Credentials: store a username and password per service in your config:
unshackle.yamlcredentials:\n EXAMPLE: \"email@example.com:your-password\"\n
Use the -p/--profile 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.
"},{"location":"getting-started/quickstart/#6-find-a-title-optional","title":"6. Find a title (optional)","text":"If you have a URL or ID already, skip this. Otherwise, find a title on the service and note the id it prints, because that is what you feed to dl:
unshackle search EXAMPLE \"My Show\"\n
You can also show what a service gives for a given title without downloading:
unshackle dl --list-titles EXAMPLE 81234567 # show seasons/episodes\nunshackle dl --list EXAMPLE 81234567 # show available tracks\n
"},{"location":"getting-started/quickstart/#7-do-your-first-download","title":"7. Do your first download","text":"A download always has three parts:
unshackle dl <FLAGS> <SERVICE-TAG> <TITLE>\n
dl carries every quality, language, track, and output flag. <SERVICE-TAG> picks which service to talk to (e.g. EXAMPLE). <TITLE> is the URL, ID, or slug the service understands.
A good first command asks for 1080p with English audio:
Your first downloadunshackle dl -q 1080 -l en EXAMPLE 81234567\n
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.
"},{"location":"getting-started/quickstart/#handy-first-flags","title":"Handy first flags","text":"Flag Meaning -q, --quality Target resolution(s), e.g. -q 1080 or -q 1080,720. Defaults to best available. -l, --lang Language(s) for video and audio, e.g. -l en or -l orig,en. orig = the title's original language. Defaults to orig. -sl, --s-lang Subtitle language(s); defaults to all. -v, --vcodec Video codec, e.g. -v H.265. Defaults to any. -r, --range Dynamic range, e.g. -r HDR10 or -r DV. Defaults to SDR. -w, --wanted Which episodes, e.g. -w S01 or -w S01E01-S01E03. For music, which tracks, e.g. -w 1-5 or -w 2x3 for disc 2 track 3. -o, --output Override the output directory for this run. --list List the tracks that would be downloaded, then stop. A few realistic variations
# 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
See Downloading for the complete flag reference, including codec, bitrate, channel-layout, and track-type selection.
"},{"location":"getting-started/quickstart/#8-where-the-output-lands","title":"8. Where the output lands","text":"By default, unshackle writes finished files to the downloads directory. unshackle env info shows its exact path. A config from unshackle setup uses the folder that you gave at its prompt. Without that setting, the default is a downloads folder one level above the installed unshackle package. Override it for one command with -o:
unshackle dl -q 1080 -o /mnt/media/incoming EXAMPLE 81234567\n
- unshackle writes movies as a single
.mkv file named from your movies template. - unshackle groups TV episodes into a per-show / per-season folder (from your
series template) unless you pass --no-folder. - unshackle builds the filename from your
output_template and adds IMDb/TMDB/TVDB IDs to the file's metadata tags when available.
To change the default output location permanently, set it in your config:
unshackle.yamldirectories:\n downloads: /mnt/media/incoming\n
"},{"location":"getting-started/quickstart/#where-to-go-next","title":"Where to go next","text":" - Downloading. The full
dl command: quality, codecs, languages, track selection, hybrid Dolby Vision, and output control. - Configuration. Every
unshackle.yaml config key, plus directories, key vaults, proxies, and naming templates. - REST API. Operate the
serve server to drive downloads over HTTP.
You are never far from help
unshackle --help, unshackle dl --help, and unshackle <command> --help show every option. When in doubt, add --list to a dl command to preview what it would do before it downloads anything.
"},{"location":"guide/cli-reference/","title":"CLI Reference","text":"A complete reference for every unshackle command, subcommand, and flag. This page groups the commands by purpose:
dl: the download pipeline (the command you use most). search: find titles on a service. import: rebuild a download from an export file. setup: install the external tools and make a first config. cfg, env: manage configuration and the environment. kv: Key Vault operations. wvd, prd: Widevine / PlayReady device management. serve: operate the local CDM and REST API server. util: helper media utilities.
Running commands from a clone
This page uses the bare unshackle command. From a git clone, the recommended install, run each command as uv run unshackle ....
Getting help on any command
Every command accepts -h, --help, or -?. For example unshackle dl --help or unshackle wvd new --help. Each service defines its own arguments for dl and search (such as a title ID or a query), so examine unshackle dl SERVICE --help for those.
"},{"location":"guide/cli-reference/#root-command","title":"Root command","text":"unshackle [OPTIONS] COMMAND [ARGS]...\n
unshackle: Modular Movie, TV, and Music Archival Software.
Every invocation prints a banner and, when you enable update_checks in your config, checks for a newer release.
Option Description -v, --version Print version information and exit. -d, --debug Enable DEBUG-level logs and JSON debug logging. Silences noisy HTTP libraries unless debug_requests is set in config. -h, --help, -? Show help and exit. Commands are auto-discovered, so third-party command modules dropped into the commands directory appear automatically.
"},{"location":"guide/cli-reference/#dl","title":"dl","text":"The download command. It is itself a group whose subcommands are the installed streaming services, so an invocation always has three layers:
unshackle dl [OPTIONS] SERVICE [SERVICE ARGS...]\n
OPTIONS: every flag below, parsed at the dl level. SERVICE: a service tag (for example EXAMPLE1 or EXAMPLE2). Tags are case-insensitive and honour each service's aliases (example+, EXAMPLE2, and the other alias forms all give the same tag). SERVICE ARGS: the title, URL, or ID, plus any service-specific options. These belong to the service, not to dl.
Typical downloads
# 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
Config-driven defaults
You can give any dl flag a default under the dl: section of unshackle.yaml, and per-service under services.<TAG>.dl. 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.
"},{"location":"guide/cli-reference/#quality-codec-bitrate-range","title":"Quality, codec, bitrate & range","text":"Flag Default Description -p, --profile - Profile for credentials and cookies. -q, --quality best Resolution(s), comma-separated, e.g. 1080,720. -q 1080 also matches anamorphic tracks by 16:9 canvas. -v, --vcodec any Video codec(s). Accepts names or values: AVC/H.264/H264, HEVC/H.265/H265, VC1/VC-1, VP8, VP9, AV1. -a, --acodec any Audio codec(s), comma-separated. Accepts AAC, AC3/DD, EC3/DD+/eac3/ddp, AC4/AC-4, OPUS, OGG/VORB/vorbis, DTS, DTSX/DTS-X, ALAC, FLAC. -vb, --vbitrate highest Exact video bitrate in kbps. -ab, --abitrate highest Exact audio bitrate in kbps. -vb-range, --vbitrate-range - Video bitrate range in kbps, e.g. 6000-7000; picks highest within. Mutually exclusive with --vbitrate. -ab-range, --abitrate-range - Audio bitrate range in kbps, e.g. 128-256. Mutually exclusive with --abitrate. -r, --range SDR Colour range(s): SDR, HLG, HDR10, HDR10P (HDR10+), DV, HYBRID. -c, --channels - Audio channels; matches sub-layouts (5.1 \u2248 6.0). -naa, --noatmos off Exclude Dolby Atmos audio tracks. --worst off Pick the lowest bitrate within the requested quality. Requires -q. --best-available, --warn-only off Warn and continue when a requested resolution, range, or language is absent, instead of failing. With --all-drm, also when one DRM system does not license. -rvb, --real-video-bitrate off Probe real media size for true video bitrates, overriding the manifest. -rab, --real-audio-bitrate off Same for audio (slower). HYBRID range
-r HYBRID fetches both HDR10/HDR10+ and Dolby Vision and merges them with dovi_tool. It requires the dovi_tool binary on your PATH.
"},{"location":"guide/cli-reference/#language-subtitles","title":"Language & subtitles","text":"Flag Default Description -l, --lang orig Language(s) for both video and audio. orig = the title's original language; e.g. orig,en. A - prefix excludes, e.g. all,-es. -vl, --v-lang - Video-only language (overrides -l for video). A - prefix excludes. -al, --a-lang - Audio-only language (overrides -l for audio). A - prefix excludes. -sl, --s-lang all Subtitle language(s). A - prefix excludes, e.g. all,-es. --require-audio - Audio langs that must exist. The title fails even with --best-available. Does not select tracks. --require-video - Video langs that must exist. The title fails even with --best-available. Does not select tracks. --require-subs - Subtitle langs that must exist. Fails the title if one is missing. --s-lang still decides what to keep. -fs, --forced-subs off Include forced subtitle tracks. -fso, --forced-subs-only off Keep only forced subtitle tracks; drop the other subtitles. Implies -fs. -fsl, --forced-s-lang none Language(s) wanted for forced subtitles; implies -fs. A - prefix excludes. --exact-lang off Exact matching only: -l es-419 matches es-419, not es-ES. Applies to selection and to sort order. --sub-format - Output subtitle format (SRT/srt, VTT/webvtt, ASS/ssa, TTML, SMI, ...), or original to keep the source format. These flags select languages, they do not order them
Naming languages with -l or -sl removes the others. To keep every language but put your preferred ones first, use audio.language_priority and subtitle.language_priority in your configuration file.
unshackle honours the special language tokens orig, all, and best everywhere it expects a language.
"},{"location":"guide/cli-reference/#title-episode-selection","title":"Title & episode selection","text":"Flag Description -w, --wanted Wanted episodes, e.g. S01-S05,S07, S01E01-S02E03. Supports exclusions with a leading - (e.g. -S03). For a split episode, .N picks one part (S01E01.2), a range must stay inside the episode (S01E01.1-S01E01.3), and S01E01 on its own takes every part. For a dated episode, a token can also be an ISO air date (2026-08-11) or a date range with a colon (2026-08-01:2026-08-31). For a music release, a token is a track number (1-5, 1,3,7), or {disc}x{track} (2x3) when the release has more than one disc. --select-titles Interactively select what to download: episodes of a series, or films when a title has more than one. Cannot combine with -w. --latest-episode Download only the single most recent episode. --latest-episodes N Download only the N most recent episodes. --list-titles List titles only; do not download."},{"location":"guide/cli-reference/#track-type-inclusion-exclusion","title":"Track-type inclusion / exclusion","text":"Keep only certain track types, or skip certain track types.
Include-only Skip -V, --video-only -nv, --no-video -A, --audio-only -na, --no-audio -S, --subs-only -ns, --no-subs -C, --chapters-only -nc, --no-chapters -nt, --no-attachments (cover art, subtitle fonts, and files the service attaches) Flag Description -ad, --audio-description Include descriptive (audio-description) tracks. -ado, --audio-description-only Keep only descriptive (audio-description) tracks; drop the standard audio. Does not need -ad. --skip-subtitle-errors Skip a failed subtitle instead of aborting the title. Video/audio failures remain fatal."},{"location":"guide/cli-reference/#output-muxing-files","title":"Output, muxing & files","text":"Flag Description --split-audio Write a separate output file per audio codec instead of merging. Defaults to config muxing.merge_audio. --merge-video Mux video tracks that share a height, range, and codec into one file, so only language varies inside a file. Defaults to config muxing.merge_video. -o, --output Override the output directory for this run. --no-folder Disable folder creation for TV shows. --no-source Remove the source tag from the filename/path. --no-mux Do not mux; keep individual track files. --sample Download a short sample and write it with a SAMPLE tag on the filename in a Sample folder inside the output folder. Bare --sample = 60 seconds from 2 minutes in; --sample 0-60 = a custom window in seconds. --include-sample Download the full title, then also cut a 60 second sample from each muxed file into a Sample folder next to it. --tag Group tag override. --repack Add a REPACK tag to the filename. --postscript Run a command after each output file, with {variable} placeholders substituted. Repeatable. Replaces the post_scripts config for this run. See Post-scripts. --no-postscript Run no post-script for this run, neither the configured ones nor --postscript."},{"location":"guide/cli-reference/#metadata-tagging","title":"Metadata & tagging","text":"Flag Description --tmdb TMDB ID (integer). Used for the tags. Skips the title search. --enrich reads it too. Needs tmdb_api_key. --imdb IMDb ID, e.g. tt1375666. Used for the tags. Skips the title search. --enrich reads it too. Needs no API key. --tvdb TVDB ID (integer). Used for the tags. Skips the series lookup that --tvdb-order would otherwise do. --enrich reads it too. Needs tvdb_api_key. --anilist AniList ID (integer), e.g. --anilist 21. A MyAnimeList ID is accepted as mal:12345 and resolved to the AniList entry. Used for the tags. Skips the title search. --enrich reads it too. Needs no API key. --enrich Overwrite show title, year and original language with the external source's. Requires one of --tmdb, --imdb, --tvdb, or --anilist. --daily Treat the title as daily/date-based content and fill missing episode air dates from TVDB. The fill needs --enrich and a TVDB ID. See Daily and date-based content. --tvdb-order Renumber episodes to a TVDB season order: official (aired), dvd, absolute, alternate, or regional. Needs tvdb_api_key. One ID at a time
You cannot combine --tmdb, --imdb and --tvdb. Give one and unshackle finds the others from it, and writes all three to the tags. --anilist 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 --tmdb with no tmdb_api_key, fails before the download starts. --anilist needs no API key, so it never fails this check.
"},{"location":"guide/cli-reference/#episode-ordering","title":"Episode ordering","text":"A service does not always number a series the way TVDB's aired order does. Some services use TVDB's alternate (Streaming) order for Futurama, for example. --tvdb-order works out which order the service used, then renumbers the episodes into the order you asked for.
Orders that do not cover the whole series
An order can ignore episodes the service carries. TVDB's dvd 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.
"},{"location":"guide/cli-reference/#drm-keys-decryption","title":"DRM, keys & decryption","text":"Flag Description --cdm-only / --vaults-only Use only the CDM, or only Key Vaults, for key acquisition. --cdm <name> Use the named CDM device from the cdm config mapping for this run, ignoring the service/default mapping. Over --remote, that device licenses the remote session, not the server CDM. --skip-dl Skip the download but still retrieve keys. --all-drm License each track with both Widevine and PlayReady. Needs a CDM for each DRM system. Key Vaults are read first; --cdm-only sends a challenge for each system. Not for use with --cdm. --export Export track info and keys to a mediaexport JSON file in the exports directory."},{"location":"guide/cli-reference/#network-proxy","title":"Network & proxy","text":"Flag Description --proxy Proxy URI, a country or location code resolved from configured providers, or provider:region (e.g. nordvpn:ca, gluetun:us, protonvpn:de:berlin, controld:yul). --no-proxy Force-disable all proxy use. --no-proxy-download Bypass the proxy for all downloads (manifest, licence, and auth stay proxied). --proxy-download Use a different proxy for all downloads, in the same forms as --proxy (manifest, licence, and auth stay on --proxy). --remote Use a remote unshackle server. --server Name a remote server from the remote_services config."},{"location":"guide/cli-reference/#concurrency-caching-listing","title":"Concurrency, caching & listing","text":"Flag Default Description --workers downloader default Per-track download threads. --adaptive-workers off Scale per-track segment workers dynamically (up to the --workers cap) based on measured CDN throughput and errors. --download-processes 1 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. --continue-downloads off Keep completed segment files across runs and resume a previously failed download. One-off enable of the continue_downloads config option. --downloads 1 Number of tracks downloaded concurrently. --speed-limit unlimited Cap total download speed across all threads and tracks, e.g. 500k, 5M, 1.5G or plain bytes/sec. Values are bytes, not bits (5M = 5.0 MB/s). off disables a configured limit. --no-cache off Bypass the title cache. --reset-cache off Clear the title cache. --list off List available/would-be-downloaded tracks; do not download. --slow - Inter-title delay. Bare --slow = 60-120s; --slow 20-40 = custom range (minimum 20s). Some flags cannot be combined
--select-titles and --wanted are mutually exclusive. --worst needs --quality. --vbitrate and --vbitrate-range (and the audio equivalents) are mutually exclusive.
"},{"location":"guide/cli-reference/#search","title":"search","text":"Find titles on a service. Like dl, search is a group whose subcommands are the installed services, and it reuses dl's authentication, cookie, and proxy machinery.
unshackle search [OPTIONS] SERVICE [QUERY...]\n
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 dl.
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 --profile has no effect.
Option Description -p, --profile Profile for credentials and cookies. --proxy Proxy URI, country or location code, or provider:region (e.g. controld:ca). --no-proxy Force-disable all proxy use. Example
unshackle search EXAMPLE \"My Show\"\nunshackle search -p myprofile EXAMPLE \"Another Show\"\nunshackle search --proxy nordvpn:ca SERVICE \"query\"\n
"},{"location":"guide/cli-reference/#import","title":"import","text":"Reconstruct a download (download \u2192 decrypt \u2192 mux) from an --export JSON file without re-contacting the service. It re-fetches the manifest, injects the stored keys, and then runs the normal dl pipeline. The service tag is read from the export file, not passed by you.
unshackle import EXPORT_FILE [DL_ARGS...]\n
unshackle forwards any dl options after the file verbatim, so you can override quality, range, proxy, and so on.
Example
unshackle import export.json\nunshackle import export.json -r HDR10 --proxy US\n
The export file can be a mediaexport file from dl --export, an export from an older version of unshackle, or an export from unidl. The file must name the service it came from.
"},{"location":"guide/cli-reference/#setup","title":"setup","text":"Install the external tools and make a first config.
unshackle setup\n
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 binaries folder, in the package folder of a git clone or in your user data directory for a uv tool install. If no unshackle.yaml exists, it writes a first one: inside the clone, or to your user config directory for a uv tool install. It then makes the data folders and imports .wvd and .prd 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 env check. 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.
Example
uv run unshackle setup # from a git clone\nunshackle setup # from a uv tool install\n
"},{"location":"guide/cli-reference/#cfg","title":"cfg","text":"Read, set, delete, or show configuration values in unshackle.yaml without hand-editing YAML.
unshackle cfg [KEY] [VALUE] [OPTIONS]\n
Argument / Option Description KEY Dotted path into the config, e.g. tag, serve.api_secret, directories.downloads. VALUE Value to set. Parsed as a Python literal when possible, so true, 123, ['a','b'], and {'k':1} become real types; bare words stay strings. --unset Remove the configuration value. --list List all set configuration values. Comments are stripped
Writing a value through cfg 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 --unset together is an error.
Example
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
"},{"location":"guide/cli-reference/#env","title":"env","text":"Inspect and manage the project environment.
unshackle env COMMAND [ARGS]...\n
"},{"location":"guide/cli-reference/#env-check","title":"env check","text":"unshackle env check\n
Prints a dependency table (Category / Tool / Status / Required / Purpose) that shows which external tools unshackle finds on your PATH. It also gives a summary of how many required tools are present. If a required tool is missing, it tells you to run unshackle setup.
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 * required. All others are optional.
"},{"location":"guide/cli-reference/#env-info","title":"env info","text":"unshackle env info\n
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).
"},{"location":"guide/cli-reference/#env-theme","title":"env theme","text":"unshackle env theme\n
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 theme config key.
"},{"location":"guide/cli-reference/#env-clear","title":"env clear","text":"Clear an environment directory. unshackle empties the directory, makes it again, and reports the number of files and bytes it freed.
Command Description unshackle env clear cache [SERVICE] Clear the cache directory, or only one service's cache subdirectory. unshackle env clear temp Clear the temp directory. Example
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
"},{"location":"guide/cli-reference/#kv","title":"kv","text":"Manage Key Vaults. You configure vaults under key_vaults in unshackle.yaml, each with a name, a type (sqlite, mysql, http, api), and type-specific options. unshackle normalises service tags automatically.
unshackle kv COMMAND [ARGS]...\n
"},{"location":"guide/cli-reference/#kv-copy-to_vault-from_vault","title":"kv copy TO_VAULT FROM_VAULT...","text":"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.
Option Description -s, --service Only copy data for a specific service. -l, --local-only Only copy data for services installed locally. Mutually exclusive with --service."},{"location":"guide/cli-reference/#kv-sync-vault","title":"kv sync VAULT...","text":"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 --service / --local-only options as copy.
"},{"location":"guide/cli-reference/#kv-add-file-service-vault","title":"kv add FILE SERVICE VAULT...","text":"Add content keys to one or more vaults for a service. FILE contains one KID:KEY pair per line (32 hex : 32 hex, UTF-8). unshackle skips every line that does not match that form.
"},{"location":"guide/cli-reference/#kv-search-kid","title":"kv search KID","text":"Find a KID (32 hex characters, no dashes) in the configured vaults and report its content key.
Option Description -s, --service Limit the search to a specific service tag. -v, --vault Limit the search to a specific configured vault by name. Note
unshackle cannot enumerate remote vaults without a service, so pass --service when you examine them.
"},{"location":"guide/cli-reference/#kv-prepare-vault","title":"kv prepare VAULT...","text":"Make service tables on vaults that use tables, for every installed service, where they do not already exist.
Example
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
"},{"location":"guide/cli-reference/#wvd","title":"wvd","text":"Manage Widevine Device (.wvd) files. Devices live in the configured WVDs directory.
unshackle wvd COMMAND [ARGS]...\n
Command Description wvd add PATHS... Validate and move one or more .wvd files into the WVDs directory. wvd delete NAMES... Delete .wvd files by name (without extension). Prompts for confirmation. wvd parse PATH Parse a .wvd and print its System ID, security level, type, flags, and client info. Relative paths resolve against the WVDs directory. wvd dump WVD_PATHS... OUT_DIR Extract a device's contents (metadata, private key, client ID, VMP) into OUT_DIR/<name>/. With no paths, dumps every WVD in the WVDs directory. wvd new NAME PRIVATE_KEY CLIENT_ID [FILE_HASHES] Create a new .wvd from a PEM private key and a ClientIdentification blob, optionally with a VMP (FileHashes) blob. wvd new options:
Option Default Description -t, --type Android Device type. -l, --level 1 Security level (1-3). -o, --output WVDs dir Output directory. Example
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
"},{"location":"guide/cli-reference/#prd","title":"prd","text":"Manage PlayReady Device (.prd) files. Devices live in the configured PRDs directory. Built on pyplayready.
unshackle prd COMMAND [ARGS]...\n
"},{"location":"guide/cli-reference/#prd-new-paths","title":"prd new PATHS...","text":"Make a new .prd. Give either a single folder that contains zgpriv.dat (group key) and bgroupcert.dat (group certificate), or two file paths (group key, then group certificate).
Option Description -e, --encryption_key Optional device ECC private encryption key (generated if omitted). -s, --signing_key Optional device ECC private signing key (generated if omitted). -o, --output Output directory or .prd file path. prd new will not overwrite an existing file.
"},{"location":"guide/cli-reference/#prd-reprovision-prd_path","title":"prd reprovision PRD_PATH","text":"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 -e / -s / -o options. By default it overwrites the device in place.
"},{"location":"guide/cli-reference/#prd-test-device","title":"prd test DEVICE","text":"Do a test of a device against the Microsoft PlayReady demo server and print the returned content keys.
Option Default Description -c, --ckt aesctr Content key encryption type: aesctr or aescbc. -sl, --security-level 2000 Minimum security level: 150, 2000, or 3000. Example
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
"},{"location":"guide/cli-reference/#serve","title":"serve","text":"Serve your local Widevine/PlayReady devices and the REST API for remote access. Built on aiohttp.
unshackle serve [OPTIONS]\n
Option Default Description -h, --host 127.0.0.1 Host to serve from. -p, --port 8786 Port to serve from. --caddy off Also serve through Caddy (requires the caddy binary and a Caddyfile). --api-only off Serve only the REST API, not the CDM endpoints. Incompatible with --no-widevine/--no-playready. --no-widevine off Disable the Widevine CDM endpoints. --no-playready off Disable the PlayReady CDM endpoints. --no-key off Disable API-key authentication (allows all requests). --debug-api off Include tracebacks/stderr in API error responses. --debug off Enable debug logging for API operations. --remote-only off Expose only the remote service session endpoints (health, services, search, session). Implies --api-only. WVD files in the WVDs directory and PRD files in the PRDs directory are auto-loaded. The REST API lives under http://<host>:<port>/api/, with Swagger UI at /api/docs/ and a health check at /api/health (exempt from auth).
Configure api_secret first
Unless you pass --no-key, serve.api_secret must be set in your config. Requests authenticate with the X-Secret-Key header. --no-key disables authentication entirely. Only use it on a trusted, private network.
unshackle.yamlserve:\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
Example
unshackle serve\nunshackle serve -h 0.0.0.0 -p 8080\nunshackle serve --api-only\nunshackle serve --remote-only\nunshackle serve --caddy\n
"},{"location":"guide/cli-reference/#util","title":"util","text":"Various helper media utilities. When you give a command a directory, it processes every .mkv/.mp4 inside it in natural (S01E01 before S01E10) order.
unshackle util COMMAND [ARGS]...\n
"},{"location":"guide/cli-reference/#util-refresh-services","title":"util refresh-services","text":"unshackle util refresh-services\n
Force a refresh (git pull / hard reset) of all service repos configured under directories.services. This updates the clones on disk. A server that is already running reloads the changed services through POST /api/maintenance/refresh-services or serve.services_refresh_interval instead.
"},{"location":"guide/cli-reference/#util-crop-path-aspect","title":"util crop PATH ASPECT","text":"Losslessly crop H.264/H.265 video at the bitstream level. ASPECT is a W:H target such as 2.39:1.
Option Default Description --letter / --pillar --letter Crop top/bottom (--letter) or the sides (--pillar). -o, --offset 0 Fine-tune the computed crop area if not perfectly centred. -p, --preview off Preview the crop in MPV (or FFplay) instead of writing a file."},{"location":"guide/cli-reference/#util-range-path","title":"util range PATH","text":"Losslessly set the video range flag to full or limited at the bitstream level.
Option Default Description --full / --limited - Full (0-255) or limited (16-235) range. -p, --preview off Preview instead of writing a file."},{"location":"guide/cli-reference/#util-test-path","title":"util test PATH","text":"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.
Option Default Description -m, --map 0 Do a test of specific tracks with FFmpeg's -map, for example 0:v:0 or 0:a. Example
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
"},{"location":"guide/cli-reference/#see-also","title":"See also","text":" - Installation: install unshackle and its dependencies.
- Quickstart: your first download.
- Configuration file: set defaults for any
dl flag and configure vaults, proxies, and directories.
"},{"location":"guide/downloading/","title":"Downloading","text":"unshackle dl 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.
Where the full flag list lives
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 unshackle dl --help. Every flag shown here can also be given a default in your configuration file. See Configuration file.
"},{"location":"guide/downloading/#command-shape","title":"Command shape","text":"A download is always three layers: the root CLI, the dl command (which is where unshackle parses all the flags below), and a service tag subcommand that carries the title argument.
unshackle dl [OPTIONS] SERVICE [SERVICE ARGUMENTS]\n
unshackle: the root command. dl: the download command. unshackle parses all of the options on this page here, so they go before the service tag. SERVICE: a service tag such as EXAMPLE1, EXAMPLE2, EXAMPLE3. Service tags are case-insensitive and honour each service's aliases (for example example+ resolves to its real tag). SERVICE ARGUMENTS: usually a title ID or URL. This positional argument belongs to the service, not to dl, so it comes after the tag.
A minimal downloadunshackle dl EXAMPLE 81234567\n
Flags belong to dl, the title belongs to the serviceunshackle dl -q 1080 -v H.265 -r HDR10 --lang en EXAMPLE 'https://www.example.com/...'\n
See what a service accepts
Because each service defines its own positional argument, use unshackle dl SERVICE --help (for example unshackle dl EXAMPLE --help) to see that service's own argument and any service-specific options.
"},{"location":"guide/downloading/#the-download-flow","title":"The download flow","text":"When you start a download, dl moves through the pipeline below. The order tells you why, for example, --list stops early, and why unshackle fetches the content keys even with --skip-dl.
- Setup: load the DRM CDM, key vaults, proxy providers, cookies, and credentials.
- Authenticate: sign in to the service with your profile's cookies/credentials.
- Fetch titles: retrieve the movie, episode list, or album (cached unless
--no-cache/--reset-cache). - Filter titles: apply
--wanted, --latest-episode, --latest-episodes, or --select-titles. - Get tracks: parse the manifest into video, audio, subtitle, and chapter tracks.
- Select tracks: narrow each type down using your quality, codec, range, language, and bitrate flags.
- Download: pull segments for the selected tracks (concurrently per
--downloads). - License & decrypt: get the content keys (vault \u2192 CDM), decrypt each track.
- Post-process: extract closed captions, convert subtitles, repack, mux with
mkvmerge, and move the finished file to your downloads directory.
--list prints the tracks a title exposes and stops before selection. --list-titles prints every title the service returned and stops before --wanted/--latest-episode/--latest-episodes filtering. --skip-dl runs the license step but skips the actual segment download.
"},{"location":"guide/downloading/#choosing-quality","title":"Choosing quality","text":""},{"location":"guide/downloading/#resolution","title":"Resolution","text":"-q / --quality takes one or more target resolutions (heights) as a comma-separated list. Without it, unshackle picks the best available resolution.
Single resolutionunshackle dl -q 1080 EXAMPLE 81234567\n
Multiple resolutions in one rununshackle dl -q 2160,1080,720 EXAMPLE 81234567\n
16:9 canvas matching
Resolution matching is by track height first. If no track height matches exactly, unshackle falls back to a 16:9-canvas match, so -q 1080 also selects an anamorphic 1920\u00d7804 track (computed as int(width \u00d7 9 / 16)). unshackle applies the fallback to each range and codec on its own. A service that crops only its HDR10 tracks therefore keeps its 3840\u00d71920 HDR10 track, even when another range has an exact 2160 height match.
"},{"location":"guide/downloading/#best-available-and-worst","title":"Best-available and worst","text":"By default a missing requested resolution is an error. Two flags change that:
Flag Behaviour --best-available (--warn-only) 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 --all-drm a DRM system that does not license. --worst Within the specified quality, pick the lowest bitrate rendition. Requires -q/--quality. Never fail on a missing resolutionunshackle dl -q 2160 --best-available EXAMPLE 0ABC123\n
"},{"location":"guide/downloading/#video-codec-and-colour-range","title":"Video codec and colour range","text":""},{"location":"guide/downloading/#codec","title":"Codec","text":"-v / --vcodec selects one or more video codecs. The default is any codec. It accepts either enum names or their values, comma-separated.
Name Value AVC H.264 HEVC H.265 VC1 VC-1 VP8 VP8 VP9 VP9 AV1 AV1 H264 and H265 are aliases of AVC and HEVC.
Either spelling worksunshackle dl -v HEVC EXAMPLE 81234567\nunshackle dl -v H.265 EXAMPLE 81234567\nunshackle dl -v hevc,avc EXAMPLE 81234567\n
"},{"location":"guide/downloading/#colour-range","title":"Colour range","text":"-r / --range selects one or more colour ranges. The default is SDR.
Range Meaning SDR Standard dynamic range (default) HLG Hybrid Log-Gamma HDR10 HDR10 HDR10P HDR10+ DV Dolby Vision HYBRID Fetch both an HDR10/HDR10+ base and a DV track, then merge them Grab HDR10 and Dolby Vision in one rununshackle dl -q 2160 -r HDR10,DV EXAMPLE '...'\n
HYBRID requires dovi_tool
-r HYBRID makes a single hybrid track by injecting the Dolby Vision RPU metadata onto an HDR10/HDR10+ base layer with dovi_tool. It requires the dovi_tool binary, resolved from unshackle's binaries/ folder, the binaries folder of your user data directory, or your PATH. The normal case is a DV track plus an HDR10 or HDR10+ base. With HDR10+ and no DV, unshackle converts the HDR10+ metadata to DV instead, which also needs hdr10plus_tool. With no DV and no HDR10+, the title fails. When HDR10+ is present, unshackle prefers it over HDR10 as the base layer.
To keep an HDR10+ deliverable alongside the hybrid, request both ranges: -r HYBRID,HDR10P. -r HYBRID on its own muxes only the merged hybrid.
"},{"location":"guide/downloading/#bitrate-selection","title":"Bitrate selection","text":"By default unshackle keeps the highest-bitrate rendition for each selected resolution/codec/range/language combination. You can constrain this.
Flag Purpose -vb / --vbitrate Exact video bitrate in kbps. -ab / --abitrate Exact audio bitrate in kbps. -vb-range / --vbitrate-range Video bitrate range in kbps, e.g. 6000-7000; picks the highest within it. -ab-range / --abitrate-range Audio bitrate range in kbps, e.g. 128-256. Exact vs range are mutually exclusive
You cannot combine --vbitrate with --vbitrate-range, and likewise for the audio pair. Pick one form.
"},{"location":"guide/downloading/#real-bitrate-probing","title":"Real bitrate probing","text":"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 --vbitrate/--vbitrate-range 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:
-rvb / --real-video-bitrate: probe real video bitrates (per codec/range). -rab / --real-audio-bitrate: probe real audio bitrates (per codec/channels/ language). Slower than the video variant because there are more renditions to probe.
Reading the probed numbers
unshackle measures a single-file track (DASH SegmentBase/BaseURL) 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.
Why not every rendition is probed
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 ffprobe. A probe failure is non-fatal: the manifest value stays in place.
"},{"location":"guide/downloading/#audio-codec-channels-and-atmos","title":"Audio codec, channels, and Atmos","text":""},{"location":"guide/downloading/#codec_1","title":"Codec","text":"-a / --acodec selects one or more audio codecs (comma-separated). The default is any.
Name Value Codec AAC AAC Advanced Audio Coding AC3 DD Dolby Digital EC3 DD+ Dolby Digital Plus AC4 AC-4 Dolby AC-4 OPUS OPUS Opus OGG VORB Vorbis DTS DTS DTS DTSX DTS-X DTS:X Profile 2 (DTS-UHD) ALAC ALAC Apple Lossless FLAC FLAC FLAC unshackle accepts names, values, and a few aliases: eac3 and ddp both give EC3, and vorbis gives OGG.
Prefer Dolby Digital Plus, fall back to AACunshackle dl -a EC3,AAC EXAMPLE 81234567\n
"},{"location":"guide/downloading/#channels-and-atmos","title":"Channels and Atmos","text":" -c / --channels: desired channel layout, for example 5.1 or 2.0. Matching is by ceiling, so 5.1 implicitly matches a 6.0-reported layout. An immersive layout such as 5.1.4 matches on its total number of channels, so -c 10 selects it. -naa / --noatmos: exclude Atmos audio tracks from selection.
5.1 audio, no Atmosunshackle dl -c 5.1 --noatmos EXAMPLE 0ABC123\n
"},{"location":"guide/downloading/#music-quality","title":"Music quality","text":"A music service gives one Audio track for each codec and bitrate it offers for a song. The audio options above choose between them: -a picks the codec and -ab or -ab-range picks the bitrate. If you set neither, unshackle takes the best track.
-q / --quality is a video height. It has no effect on a music download.
Take the lossless trackunshackle dl -a FLAC EXAMPLE 81234567\n
Take the lossy track at 320 kb/sunshackle dl -a AAC -ab 320 EXAMPLE 81234567\n
Two FLAC tracks in one release
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 --list to read the bitrates, then give -ab the one you want.
"},{"location":"guide/downloading/#languages","title":"Languages","text":""},{"location":"guide/downloading/#video-and-audio-language","title":"Video and audio language","text":"-l / --lang sets the wanted language(s) for both video and audio. The default is orig, the title's original language.
Original language plus Englishunshackle dl -l orig,en EXAMPLE 81234567\n
unshackle changes the special token orig to the title's own original language everywhere you use it. You can override each track type independently:
-vl / --v-lang: language for video only (overrides -l for video). Useful when the burned-in video language differs from the audio you want. -al / --a-lang: language for audio only (overrides -l for audio).
English audio over the original videounshackle dl -al en EXAMPLE 81234567\n
"},{"location":"guide/downloading/#excluding-languages","title":"Excluding languages","text":"Put a - in front of a language to remove it from the selection. This works on -l, -vl, -al, -sl, and -fsl, in the same way as it works on -w / --wanted.
Every subtitle language except Spanishunshackle dl -sl all,-es EXAMPLE 81234567\n
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: -sl -es is the same as -sl all,-es, and -l -es is the same as -l orig,-es.
Only exclusions# 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
-vl and -al have no default of their own: they cascade to -l. An override that names a language replaces -l for that track type, exclusions included. An override that gives only exclusions adds them to the ones from -l.
Cascade# video keeps the Japanese track; only the audio drops Spanish\nunshackle dl -l en,-es -vl ja EXAMPLE 81234567\n
Rules for exclusion tokens
orig becomes the title's own original language, so -sl -orig drops the subtitles in that language. --exact-lang applies to exclusions with the same matching rules as selection: -es removes exactly the tracks that es would select. Without it, -es also removes es-419 and es-ES. - Tracks with no language tag are never excluded.
- unshackle rejects
-all. Name the languages you do not want instead. - The comma form is the documented style.
-sl -es also works, but a shell can read a lone -es as another option.
"},{"location":"guide/downloading/#sort-order","title":"Sort order","text":"-l and -sl 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:
unshackle.yamlaudio:\n language_priority: [orig, en]\nsubtitle:\n group_by: language\n language_priority: [en, es, fr]\n
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.
See subtitle.language_priority for the details.
"},{"location":"guide/downloading/#exact-vs-fuzzy-matching","title":"Exact vs fuzzy matching","text":"By default language matching is fuzzy: -l en also accepts en-US, en-GB, and the other regional forms (up to a small distance). Pass --exact-lang when only an exact match is acceptable: with it, -l es-419 selects only es-419, not es-ES.
The all and best tokens
For audio, the tokens all and best bypass the usual one-track-per-language pick and instead select the best track for each language present. For subtitles, all keeps every subtitle language.
"},{"location":"guide/downloading/#subtitles","title":"Subtitles","text":""},{"location":"guide/downloading/#selecting-subtitle-languages","title":"Selecting subtitle languages","text":"-sl / --s-lang sets the wanted subtitle language(s). The default is all, so unshackle downloads every available subtitle language.
Only English and Spanish subtitlesunshackle dl -sl en,es EXAMPLE 81234567\n
To keep the default and drop one language, use the - prefix described in Excluding languages. -sl all,-es keeps every subtitle language except Spanish, forced Spanish subtitles included.
"},{"location":"guide/downloading/#requiring-subtitles","title":"Requiring subtitles","text":"--require-subs takes a list of languages that must exist. If any is missing, the title fails, even under --best-available / --warn-only. Use it when a download is only worth keeping if a specific subtitle track is present.
It gates the title. It does not select tracks: --s-lang still decides what to keep, and it defaults to all:
# 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
"},{"location":"guide/downloading/#requiring-audio-and-video-languages","title":"Requiring audio and video languages","text":"--require-audio and --require-video take a list of languages that must exist. If one is missing, the title fails, even under --best-available / --warn-only. Like --require-subs, they gate the title without selecting tracks: -l / -al / -vl still decide what unshackle downloads.
This matters most with -l best or -l all, which accept whatever the service offers and so never report a missing language on their own:
# 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
The check runs against the full track list, before any language selection or exclusion. orig resolves to the title language, and --exact-lang applies. Audio carried inside the video track counts. --no-audio and --no-video drop the matching requirement.
"},{"location":"guide/downloading/#forced-subtitles-and-output-format","title":"Forced subtitles and output format","text":" -fs / --forced-subs: include forced subtitle tracks (signs/foreign dialogue). Without this flag, unshackle drops forced subtitle tracks from the selection. -fsl / --forced-s-lang: keep forced subtitles only in these languages (implies -fs). Works independently of --s-lang, so -sl all -fsl en grabs every full subtitle but only the English forced track. It accepts exclusions too: -fsl all,-es keeps every forced subtitle except the Spanish one, and -fsl -es means the same. -fso / --forced-subs-only: keep only the forced subtitle tracks and drop every other subtitle (implies -fs). --s-lang and -fsl still select the languages. --sub-format: set the output subtitle format, converting only when necessary. Accepts codec names/values and common aliases (srt, vtt, ass, ssa, ttml, and the other codec aliases), or the literal original to keep the source format.
Value Format SRT / srt SubRip VTT / vtt WebVTT ASS / ass Advanced SubStation Alpha SSA / ssa SubStation Alpha TTML / ttml Timed Text Markup original Keep the source format, no conversion Convert subtitles to SRTunshackle dl --sub-format srt EXAMPLE 81234567\n
SDH stripping happens by default
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 subtitle.strip_sdh config option controls this behaviour (default on).
"},{"location":"guide/downloading/#selecting-episodes-and-tracks","title":"Selecting episodes and tracks","text":"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.
"},{"location":"guide/downloading/#wanted-ranges","title":"Wanted ranges","text":"-w / --wanted accepts season and episode ranges, comma-separated. Prefix a token with - to exclude it. For a music release, the same option takes track numbers. Read music tracks below.
Whole seasonsSpecific episodesExclusionsSplit episodesAir dates unshackle dl -w S01 EXAMPLE 81234567\nunshackle dl -w S01-S03 EXAMPLE 81234567\nunshackle dl -w S01,S03,S05 EXAMPLE 81234567\n
unshackle dl -w S01E01 EXAMPLE 81234567\nunshackle dl -w S01E01-S01E05 EXAMPLE 81234567\nunshackle dl -w S01E01-S02E03 EXAMPLE 81234567\n
# Seasons 1 through 5, but not season 3\nunshackle dl -w S01-S05,-S03 EXAMPLE 81234567\n
# 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
# 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
"},{"location":"guide/downloading/#music-tracks","title":"Music tracks","text":"-w 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 {disc}x{track} 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.
TracksMore than one discExclusions # 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
# 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
# Tracks 1 through 8, but not track 4\nunshackle dl -w 1-8,-4 EXAMPLE 81234567\n
Read the track list first
--list-titles prints the release with its disc and track numbers, so you can see which numbers to give -w.
"},{"location":"guide/downloading/#daily-and-date-based-content","title":"Daily and date-based content","text":"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 Show.YYYY.MM.DD instead of SxxExx, the {date} token holds the ISO date, and the season folder becomes the year.
A service that only carries this kind of title sets DAILY = True on its class, and a service can set air_date on each episode itself. Add --daily to mark any other title as date-based:
unshackle dl --daily --tvdb 73871 --enrich EXAMPLE 81234567\n
With --enrich and a TVDB ID, --daily 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 --enrich unshackle has no source to fill from, and says so.
A dated episode answers to its air date in -w, as well as to its SxxExx token. A date token is a plain ISO date (2026-08-11). A date range uses a colon (2026-08-01:2026-08-31), 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 SxxExx tokens in one -w.
"},{"location":"guide/downloading/#split-episodes","title":"Split episodes","text":"A few services split one episode into several separately playable videos. Where a service reports that, add .N after the episode to pick one part.
Token Selects S01E01 All parts of episode 1. S01E01.2 Part 2 of episode 1, and nothing else. S01E01.1-S01E01.3 Parts 1 to 3 of episode 1. S01,-S01E01.2 All of season 1 except episode 1 part 2. Parts 1 and 3 are kept. A season token such as S01 covers every episode and every part, so you only need .N when you want a part on its own.
A part range stays inside one episode
S01E01.1-S01E01.3 is valid. unshackle rejects S01E01.1-S01E02.3, 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: -w S01E01.2,S01E02.1.
A part of an unsplit episode selects nothing
-w S01E02.2 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 --list-titles to see which episodes carry parts.
"},{"location":"guide/downloading/#other-selection-flags","title":"Other selection flags","text":"Flag Behaviour --select-titles Interactively pick episodes of a series, or films when a title has more than one. Cannot combine with -w. --latest-episode Download only the single most recent episode. --latest-episodes N 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. --list-titles List every title the service returned, then stop. -w, --latest-episode and --latest-episodes are not applied to this listing. When --latest-episode or --latest-episodes is set, -w has no effect.
Grab just the newest episodeunshackle dl --latest-episode EXAMPLE 81234567\n
Grab the three newest episodesunshackle dl --latest-episodes 3 EXAMPLE 81234567\n
"},{"location":"guide/downloading/#including-and-excluding-track-types","title":"Including and excluding track types","text":"You can restrict a download to certain track categories, either positively (only these) or negatively (everything but these).
Only these types (*-only flags):
-V / --video-only -A / --audio-only -S / --subs-only -C / --chapters-only
Skip these types (no-* flags):
-nv / --no-video -na / --no-audio -ns / --no-subs -nc / --no-chapters -nt / --no-attachments (cover art, subtitle fonts, and files the service attaches)
Additional track-type flags:
-ad / --audio-description: include descriptive (audio-description) tracks, which unshackle drops by default. -ado / --audio-description-only: keep only the descriptive tracks and drop the standard audio. It does not need -ad. Add -A to download no video or subtitles. --skip-subtitle-errors: if a subtitle fails to download, skip it and continue rather than aborting the whole title. Video and audio failures remain fatal.
The -only kind flags
-ado and -fso each keep one kind of track inside its track type. They do not drop the other track types: -ado still downloads the video, and -fso still downloads video and audio. Add -A or -S for that.
- The language flags still apply. With the default
-l orig, -ado fails when the descriptive track is not in the original language. Select the language with -al. - A flag that drops the same tracks is an error, for example
-ado with --no-audio or -fso with -A. - 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.
- 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.
Audio description only, in Englishunshackle dl -A -ado -al en EXAMPLE 81234567\n
Subtitles onlyunshackle dl -S -sl en EXAMPLE 81234567\n
Everything except chaptersunshackle dl -nc EXAMPLE 81234567\n
Note
You can combine an *-only flag with no-* flags to fine-tune: *-only chooses the starting set of categories, then no-* subtracts from it. Attachments (for example fonts) are always kept.
"},{"location":"guide/downloading/#listing-and-dry-runs","title":"Listing and dry runs","text":"Before committing to a long download, inspect what unshackle would do:
Flag Effect --list List the tracks the service exposes for each title, then stop. No selection, no download. --list-titles List every title the service returned, then stop. -w, --latest-episode and --latest-episodes are not applied to this listing. --skip-dl Skip downloading but still acquire the decryption keys. --all-drm License each track with both Widevine and PlayReady. See Widevine and PlayReady on the same title. See the track selection without downloadingunshackle dl -q 1080 -v H.265 -r HDR10 --list EXAMPLE 81234567\n
"},{"location":"guide/downloading/#output-and-muxing","title":"Output and muxing","text":""},{"location":"guide/downloading/#output-location-and-folders","title":"Output location and folders","text":" -o / --output: override the output directory for this run (otherwise unshackle uses the configured downloads directory). --no-folder: do not make a per-show folder for TV downloads. --no-source: remove the service source tag from the filename and path.
Send this download somewhere specificunshackle dl -o ~/Videos/incoming EXAMPLE 81234567\n
"},{"location":"guide/downloading/#muxing-behaviour","title":"Muxing behaviour","text":"By default, mkvmerge muxes the tracks of a movie or an episode into a single Matroska (.mkv) file. These flags change how unshackle assembles the output:
Flag Behaviour Default source --no-mux Do not mux; keep the individual track files. - --sample Download a short sample: 60 seconds from 2 minutes in, or --sample START-END for a window in seconds. - --include-sample Download the full title, then also cut a 60 second sample from each muxed file into a Sample folder. - --split-audio Write a separate output file per audio codec instead of merging all audio. config muxing.merge_audio (on) --merge-video Mux video tracks that share a height, range, and codec into one file, so only language varies inside a file. config muxing.merge_video (off) --sample needs a segmented track
--sample downloads only the segments that hold the window, and mkvmerge 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.
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.
A sidecar subtitle file with sidecar_format: original is not trimmed. It holds the segments around the window, or the whole file when the track is one file.
Music is never muxed
A song skips the muxer. unshackle keeps the container that the service delivered, such as .flac, .m4a, or .mp3, and writes the metadata into that file. Read Music output files.
"},{"location":"guide/downloading/#after-the-download","title":"After the download","text":"--postscript \"<command>\" runs your own command once per output file, with unshackle's metadata substituted into {variable} placeholders. It is repeatable, and it replaces the post_scripts config for that run. No success post-script operates under --no-mux, because that run writes no muxed output. A failure post-script still operates if the download fails.
Hand each finished file to an uploaderunshackle dl --postscript \"python /opt/upload.py {filepath} --service={service}\" EXAMPLE 81234567\n
--no-postscript operates the run with no post-script at all. It silences the post_scripts config and --postscript together, for every event and mode.
Skip the uploader for one rununshackle dl --no-postscript EXAMPLE 81234567\n
For post-scripts that continue across runs, for the season and run modes, for failure post-scripts and for the full variable list, see Post-scripts.
"},{"location":"guide/downloading/#naming-tags","title":"Naming tags","text":" --tag: set the release group tag (overrides the configured tag). --repack: add a REPACK tag to the output filename.
Custom group tag and a REPACK labelunshackle dl --tag MYGRP --repack EXAMPLE 81234567\n
"},{"location":"guide/downloading/#proxies","title":"Proxies","text":"--proxy accepts a full proxy URI, a country or location code (resolved through your configured proxy providers), or a provider:region form. See Proxies & VPN for the exact grammar.
Proxy formsunshackle 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
Three related flags:
--no-proxy: force-disable all proxy use for this run. --no-proxy-download: 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. --proxy-download: use a different proxy for all downloads. The manifest, license, and authentication requests still go through --proxy. Takes the same forms as --proxy.
"},{"location":"guide/downloading/#performance-and-caching","title":"Performance and caching","text":"Flag Purpose --workers N Threads used per track for segment downloads. Default depends on the downloader. --adaptive-workers Opt-in: start the per-track worker count at --workers, reduce it when the CDN returns errors, then raise it again while the extra workers add measured throughput. The count never goes above --workers. Off by default (fixed worker count). --download-processes N Opt-in: split a large segment batch across N download processes, each with its own worker pool. A single process tops out around 1.3 Gb/s (Python interpreter limit); 2 reaches 2.5GbE line rate on fast CDNs. Only engages for batches of 24+ segments. Ignored while --speed-limit (or serve's global_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. The download stays in a single process instead of running with the wrong settings. Default 1. --continue-downloads 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 continue_downloads config option, which documents what can and cannot resume. --downloads N Number of tracks downloaded concurrently. Default 1. --slow [MIN-MAX] Add a delay between titles to look more like a real device. --slow alone means 60-120s; --slow 20-40 sets a custom range. Minimum 20s. --no-cache Bypass the title cache for this download. --reset-cache Clear the title cache before fetching. Two tracks at a time, eight threads eachunshackle dl --downloads 2 --workers 8 EXAMPLE 81234567\n
Space out a season downloadunshackle dl -w S01 --slow 30-60 EXAMPLE 81234567\n
"},{"location":"guide/downloading/#keys-vaults-and-export","title":"Keys, vaults, and export","text":"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:
--cdm-only: only use the CDM (skip vaults). Over a server_cdm 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. --cdm <name>: use the named CDM device for this run, ignoring the cdm config mapping (including its quality and Widevine/PlayReady sub-entries). Over --remote, that device licenses the remote session, not the server CDM. --vaults-only: only use key vaults and never license through the CDM. A missing content key fails.
Fetch keys only, no downloadunshackle dl --skip-dl EXAMPLE 81234567\n
--export writes a mediaexport 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. unshackle import 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 version: 2 files and unidl's own export files.
Export track info and keysunshackle dl --skip-dl --export EXAMPLE 81234567\n
Add --all-drm 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 --cdm-only to send a challenge for each DRM system.
License with Widevine and PlayReady, no downloadunshackle dl --skip-dl --all-drm --export EXAMPLE 81234567\n
The file name tells what the file holds, in the form {title}.{scope}.{resolutions}.{codecs}.{ranges}.{manifests}.{audio}-{SERVICE}.json:
Export File name A movie Example.Movie.2024.1080p.h264.sdr.hls.aac2.0-EXAMPLE.json A whole season Example.Show.S01.2160p.h265.sdr.hdr10.dash.dd5.1-EXAMPLE.json Episodes 5 to 9 and 12 Example.Show.S01E05-E09.S01E12.1080p.h264.sdr.dash.aac2.0-EXAMPLE.json - A dot separates each part and each word of the title. The name has no spaces or underscores. It does not follow your
output_template: a template with spaces does not change the export name. - The scope is
S01 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 S01-S03. After three parts, +N counts the parts left out. A movie has no scope. - The quality parts come from the video and audio tracks selected for the titles in the file. Each value shows once.
- 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.
- When another file already has the name, unshackle adds
-2, -3, and so on. It never writes over another export.
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.
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 -a AAC,EC3 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, orig has no value: select the languages with -l and -vl.
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.
The export file is a secret
It holds the content keys and usually a signed manifest URL. Hand it over on purpose, not by accident.
The mediaexport package specifies the mediaexport format and is the reader and writer unshackle uses.
Region is recorded only with a proxy
When you use --proxy, the export records the region so an import can reproduce the correct geofence. Without a proxy, the export stores no region.
Some DASH and Smooth exports need a title language
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 Title.language 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.
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.
"},{"location":"guide/downloading/#metadata-and-tagging","title":"Metadata and tagging","text":"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 --enrich. Give at most one of --tmdb, --imdb and --tvdb, and unshackle works the rest out from it. To stop the automatic lookups but keep the IDs you give, set disable_metadata in your config.
Flag Example Purpose --tmdb --tmdb 27205 Use this TMDB ID instead of an automatic search. Needs tmdb_api_key. --imdb --imdb tt1375666 Use this IMDb ID instead of an automatic search. Needs no API key. --tvdb --tvdb 73871 Use this TVDB ID instead of looking the series up. Needs tvdb_api_key. --anilist --anilist 21 Use this AniList ID instead of an automatic search. mal:12345 is also accepted. Needs no API key. --enrich - Overwrite the show title, year and original language with the external source's. Requires one of --tmdb, --imdb, --tvdb, or --anilist. --tvdb-order --tvdb-order dvd Renumber episodes to a TVDB season order. Needs tvdb_api_key. Force the right IMDb match, and keep the service's own namingunshackle dl --imdb tt1375666 EXAMPLE 81234567\n
Force the match and take IMDb's title, year and language toounshackle dl --imdb tt1375666 --enrich EXAMPLE 81234567\n
"},{"location":"guide/downloading/#what-each-metadata-provider-supplies","title":"What each metadata provider supplies","text":"Metadata providers differ in what they answer with, so the fields --enrich can replace depend on which ID you gave. Every metadata provider except imdb and anilist only operates when you set its config key:
Provider Config key Title and year Original language External IDs it returns TMDB tmdb_api_key yes yes, alpha-2 such as ko IMDb, TMDB, TVDB TVDB tvdb_api_key yes yes, alpha-3 such as kor TMDB, TVDB, sometimes IMDb OMDb omdb_api_key yes yes, as an English name such as Korean IMDb IMDb (no config key needed) yes yes, alpha-2 such as ko IMDb SIMKL simkl_client_id 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 ja AniList Whatever the tag looks like, unshackle normalises it before use, so ko, kor and Korean all end up as the same language.
AniList only answers for anime
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 anilist earlier in metadata_providers if you mostly download anime. anilist_title_language sets which of the three AniList title variants unshackle uses.
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.
Each ID goes to the providers that read that kind of ID, in metadata_providers order:
--tmdb reads TMDB. --imdb 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. --tvdb reads TVDB. It needs tvdb_api_key. --anilist 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 --tmdb, --imdb or --tvdb when you want those tags as well.
Give one of --tmdb, --imdb and --tvdb. 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. --anilist is the exception and still pairs with one of the three, which is how you tag an anime title with a western ID.
The ID you give must have a metadata provider that can find it, so unshackle makes sure of that before it downloads anything. --tmdb without tmdb_api_key, or an ID whose metadata providers your metadata_providers list leaves out, fails immediately with a message naming what to set. --imdb needs no API key, because the imdb metadata provider is keyless and in the default order.
With --enrich, 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.
--enrich 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 {absolute} naming variable. --enrich never changes the season and episode numbers.
With --daily, --enrich also fills in the air date of each episode from TVDB. See Daily and date-based content.
--enrich replaces the original language, which affects more than the filename
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 --enrich, unshackle keeps the service's own value and does not change track selection.
"},{"location":"guide/downloading/#episode-ordering","title":"Episode ordering","text":"A service does not always number a series the way TVDB's aired order does. Some services use TVDB's alternate (Streaming) order for Futurama, for example, while TVDB's official order holds back four season-one episodes to the start of season two. --tvdb-order works out which order the service used, then renumbers the episodes into the order you asked for:
Download Futurama in DVD orderunshackle dl --tvdb-order dvd EXAMPLE 81234567\n
Available orders are official (aired), dvd, absolute, alternate, and regional. Set tvdb_order in your config to apply one by default.
Orders that do not cover the whole series
An order can leave out episodes the service carries. TVDB's dvd 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.
"},{"location":"guide/downloading/#configuration-defaults","title":"Configuration defaults","text":"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 dl: block and per-service overrides.
Explicit flags always win
A value you pass on the command line (or through an environment variable) always takes precedence over both the global dl: defaults and any per-service dl: overrides. Config only fills in options you did not set explicitly.
"},{"location":"guide/downloading/#quick-reference","title":"Quick reference","text":"A condensed lookup of the most-used options. Use unshackle dl --help for the complete, authoritative list.
Flag Short Meaning --quality -q Target resolution(s), e.g. 1080,720. --vcodec -v Video codec(s). --acodec -a Audio codec(s). --range -r Colour range(s). Default SDR. --channels -c Audio channel layout. --noatmos -naa Exclude Atmos audio. --lang -l Video + audio language(s); default orig. - excludes, e.g. all,-es. --a-lang -al Audio-only language override. - excludes. --v-lang -vl Video-only language override. - excludes. --s-lang -sl Subtitle language(s); default all. - excludes, e.g. all,-es. --forced-subs -fs Include forced subtitles. --forced-s-lang -fsl Forced subtitle language(s); implies -fs. - excludes. --sub-format Output subtitle format. --wanted -w Episode/season range, an air date, or a track number for a music release (1-5, 2x3). --daily Fill missing air dates from TVDB during --enrich. --select-titles Interactively pick episodes or films. --latest-episode Only the newest episode. --latest-episodes N Only the N newest episodes. --video-only / --audio-only / --subs-only -V / -A / -S Restrict track types. --no-video / --no-audio / --no-subs / --no-chapters / --no-attachments -nv / -na / -ns / -nc / -nt Skip track types. --worst Lowest bitrate within -q. --require-audio Audio languages that must exist. The title fails if one is missing. --require-video Video languages that must exist. The title fails if one is missing. --best-available Degrade gracefully instead of failing. --output -o Output directory for this run. --split-audio / --merge-video / --no-mux Muxing behaviour. --postscript / --no-postscript Run a command after each output file, or run none. --proxy / --no-proxy / --no-proxy-download / --proxy-download Proxy control. --workers / --downloads / --slow Concurrency and pacing. --list / --list-titles / --skip-dl Dry runs. --cdm-only / --vaults-only Content key source control. --cdm <name> Pin one CDM device, bypassing the cdm config mapping. --export Export track info and keys to JSON. --tmdb / --imdb / --tvdb / --anilist / --enrich Metadata overrides. --tvdb-order Renumber episodes to a TVDB season order."},{"location":"guide/drm-and-cdm/","title":"DRM & CDM Setup","text":"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.
Who this page is for
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.
"},{"location":"guide/drm-and-cdm/#key-concepts","title":"Key concepts","text":"Before configuring anything, it helps to know the vocabulary. unshackle draws a firm line between two things:
- 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.
- 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.
A handful of other terms show up throughout:
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. 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.
"},{"location":"guide/drm-and-cdm/#supported-drm-systems","title":"Supported DRM systems","text":"unshackle implements five DRM systems. Only the first two need a device file and a license-server handshake. The rest are special cases.
System Device file License flow Decryption Widevine (Google) .wvd CDM challenge \u2192 license server \u2192 CDM parses \u2192 keys shaka-packager / mp4decrypt PlayReady (Microsoft) .prd CDM challenge (WRM header) \u2192 license server \u2192 CDM parses \u2192 keys shaka-packager / mp4decrypt ClearKey (CENC), W3C EME org.w3.clearkey none JSON {\"kids\":[...],\"type\":\"temporary\"} \u2192 license server returns a JWK Set. No CDM. shaka-packager / mp4decrypt ClearKey (HLS), AES-128 EXT-X-KEY none Key fetched directly from a URI or data: URL. No CDM, no challenge. in-process AES-CBC MonaLisa (proprietary, WASM) .mld Ticket from the service API; keys extracted locally via WASM. No license server. ML-Worker binary + AES-ECB, per segment Two different ClearKeys
\"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 EXT-X-KEY tag references, and unshackle decrypts it in-process. The CENC variant is the W3C EME org.w3.clearkey scheme. It delivers keys as a JWK Set, and shaka-packager or mp4decrypt decrypts it like Widevine. Neither involves a device file.
"},{"location":"guide/drm-and-cdm/#widevine-vs-playready","title":"Widevine vs PlayReady","text":"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:
- Device file: Widevine uses a
.wvd. PlayReady uses a .prd. - 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).
To download a Widevine-protected title you need a .wvd device. For PlayReady you need a .prd device. You can hold both, and unshackle automatically selects the appropriate one for each track.
Obtaining device files
A .wvd or .prd 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 wvd and prd commands below manage and provision device files once you have the raw cryptographic material.
"},{"location":"guide/drm-and-cdm/#providing-a-device-with-the-wvd-and-prd-commands","title":"Providing a device with the wvd and prd commands","text":"Device files live in dedicated directories, by default:
Kind Default directory Widevine .wvd data/WVDs PlayReady .prd data/PRDs You can move these with the directories section of your unshackle.yaml:
unshackle.yamldirectories:\n wvds: /home/george/unshackle-data/WVDs\n prds: /home/george/unshackle-data/PRDs\n
"},{"location":"guide/drm-and-cdm/#widevine-devices-the-wvd-command","title":"Widevine devices: the wvd command","text":"The wvd command group manages .wvd files.
Add an existing deviceInspect a deviceCreate from raw materialDelete / dump $ unshackle wvd add ./nexus_6p.wvd\n
unshackle validates the file and moves it into the WVDs directory. You can add several at once by passing multiple paths.
$ unshackle wvd parse nexus_6p\n
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.
$ unshackle wvd new \"Nexus 6P\" ./private_key.pem ./client_id.bin ./vmp.bin -t ANDROID -l 3\n
Builds a .wvd from a PEM private key, a Client ID blob, and an optional FileHashes (VMP) blob. -t/--type is the device type (default Android) and -l/--level is the security level 1 to 3 (default 1). The VMP argument is optional.
$ unshackle wvd delete nexus_6p\n$ unshackle wvd dump nexus_6p ./out\n
delete removes a device (with a confirmation prompt). dump extracts a device's contents (metadata, private key, Client ID, VMP) into a folder.
v1 WVD files must be migrated
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:
$ pywidevine migrate --help\n
"},{"location":"guide/drm-and-cdm/#playready-devices-the-prd-command","title":"PlayReady devices: the prd command","text":"The prd command group creates and maintains .prd files.
Create a new deviceReprovisionTest against Microsoft's demo server $ unshackle prd new ./zgpriv.dat ./bgroupcert.dat\n
Provision a new device from a group key and group certificate. You can instead point at a single folder that contains zgpriv.dat and bgroupcert.dat:
$ unshackle prd new ./device_folder/\n
unshackle makes a fresh leaf certificate and writes the device to the PRDs directory (or to -o/--output). Use -e/--encryption_key and -s/--signing_key to supply your own ECC keys instead of generating them.
$ unshackle prd reprovision ./data/PRDs/mydevice.prd\n
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).
$ unshackle prd test ./data/PRDs/mydevice.prd -sl 2000 -c aesctr\n
Runs a full challenge/license/keys cycle against Microsoft's public PlayReady test server and prints the returned keys, confirming the device works. -sl/--security-level accepts 150, 2000, or 3000 (default 2000). -c/--ckt accepts aesctr or aescbc.
"},{"location":"guide/drm-and-cdm/#selecting-which-device-to-use-the-cdm-config","title":"Selecting which device to use: the cdm config","text":"A device on disk is not enough. You must tell unshackle which device to use for which service. That is the job of the cdm section, which maps a service tag to a device name (the file's name without extension). A default entry acts as the fallback:
unshackle.yamlcdm:\n default: nexus_6p_26830_l3\n EXAMPLE1: chromecdm_l3\n EXAMPLE2: sm_g935f_l1\n
Lookups are case-insensitive.
The device name is the file name
A device named chromecdm_l3 in the config resolves to chromecdm_l3.wvd in the WVDs directory (or chromecdm_l3.prd in the PRDs directory). It may also be the name of a remote CDM defined in remote_cdm. See Remote CDMs below.
"},{"location":"guide/drm-and-cdm/#advanced-selection-by-quality-drm-or-profile","title":"Advanced selection: by quality, DRM, or profile","text":"Instead of a plain name, a cdm 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.
By qualityBy DRM systemBy profile unshackle compares each config key against the video height. You can use exact heights or comparisons (>=1080, >720, <=576, <480). The most specific one wins.
cdm:\n SOMESERVICE:\n \">=1080\": sm_g935f_l1\n default: chromecdm_l3\n
Keys widevine and playready select a device per system. unshackle applies these automatically, using the widevine device for Widevine tracks and the playready device for PlayReady tracks.
cdm:\n SOMESERVICE:\n widevine: sm_g935f_l1\n playready: mydevice_sl3\n
unshackle compares each config key against the active profile, with a default fallback.
cdm:\n SOMESERVICE:\n premium: sm_g935f_l1\n default: chromecdm_l3\n
"},{"location":"guide/drm-and-cdm/#local-vs-remote-cdms","title":"Local vs remote CDMs","text":"A CDM can operate in two places:
- A local CDM loads a
.wvd or .prd device from your machine and performs the challenge/license/keys handshake locally. This is what the cdm mapping above resolves to by default. - 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.
The device name in your cdm mapping resolves to a remote CDM whenever it matches the name of an entry in the remote_cdm list. Otherwise it falls back to a local .prd/.wvd file of that name.
"},{"location":"guide/drm-and-cdm/#remote-cdms","title":"Remote CDMs","text":"You declare remote CDMs as a list under remote_cdm. Each entry has a name (which you then reference from the cdm mapping) and a shape that depends on its type. There are four kinds.
"},{"location":"guide/drm-and-cdm/#widevine-remote-cdm-pywidevine-serve","title":"Widevine remote CDM (pywidevine serve)","text":"With no type field and a non-PlayReady device type, unshackle treats the entry as a standard pywidevine \"serve\" endpoint:
unshackle.yamlremote_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
security_level defaults to 3000 if omitted. unshackle reads field names case-insensitively, so Device Type/device_type, System ID/system_id, and the other field names are all accepted.
"},{"location":"guide/drm-and-cdm/#playready-remote-cdm","title":"PlayReady remote CDM","text":"If the device type is PLAYREADY, unshackle routes the entry to the pyplayready remote CDM:
unshackle.yamlremote_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
The host must end in /playready
For a PlayReady remote CDM the host URL has to include the trailing /playready path segment (e.g. https://cdm.example.com/playready). pyplayready's RemoteCdm treats host 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 404 responses from the server rather than an obvious configuration error.
A pywidevine or pyplayready serve API can operate behind a reverse proxy or a CDN. Refer to Serve APIs behind a proxy.
"},{"location":"guide/drm-and-cdm/#decrypt-labs-hosted-keyxtractor-api","title":"Decrypt Labs (hosted KeyXtractor API)","text":"Set type: decrypt_labs to use Decrypt Labs' hosted KeyXtractor service, which includes an intelligent key-caching layer:
unshackle.yamlremote_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
unshackle sends the API key as the decrypt-labs-api-key header. If you do not write secret on the entry, unshackle falls back to the global decrypt_labs_api_key value. If neither is present it raises an error. The host defaults to https://keyxtractor.decryptlabs.com. PlayReady devices (SL2/SL3) default to security level 2000/3000 respectively. Widevine devices default to system_id: 26830, security_level: 3.
"},{"location":"guide/drm-and-cdm/#custom-api-custom_api","title":"Custom API (custom_api)","text":"For an arbitrary CDM HTTP API, type: custom_api provides a fully configurable client that adapts to almost any request/response shape through YAML alone. A minimal example:
unshackle.yamlremote_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
The custom_api type supports much more: request/response field remapping, transforms (base64/hex/JSON encoding, kid:key 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.
Developer: full custom_api schema
A custom_api entry accepts these sub-objects:
device (name, type, system_id, security_level) auth (type of header/bearer/basic with the matching credential fields, plus custom_headers) endpoints (get_request and decrypt_response, each {path, method, timeout}) - per-endpoint
request_mapping (param_names, static_params, conditional_params, transforms, nested_params, exclude_params) and response_mapping (fields, transforms, response_types, success_conditions, error_fields, key_fields) caching (enabled, use_vaults, check_cached_first) legacy and timeout
unshackle infers PlayReady mode when device.type == PLAYREADY or the device name is SL2/SL3.
"},{"location":"guide/drm-and-cdm/#decryption-backends","title":"Decryption backends","text":"Once unshackle knows the content keys, one of two external tools decrypts the encrypted file (for Widevine, PlayReady, and ClearKey-CENC):
- shaka-packager is the default.
- mp4decrypt is part of the Bento4 tools.
Both must be discoverable in unshackle's bundled binaries/ directory, the binaries folder of your user data directory, or on your PATH. 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.
You choose the backend with the decryption config key. It can be a single value applied globally, or a per-service mapping:
Global defaultPer service unshackle.yamldecryption: shaka\n
unshackle.yamldecryption:\n default: shaka\n SOMESERVICE: mp4decrypt\n
How the value is interpreted
The default is shaka. Only the exact value mp4decrypt selects mp4decrypt. Anything else (including shaka) selects shaka-packager. Per-service lookups are case-insensitive, with the default/DEFAULT entry used as the fallback.
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 mp4decrypt if you find a track that shaka-packager cannot decrypt.
ClearKey (HLS) does not use these tools
unshackle decrypts an HLS AES-128 ClearKey title in-process with AES-CBC, and ignores the decryption setting entirely. You do not need to configure anything.
"},{"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":"When an HLS playlist references a content key with an EXT-X-KEY tag, unshackle fetches the content key directly (from the given URI or an inline data: 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.
"},{"location":"guide/drm-and-cdm/#clearkey-over-cenc-w3c-eme-orgw3clearkey","title":"ClearKey over CENC (W3C EME org.w3.clearkey)","text":"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:
{\"kids\": [\"<base64url-kid>\", ...], \"type\": \"temporary\"}\n
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 decryption setting applies.
"},{"location":"guide/drm-and-cdm/#widevine-and-playready-on-the-same-title","title":"Widevine and PlayReady on the same title","text":"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 cdm mapping. If it cannot find a matching device, it fails with a clear message such as:
Title needs a Widevine CDM but SOMESERVICE is configured with PlayReady.\n
Use the cdm mapping's DRM-based selection to configure a device for each system. unshackle selects the right one per track automatically.
"},{"location":"guide/drm-and-cdm/#license-both-systems-with-all-drm","title":"License both systems with --all-drm","text":"By default a track licenses with one DRM system. --all-drm gets the content keys for Widevine and for PlayReady on each track that offers both. Use it with --skip-dl and --export 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.
unshackle dl --skip-dl --all-drm --export EXAMPLE 81234567\n
- The
cdm mapping must name a device for each system. A single device name, or --cdm, stops the run with an error that names the missing system. - The order of the
widevine and playready config keys in the cdm 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. - 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.
- With
--cdm-only, unshackle does not read the Key Vaults, and each DRM system sends one challenge for a set of KIDs in a run. - 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.
- If one DRM system does not license, the title fails. With
--best-available 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. - 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.
- With
--cdm-only, the service gets a challenge from each DRM system for each set of KIDs. A licence server that limits the request rate can answer 429, and unshackle then tries again.
Where --all-drm licenses one system only
- A service that gets a different manifest for each DRM system. unshackle shows a warning one time when a track offers one system only.
- 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
--best-available. - An HLS playlist that changes its
EXT-X-KEY entries part-way: only the first set licenses with the second system. - A remote session that the server CDM licenses, and
unshackle import. unshackle shows a warning and ignores the flag. - A remote CDM that stores content keys can answer without a challenge to the service.
"},{"location":"guide/drm-and-cdm/#keys-vaults-and-caching","title":"Keys, vaults, and caching","text":"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:
- Keys already known for the current DRM object.
- An in-process cache of content keys, for the current
dl run. - Your configured key vaults.
- Only if still missing, a live license request.
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 dl command:
Flag Effect --vaults-only Never send a license request; use only cached/vault keys. Fails if a content key is missing. --cdm-only Ignore vaults for sourcing keys and always perform a fresh license request. Over a server_cdm remote session the server still reads its own vaults; the flag only skips the client's decode check on the key it gets back. --cdm <name> Use the named CDM device for this run instead of the one the cdm config maps for the service. Over --remote, that device licenses the remote session, not the server CDM. See key vaults for how to configure vault backends.
"},{"location":"guide/drm-and-cdm/#debugging-drm-issues","title":"Debugging DRM issues","text":"A few configuration toggles help when a title will not decrypt:
Config key Default Effect debug false Global debug output. debug_keys false Log decryption keys. debug_requests false Log HTTP requests. unshackle.yamldebug_keys: true\ndebug_requests: true\n
Keys and paths in logs
When you enable key logging, unshackle writes content keys (KID:key pairs) to the logs. Treat those logs as sensitive. The unrelated redact_paths option (default true) masks local directory paths in log output.
"},{"location":"guide/drm-and-cdm/#see-also","title":"See also","text":" - Downloading: the
dl command and its DRM-related flags. - Key vaults: caching content keys across downloads.
- Configuration: the full
unshackle.yaml reference. - Dependencies: installing shaka-packager and mp4decrypt.
"},{"location":"guide/output-and-naming/","title":"Output & Naming","text":"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 {variable} 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.
If you have not configured unshackle.yaml yet, read Configuration File first. Everything below lives in that file.
"},{"location":"guide/output-and-naming/#how-unshackle-assembles-an-output-path","title":"How unshackle assembles an output path","text":"When a download finishes, unshackle builds the final path from three pieces:
<output directory> / <folder template> / <filename template><extension>\n
- Output directory:
directories.downloads from your config, or whatever you pass to -o/--output on the command line for a single run. - 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
movies folder template, or a single-string folder template that applies to all title kinds (see Folder templates). - Filename template: the
output_template for the title kind (movie, series, or song). - Extension: chosen by the muxer for a movie or an episode:
.mkv for video, .mka for audio-only, .mks for subtitle-only, .mp4 for DTS:X Profile 2 audio. unshackle does not mux a song. It remuxes a song into the container of its codec, such as .flac, .opus, or .m4a. Read Music output files.
A typical episode path
/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
The folder name comes from the series folder template and the file from the series output template. Two command-line flags change this layout for a single run:
Flag Effect -o, --output Use this directory instead of directories.downloads. --no-folder Skip the per-title subfolder; write the file directly into the output directory. --no-source Omit the service source tag from both the filename and folder (the {source} variable resolves to empty)."},{"location":"guide/output-and-naming/#output-templates","title":"Output templates","text":"Filename templates live under the output_template config key, keyed by title kind. Each value is a format string built from {variable} placeholders.
unshackle.yamloutput_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
The recognized kinds are:
Kind Applies to Default when unset movies Movies (required for movie downloads to be named, no built-in default) series TV episodes (required for episode downloads to be named) songs Music tracks \"{track_number}. {title}\" albums Album folders only (see below) - Note
movies and series have no hardcoded filename fallback. If you download those title types, define their templates. songs falls back to \"{track_number}. {title}\" when omitted.
"},{"location":"guide/output-and-naming/#required-vs-optional-variables","title":"Required vs. optional variables","text":" {variable}: 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\". {variable?}: optional. A trailing ? marks the variable conditional. When it is empty, unshackle removes the placeholder and one adjacent separator (., -, or space), so the surrounding text collapses cleanly.
Use ? for anything that is not always there
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:
series: \"{title}.{season_episode}.{episode_name?}.{quality}.{hdr?}.{source}-{tag?}\"\n
For an episode with no on-screen name, {episode_name?} and its adjacent dot disappear."},{"location":"guide/output-and-naming/#separator-style-dots-vs-spaces","title":"Separator style (dots vs. spaces)","text":"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.
Scene style (dots)Readable style (spaces) output_template:\n movies: \"{title}.{year}.{quality}.{source}.WEB-DL.{audio_full}.{video}-{tag}\"\n
The.Movie.2024.1080p.EXAMPLE.WEB-DL.DDP5.1.H.264-TAG.mkv\n
output_template:\n movies: \"{title} ({year}) {quality} {source} WEB-DL {audio_full} {video}\"\n
The Movie (2024) 1080p EXAMPLE WEB-DL DDP5.1 H.264.mkv\n
"},{"location":"guide/output-and-naming/#template-variables","title":"Template variables","text":"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.
"},{"location":"guide/output-and-naming/#common-video","title":"Common / video","text":"Variable Meaning Example title Title name (movie/show/song name; $ is rendered as S) The Show title_type Media kind of the title movie, series, music year Release year 2024 source Service tag / class name (empty with --no-source) EXAMPLE quality Resolution with scan suffix 1080p, 2160p, 576i resolution Resolution number only 1080 video Video codec H.264, H.265 hdr Dynamic-range label HDR, HDR10P, DV, DV.HDR, DV.HDR10P, HLG hfr High frame rate marker (frame rate > 30) HFR edition Edition label from the track, if any Directors Cut tag Release-group tag (from config.tag or --tag) TAG repack REPACK when the --repack flag is used REPACK lang_tag Result of your language_tags rules, if configured MULTi How language_tags rules match
unshackle tries the rules in order, but language comparison is fuzzy: a rule condition of en matches en-US, en-GB, and any other en-* form. Within a single rule, all conditions must match (AND logic) for it to apply. The first rule that fully matches wins. If none match, unshackle removes {lang_tag?} from the filename cleanly.
"},{"location":"guide/output-and-naming/#episode-specific","title":"Episode-specific","text":"Variable Meaning Example season Zero-padded season (S%02d) S01 episode Zero-padded episode (E%02d) E05 season_episode Combined S01E05 episode_name Episode title Pilot part Part index of a split episode, empty otherwise 2 absolute Absolute episode number, zero-padded to 3 digits, empty when unknown 007 date ISO air date, empty when the episode has none 2024-06-01 Daily & sports content
When an episode has an air date, unshackle switches to date-based naming automatically. season and season_episode become the formatted air date, unshackle clears episode and year, and {date} holds the ISO date. The date's internal separator (dots or spaces) follows your series template style.
"},{"location":"guide/output-and-naming/#split-episodes","title":"Split episodes","text":"A few services split one episode into several separately playable videos. Where a service reports that, unshackle folds the part index into {episode} and {season_episode}, so the stock series template names it with no change to your config.
Show.Name.S01E01.Part.2.1080p.EXAMPLE.WEB-DL.DDP5.1.H.264-TAG.mkv\n
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 S01E01 Part 2 instead.
The part is left out of the folder name, so every part of an episode lands in the same season folder:
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
The same holds for a folder template of your own: {season} never picks up the part, and {season_episode} drops it inside a folder template. unshackle names an episode with no part like any other episode.
What media servers do with the part token
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.
For custom templates there is also a standalone {part} variable. You rarely want it, see the caveat on that page.
"},{"location":"guide/output-and-naming/#audio","title":"Audio","text":"Variable Meaning Example audio Audio codec DDP, DD, AAC, DTS-X audio_channels Channel layout; bed.LFE.heights when the track has height channels 5.1, 2.0, 5.1.4 audio_full Codec + channels combined DDP5.1, DTS-X.5.1.4 atmos Atmos when any track carries JOC Atmos dual DUAL for two audio languages (see dual_multi_mode) DUAL multi MULTi for more than two audio languages MULTi dubbed DUBBED for a single audio language that is not the original (strict mode only) DUBBED"},{"location":"guide/output-and-naming/#music-specific","title":"Music-specific","text":"Variable Meaning track_number Zero-padded track number artist / album_artist Artist / album artist (falls back to artist) album Album name disc Disc number (only shown when greater than 1) track_total / disc_total Totals release_type album, single, ep, or another type the service supplies genre Genre explicit Explicit when flagged isrc / upc / label ISRC, UPC and record label Unknown variables are ignored, not errors
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 {quailty} stays in the filename literally, or unshackle drops it. unshackle does not fill it in.
"},{"location":"guide/output-and-naming/#folder-templates","title":"Folder templates","text":"Folder templates sit under a special folder config key inside output_template. 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.
Single folder templatePer-kind folder templates unshackle.yamloutput_template:\n movies: \"{title}.{year}.{quality}.{source}-{tag}\"\n series: \"{title}.{season_episode}.{quality}.{source}-{tag}\"\n folder: \"{title}.{year}\"\n
unshackle.yamloutput_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
The per-kind folder config keys are movies, series, songs, and albums. Any other config key gives a startup warning. Folder templates permit path separators (/ or \\). unshackle formats each segment independently, so you can assemble nested directory structures like Show/Season 01. unshackle reads the separator style from the whole template, so it spaces every segment alike.
Fallback behaviour:
- A per-kind folder template wins if present. If there is none, unshackle uses the single
folder string. If there is no folder string either, unshackle falls back to a built-in default. - Built-in defaults when no folder template is set. Movies get no folder at all unless a
movies folder template (or a single-string folder template) exists. Series fall back to a folder derived from the series output template (stripping {episode}, {episode_name}, and collapsing {season_episode} down to {season}). Music albums fall back to {artist} - {album} ({year}). If the song has no year, the folder name is only {artist} - {album}.
Movies are flat by default
Episodes and songs are always foldered. unshackle writes movies directly into the output directory unless you define a movies folder template (or a single-string folder template, which folders every kind). Set one if you want each movie in its own directory.
"},{"location":"guide/output-and-naming/#music-output-files","title":"Music output files","text":"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.
Codec Extension FLAC .flac Opus .opus Vorbis .ogg AAC, ALAC, and all other codecs .m4a 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.
unshackle writes no .mkv file for music, and the muxing options below do not apply.
The songs output template names the file. The albums folder template names the folder around it.
/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
"},{"location":"guide/output-and-naming/#music-metadata","title":"Music metadata","text":"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 tag and tag_group_name are set, unshackle also writes the group name into a GROUP tag.
unshackle embeds cover art when the service gives an artwork URL. It downloads the image and puts it in the file.
unshackle writes lyrics when the service supplies them: a LYRICS Vorbis comment for FLAC, a USLT frame for MP3, and a \u00a9lyr atom for M4A. Ogg uses the same LYRICS field as FLAC. unshackle does not write synchronized lyrics (SYLT).
A metadata fault does not stop the run. The file is already in place, so unshackle writes a warning and continues.
--no-mux leaves music files untagged
--no-mux 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.
"},{"location":"guide/output-and-naming/#muxing-options","title":"Muxing options","text":"Height channels
A track with height channels is named bed.LFE.heights, such as 5.1.4.
"},{"location":"guide/output-and-naming/#dtsx-profile-2-output","title":"DTS:X Profile 2 output","text":"A title whose audio holds a dtsx or dtsy sample entry (DTS:X Profile 2, DTS-UHD) muxes to MP4 with MP4Box, because Matroska has no CodecID for it. Without MP4Box installed the mux stops.
DTS:X Profile 1 is DTS-HD Master Audio and muxes to MKV as usual.
An MP4 title loses:
- the forced, hearing-impaired and original track flags
- attachments, such as subtitle fonts
- SubStation Alpha (
.ass) subtitles - container tags (
mkvpropedit)
You configure muxing (the combination of video, audio, subtitle, chapter and attachment tracks into a single Matroska file with mkvmerge) under the muxing config key. unshackle muxes only movies and episodes. Read Music output files for what a music download does instead.
unshackle.yamlmuxing:\n set_title: true\n merge_video: false\n merge_audio: true\n default_language:\n audio: en\n subtitle: en\n
Key Type Default Effect set_title bool true Write the title name into the MKV container title with --title. Set to false to omit it. merge_video bool false Group video tracks that share the same resolution, range, and codec into one file so only language varies inside it. merge_audio bool true Merge audio tracks of the same kind so multiple languages sit in one file. default_language map (unset) Preferred language per track type (video / audio / subtitle). A track in the preferred language is flagged as the default track. 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.
default_language only sets the default-track flag
default_language controls which track carries the MKV --default-track flag. Nothing else. It does not change track selection (that stays with -l/--a-lang and friends). It also does not touch which track carries the original flag: --original-flag 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.
merge_video collapses only the language dimension
merge_video groups video tracks by (resolution, range, codec) 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 -r HYBRID,DV,HDR10,SDR --merge-video 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. merge_audio works the same way for audio languages.
A few muxing behaviors are automatic and not configurable:
--no-date is always passed for privacy (no timestamps embedded). - Descriptive audio gets the visually-impaired flag. SDH subtitles get the hearing-impaired flag. Forced subtitles get the forced flag.
- unshackle writes the chapters from the title's chapter list (see Chapters below).
The --no-mux flag skips muxing entirely and writes the individual track files, each with a track-type suffix, into the same output/folder structure.
"},{"location":"guide/output-and-naming/#sample-files","title":"Sample files","text":"--sample and --include-sample write a sample into a Sample folder inside the output folder of the title. The sample keeps the filename of the title, with a SAMPLE tag at the end. The tag uses the separator of the output template.
A movie with --include-sampleSome.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
With --sample, the Sample folder holds the only output file. If the run makes no title folder, the Sample folder is in the downloads directory.
"},{"location":"guide/output-and-naming/#tags-group-naming","title":"Tags & group naming","text":"The release-group tag is the -TAG portion at the end of scene-style names, which the {tag} variable gives. You can swap it per release with tag_rules: ordered rules whose conditions read the release-attribute variables only (quality, resolution, hdr, source, lang_tag, title_type, and so on), and the first rule that matches wins. tag_rules cannot read the title's own fields, such as title and season_episode. See the reference page for the exact list.
unshackle.yamltag: \"MYGROUP\"\ntag_group_name: true\ntag_imdb_tmdb: true\n
Key Type Default Effect tag str \"\" The release-group tag used for {tag}. tag_group_name bool true Write the group name (config.tag) into the MKV Group metadata tag. tag_imdb_tmdb bool true Look up and embed IMDb / TMDB / TVDB external-ID tags in the MKV metadata (uses tmdb_api_key / tvdb_api_key / simkl_client_id when available). unshackle writes the IDs as the Matroska IMDB, TMDB, and TVDB2 tags. TVDB2 values carry the entity prefix the Matroska tagging spec requires: series/73871 for a show, movies/113 for a film.
You can override the tag per run without editing config:
unshackle dl --tag OTHERGROUP EXAMPLE \"...\"\n
The --repack flag adds the REPACK marker (surfaced through the {repack} variable) to the filename for that run:
unshackle dl --repack EXAMPLE \"...\"\n
Empty tags collapse cleanly
If config.tag is empty and your template ends with -{tag?}, the trailing - and the placeholder are both removed. Use the optional form {tag?} if you sometimes download without a tag set.
"},{"location":"guide/output-and-naming/#unicode-filenames","title":"Unicode filenames","text":"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 unicode_filenames to keep the native characters.
unshackle.yamlunicode_filenames: true\n
Value Result false (default) \uae30\uc0dd\ucda9 \u2192 transliterated ASCII; accents stripped. true Native characters preserved in filenames and folders, with the vowel and tone marks of languages such as Thai, Hindi and Bengali. 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.
Regardless of this setting, unshackle always removes or replaces a set of filesystem-unsafe and structural characters during sanitisation. For example, / and ; become &, and unshackle removes characters like \\ * ! ? , ' \" < > | $ # ~. This is why you must never put path-unsafe characters directly in a template.
unshackle warns at startup about a template that contains < > : \" / \\ | ? *. It examines a folder template per path segment, so you can use / there as a directory separator.
"},{"location":"guide/output-and-naming/#directory-filename-configuration","title":"Directory & filename configuration","text":"The directories 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.
unshackle.yamldirectories:\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
Name Purpose downloads Default output directory for finished files. temp Working directory for in-progress downloads, muxing, and intermediate files. cache Title/HTTP cache and update-check state. cookies Per-service cookie files. logs Log files. exports Export JSONs. services, vaults, fonts, commands Search paths for services, key-vault backends, bundled fonts, and CLI commands. wvds, prds, dcsl Widevine devices, PlayReady devices, and DCSL data. Paths can hold a ~ for expansion. unshackle protects the names app_dirs, core_dir, namespace_dir, user_configs, and data, so you cannot change them.
"},{"location":"guide/output-and-naming/#filename-patterns","title":"Filename patterns","text":"The filenames 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.
unshackle.yamlfilenames:\n log: \"unshackle_{name}_{time}.log\"\n chapters: \"Chapters_{title}_{random}.txt\"\n subtitle: \"Subtitle_{id}_{language}.srt\"\n
Name Default Where log unshackle_{name}_{time}.log directories.logs debug_log unshackle_debug_{service}_{time}.jsonl directories.logs config config.yaml per-service directory root_config unshackle.yaml main config filename chapters Chapters_{title}_{random}.txt directories.temp subtitle Subtitle_{id}_{language}.srt directories.temp"},{"location":"guide/output-and-naming/#chapters-naming","title":"Chapters naming","text":"When a title has chapters, unshackle writes them to an OGM chapters file (filenames.chapters) and passes it to the muxer. Unnamed chapters use the chapter_fallback_name template:
unshackle.yamlchapter_fallback_name: \"Chapter {i:02}\"\n
The fallback can hold two placeholders: {i} (chapter number, starting at 1) and {j} (which increments only for unnamed chapters). It permits standard format directives like {i:02}.
"},{"location":"guide/output-and-naming/#removed-migrated-options","title":"Removed & migrated options","text":"scene_naming was removed
The old scene_naming option no longer exists. If it is present in your config, unshackle exits immediately with an error asking you to configure output_template instead. Migrate any scene-naming setup to the templates described on this page.
"},{"location":"guide/output-and-naming/#worked-examples","title":"Worked examples","text":"Each tab shows a template and what it produces for a few different downloads, so you can see how the optional (?) variables appear and disappear.
MoviesTV seriesMulti-languageDaily showsMusic output_template:\n movies: \"{title}.{year}.{edition?}.{quality}.{source}.WEB-DL.{audio_full}.{atmos?}.{video}.{hdr?}-{tag?}\"\n folder:\n movies: \"{title} ({year})\"\n
A 4K Atmos HDR download fills every placeholder:
The Movie (2024)/\n \u2514\u2500 The.Movie.2024.2160p.EXAMPLE.WEB-DL.DDP5.1.Atmos.H.265.HDR-TAG.mkv\n
The same template on a plain 1080p SDR stereo download, where {edition?}, {atmos?} and {hdr?} collapse along with their dots:
The Movie (2024)/\n \u2514\u2500 The.Movie.2024.1080p.EXAMPLE.WEB-DL.AAC2.0.H.264-TAG.mkv\n
A director's cut fills {edition?}:
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
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
The Show (2023)/Season S02/\n \u2514\u2500 The.Show.S02E04.The.Reckoning.2160p.EXAMPLE.WEB-DL.DDP5.1.H.265-TAG.mkv\n
unshackle decides the separator style once for the whole folder template, and every segment then follows it. Spaces outnumber dots in {title} ({year})/Season {season}, so Season {season} keeps its space even though it holds only one variable.
When an episode has no on-screen name, {episode_name?} disappears cleanly:
The Show (2023)/Season S02/\n \u2514\u2500 The.Show.S02E05.2160p.EXAMPLE.WEB-DL.DDP5.1.H.265-TAG.mkv\n
Place {dual?}, {multi?} and {dubbed?} next to each other. At most one of them is ever set (see dual_multi_mode), and the empty ones collapse:
output_template:\n movies: \"{title}.{year}.{quality}.{source}.WEB-DL.{dual?}.{multi?}.{dubbed?}.{audio_full}.{video}-{tag}\"\n
Original English audio plus a French dub (-l en,fr):
The.Movie.2024.1080p.EXAMPLE.WEB-DL.DUAL.DDP5.1.H.264-TAG.mkv\n
Original plus several dubs (-l en,fr,de,es):
The.Movie.2024.1080p.EXAMPLE.WEB-DL.MULTi.DDP5.1.H.264-TAG.mkv\n
Only a dub, original audio left out (-l de on an English-original title):
The.Movie.2024.1080p.EXAMPLE.WEB-DL.DUBBED.DDP5.1.H.264-TAG.mkv\n
Two dialects of one language (en-US + en-GB) count as a single language, so none of the three variables is set:
The.Movie.2024.1080p.EXAMPLE.WEB-DL.DDP5.1.H.264-TAG.mkv\n
For finer control (for example a SUBBED tag driven by subtitle languages), use {lang_tag?} with language_tags rules instead.
Daily content needs no special template. When an episode carries an air date, {season_episode} becomes the date automatically and {episode} and {year} clear:
output_template:\n series: \"{title}.{season_episode}.{episode_name?}.{quality}.{source}.WEB-DL.{audio_full}.{video}-{tag}\"\n
A normal episode and a dated one, same template:
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
The date separator follows your template style: dots here, spaces if your series template uses spaces.
In folder names, {season} becomes the air year (Season 2024 style grouping), and unshackle skips a {year?} in the folder template when it would only repeat that year.
output_template:\n songs: \"{track_number}. {title}\"\n folder:\n albums: \"{album_artist} - {album} ({year})\"\n
The Artist - The Album (2024)/\n \u2514\u2500 01.Opening.Track.mka\n
In \"{track_number}. {title}\" 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.
A multi-disc album with explicit tracks, using more of the music variables. {disc} is empty on disc 1, so {disc?} and its separator only appear from disc 2 onward:
output_template:\n songs: \"{disc?}-{track_number}. {title} {explicit?}\"\n folder:\n albums: \"{album_artist} - {album} ({year}) [{label?}]\"\n
The Artist - The Album (2024) [The Label]/\n \u251c\u2500 01. Opening Track.mka\n \u2514\u2500 02-03. Closing Track Explicit.mka\n
"},{"location":"guide/output-and-naming/#see-also","title":"See also","text":" - Configuration File: the full
unshackle.yaml structure. - Downloading: the
dl command and per-run flags like -o, --no-folder, --tag, and --repack.
"},{"location":"guide/proxies-and-vpn/","title":"Proxies & VPN","text":"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.
The --proxy 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.
Where proxies are configured
All proxy provider configuration lives under the top-level proxy_providers: config key in your unshackle.yaml. 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.
"},{"location":"guide/proxies-and-vpn/#the-proxy-flag","title":"The --proxy flag","text":"Four options on the dl command control proxying at download time:
Option Effect --proxy The proxy to use. Either an explicit URI, or a query that unshackle resolves against your configured providers. --no-proxy Force all proxy use off. No providers are initialised and no proxy query is resolved. --no-proxy-download Use the proxy for the manifest, licence, and authentication, but bypass it for the downloads themselves. --proxy-download Use --proxy for the manifest, licence, and authentication, and a different proxy for the downloads. Takes the same forms as --proxy. Explicit proxy URIunshackle dl --proxy http://user:pass@1.2.3.4:8080 EXAMPLE 81234567\n
Resolve a US server from your configured providersunshackle dl --proxy us EXAMPLE 81234567\n
Target a specific providerunshackle dl --proxy nordvpn:us EXAMPLE 81234567\n
Set a default proxy in config
Like every dl flag, you can give --proxy a default in your configuration, so you do not have to pass it on every command. See Downloading for how dl options and config defaults interact.
"},{"location":"guide/proxies-and-vpn/#-no-proxy-download","title":"--no-proxy-download","text":"Segment downloads are usually the largest share of traffic, and a residential-grade VPN proxy is frequently the slowest part of the chain. --no-proxy-download 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.
Proxy the manifest and licence, download segments directunshackle dl --proxy gb --no-proxy-download EXAMPLE 10a1234\n
When this is unsafe
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 --no-proxy-download, remove it.
"},{"location":"guide/proxies-and-vpn/#-proxy-download","title":"--proxy-download","text":"--proxy-download is the middle ground: the manifest, licence, and authentication go through --proxy, 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 --proxy, so a country code or provider:region resolves against the same providers.
Manifest and licence over NordVPN, downloads over Windscribeunshackle dl --proxy nordvpn:us --proxy-download windscribevpn:us EXAMPLE 10a1234\n
--no-proxy and --no-proxy-download both override --proxy-download. The same region warning applies: if the service ties segment delivery to the manifest region, keep both proxies in that region.
"},{"location":"guide/proxies-and-vpn/#how-proxy-resolution-works","title":"How proxy resolution works","text":"unshackle interprets the value you pass to --proxy in one of three ways. It tries them in this order.
flowchart TD\n A[\"--proxy value\"] --> B{\"Looks like a URI?<br/>http:// https:// socks\"}\n B -- yes --> C[\"Use it verbatim\"]\n B -- no --> D{\"Has a provider prefix?<br/>provider:query\"}\n D -- yes --> E[\"Ask that one provider<br/>for the query\"]\n D -- no --> F[\"Ask every provider in order,<br/>first match wins\"]
- An explicit URI. unshackle uses anything shaped like
http://..., https://..., or a socks... URI exactly as you give it. unshackle logs Using explicit Proxy: ... and does no lookup. A host:port value such as localhost:8080 is also an explicit proxy. - A provider-prefixed query:
provider:query, for example nordvpn:us or gluetun:windscribe:us. 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. - A bare query: a region like
us, gb, or us1234. unshackle asks each loaded proxy provider in order and uses the first proxy any of them returns. A bare city query such as us:seattle does not work: unshackle reads us as a proxy provider name. Use the proxy provider prefix, for example nordvpn:us:seattle. If no proxy provider has a proxy for the query, unshackle stops with No proxy provider had a proxy for <query> and does not continue without a proxy.
unshackle compares the query against a region grammar: a country or location code of two to four letters, with an optional _code part (res_yyz), then an optional server number and/or a :city or -city part. A host:port 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.
A Control D resolver, controld://<resolver>@dns.controld.com, is a fourth form. A --remote client sends it to a server in place of a proxy URI, and the server starts a forwarder for it. See Control D.
"},{"location":"guide/proxies-and-vpn/#provider-load-order","title":"Provider load order","text":"When you do a download without --no-proxy, unshackle instantiates every configured proxy provider once, in this fixed order. It uses that same order for bare-query resolution:
Basic \u2192 ExpressVPN \u2192 NordVPN \u2192 Proton VPN \u2192 Surfshark \u2192 Windscribe \u2192 Gluetun \u2192 Hola \u2192 Control D
So if you have both Basic and NordVPN configured and use --proxy us, a us entry in your Basic config wins, because unshackle tries Basic first. To skip ahead to a specific proxy provider, prefix the query (--proxy nordvpn:us).
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 --proxy nordvpn:us, fails and shows the reason it did not load.
A bare region reaches Control D last
unshackle asks Control D for a bare region such as --proxy us only when no other loaded proxy provider has a proxy for it. Hola loads automatically when the hola-proxy binary is on your PATH, 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 unshackle-us profile and endpoint. The geofence auto-proxy uses the same order. To use Control D directly, prefix the query (--proxy controld:us).
Auto-loading providers
Most providers only load when you configure them under proxy_providers:. 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 hola-proxy binary is found on your PATH.
"},{"location":"guide/proxies-and-vpn/#connection-feedback","title":"Connection feedback","text":"After a proxy provider resolves a query, unshackle prints a line so you can see where you came out:
- Gluetun reports the verified exit IP, country, and city of the container.
- ExpressVPN and Proton VPN print a location summary such as
(USA - New York, #3 of 5): .214. - Other proxy providers log the resolved proxy URL.
"},{"location":"guide/proxies-and-vpn/#exit-check","title":"Exit check","text":"Before the service sends a request, unshackle looks up the proxy exit IP through the proxy. The service stops with Proxy check failed in two cases:
- No IP lookup gets through the proxy. The proxy is down, or it refused the connection.
- The proxy exit IP is the same as your own IP, so traffic does not go through the proxy.
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.
Over the REST API, the server returns this failure to the client as INVALID_PROXY.
"},{"location":"guide/proxies-and-vpn/#basic-static-proxies","title":"Basic (static proxies)","text":"The Basic 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).
Under each two-letter country code you can put either a single proxy string or a list of them:
unshackle.yamlproxy_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
Query forms:
Query Meaning us A proxy for the US. If several are listed, one is chosen at random. us2 The 2nd entry in the US list (1-based). - If a country has a single proxy string, that proxy is always returned.
- If it has a list and you give a plain country code, unshackle picks one at random. Append an index (
de1, de2) to pin a specific entry. - unshackle normalises each URL (a missing scheme defaults to
http) and validates it, so it rejects a malformed URI up front and does not fail mid-download.
unshackle dl --proxy de2 EXAMPLE 81234567\n
"},{"location":"guide/proxies-and-vpn/#control-d","title":"Control D","text":"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, --proxy-download) sees an ordinary HTTP proxy.
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. --proxy controld:yyz --proxy-download controld:yul 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).
Keep both locations in one country. Some CDNs also check the country of the download IP, and refuse a --proxy-download exit in another country with a 403. This applies to every proxy provider.
unshackle search --proxy controld:ca works the same way as dl.
"},{"location":"guide/proxies-and-vpn/#what-you-need","title":"What you need","text":" - 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.
- 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.
unshackle.yamlproxy_providers:\n controld:\n token: api.xxxxxxxxxxxx # a Write API token, from the Control D dashboard\n
unshackle dl --proxy controld:ca EXAMPLE 81234567\n
The token is the only required key. You do not need to create a profile or an endpoint, or to give a profile and resolver: unshackle creates an unshackle-<region> profile and endpoint on your account the first time it needs one, and uses it again on the next run. Give profile and resolver only to use a profile that you made yourself (see How unshackle chooses a profile).
The returned proxy is HTTP on loopback, http://127.0.0.1:{port}. 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:
Query Meaning ca One of Control D's Canadian locations, at random. yul That exact location, by its code. res_yyz A residential location, by its code. A country pick never uses a residential location, so name it this way. The configuration reference lists every controld config key.
"},{"location":"guide/proxies-and-vpn/#how-unshackle-chooses-a-profile","title":"How unshackle chooses a profile","text":"Each region query gets a profile and an endpoint named after it: --proxy controld:ca uses unshackle-ca. For each region, unshackle uses the first match in this list:
- A profile that this process already pointed at that region.
- The endpoint named
unshackle-<region> on your account, made by an earlier run. -
A profile from your config that this process does not use yet. These are optional:
unshackle.yamlproxy_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
The resolver ID is the last part of the endpoint's DoH URL, https://dns.controld.com/<resolver>. You can also give the full URL.
-
A new profile and endpoint named unshackle-<region>, while your config pairs plus the unshackle-* endpoints on the account are fewer than max_profiles. unshackle keeps them for the next run. max_profiles limits only this step: unshackle uses every pair in your config, even more than max_profiles.
- 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
unshackle-* profile that moves, and its endpoint, get the new region's name. unshackle logs Every Control D profile is in use; moving profile \u2026 to \u2026, and connections already open keep the old exit until they close.
Because the names live on the account, every unshackle process agrees on them: two runs, or two jobs on a serve instance, that ask for ca both use unshackle-ca. Two processes can still move a profile under each other when they run out of profiles (step 5).
unshackle changes only the profiles in your config and the profiles of unshackle-* endpoints. It skips an unshackle-* endpoint whose profile an endpoint without that name also uses, so unshackle never redirects a profile that serves your own devices. Leave the unshackle-* profiles empty: no services, no custom rules. unshackle sets their default rule to REDIRECT, 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.
Business accounts pay per endpoint
Personal plans allow an unlimited number of profiles and endpoints. Business plans bill each endpoint every month, so each unshackle-<country> 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 max_profiles to that number. unshackle then never creates a profile.
Everything goes through the proxy, including the segments
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 --no-proxy-download to keep the geo-check on the manifest and the licence while pulling the files over your own connection.
The switch is not instant
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.
Same machine, same IP, over IPv4
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 HTTPS_PROXY for these queries.
The forwarder refuses a connection to an IP address with a 502, 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.
With --remote, the server resolves
unshackle does not send your API token to a server. For --proxy controld:ca with --remote, unshackle points unshackle-ca at Canada with your token, then sends the server only that endpoint's resolver ID, as controld://<resolver>@dns.controld.com. 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.
The server must run a version of unshackle that knows controld://. An older server rejects it with INVALID_PROXY: Proxy provider 'controld' not found when your API key has server_proxy, else a message that asks for a full proxy URI. A bare region, such as --proxy ca, skips Control D with --remote, 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.
"},{"location":"guide/proxies-and-vpn/#troubleshooting-control-d","title":"Troubleshooting Control D","text":"Symptom Cause and fix Proxy check failed, 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. A 502 Bad Gateway for one host. With -d, the log shows Control D returned no A record for \u2026. Control D gave no IPv4 address for that host. A 502 Bad Gateway for one host only. With -d, the log shows Refused \u2026, an address that Control D cannot redirect. The request names the host by IP address. The forwarder refuses it. See the note on IPv4 above. An HTTP 401 or 403 from api.controld.com. The token is a Read token, or its Allowed IPs do not include this machine. Use a Write token. Control D needs both a profile and a resolver or Control D needs max_profiles of 1 or more at startup. The controld config is not valid. Give profile and resolver together, and a max_profiles of 1 or more. Every run fails until you correct it, also a run that does not use Control D. Could not read Control D's locations. unshackle could not get the location list. It tries again at the next Control D query. A 403 for the segments only, with --proxy-download in another country. The CDN checks the country of the download IP. Keep --proxy-download in the same country as --proxy."},{"location":"guide/proxies-and-vpn/#gluetun","title":"Gluetun","text":"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 qmcgaw/gluetun image. That container establishes a WireGuard or OpenVPN tunnel to your chosen VPN provider and exposes a plain HTTP proxy on localhost, which unshackle then routes traffic through. When the download finishes, the container is torn down automatically.
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.
Not available with --remote
Gluetun listens on your machine, so a server on another machine cannot reach it. With --remote, unshackle stops with an error for --proxy gluetun:..., and for any proxy that resolves to localhost or a loopback address, such as a region query that Gluetun answers. Give --remote a proxy the server can reach, or run the service locally. A server on this machine (a remote_services URL on 127.0.0.1) can reach a local proxy, so it is exempt.
Docker is required
Gluetun needs a working Docker installation on your PATH. If Docker is not found, the proxy provider fails to load with an error linking to the install docs. The container also needs the NET_ADMIN capability and access to /dev/net/tun to bring up the tunnel. unshackle requests both automatically.
"},{"location":"guide/proxies-and-vpn/#query-format","title":"Query format","text":"Gluetun uses a nested selector: the proxy provider prefix picks Gluetun, and the rest names the VPN provider and the region.
gluetun:<vpn-provider>:<region>\n
A Windscribe US exit via Gluetununshackle dl --proxy gluetun:windscribe:us EXAMPLE 81234567\n
A NordVPN Germany exit via Gluetununshackle dl --proxy gluetun:nordvpn:de EXAMPLE 81234567\n
After unshackle strips the leading gluetun:, the proxy provider receives exactly provider:region. It must be two colon-separated parts, and anything else is an error. The <vpn-provider> must be one you have configured under gluetun.providers, and unshackle normalises friendly names to Gluetun's identifiers (for example pia and privateinternetaccess both map to private internet access).
"},{"location":"guide/proxies-and-vpn/#configuration","title":"Configuration","text":"Each VPN provider you want to use gets an entry under providers:, carrying its VPN type, credentials, and how your region aliases map onto Gluetun's server selectors.
unshackle.yamlproxy_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
Per-provider keys:
Key Purpose vpn_type wireguard (default) or openvpn. credentials The secrets for the tunnel; see the credential rules below. server_countries Maps your region alias (e.g. us) to Gluetun's country value (e.g. US). server_cities Optional. Maps an alias to a Gluetun city. server_hostnames Optional. Maps an alias directly to a specific server hostname. extra_env Optional. Raw environment variables merged into the container last, for any Gluetun setting not covered above. Credential rules by VPN type:
WireGuardOpenVPN private_key is always required. surfshark, mullvad, and ivpn also require addresses. windscribe additionally requires both addresses and preshared_key (preshared_key may be an empty string, but the config key must be present). - NordVPN and Proton VPN need only
private_key.
- Requires
username and password.
Which vpn_type should I pick?
WireGuard is the default because it can be faster, but it needs the fiddlier credential setup above (private keys, and for some providers addresses and a preshared_key). 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.
Global keys:
Key Default Purpose base_port 8888 The first local port to expose proxies on. Additional containers take the next free ports. auto_cleanup true Remove containers on exit. If false, containers are only stopped, not deleted. container_prefix unshackle-gluetun Prefix for Docker container names. auth_user / auth_password null Optional HTTP-proxy credentials. If set, the local proxy requires auth and the credentials are embedded in the proxy URL. verify_ip true After connecting, verify the container's real exit IP and region."},{"location":"guide/proxies-and-vpn/#region-selection","title":"Region selection","text":"For a given query region, Gluetun resolves the server like this:
- An explicit entry in
server_hostnames, server_cities, or server_countries for that alias always wins. - unshackle changes a
us1239-style query (country code + number) with no explicit mapping into a provider-specific server hostname (for example us1239.nordvpn.com for NordVPN). Surfshark has no numbered servers, so map a Surfshark region to a server name such as us-dal.prod.surfshark.com in server_hostnames. - unshackle expands a bare two-letter code to the full country name Gluetun expects.
A few providers (Windscribe, VyprVPN, VPN Secure) select by region rather than country, and unshackle converts Windscribe region names automatically. For instance us becomes US East and uk/gb become United Kingdom.
"},{"location":"guide/proxies-and-vpn/#container-lifecycle","title":"Container lifecycle","text":"Understanding what Gluetun does behind the scenes helps when something goes wrong:
- Image check. unshackle pulls
qmcgaw/gluetun:latest if it is not already present. - Reuse. If a container for this exact
provider:region 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.
Expect a slow first request, then instant reuse
Bringing up a fresh tunnel takes roughly 10 to 30 seconds for the first request to a given provider:region. 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.
- Port allocation. unshackle chooses a free local port, starting from
base_port. - Start. unshackle launches the container bound to
127.0.0.1:{port}. It passes credentials through a temporary, 0600-permission env-file (never as -e flags), and it overwrites and deletes that file immediately after. - 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
authentication failed or invalid credentials abort early, and unshackle attaches recent logs to the error to help you diagnose it. - IP verification. When
verify_ip 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. - Proxy handed back. You get
http://localhost:{port} (or with auth credentials if configured).
Cleanup and Ctrl+C
unshackle cleans up containers with an atexit handler on normal exit. Gluetun deliberately does not install its own signal handlers, so Ctrl+C continues to work as you expect. If something kills a run hard (for example kill -9), a container can stay behind. With auto_cleanup: true the next run that adopts that name still works, or you can remove it manually with docker rm -f.
"},{"location":"guide/proxies-and-vpn/#troubleshooting","title":"Troubleshooting","text":"Common Gluetun issues
RuntimeError about Docker not found. Install Docker and make sure that docker is on your PATH. invalid credentials / authentication failed in the readiness wait. Your WireGuard/OpenVPN credentials are wrong or in the wrong fields. Double-check private_key, addresses, and (for Windscribe) preshared_key. - Region mismatch error. The VPN connected but exited in a different country than requested. Examine your
server_countries mapping, or set verify_ip: false if you intentionally use a nearby region. - Timeout after 60 seconds. The tunnel never came up. Inspect the container logs (
docker logs <container>) for the underlying VPN error.
"},{"location":"guide/proxies-and-vpn/#expressvpn","title":"ExpressVPN","text":"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.
Enable it and do a download interactively once:
unshackle.yamlproxy_providers:\n expressvpn:\n enable: true\n
With enable: true 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 enable after the first login, but you can keep a YAML block to pin regions or servers:
unshackle.yaml (optional)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
Default file location:
File Default path Token cache {cache}/vpn/expressvpn_tokens.json Where {cache} is your configured cache directory.
Query forms:
Query Meaning us A smart, random US location. us-ny US, New York. us-ny-2 / us-ny2 US, New York, the 2nd server. usny-newyork-2 A full location slug. hostname.expressprovider.com A direct endpoint hostname. The resolved proxy is an HTTPS proxy on port 443. On success, unshackle prints a location summary such as (USA - New York, #3 of 5): .214.
Cache safety
unshackle writes ExpressVPN's token cache with 0600 permissions, so the refresh token is never briefly world-readable.
"},{"location":"guide/proxies-and-vpn/#nordvpn","title":"NordVPN","text":"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.
unshackle.yamlproxy_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
Required keys: username, password. 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 @. If validation fails, you have almost certainly used your login credentials instead of your service credentials.
server_map is optional and maps a region (or code:city) to a pinned NordVPN server ID. Its main use is to tune performance: for a given streaming service one specific server often performs noticeably better than NordVPN's recommended pick. So you can hard-code that server for a day or two as a workaround, until it degrades and you swap in another.
Use gb, not uk, for the United Kingdom
Query the UK as gb. unshackle uses the Alpha-2 country code gb deliberately to stay consistent with its other regional/country-code systems and avoid the language-vs- country-code confusion that uk invites.
Query forms:
Query Meaning us A recommended US server. us1234 The specific server us1234. nordvpn:us:seattle A recommended server in Seattle. 228 A NordVPN numeric country ID. The returned proxy is HTTPS on port 89 (NordVPN disabled its plain-HTTP proxies on port 80 in 2021).
unshackle dl --proxy nordvpn:us:seattle EXAMPLE 81234567\n
"},{"location":"guide/proxies-and-vpn/#proton-vpn","title":"Proton VPN","text":"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.
TV login (recommended)Exported cookies 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:
unshackle.yamlproxy_providers:\n protonvpn:\n enable: true\n
With enable: true 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.
Export your account.proton.me cookies (the AUTH-<UID> cookie) to the Proton cookie file. This method is access-only: it cannot refresh, so you must re-export when it expires.
The AUTH-<UID> cookie is HttpOnly
This is the single most common cause of a failed Proton cookie import: the required AUTH-<UID> 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.
Why this session can't refresh, and lapses after ~24h
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.
Default file locations:
File Default path Cookies {cookies}/vpn/protonvpn.txt Session cache {cache}/vpn/protonvpn.json Proton VPN auto-loads if its cookie file exists. Like ExpressVPN, unshackle writes its cache file with 0600 permissions.
Cache vs cookie precedence
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.
Query forms (after the protonvpn: prefix):
Query Meaning us A random US server (paid tiers preferred over free). us12 Proton US server #12. us:ny A server in New York. 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 (Name - City): server-host.
Proton server numbers aren't sequential
When pinning a server with protonvpn:deNN, do not guess a low number. A country may have non-contiguous IDs like #203, #813, and so on. Copy the number from a previous run's log line (e.g. DE#203) instead.
"},{"location":"guide/proxies-and-vpn/#hola","title":"Hola","text":"Hola requires no configuration at all. It uses the hola-proxy binary, and auto-loads whenever that binary is found on your PATH. If you query Hola but the binary is missing, the proxy provider raises an error that tells you to install it.
The hola-proxy 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. go install puts the binary in $(go env GOPATH)/bin, which must be on your PATH.
Build hola-proxy, then query a countrygo install github.com/Snawoot/hola-proxy@v1.18.2\nunshackle dl --proxy hola:us EXAMPLE 81234567\n
Query forms: a two-letter country code (e.g. us, gb). unshackle asks hola-proxy for available proxies in that country and picks one at random, returning an HTTP proxy.
Temporary bans
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, hola-proxy does not stop, so unshackle waits 30 seconds and then reports the ban. Hola currently uses only datacenter proxies.
"},{"location":"guide/proxies-and-vpn/#surfshark","title":"Surfshark","text":"Surfshark, like NordVPN, uses Service Credentials rather than your login. Make them from the Surfshark manual-setup page.
unshackle.yamlproxy_providers:\n surfsharkvpn:\n username: YOUR_SERVICE_USERNAME\n password: YOUR_SERVICE_PASSWORD\n server_map: # optional: region -> server name\n us: us-dal\n us:seattle: us-sea\n
Required keys: username, password, validated with the same 48-character rule as NordVPN (combined username+password must be 48 alphanumeric characters, case-insensitive, no @). server_map optionally pins a server per region. Give the server name from Surfshark's server list, for example us-dal. A full hostname such as us-dal.prod.surfshark.com also works. Surfshark does not use numeric server IDs. unshackle ignores a numeric or empty value and logs a warning. A us:seattle entry applies only to that city query, and it does not fall back to the us entry.
Query forms:
Query Meaning surfsharkvpn:us A random US server. uk and gb both give a UK server. surfsharkvpn:us-bos A specific server from Surfshark's server list. surfsharkvpn:us:seattle A random server in Seattle. unshackle ignores case, spaces, hyphens and accents in a city name, so us:new-york matches New York. A city also matches the start of a longer name: de:frankfurt matches Frankfurt am Main. A bare us also reaches Surfshark. A bare us-bos can stop at a proxy provider earlier in the order, and a bare us:seattle does not work, so use the surfsharkvpn: prefix for those forms.
The returned proxy is HTTPS on port 443.
"},{"location":"guide/proxies-and-vpn/#windscribe","title":"Windscribe","text":"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).
unshackle.yamlproxy_providers:\n windscribevpn:\n username: YOUR_SERVICE_USERNAME\n password: YOUR_SERVICE_PASSWORD\n server_map: # optional: alias -> hostname\n us: us-east.totallyacdn.com\n us:seattle: us-seattle.totallyacdn.com\n
Required keys: username, password. server_map optionally maps a region (or region:city) directly to a hostname.
Query forms:
Query Meaning us A random US server. us150 / sg007 A specific numbered server. windscribevpn:us:seattle A random server in Seattle. The returned proxy is HTTPS on port 443.
Windscribe is not loaded by the REST API resolver
The dl 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.
"},{"location":"guide/proxies-and-vpn/#developer-notes","title":"Developer notes","text":"Two resolution paths (developers)
unshackle has two proxy-resolution code paths that are intentionally not identical:
unshackle/commands/dl.py inlines its own logic and loads all nine providers, including Windscribe and Gluetun. unshackle/core/proxies/resolve.py::initialize_proxy_providers() is the shared resolver used by the REST API handlers and the remote-service client. It omits Windscribe and Gluetun.
Both paths accept the same query grammar (a direct URI, a provider:query, a bare country query tried against providers in order, or a controld:// resolver), but the set of available providers differs. Keep this in mind when you add a proxy provider: an entry in dl.py does not make it available over the API, and the opposite is also true.
The remote-service client resolves --proxy with its own resolve_remote_proxy_arg(). It changes a controld: query to a controld:// resolver for the server with get_remote_proxy(), and it removes Control D from a bare query, because a loopback forwarder is of no use to a server on another machine.
Implementing a new provider (developers)
Every proxy provider subclasses unshackle.core.proxies.proxy.Proxy and has three methods:
__init__(self, **kwargs) receives its proxy_providers sub-dict splatted as keyword arguments, so YAML keys map 1:1 to constructor parameters. Do authentication and catalogue pre-fetching here. __repr__(self) is a human summary, conventionally \"{n} Countries ({m} Servers)\". get_proxy(self, query) returns a Requests-compatible proxy URI, or None only when the query was valid but no proxy exists. Raise on genuine errors or bad queries.
Optionally add get_connection_info(query) (as Gluetun does) or last_connection_display() (as ExpressVPN and Proton VPN do) to make dl print a friendly connection line instead of the raw proxy URL.
"},{"location":"guide/proxies-and-vpn/#see-also","title":"See also","text":" - Downloading: the full
dl command guide, including where proxy flags sit in the download flow. - Configuration file: the
unshackle.yaml reference, including directories for cookies and cache used by the cookie-based providers. - Configuration reference: the developer-facing configuration API, including the
proxy_providers structure.
"},{"location":"guide/subtitles/","title":"Subtitles","text":"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.
A handful of dl flags and a small subtitle block in your configuration file control most of this. See Downloading for how subtitle flags fit into a full download command.
"},{"location":"guide/subtitles/#supported-formats","title":"Supported formats","text":"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.
Codec (internal name) Format Extension Notes SubRip SRT srt SubRip, the most widely compatible plain-text format SubStationAlpha SSA ssa SubStation Alpha (styled) SubStationAlphav4 ASS ass Advanced SubStation Alpha (styled) TimedTextMarkupLang TTML ttml Timed Text Markup Language (IMSC/DFXP) WebVTT VTT vtt WebVTT SAMI SMI smi Synchronized Accessible Media Interchange MicroDVD SUB sub MicroDVD MPL2 MPL2 mpl2 MPL2 TMP TMP tmp TMP fTTML STPP stpp MPEG-DASH box-encapsulated TTML (IMSC1) fVTT WVTT wvtt MPEG-DASH box-encapsulated WebVTT The two boxed formats convert automatically
fTTML (STPP) and fVTT (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 (fTTML becomes TTML and fVTT 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.
"},{"location":"guide/subtitles/#what-happens-to-a-subtitle-after-download","title":"What happens to a subtitle after download","text":"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:
- Encoding: unshackle forces non-boxed subtitles to UTF-8, and unescapes stray
‎ / ‏ bidirectional entities. - 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.
- WebVTT sanitization: merged WebVTT runs through a repair pipeline that clamps negative timestamps to
00:00:00.000, removes stray cue identifiers (like Q0, Q1) 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 preserve_formatting). - Cue markup normalisation: unshackle removes the WebVTT-only parts of a cue payload, so no player draws them as dialogue. See Cue markup.
- 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
fTTML is likewise unwrapped to TTML first.
You normally do not need to think about any of this. It gives a clean file.
"},{"location":"guide/subtitles/#selecting-and-filtering-subtitles","title":"Selecting and filtering subtitles","text":"Subtitle selection happens through dl flags. The most important is language selection.
Flag Purpose -sl, --s-lang Language(s) wanted for subtitles. Defaults to all. A - prefix excludes, e.g. all,-es. --require-subs Require these languages to exist; if present, download all subtitles. Cannot be combined with --s-lang. -fs, --forced-subs Include forced subtitle tracks (excluded by default). -fso, --forced-subs-only Keep only forced subtitle tracks and drop the other subtitles; implies -fs. -fsl, --forced-s-lang Language(s) wanted for forced subtitles; implies -fs. A - prefix excludes. --exact-lang Exact language matching, with no regional variants. -S, --subs-only Download only subtitle tracks. -ns, --no-subs Do not download subtitle tracks at all. --sub-format Output subtitle format / conversion target (see conversion). --skip-subtitle-errors Skip a subtitle that fails to download instead of aborting the whole title."},{"location":"guide/subtitles/#choosing-languages","title":"Choosing languages","text":"By default (--s-lang all) unshackle keeps every subtitle language the service offers. To narrow it down, pass a comma-separated list of language tags:
English and Spanish subtitles onlyunshackle dl --s-lang en,es EXAMPLE 81234567\n
Language matching is fuzzy by default: en matches en-US, en-GB, and similar variants. If a requested language is missing but others were found, unshackle continues with whatever remains and tells you which languages it dropped.
For strict matching, where es-419 matches only es-419 and never es-ES, add --exact-lang:
Only Latin-American Spanish, no other Spanish variantsunshackle dl --s-lang es-419 --exact-lang EXAMPLE 'https://www.example.com/...'\n
"},{"location":"guide/subtitles/#requiring-languages-before-downloading","title":"Requiring languages before downloading","text":"--require-subs 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.
Fail unless both English and French subs exist, then grab everythingunshackle dl --require-subs en,fr EXAMPLE B0ABCDEFGH\n
--require-subs and --s-lang are mutually exclusive
Because --require-subs forces downloading of all subtitle languages, it cannot be combined with --s-lang. Choose one or the other.
"},{"location":"guide/subtitles/#forced-subtitles","title":"Forced subtitles","text":"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 -fs / --forced-subs to include them:
Include forced tracks alongside full subtitlesunshackle dl --s-lang en --forced-subs EXAMPLE 81234567\n
-fs keeps forced tracks in every selected language. If you only want forced tracks in certain languages, use -fsl / --forced-s-lang instead. It implies -fs, so you do not need both:
All full subtitles, but only the English forced trackunshackle dl --s-lang all --forced-s-lang en EXAMPLE 81234567\n
If you pass both flags, -fsl wins and keeps only forced tracks in its languages. It also understands orig (the title's original language) and all (every forced track, same as plain -fs).
To download the forced tracks and no other subtitle, use -fso / --forced-subs-only. It implies -fs, and --s-lang and -fsl still select the languages:
Only the English forced trackunshackle dl --s-lang en --forced-subs-only EXAMPLE 81234567\n
-fso does not drop video or audio. Add -S 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.
"},{"location":"guide/subtitles/#track-types-forced-sdh-and-cc","title":"Track types: forced, SDH, and CC","text":"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.
- Forced: only signs and foreign dialogue, meant to play when the audio language matches. Off by default. Enable it with
--forced-subs. - SDH (Subtitles for the Deaf and Hard-of-Hearing, also called HOH): a full transcript that includes both dialogue and non-speech sound cues.
- CC (Closed Captions): captions originating from an EIA-608/708 broadcast stream, often uppercase with
>>> speaker markers and sound cues.
SDH and CC are treated together for sorting and stripping
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.
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 subtitle.group_by to language. Use subtitle.type_priority to change the Forced \u2192 Normal \u2192 SDH/CC order itself.
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.
"},{"location":"guide/subtitles/#closed-captions-embedded-in-video","title":"Closed captions embedded in video","text":"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 (SRT) subtitle flagged as CC. This runs automatically unless you disabled subtitles (--no-subs) or video (--no-video / --video-only semantics), and it requires the CCExtractor tool on your PATH.
"},{"location":"guide/subtitles/#automatic-sdh-stripping","title":"Automatic SDH stripping","text":"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 strip_sdh config key.
The check is deliberately loose: if a close-enough plain track already exists (for example an en-GB non-SDH track when the SDH track is en-US), no stripped copy is created. When a stripped copy is created, the original SDH track is kept as well, so you end up with both.
The sdh_method config key selects the stripping engine itself. The default (auto) prefers the subby cleaner for SRT, falls back to SubtitleEdit when you install it, and otherwise uses the built-in filter-subs approach.
Every engine removes the same three things: bracketed sound effects ([MUSIC PLAYING], (door creaks)), speaker labels (MAN:), and font tags. Every engine keeps plain dialogue and inline <i> styling. They differ on music and lyric lines:
sdh_method Engine that runs Lyric lines (\u266a ... \u266a) auto subby for an SRT track. SubtitleEdit for any other format when you install it, otherwise filter-subs. Kept, unless the fallback reaches filter-subs. subby subby, but only for a track that is already SRT. Any other format falls through to filter-subs. Kept for SRT, removed otherwise. subtitleedit SubtitleEdit when you install it, otherwise filter-subs. Kept with SubtitleEdit, removed without it. filter-subs filter-subs always. Removed. Pick filter-subs when you want lyrics gone as well. Pick subby or install SubtitleEdit when you want to read along with the songs.
Why convert_before_strip exists
subby'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 convert_before_strip: non-SubtitleEdit engines need the subtitle converted to SRT first, or the hearing-impaired cues stay in the file.
"},{"location":"guide/subtitles/#converting-subtitle-formats","title":"Converting subtitle formats","text":"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 --sub-format:
Convert every subtitle to SRTunshackle dl --s-lang en,es --sub-format srt EXAMPLE 81234567\n
--sub-format accepts the common format names and aliases, including srt, vtt, ssa, ass, and ttml. Pass original to explicitly keep the source format and skip all conversion:
Keep whatever the service deliveredunshackle dl --sub-format original EXAMPLE 'https://www.example.com/...'\n
Conversion only runs when the source format differs from the target, so --sub-format srt on a track that is already SRT is a no-op.
Down-converting styled subtitles is lossy
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 --sub-format. If you want to preserve styling, convert to a format that supports it (or keep original).
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 sidecar_format: srt will still lossily flatten styled subtitles, dropping positioning, colours, and styling, and a per-download --sub-format srt forces the muxed track to convert as well. To keep raw styled sidecars, set sidecar_format: original.
"},{"location":"guide/subtitles/#how-the-conversion-backend-is-chosen","title":"How the conversion backend is chosen","text":"Under the hood unshackle picks the highest-fidelity converter that supports the source\u2192target pair. Which converter runs depends on the conversion_method config key (default auto) and the formats involved:
Backend Best at Requires subtitleedit Highest fidelity; preserves positioning and italics SubtitleEdit installed subby Native SRT output with clean-up - pysubs2 Best fidelity for styled SSA/ASS - (pure Python, always available) pycaption Last-resort fallback; flattens styling - With conversion_method: auto, 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.
"},{"location":"guide/subtitles/#what-each-backend-preserves","title":"What each backend preserves","text":"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. \u2014 means that the backend cannot convert that pair.
Conversion subtitleedit pysubs2 subby pycaption 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 Reading the table:
- Keep the original: leaving
--sub-format unset (or set to original) never round-trips the file, so every style survives. Only convert when your player cannot read the source format. subtitleedit (SubtitleEdit / seconv): the best choice for anything \u2192 SRT. It is the only backend that carries colour, and it embeds {\\an8} 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. pysubs2: 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. subby: reads only WebVTT/fVTT/SAMI (never ASS), and it is best for \u2192 SRT, where it uniquely converts WebVTT cue settings into {\\an8} positioning. Its CommonIssuesFixer may also drop near-duplicate cues. pycaption: removes all styling. Last-resort fallback only.
What auto picks
auto prefers subtitleedit first when you install it, then falls back to subby for \u2192 SRT and pysubs2 otherwise. The one exception comes from the table above: for ASS/SSA \u2192 TTML or WebVTT it picks pysubs2 even when SubtitleEdit is installed, since SubtitleEdit flattens inline styling on those pairs. Most installs do not ship SubtitleEdit, so in practice auto means subby (\u2192 SRT) or pysubs2. Install SubtitleEdit / seconv if you need colour or the highest \u2192 SRT fidelity.
"},{"location":"guide/subtitles/#cue-markup-and-html-entities","title":"Cue markup and HTML entities","text":"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 conversion_method:
WebVTT markup Result <c.bg_transparent>text</c> Tags removed, text kept. A class only selects a CSS ::cue rule that no player ever receives, so it carries no styling. <i.loud>, <b.x>, <u.y> Class list removed, the styling tag kept. <v Bob>, <lang ja>, <ruby>, <rt> Tags removed, text kept. <00:00:02.000> Removed. These are karaoke timings that no subtitle player renders. &, , ' Decoded to real characters for SRT, SSA, and ASS output. Kept escaped for WebVTT and TTML, which need them. A class list breaks more than you expect
FFmpeg reads SubRip markup as a tag only while the tag name stays inside [0-9a-zA-Z_/]. The dot in <i.loud> 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 i, b, and u exactly, so there the same class silently loses the styling. mpv, VLC, Plex, and Jellyfin all use one of those two readers.
Config wins over a service's preference
A service may set a preferred_conversion_method on its own tracks (for example when it ships subtitles that a particular backend handles best). An explicit conversion_method in unshackle.yaml always overrides that per-track preference, so your config takes precedence. This only matters when a service ships a non-default preference. Leave conversion_method at auto to let the service's hint stand.
"},{"location":"guide/subtitles/#muxed-vs-sidecar-output","title":"Muxed vs. sidecar output","text":"By default unshackle muxes subtitles into the final .mkv. You can instead (or additionally) write them as separate sidecar files next to the video, controlled by the output_mode config key:
mux (default)sidecarboth unshackle.yamlsubtitle:\n output_mode: mux\n
unshackle embeds the subtitles in the Matroska file. It writes nothing separately.
unshackle.yamlsubtitle:\n output_mode: sidecar\n sidecar_format: srt\n
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).
unshackle.yamlsubtitle:\n output_mode: both\n sidecar_format: srt\n
unshackle muxes the subtitles into the video and writes them as sidecar files.
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:
Show.S01E01.1080p.WEB.en.srt\nShow.S01E01.1080p.WEB.en.forced.srt\nShow.S01E01.1080p.WEB.en.sdh.srt\n
The pattern is {base}.{language}[.forced][.sdh].{extension}. The sidecar_format config key sets the sidecar file format. Use a format name like srt or vtt, or original to keep each subtitle in its downloaded format.
"},{"location":"guide/subtitles/#fonts-for-styled-subtitles","title":"Fonts for styled subtitles","text":"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.
"},{"location":"guide/subtitles/#subtitle-configuration","title":"Subtitle configuration","text":"You can set defaults for all of the behaviour above in the subtitle block of your configuration file:
unshackle.yamlsubtitle:\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
Key Default Values Purpose strip_sdh true true / false Auto-generate a stripped non-SDH copy when a language has only an SDH track. preserve_formatting true true / false Keep original WebVTT styling and layout during sanitization. When false, WebVTT is re-encoded more aggressively (merging identical cues, dropping empty ones). conversion_method auto auto, subby, pysubs2, subtitleedit, pycaption Which conversion backend to prefer. auto ranks them per conversion. sdh_method auto auto, subby, subtitleedit, filter-subs Engine used to strip hearing-impaired cues. convert_before_strip true true / false Convert a subtitle to SRT before stripping SDH (for non-SubtitleEdit engines). output_mode mux mux, sidecar, both Whether subtitles are embedded, written as sidecars, or both. sidecar_format srt a format name (e.g. srt, vtt) or original Format used for sidecar files. group_by type type, language Whether all tracks of one type stay together, or each language stays next to its own variants. language_priority (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":"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:
If you want Set Every original style kept, with no re-encode at all --sub-format original, and sidecar_format: original for sidecars The highest conversion fidelity, including colour Install SubtitleEdit. conversion_method stays auto Music and lyric lines stripped along with the sound effects sdh_method: filter-subs Lyric lines kept sdh_method: subby, or install SubtitleEdit No stripped copies made at all strip_sdh: false One backend for every conversion, whatever you install conversion_method: <backend> Two keys read as if they control markup, and do not:
preserve_formatting decides whether unshackle re-encodes a WebVTT file after the repair pipeline. Left true, the cue text passes through as written. Set to false, 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. convert_before_strip 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 subby and filter-subs no-ops on anything that is not already SRT.
SubtitleEdit is optional but recommended
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 PATH. See Installation for how to add it. Without it, unshackle falls back to its built-in Python backends.
"},{"location":"guide/subtitles/#developer-reference","title":"Developer reference","text":"Audience
This section is for people extending unshackle or writing services. Everyday users can stop here.
The subtitle model lives in unshackle.core.tracks.Subtitle. A few internals worth knowing when working with subtitle tracks in code:
- Flags and validation:
Subtitle(codec=..., cc=..., sdh=..., forced=...). A track cannot be both cc and sdh, and you cannot combine forced with either. Both raise ValueError at construction. convert(codec, *, forced=False): converts the downloaded file in place through the backend chain in subtitle_convert.run_conversion. forced=True (what --sub-format sets) is the only way to permit lossy styled down-converts such as ASS\u2192SRT. Raises NotImplementedError if no backend supports the pair and RuntimeError if all attempts fail. strip_hearing_impaired(): removes SDH cues using the engine selected by config.subtitle[\"sdh_method\"]. reverse_rtl(): fixes right-to-left sentence-ending positioning with SubtitleEdit (requires the binary). parse(data, codec): the central parser, returning a pycaption.CaptionSet. It handles the boxed DASH formats, SAMI, and the WebVTT repair helpers. extract_fonts(text): returns the set of font names referenced by an ASS/SSA subtitle, used to decide which fonts to attach at mux time.
The conversion backends (SubtitleEditBackend, SubbyBackend, Pysubs2Backend, PycaptionBackend) each have a small protocol (is_available(), can_convert(), rank(), convert()), and unshackle tries them in rank order, lowest rank first. See the Tracks API reference for the full model.
"},{"location":"guide/troubleshooting/","title":"Troubleshooting & Debugging","text":"When a download fails, a service misbehaves, or unshackle cannot get a content key, unshackle gives you three tools to find out why:
- Debug logging: verbose
DEBUG-level console output plus a structured, machine-readable log file. unshackle env: make sure that unshackle finds the external tools it depends on, and see exactly which directories and config file are in use. - Targeted toggles:
debug_keys and debug_requests for the two areas (DRM keys and raw HTTP traffic) that are deliberately quiet by default.
The sections below cover how to enable each of them, how to read what they give, and which diagnostic fits which failure mode.
"},{"location":"guide/troubleshooting/#turning-on-debug-logging","title":"Turning on debug logging","text":"There are two independent ways to enable debug logging, and they do slightly different things.
The -d / --debug flagThe debug config key The root-level flag turns on verbose logging for a single invocation:
unshackle -d dl SERVICE TITLE_ID\n
It must come before the subcommand, because it is an option on the root unshackle command, not on dl.
-d does three things:
- Sets the console log level to
DEBUG, so every module logs its full detail. - Enables the structured JSON debug log file (see below).
- Adds source-path annotations to console log lines (which file and line each message came from).
To make debug logging the default for every run without typing -d each time, set it in your unshackle.yaml:
debug: true\n
or with the cfg command:
unshackle cfg debug true\n
debug: true is not identical to -d
The debug config key enables the JSON debug log file, but it does not raise the console to DEBUG level and does not add source-path annotations. Those only happen when you pass the -d 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 -d is the most complete option, and you can combine both.
Debug logging can be noisy and revealing
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.
"},{"location":"guide/troubleshooting/#the-structured-json-debug-log","title":"The structured JSON debug log","text":"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 (jq, grep, a text editor). It is safe to attach to a bug report, because unshackle redacts it.
"},{"location":"guide/troubleshooting/#where-it-is-written","title":"Where it is written","text":"unshackle makes the debug log during a dl run, and during import, which wraps dl. The path is:
<logs directory>/unshackle_debug_<service>_<timestamp>.jsonl\n
For example, unshackle_debug_EXAMPLE_20260703-142530.jsonl. The <service> tag and the timestamp mean each download gets its own file, so runs never overwrite each other.
Find your logs directory
The logs directory defaults to a logs folder inside the package data directory, but you can move it with the directories.logs config key. To see the exact resolved path on your machine, use unshackle env info and read the Directories table.
"},{"location":"guide/troubleshooting/#what-a-log-entry-looks-like","title":"What a log entry looks like","text":"Every line is a self-contained JSON object. The first line of each log file records the environment:
{\"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
Quote unshackle_code_hash 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.
Subsequent lines record the operations: service calls, DRM licence requests, vault lookups, downloader progress, and errors. Common fields include:
Field Meaning timestamp UTC ISO-8601 time of the entry. session_id Short random ID shared by every entry in one run, handy for correlating lines. level DEBUG, INFO, WARNING, or ERROR. operation The action being logged, e.g. service_call, download_init, drm_get_widevine_license, vault_get_key, session_end. message Human-readable description (redacted). service Service tag the entry belongs to, when applicable. context Arbitrary structured detail for the operation. request / response HTTP method/URL and response metadata for network operations. duration_ms How long a timed operation took. success Whether the operation succeeded. error On failures: the exception type, message, and a full traceback array (all redacted)."},{"location":"guide/troubleshooting/#reading-and-filtering-the-log","title":"Reading and filtering the log","text":"Because each line is independent JSON, jq is the natural tool:
# 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
unshackle logs the binary-tool versions (shaka-packager, mp4decrypt, mkvmerge, FFmpeg, FFprobe) near the start of a dl run. Often that is the fastest way to make sure that a muxing or decryption failure is really a wrong-version problem.
"},{"location":"guide/troubleshooting/#debugging-drm-keys-with-debug_keys","title":"Debugging DRM keys with debug_keys","text":"By default, unshackle redacts the content keys in the JSON debug log. It writes any field that looks like a content key as [REDACTED]. 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 debug_keys:
debug_keys: true\n
unshackle cfg debug_keys true\n
With debug_keys: true, 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.
Keys are sensitive, turn this back off
debug_keys 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 false when you are done. Note that debug_keys only affects the JSON debug log file. It does not change what the console prints.
Fields that are always redacted regardless of debug_keys (anything whose name contains password, token, secret, auth, or cookie) stay masked, so credentials never leak even in a keys-on log.
"},{"location":"guide/troubleshooting/#debugging-http-traffic-with-debug_requests","title":"Debugging HTTP traffic with debug_requests","text":"When you pass -d, unshackle raises its own modules to DEBUG but deliberately silences the noisy low-level HTTP libraries (urllib3, requests, rnet, httpx, httpcore, hpack, h2) back down to WARNING. Without this, a single download would bury the useful output under thousands of connection-pool and HTTP/2 frame messages.
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 debug_requests:
debug_requests: true\n
unshackle cfg debug_requests true\n
With debug_requests: true, unshackle leaves those libraries at DEBUG level when you operate it with -d, so their request/response chatter appears in the console.
debug_requests needs -d to have any effect
The debug_requests toggle only decides whether unshackle silences the HTTP libraries when the -d flag is active. If you do not operate unshackle with -d (verbose console logging), it changes nothing. Combine them: unshackle -d dl ... with debug_requests: true in config.
"},{"location":"guide/troubleshooting/#what-gets-redacted","title":"What gets redacted","text":"unshackle redacts logged strings so that debug output is safe to share. It applies three passes to every logged message, error, and structured value:
- Secrets: unshackle replaces passwords, tokens, API secrets, auth values, and cookies with
[REDACTED]. - URLs: unshackle collapses every
http(s) URL to redacted. It keeps only the file extension, so a manifest still shows as redacted.mpd and a segment as redacted.m4s. This hides the CDN, manifest, segment, and licence-server locations, but keeps the type of resource. - Local paths: unshackle replaces install-root, virtualenv, and home-directory prefixes with tokens, so your username and machine layout do not appear in logs.
The redact_paths config key controls path redaction, and it is on by default:
redact_paths: true # default - mask local base directories in logged paths\n
Set redact_paths: false 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.
"},{"location":"guide/troubleshooting/#checking-your-environment","title":"Checking your environment","text":"Many \"download failed\" problems are really missing external tools or a config file that is not where you think it is. The unshackle env command group answers both questions before you dig into logs.
"},{"location":"guide/troubleshooting/#env-check","title":"env check","text":"unshackle env check verifies every external binary unshackle can use and prints a table of what's installed:
unshackle env check\n
It reports each tool's status (\u2713 installed / \u2717 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.
The required tools (unshackle will not get far without them) are:
Tool Purpose FFmpeg Media processing FFprobe Media analysis MKVToolNix (mkvmerge) MKV muxing mkvpropedit MKV metadata shaka-packager DRM decryption Optional tools unlock extra capabilities. For example, mp4decrypt (alternative decryptor), dovi_tool / HDR10Plus_tool (Dolby Vision / HDR10+), SubtitleEdit / CCExtractor (subtitle conversion and CC extraction), MPV / FFplay (playback preview), and git (service repositories) or docker (Gluetun VPN, see Proxies & VPN).
First thing to run when something breaks
If a decryption step errors, a mux fails, or a Dolby Vision title will not process, use unshackle env check first. A red \u2717 next to the relevant tool is the answer far more often than a bug in unshackle.
"},{"location":"guide/troubleshooting/#env-info","title":"env info","text":"unshackle env info shows where unshackle reads configuration from and where every working directory lives:
unshackle env info\n
- 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.
- It then prints a Directories table for every configured path:
downloads, temp, cache, cookies, logs, exports, wvds, prds, the services search paths, and more.
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 directories: overrides from your config.
"},{"location":"guide/troubleshooting/#env-clear","title":"env clear","text":"Stale cache or leftover temp files can cause confusing behaviour (an old cached title list, a half-written temp file). env clear wipes those directories safely:
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
Each command reports how many files it removed and how much space it freed, then recreates the empty directory.
Cache-related weirdness
If a service keeps returning stale titles or metadata even after the source changed, clear that service's cache with unshackle env clear cache <SERVICE>. See Vaults for the separate, persistent key-vault store, which env clear does not touch.
"},{"location":"guide/troubleshooting/#common-failure-modes-and-how-to-inspect-them","title":"Common failure modes and how to inspect them","text":"A required tool is missing
Symptom: decryption, muxing, or analysis fails early, sometimes with a \"binary not found\" style error.
Inspect: use unshackle env check and look for a red \u2717 on a required row. Run unshackle setup to install it, or install it by hand, and re-run.
Decryption produces garbage or fails
Symptom: the download completes but the file will not play, or the decrypt step errors.
Inspect: enable debug_keys and operate unshackle with -d. Then examine the JSON debug log's drm_* and vault_* operations to see which content keys unshackle fetched, and from where. Also make sure that shaka-packager (or mp4decrypt) shows a sane version in the download_init binary-versions entry. See DRM & CDM.
A vault served a wrong content key
Symptom: a warning names a content key and the vault it came from, either was bad, trying other vaults (the decode check failed) or is flagged bad, skipping (an earlier run flagged it). The download stops with The content key from the vault did not decrypt the track; run again, was bad and no other source has the key, or No vault or CDM produced a content key that decrypts the track when no source is left to try.
Inspect: while it decrypts a track whose content key came from a vault, unshackle keeps the ciphertext as a .enc 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 bad_keys 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.
A network request fails at the connection or TLS layer
Symptom: timeouts, connection resets, or handshake errors, and unshackle's own logs do not give the full cause.
Inspect: set debug_requests: true and operate unshackle with -d to show the underlying urllib3 / rnet / httpx logs. In the JSON debug log, filter for service_call operations to see which request failed. If you use a proxy, also read Proxies & VPN.
The wrong titles/metadata keep coming back
Symptom: a service returns outdated titles even after the source changed.
Inspect: the title cache is likely serving stale data. Clear it with unshackle env clear cache <SERVICE>, or bypass it for one run using the dl no-cache / reset-cache options (see Downloading and the CLI Reference).
A config value doesn't seem to apply
Symptom: a setting you edited has no effect.
Inspect: use unshackle env info to see which config file unshackle loaded, and unshackle cfg --list to dump the effective values. It is common to edit a config file in a location unshackle does not read from. See below.
"},{"location":"guide/troubleshooting/#why-is-my-config-not-being-picked-up","title":"Why is my config not being picked up?","text":"unshackle loads the first unshackle.yaml it finds, in this order:
unshackle.yaml inside the package's namespace directory. unshackle.yaml in the parent of that directory. unshackle.yaml in your OS user-config directory: on Linux ~/.config/unshackle/unshackle.yaml, on Windows %LOCALAPPDATA%\\unshackle\\unshackle.yaml, on macOS ~/Library/Application Support/unshackle/unshackle.yaml.
If you have config in more than one of these, an earlier one wins and unshackle silently ignores your edits to a later file. unshackle env info 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 cfg command.
Developer note: structured logging in code
Service and command code sends entries through the shared log_event(...) helper (and the timed_operation(...) context manager for timing a block) from unshackle.core.utilities. 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 log_event(\"my_feature_event\", message=\"...\", context={...}). 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 debug_keys enabled.
"},{"location":"guide/troubleshooting/#logging-conventions-when-adding-entries","title":"Logging conventions when adding entries","text":"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 log_event signature does not enforce them, so they are easy to miss and worth stating explicitly.
Log levels are a flow skeleton, not just severity
Treat level as structure, not decoration. Send exactly one INFO milestone per pipeline stage so that jq 'select(.level==\"INFO\")' reads back the whole end-to-end flow of a run. Everything internal goes to DEBUG. Failures go to ERROR. A sparse INFO is the whole point. It is the line a developer skims first to see where a run got to before it broke.
# Read the pipeline's high-level flow, one line per stage\njq 'select(.level == \"INFO\")' unshackle_debug_EXAMPLE_20260703-142530.jsonl\n
No raw dumps
Never log a full Tracks object, an MPD/manifest body, or a response payload. Log only counts, ids, sizes, and safe_display_url(url). 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.
Operation names: <area>_<event>, no registry
Operation names are plain lowercase strings that follow an <area>_<event> convention: manifest_dash_parse, drm_decrypt, vault_get_key, tool_run. 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.
Message reads alone; data lives in fields
Give every entry a single-sentence message that stands on its own. Put all structured data (context, counts, ids, duration_ms) in fields, not in the prose. This separation lets the log be both human-scannable and machine-filterable. A message like \"Parsed DASH manifest\" with context={\"video\": 4, \"audio\": 2} beats \"Parsed manifest with 4 video and 2 audio tracks\".
Let tool runs log themselves
For external-tool calls (FFmpeg, mkvmerge, dovi_tool, and friends), route through run_step / ffprobe, which auto-emit a tool_run entry capturing the binary's version, return code, and duration consistently. Only fall back to calling log_tool_run manually for a direct subprocess.run you genuinely cannot route through run_step. Auto-logging is the preferred path precisely because it captures those fields the same way every time.
"},{"location":"guide/vaults/","title":"Key Vaults","text":"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.
Vaults are entirely optional, but if you download regularly they are one of the biggest quality-of-life improvements you can configure.
Vaults save license calls even on the very first download
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.
"},{"location":"guide/vaults/#what-a-vault-stores","title":"What a vault stores","text":"A vault stores every content key as a KID \u2192 KEY pair, grouped by service:
- KID (Key ID): a 16-byte identifier for a specific encrypted track, stored as 32 lowercase hex characters with no dashes.
- KEY: the 16-byte content key that decrypts that track, also 32 hex characters.
- Service: the canonical service tag (for example
EXAMPLE, not ExampleService) that namespaces the key. Each service gets its own logical table.
Why keys are matched by KID
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.
Null keys are ignored everywhere
A content key made entirely of zeroes (00000000000000000000000000000000) 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.
"},{"location":"guide/vaults/#how-lookups-and-caching-work","title":"How lookups and caching work","text":"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.
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:
- unshackle skips keys that already exist in a vault (it never overwrites or deletes existing data).
- A vault marked
no_push: true receives lookups, but unshackle never writes to it. This is useful for read-only or shared upstream vaults you do not own.
unshackle pushes keys from every source, not only a local CDM. A run against a remote server that licenses with its own CDM (--remote) writes the keys the server returns, and unshackle import writes the keys it reads from an export file.
"},{"location":"guide/vaults/#wrong-keys-from-a-poisoned-vault","title":"Wrong keys from a poisoned vault","text":"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. A KID that is not in this map, 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. Without FFmpeg there is no check at all.
When the decode fails, unshackle:
- Flags the KID:KEY in the
bad_keys 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 no_push, where only the flag is written. A flagged pair cannot go back into a local vault from another vault, a later run, or kv copy. A licence that returns the pair clears the flag and stores it. An API vault that served the pair also gets a report; HTTP and MySQL 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. - 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.
- 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.
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.
Per-segment decryption gives up the retry. With decrypt_segments 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.
unshackle copies a content key from one vault to the others only after this check passes, so a wrong content key 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 bad_keys.
A good two-vault setup
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.
"},{"location":"guide/vaults/#configuring-vaults","title":"Configuring vaults","text":"Declare vaults under the key_vaults list in your unshackle config file. Each entry is a mapping with two required fields, type (which backend to use) and name (a label you choose), plus whatever settings that backend needs.
unshackle.yamlkey_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
The type value is matched to a vault backend by name. The four backends that ship with unshackle are SQLite, MySQL, HTTP, and API, described below.
SQLite vaults are loaded critically
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. MySQL, HTTP, and API vaults are loaded leniently: if one fails to load it is logged and skipped, and the download continues with the remaining vaults.
"},{"location":"guide/vaults/#vault_timeout","title":"vault_timeout","text":"Network-backed vaults (HTTP and API) accept an optional per-vault timeout in seconds. If you omit it, unshackle injects the global default:
unshackle.yamlvault_timeout: 10.0 # default, in seconds\n
A timeout set inline on an individual vault always wins over this global value. The SQLite and MySQL backends do not take a timeout field. MySQL uses vault_timeout as its connect_timeout instead, and falls back to the pymysql default of 10 seconds when vault_timeout is 0. To use a different connect timeout, set connect_timeout on the vault.
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.
"},{"location":"guide/vaults/#sqlite-backend","title":"SQLite backend","text":"A locally-accessed SQLite database file. This is the simplest and fastest option and needs no server.
unshackle.yamlkey_vaults:\n - type: SQLite\n name: local\n path: ~/.local/share/unshackle/vaults/local.db\n
Field Required Description type yes Must be SQLite. name yes A label for this vault. path yes Path to the database file. ~ is expanded. The file (and its tables) are created automatically on first use. no_push no If true, keys are read but never written. Defaults to false. Each service gets its own table (named after the service tag), created on demand with kid and key_ columns. Connections use WAL journaling with a 30-second busy timeout, so multiple threads can safely use the same database file.
One more table, bad_keys, 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.
Moving the .db file silently forks your vault
Because the file is created on demand, if you relocate an existing .db without updating path 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.
Keep a local SQLite vault even when you share a MySQL one
The SQLite vault is best thought of as an offline-only backup should anything ever happen to a shared MySQL 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.
"},{"location":"guide/vaults/#mysql-backend","title":"MySQL backend","text":"A remotely-accessed MySQL/MariaDB database, ideal for sharing keys across several machines. It connects via pymysql. Prefer MariaDB over MySQL where you have the choice.
The vault connects directly to the database server
A MySQL vault (like SQLite) 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.
unshackle.yamlkey_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
Field Required Description type yes Must be MySQL. name yes A label for this vault. host yes Database server hostname or IP. database yes Database (schema) name. username yes Login user. no_push no If true, keys are read but never written. Any additional fields you provide (such as password, port, or ssl) are passed straight through to pymysql.connect, so you can use the full range of its connection options.
Account security is on you, not on unshackle
unshackle enforces none of this. It is operational policy for a database that may be shared with a group. Never connect with the root 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 unshackle database, and grant normal users only SELECT and INSERT. Reserve the CREATE grant for a single trusted user who bootstraps the service tables (see kv prepare); everyone else can insert new keys but should not be creating tables.
Grants determine what the vault can do
On connection the backend reads its own SHOW GRANTS. It requires at least SELECT to load at all (a missing SELECT grant makes the vault fail to load). Writing keys additionally needs INSERT, and creating a new service table needs CREATE. A read-only account still works fine as a lookup source. It cannot push new keys. Because MySQL is loaded leniently during downloads, a permission problem will not abort the run.
"},{"location":"guide/vaults/#http-backend","title":"HTTP backend","text":"A flexible HTTP vault that speaks one of three wire protocols, selected with api_mode. Use this to integrate with a community or self-hosted vault service.
api_mode Transport Authentication Notes query (default) GET with query parameters username + password Full read and write. json POST with a JSON payload password used as a token Read and write per content key; cannot bulk-enumerate keys. decrypt_labs POST in DecryptLabs format api_key sent as a header Read-only. no_push is forced on. query modejson modedecrypt_labs mode unshackle.yamlkey_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
Query mode requires username. Both the username and password are sent as query parameters on each request.
unshackle.yamlkey_vaults:\n - type: HTTP\n name: jsonvault\n host: https://vault.example.com/rpc\n api_mode: json\n password: \"your-api-token\"\n
Requests are POSTed as {\"method\": ..., \"params\": ..., \"token\": ...} using methods like GetKey, InsertKey, and GetServices. Bulk writes (kv copy, kv add) first try InsertKeys with params: {\"keys\": {kid: key, ...}, \"service\": ..., \"title\": ...} (up to 500 content keys per call) and expect {\"inserted\": <count>} back. A server that answers HTTP 404 or Unknown JSON-RPC method to InsertKeys gets one InsertKey call per content key for the rest of the run instead. This mode cannot list all keys in bulk, so a kv copy from a json vault relies on the remote server's own duplicate handling.
unshackle.yamlkey_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
A read-only lookup source. The API key is sent in a decrypt-labs-api-key header and the vault refuses all writes.
Field Required Description type yes Must be HTTP. name yes A label for this vault. host yes Base URL of the vault API. api_mode no query (default), json, or decrypt_labs. username for query Required in query mode; ignored otherwise. password one of these Password (query mode) or token (json mode). api_key one of these Alternative to password; used for decrypt_labs. If you give both, api_key wins. no_push no Read-only when true (always true for decrypt_labs). timeout no Request timeout in seconds; defaults to vault_timeout. You must supply either password or api_key, or the vault will fail to load.
"},{"location":"guide/vaults/#api-backend","title":"API backend","text":"A simple RESTful HTTP vault with a fixed, well-defined protocol. Authentication is a bearer token.
unshackle.yamlkey_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
Field Required Description type yes Must be API. name yes A label for this vault. uri yes Base URI of the vault API (a trailing slash is trimmed). token yes Bearer token, sent as Authorization: Bearer <token>. no_push no If true, keys are read but never written. timeout no Request timeout in seconds; defaults to vault_timeout. headers no Extra HTTP headers sent with every request, for example the Cloudflare Access service-token headers CF-Access-Client-Id and CF-Access-Client-Secret. The backend talks to endpoints under uri (for example GET {uri}/{service}/{kid} to look up a single key). It interprets a numeric code field in each JSON response to detect errors such as an invalid token, rate limiting, or an invalid service tag.
This is unshackle's own protocol, not a generic vault client
The API 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 HTTP 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.
DecryptLabs shortcut
An API vault whose name contains decrypt_labs will have its token filled in automatically from a global decrypt_labs_api_key in your config if you leave token unset. This lets you keep the API key in one place.
"},{"location":"guide/vaults/#managing-vaults-with-unshackle-kv","title":"Managing vaults with unshackle kv","text":"The kv command group manages the contents of your configured vaults. Every subcommand refers to vaults by the name you gave them in key_vaults; an unknown name is an error.
$ unshackle kv --help\n
"},{"location":"guide/vaults/#kv-add-import-keys-from-a-file","title":"kv add: import keys from a file","text":"Add KID:KEY pairs to one or more vaults for a given service. The file must contain one pair per line as HEX:HEX (32 hex characters each); lines that do not match are ignored.
$ unshackle kv add keys.txt EXAMPLE local shared\n
keys.txt9a04f07998404286ab92e65be0885f95:b1c2d3e4f5a6978012345678deadbeef\n0e7cc1a4e2f9411db0f24a3fbb8f8b21:00112233445566778899aabbccddeeff\n
The service argument (EXAMPLE above) is normalized to its canonical tag automatically. Keys that already exist in a vault are reported as skipped.
"},{"location":"guide/vaults/#kv-search-find-a-content-key-by-kid","title":"kv search: find a content key by KID","text":"Search your vaults for a KID and print any matching content key.
$ unshackle kv search 9a04f07998404286ab92e65be0885f95\n
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:
Option Description -s, --service Limit the search to a single service tag. -v, --vault Limit the search to one configured vault by name. Note
Remote vaults that cannot enumerate their service tables (for example an HTTP vault in json or decrypt_labs mode) can only be searched when you also pass --service. Without it, they are skipped.
"},{"location":"guide/vaults/#kv-copy-copy-keys-between-vaults","title":"kv copy: copy keys between vaults","text":"Copy every content key from one or more source vaults into a single destination vault. kv copy never alters existing rows; it adds only genuinely new KIDs and skips null keys.
$ unshackle kv copy shared local\n
The first argument is the destination; the rest are sources. You can supply several sources at once:
$ unshackle kv copy local shared community\n
Option Description -s, --service Only copy the given service. -l, --local-only Only copy services you have installed locally, skipping tables for unknown services. --service and --local-only are mutually exclusive.
A pair the destination vault has flagged in bad_keys is left behind, so a copy does not undo a flag. bad_keys is never treated as a service, so its rows are never copied into a service table.
"},{"location":"guide/vaults/#kv-sync-mirror-vaults-both-ways","title":"kv sync: mirror vaults both ways","text":"Make each of two or more vaults hold every content key the others have. This is effectively a two-way copy between each pair, so afterwards all listed vaults hold the same set of keys.
$ unshackle kv sync local shared\n
It accepts the same --service and --local-only options as copy, and requires at least two vaults. It runs copy between each pair, so it skips flagged pairs and the bad_keys table in the same way.
"},{"location":"guide/vaults/#kv-prepare-pre-create-service-tables","title":"kv prepare: pre-create service tables","text":"Create the per-service tables on table-based vaults (SQLite, MySQL) ahead of time, for every service you have installed. Vaults that do not use tables (the network-backed HTTP and API backends) are skipped.
$ unshackle kv prepare shared\n
This is mainly useful with a MySQL vault where you want the tables created once by an account that has the CREATE grant.
"},{"location":"guide/vaults/#see-also","title":"See also","text":" - Downloading: how keys are recovered and used during a download.
"},{"location":"reference/api/config/","title":"Config API","text":"Auto-generated reference for the Config object that models the unshackle configuration file. For a human-friendly walkthrough of every config key, see the Configuration Reference.
"},{"location":"reference/api/config/#unshackle.core.config.Config","title":"Config","text":"Config(**kwargs)\n
"},{"location":"reference/api/config/#unshackle.core.config.Config.validate_output_templates","title":"validate_output_templates","text":"validate_output_templates()\n
Validate output template configurations and warn about potential issues.
"},{"location":"reference/api/config/#unshackle.core.config.Config.get_folder_template","title":"get_folder_template","text":"get_folder_template(kind)\n
Find the folder template for the given title kind.
kind: one of \"movies\", \"series\", \"songs\", \"albums\". Falls back to the legacy single-string folder template, then \"\".
"},{"location":"reference/api/config/#unshackle.core.config.Config.get_template_separator","title":"get_template_separator","text":"get_template_separator(template_type='movies')\n
Get the filename separator for the given template type.
Analyzes the active template to determine whether it uses dots or spaces between variables. Falls back to dot separator (scene-style) by default.
Parameters:
Name Type Description Default template_type str One of \"movies\", \"series\", or \"songs\".
'movies'"},{"location":"reference/api/config/#unshackle.core.config.restore_bool_languages","title":"restore_bool_languages","text":"restore_bool_languages(data)\n
Put back the language tags no and yes, which YAML reads as booleans.
"},{"location":"reference/api/config/#unshackle.core.config.resolve_decryption","title":"resolve_decryption","text":"resolve_decryption(decryption_map, default, service)\n
Pick the decryption backend for a service (case-insensitive), falling back to default.
"},{"location":"reference/api/config/#unshackle.core.config.resolve_cdm_name","title":"resolve_cdm_name","text":"resolve_cdm_name(cdm, service, override=None)\n
Find a service's top-level CDM entry (case-insensitive), with default fallback.
"},{"location":"reference/api/config/#unshackle.core.config.cdm_entry_names_device","title":"cdm_entry_names_device","text":"cdm_entry_names_device(entry, profile=None)\n
Whether a per-service cdm entry names a device when no quality is known.
An entry that selects only by quality, or by a different profile, names none.
"},{"location":"reference/api/config/#unshackle.core.config.get_config_path","title":"get_config_path","text":"get_config_path()\n
Get Path to Config from any one of the possible locations.
Returns None if no config file could be found.
"},{"location":"reference/api/drm/","title":"DRM API","text":"Auto-generated reference for the DRM systems: Widevine, PlayReady, ClearKey, and related helpers. For configuring DRM as a user, see DRM & CDM Setup.
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKey","title":"ClearKey","text":"ClearKey(key, iv=None)\n
AES-128 ClearKey (HLS) DRM system.
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.
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKey.warn_clear","title":"warn_clear","text":"warn_clear(reason)\n
Warn once per track that unshackle passed a segment through undecrypted.
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKey.decrypt","title":"decrypt","text":"decrypt(path)\n
Decrypt a Track with AES-128 ClearKey (HLS) DRM.
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKey.from_m3u_key","title":"from_m3u_key classmethod","text":"from_m3u_key(m3u_key, session=None)\n
Load a ClearKey from an M3U(8) Playlist's EXT-X-KEY.
Parameters:
Name Type Description Default m3u_key Key A Key object parsed from a m3u(8) playlist using the m3u8 library.
required session Optional[Session] Optional HTTP session used to request external URIs with. Useful to set headers, proxies, cookies, and so forth.
None"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC","title":"ClearKeyCENC","text":"ClearKeyCENC(kids, laurl=None, content_keys=None, **kwargs)\n
W3C EME ClearKey (org.w3.clearkey) DRM System over MPEG-CENC tracks.
Distinct from the HLS AES-128 ClearKey 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).
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.kid","title":"kid property","text":"kid\n
Get first Key ID, if any.
"},{"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":" Bases: Exception
KID (Encryption Key ID) was not found.
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.Exceptions.CEKNotFound","title":"CEKNotFound","text":" Bases: Exception
CEK (Content Encryption Key) for KID was not found in License.
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.Exceptions.EmptyLicense","title":"EmptyLicense","text":" Bases: Exception
License returned no Content Encryption Keys.
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.to_dict","title":"to_dict","text":"to_dict()\n
Serialise this DRM instance for export/import (KIDs + license URL).
unshackle stores the content keys once at the export's track level, and does not duplicate them here.
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.get_license_challenge","title":"get_license_challenge","text":"get_license_challenge()\n
Assemble the W3C EME ClearKey JSON license request for the unkeyed KIDs.
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.get_content_keys","title":"get_content_keys","text":"get_content_keys(*, licence, session=None)\n
Get Content Keys for this DRM Instance from a ClearKey license server.
The licence param is a function. unshackle gives it the W3C JSON license request as challenge. 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.
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.decrypt","title":"decrypt","text":"decrypt(path)\n
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.
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.mp4decrypt_key_args","title":"mp4decrypt_key_args","text":"mp4decrypt_key_args()\n
Build the mp4decrypt --key arguments for every content key.
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.decrypt_with_mp4decrypt","title":"decrypt_with_mp4decrypt","text":"decrypt_with_mp4decrypt(path)\n
Decrypt using mp4decrypt
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.decrypt_with_shaka_packager","title":"decrypt_with_shaka_packager","text":"decrypt_with_shaka_packager(path)\n
Decrypt with shaka-packager
"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa","title":"MonaLisa","text":"MonaLisa(ticket, device_path, tool_path=None, **kwargs)\n
MonaLisa DRM System.
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.
Initialise MonaLisa DRM.
Parameters:
Name Type Description Default ticket Union[str, bytes] PSSH value from service API (base64 string or raw bytes).
required device_path Path Path to the CDM device file (.mld).
required tool_path Optional[Path] Optional path to an external decryption binary.
None **kwargs Any Additional metadata stored in self.data.
{} Raises:
Type Description TicketNotFound If ticket/PSSH is empty.
KeyExtractionFailed If content key extraction fails.
"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.kid","title":"kid property","text":"kid\n
Get the Key ID.
"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.key","title":"key property","text":"key\n
Get the content key as hex string.
"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.pssh","title":"pssh property","text":"pssh\n
Get the raw PSSH/ticket value as a string.
Returns:
Type Description str The raw PSSH value as a base64 string.
"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.content_id","title":"content_id property","text":"content_id\n
Extract the Content ID from the PSSH for display.
The PSSH contains an embedded Content ID at bytes 21-75 with format: H5DCID-V3-P1-YYYYMMDD-HHMMSS-MEDIAID-TIMESTAMP-SUFFIX
Returns:
Type Description Optional[str] The Content ID string if extractable, None otherwise.
"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.content_keys","title":"content_keys property","text":"content_keys\n
Get content keys in the same format as Widevine/PlayReady.
Returns:
Type Description dict[UUID, str] Dictionary mapping KID to the content key hex string.
"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.key_pair","title":"key_pair property","text":"key_pair\n
The formatted KID:KEY for CLI decryptors (32hex:32hex).
"},{"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":" Bases: Exception
Raised when the caller gives no PSSH/ticket data.
"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.Exceptions.KeyExtractionFailed","title":"KeyExtractionFailed","text":" Bases: Exception
Raised when content key extraction from the ticket fails.
"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.extract_keys","title":"extract_keys","text":"extract_keys()\n
Extract keys from the ticket using the MonaLisa CDM.
"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.from_ticket","title":"from_ticket classmethod","text":"from_ticket(ticket, device_path, tool_path=None)\n
Make a MonaLisa DRM instance from a PSSH/ticket.
Parameters:
Name Type Description Default ticket Union[str, bytes] PSSH value from service API.
required device_path Path Path to the CDM device file (.mld).
required tool_path Optional[Path] Optional path to an external decryption binary.
None Returns:
Type Description MonaLisa MonaLisa DRM instance with extracted keys.
"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.decrypt_segment","title":"decrypt_segment","text":"decrypt_segment(segment_path, output_path=None)\n
Decrypt an individual segment file using the configured CLI tool via subprocess.
Parameters:
Name Type Description Default segment_path Path Path to the segment file to decrypt.
required output_path Optional[Path] Optional path for the decrypted output segment.
None"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.decrypt","title":"decrypt","text":"decrypt(path, output_path=None, *, is_segment=False)\n
Decrypt a media file (segment or track) using the configured CLI tool via subprocess.
Parameters:
Name Type Description Default path Path Path to the target file to decrypt.
required output_path Optional[Path] Optional path for the decrypted output file.
None is_segment bool Set True if this is an individual segment rather than a full track.
False"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady","title":"PlayReady","text":"PlayReady(pssh, kid=None, pssh_b64=None, **kwargs)\n
PlayReady DRM System.
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.extract_kids_from_pssh_b64","title":"extract_kids_from_pssh_b64","text":"extract_kids_from_pssh_b64(pssh_b64)\n
Extract all KIDs from base64-encoded PSSH data.
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.to_dict","title":"to_dict","text":"to_dict()\n
Serialise this DRM instance for export/import (PSSH + KIDs).
unshackle stores the content keys once at the export's track level, and does not duplicate them here.
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.header_kids","title":"header_kids staticmethod","text":"header_kids(header)\n
Return the KIDs one WRM header names, in header order.
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.absorb","title":"absorb","text":"absorb(*others)\n
Fold sibling PlayReady objects into this one so their headers and KIDs get licensed too.
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.
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.distinct_headers","title":"distinct_headers","text":"distinct_headers()\n
Return the WRM headers to license, deduplicated by the KID set each one names.
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.
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.pro_b64_for","title":"pro_b64_for staticmethod","text":"pro_b64_for(header)\n
Build a base64 one-record PlayReady Object holding only this header.
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.
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.extract_keys_from_cdm","title":"extract_keys_from_cdm","text":"extract_keys_from_cdm(cdm, session_id)\n
Extract keys from CDM session with cross-library compatibility.
Parameters:
Name Type Description Default cdm Cdm CDM instance
required session_id bytes Session identifier
required Returns:
Type Description dict Dictionary mapping KID UUIDs to hex keys
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.get_content_keys","title":"get_content_keys","text":"get_content_keys(cdm, certificate, licence)\n
License every distinct WRM header whose KIDs still lack a content key.
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.
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.
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.detect_revocation","title":"detect_revocation staticmethod","text":"detect_revocation(text)\n
Return the decoded error string if a revocation HRESULT is present, else None.
Reads the code from the raw SOAP body (0x8004C065) or from an exception message that carries it, so this method covers any service.
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.decrypt","title":"decrypt","text":"decrypt(path)\n
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.
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.own_kids","title":"own_kids","text":"own_kids()\n
Return the KIDs that identify this track's own content key.
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.
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.mp4decrypt_key_args","title":"mp4decrypt_key_args","text":"mp4decrypt_key_args()\n
Build the mp4decrypt --key arguments for every content key and the zero-KID fallback.
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.decrypt_with_mp4decrypt","title":"decrypt_with_mp4decrypt","text":"decrypt_with_mp4decrypt(path)\n
Decrypt using mp4decrypt
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.decrypt_with_shaka_packager","title":"decrypt_with_shaka_packager","text":"decrypt_with_shaka_packager(path)\n
Decrypt with shaka-packager (original method)
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine","title":"Widevine","text":"Widevine(pssh, kid=None, **kwargs)\n
Widevine DRM System.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.pssh","title":"pssh property","text":"pssh\n
Get Protection System Specific Header Box.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.kid","title":"kid property","text":"kid\n
Get first Key ID, if any.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.kids","title":"kids property","text":"kids\n
Get all Key IDs from PSSH, falling back to the externally provided KID.
"},{"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":" Bases: Exception
PSSH (Protection System Specific Header) was not found.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.Exceptions.KIDNotFound","title":"KIDNotFound","text":" Bases: Exception
KID (Encryption Key ID) was not found.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.Exceptions.CEKNotFound","title":"CEKNotFound","text":" Bases: Exception
CEK (Content Encryption Key) for KID was not found in License.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.Exceptions.EmptyLicense","title":"EmptyLicense","text":" Bases: Exception
License returned no Content Encryption Keys.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.from_track","title":"from_track classmethod","text":"from_track(track, session=None)\n
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.
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.
You can give your own requests.Session to use custom headers and more.
Raises:
Type Description PSSHNotFound If the PSSH was not found within the data.
KIDNotFound If the KID was not found within the data or PSSH.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.from_init_data","title":"from_init_data classmethod","text":"from_init_data(init_data)\n
Get PSSH and KID from within Initialization Segment Data.
Use this method only when a PSSH cannot be given directly. It is rare to need to use this.
Raises:
Type Description PSSHNotFound If the PSSH was not found within the data.
KIDNotFound If the KID was not found within the data or PSSH.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.to_dict","title":"to_dict","text":"to_dict()\n
Serialise this DRM instance for export/import (PSSH + KIDs).
unshackle stores the content keys once at the export's track level, and does not duplicate them here.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.get_content_keys","title":"get_content_keys","text":"get_content_keys(cdm, certificate, licence)\n
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.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.decrypt","title":"decrypt","text":"decrypt(path)\n
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.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.own_kids","title":"own_kids","text":"own_kids()\n
Return the KIDs that identify this track's own content key.
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.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.mp4decrypt_key_args","title":"mp4decrypt_key_args","text":"mp4decrypt_key_args()\n
Build the mp4decrypt --key arguments for every content key and the zero-KID fallback.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.decrypt_with_mp4decrypt","title":"decrypt_with_mp4decrypt","text":"decrypt_with_mp4decrypt(path)\n
Decrypt using mp4decrypt
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.decrypt_with_shaka_packager","title":"decrypt_with_shaka_packager","text":"decrypt_with_shaka_packager(path)\n
Decrypt with shaka-packager (original method)
"},{"location":"reference/api/drm/#unshackle.core.drm.drm_from_dict","title":"drm_from_dict","text":"drm_from_dict(data)\n
Reconstruct a Widevine/PlayReady/ClearKeyCENC DRM instance from its to_dict() form.
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.
"},{"location":"reference/api/drm/#unshackle.core.drm.real_kids","title":"real_kids","text":"real_kids(drm)\n
Return the KIDs a DRM object names, without the all-zero and test-pattern placeholders.
"},{"location":"reference/api/drm/#unshackle.core.drm.own_kids","title":"own_kids","text":"own_kids(drm)\n
Return the real KIDs that identify the track's own content key, as the DRM object knows them.
"},{"location":"reference/api/service/","title":"Service API","text":"Auto-generated reference for the Service base class that every service plugin subclasses. See Creating a Service for a guided walkthrough and Service Architecture for the wider object model.
"},{"location":"reference/api/service/#unshackle.core.service.TimeoutSession","title":"TimeoutSession","text":" Bases: Session
requests.Session applying DEFAULT_TIMEOUT when the caller passes none.
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 timeout= wins. :class:TimeoutHTTPAdapter on the mounted adapters still replaces an explicit timeout=None with the default, so there is no unbounded read, as with RnetSession where the client-level timeouts always apply. Pass a large timeout instead.
"},{"location":"reference/api/service/#unshackle.core.service.TimeoutHTTPAdapter","title":"TimeoutHTTPAdapter","text":"TimeoutHTTPAdapter(\n *args, timeout=DEFAULT_TIMEOUT, **kwargs\n)\n
Bases: HTTPAdapter
HTTPAdapter applying DEFAULT_TIMEOUT when the caller passes none.
Backstops :class:TimeoutSession for the session.send(prepared) path, which bypasses Session.request. RnetSession bounds those too through its client, so this keeps parity. A per-request non-None timeout= wins. None (unset, or explicitly passed) gets the default, because the adapter cannot distinguish the two, and rnet has no unbounded mode either.
Source code in unshackle/core/service.py def __init__(self, *args: Any, timeout: Any = DEFAULT_TIMEOUT, **kwargs: Any) -> None:\n self.default_timeout = timeout\n super().__init__(*args, **kwargs)\n
"},{"location":"reference/api/service/#unshackle.core.service.TrackRequest","title":"TrackRequest dataclass","text":"TrackRequest(\n codecs=list(),\n ranges=(lambda: [SDR])(),\n best_available=False,\n)\n
Holds what the user requested for video codec and range selection.
Services read from this instead of ctx.parent.params for vcodec/range.
Attributes:
Name Type Description codecs list[Codec] Requested codecs from CLI. Empty list means no filter (accept any).
ranges list[Range] Requested ranges from CLI. Defaults to [SDR].
"},{"location":"reference/api/service/#unshackle.core.service.Service","title":"Service","text":"Service(ctx)\n
The Service Base Class.
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.
Source code in unshackle/core/service.py def __init__(self, ctx: click.Context):\n console.print(Padding(Rule(f\"[rule.text]Service: {self.__class__.__name__}\"), (1, 2)))\n\n self.config = ctx.obj.config\n\n self.log = logging.getLogger(self.__class__.__name__)\n\n self.session = self.get_session()\n self.cache = Cacher(self.__class__.__name__)\n self.title_cache = TitleCacher(self.__class__.__name__)\n self.cache_dir = config.directories.cache / self.__class__.__name__\n\n self.ctx = ctx\n self.credential = None # Will be set in authenticate()\n self.current_region = None # Will be set based on proxy/geolocation\n self._input_bridge: Optional[InputBridge] = None\n\n # Set track request from CLI params - services can read/override in their __init__\n vcodec = ctx.parent.params.get(\"vcodec\") if ctx.parent else None\n range_ = ctx.parent.params.get(\"range_\") if ctx.parent else None\n best_available = ctx.parent.params.get(\"best_available\", False) if ctx.parent else False\n self.track_request = TrackRequest(\n codecs=list(vcodec) if vcodec else [],\n ranges=list(range_) if range_ else [Video.Range.SDR],\n best_available=bool(best_available),\n )\n\n 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} -> {sanitize_proxy_for_log(mapped_value)}\"\n )\n if proxy_provider_name:\n # Specific provider requested\n try:\n proxy_provider = find_provider(ctx.obj.proxy_providers, proxy_provider_name)\n except ValueError:\n proxy_provider = None\n if proxy_provider:\n mapped_proxy_uri = proxy_provider.get_proxy(mapped_value)\n if mapped_proxy_uri:\n proxy = mapped_proxy_uri\n self.log.info(\n f\"Using mapped proxy from {proxy_provider.__class__.__name__}: \"\n f\"{sanitize_proxy_for_log(proxy, mask_host=isinstance(proxy_provider, Basic))}\"\n )\n else:\n self.log.warning(\n f\"Failed to get proxy for mapped value '{sanitize_proxy_for_log(mapped_value)}', using default\"\n )\n else:\n self.log.warning(f\"Proxy provider '{proxy_provider_name}' not found, using default proxy\")\n else:\n for proxy_provider in ctx.obj.proxy_providers:\n mapped_proxy_uri = proxy_provider.get_proxy(mapped_value)\n if mapped_proxy_uri:\n proxy = mapped_proxy_uri\n self.log.info(\n f\"Using mapped proxy from {proxy_provider.__class__.__name__}: \"\n f\"{sanitize_proxy_for_log(proxy, mask_host=isinstance(proxy_provider, Basic))}\"\n )\n break\n else:\n self.log.warning(\n f\"No provider could resolve mapped value '{sanitize_proxy_for_log(mapped_value)}', using default\"\n )\n\n if not proxy:\n # don't override the explicit proxy set by the user, even if they may be geoblocked\n with console.status(\"Checking if current region is Geoblocked...\", spinner=\"dots\"):\n if self.GEOFENCE 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 \"Pass --proxy with a proxy outside the blocked regions.\"\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 for proxy_provider in ctx.obj.proxy_providers:\n proxy = proxy_provider.get_proxy(requested_proxy)\n if proxy:\n self.log.info(f\"Got Proxy from {proxy_provider.__class__.__name__}\")\n break\n if not proxy:\n self.log.warning(\n f\"No proxy available for {requested_proxy}. \"\n f\"Pass --proxy with a proxy in {requested_proxy}, or the request can fail.\"\n )\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 # 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 \"Pass --proxy with a proxy outside the blocked regions.\"\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
"},{"location":"reference/api/service/#unshackle.core.service.Service.is_region_allowed","title":"is_region_allowed classmethod","text":"is_region_allowed(region)\n
True when an exit IP in region (two-letter region code, any case) can use the service.
An unknown region (None or empty) is allowed, because there is nothing to compare.
Source code in unshackle/core/service.py @classmethod\ndef is_region_allowed(cls, region: Optional[str]) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.get_tracks_for_variants","title":"get_tracks_for_variants","text":"get_tracks_for_variants(title, fetch_fn)\n
Call fetch_fn for each codec/range combo in track_request, merge results.
Services that need separate API calls per codec/range combo can use this helper from their get_tracks() implementation.
The fetch_fn signature should be: (title, codec, range_) -> Tracks
For HYBRID range, this helper calls fetch_fn with HDR10 and DV separately, then merges the DV video tracks into the HDR10 result.
Parameters:
Name Type Description Default title Title_T The title to process.
required fetch_fn Callable[..., Tracks] A callable that fetches tracks for a specific codec/range.
required Source code in unshackle/core/service.py def get_tracks_for_variants(\n self,\n title: Title_T,\n fetch_fn: Callable[..., Tracks],\n) -> Tracks:\n \"\"\"Call fetch_fn for each codec/range combo in track_request, merge results.\n\n Services that need separate API calls per codec/range combo can use this\n helper from their get_tracks() implementation.\n\n The fetch_fn signature should be: (title, codec, range_) -> Tracks\n\n For HYBRID range, this helper calls fetch_fn with HDR10 and DV separately,\n then merges the DV video tracks into the HDR10 result.\n\n Args:\n title: The title to process.\n fetch_fn: A callable that fetches tracks for a specific codec/range.\n \"\"\"\n all_tracks = Tracks()\n first = True\n\n codecs = self.track_request.codecs or [None]\n ranges = self.track_request.ranges or [Video.Range.SDR]\n\n for range_val in ranges:\n if range_val == Video.Range.HYBRID:\n # HYBRID: fetch HDR10 first (full tracks), then DV (video only)\n for codec_val in codecs:\n try:\n hdr_tracks = fetch_fn(title, codec=codec_val, range_=Video.Range.HDR10)\n except (ValueError, SystemExit) as e:\n if self.track_request.best_available:\n self.log.warning(f\" - HDR10 not available for HYBRID, skipping ({e})\")\n continue\n raise\n if first:\n all_tracks.add(hdr_tracks, warn_only=True)\n if hdr_tracks.manifest_url and not all_tracks.manifest_url:\n all_tracks.manifest_url = hdr_tracks.manifest_url\n first = False\n else:\n for video in hdr_tracks.videos:\n all_tracks.add(video, warn_only=True)\n\n try:\n dv_tracks = fetch_fn(title, codec=codec_val, range_=Video.Range.DV)\n for video in dv_tracks.videos:\n all_tracks.add(video, warn_only=True)\n except (ValueError, SystemExit):\n self.log.info(\" - No DolbyVision manifest available for HYBRID\")\n else:\n for codec_val in codecs:\n try:\n tracks = fetch_fn(title, codec=codec_val, range_=range_val)\n except (ValueError, SystemExit) as e:\n if self.track_request.best_available:\n codec_name = codec_val.name if codec_val else \"default\"\n self.log.warning(f\" - {range_val.name}/{codec_name} not available, skipping ({e})\")\n continue\n raise\n if first:\n all_tracks.add(tracks, warn_only=True)\n if tracks.manifest_url and not all_tracks.manifest_url:\n all_tracks.manifest_url = tracks.manifest_url\n first = False\n else:\n for video in tracks.videos:\n all_tracks.add(video, warn_only=True)\n\n return all_tracks\n
"},{"location":"reference/api/service/#unshackle.core.service.Service.get_session","title":"get_session staticmethod","text":"get_session()\n
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
Source code in unshackle/core/service.py @staticmethod\ndef get_session() -> requests.Session:\n \"\"\"\n Creates a Python-requests HTTP session, adds common headers\n from config, cookies, retry handler, and a proxy if available.\n :returns: Prepared Python-requests HTTP session\n \"\"\"\n session = TimeoutSession()\n session.headers.update(config.headers)\n # Retry / pool policy mirrors RnetSession via the shared constants in session.py:\n # same total, forcelist, backoff cap, allowed_methods (incl. POST, so license\n # requests retry on both paths), and pool size. Accepted divergence: urllib3's\n # backoff_jitter adds an absolute 0..N seconds whereas rnet jitters \u00b110% of the\n # backoff, the only intentional difference, not worth hand-rolling a retry loop.\n session.mount(\n \"https://\",\n TimeoutHTTPAdapter(\n max_retries=Retry(\n total=MAX_RETRIES,\n backoff_factor=BACKOFF_FACTOR,\n backoff_max=MAX_BACKOFF,\n backoff_jitter=0.2,\n status_forcelist=STATUS_FORCELIST,\n allowed_methods=RETRY_METHODS,\n respect_retry_after_header=True,\n ),\n pool_connections=POOL_MAX_SIZE,\n pool_maxsize=POOL_MAX_SIZE,\n pool_block=True,\n ),\n )\n session.mount(\"http://\", session.adapters[\"https://\"])\n return session\n
"},{"location":"reference/api/service/#unshackle.core.service.Service.get_binaries","title":"get_binaries staticmethod","text":"get_binaries()\n
Declare custom binary dependencies required by this service. :returns: List of dicts, each with a name and optional candidates and desc.
Source code in unshackle/core/service.py @staticmethod\ndef get_binaries() -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.authenticate","title":"authenticate","text":"authenticate(cookies=None, credential=None)\n
Authenticate the Service with Cookies and/or Credentials (Email/Username and Password).
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 ANONYMOUS_SEARCH, which does not operate this method.
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.
Do not store the cookies outside this function either. However, you can load the cookies into the service HTTP session.
Source code in unshackle/core/service.py def authenticate(self, cookies: Optional[CookieJar] = None, credential: Optional[Credential] = None) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.request_input","title":"request_input","text":"request_input(prompt)\n
Request interactive input from the user.
Locally, prompts through the shared rich console so the prompt renders alongside Live progress. A remote-dl session relays it through its :class:InputBridge, and a REST download job relays it through prompt_user to the job's input_prompt.
Source code in unshackle/core/service.py def request_input(self, prompt: str) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.wait_for_approval","title":"wait_for_approval","text":"wait_for_approval(message, check, timeout, interval=3.0)\n
Show message, then call check until it returns a value.
Use it for a login that the user approves on another device, such as a pair code. check returns None while the approval is pending, and must return within a few seconds. Raises TimeoutError after timeout seconds, and RuntimeError when the remote session no longer exists. A REST download job shows message as its notice.
Source code in unshackle/core/service.py def wait_for_approval(\n self, message: str, check: Callable[[], Optional[T]], timeout: float, interval: float = 3.0\n) -> 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 >= deadline:\n raise TimeoutError(f\"No approval within {timeout:.0f}s\")\n time.sleep(interval)\n finally:\n show_notice(None)\n
"},{"location":"reference/api/service/#unshackle.core.service.Service.search","title":"search","text":"search()\n
Find titles from the Service by query.
The Service class must take the query as a CLI argument. Ideally re-use the title ID argument (that is, self.title).
unshackle displays the search results in the order yielded.
Source code in unshackle/core/service.py def search(self) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.get_widevine_service_certificate","title":"get_widevine_service_certificate","text":"get_widevine_service_certificate(\n *, challenge, title, track\n)\n
Get the Widevine Service Certificate used for Privacy Mode.
:param challenge: The service challenge, providing this to a License endpoint should return the privacy certificate that the service uses. :param title: The current Title 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 Track needing decryption. Provided for same reason as title. :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.
Source code in unshackle/core/service.py def get_widevine_service_certificate(\n self, *, challenge: bytes, title: Title_T, track: AnyTrack\n) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.get_widevine_license","title":"get_widevine_license","text":"get_widevine_license(*, challenge, title, track)\n
Get a Widevine License message by sending a License Request (challenge).
This License message contains the encrypted content keys and will be read by the Cdm and decrypted.
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.
:param challenge: The license challenge from the Widevine CDM. :param title: The current Title 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 Track needing decryption. Provided for same reason as title. :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.
Source code in unshackle/core/service.py def get_widevine_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.get_playready_license","title":"get_playready_license","text":"get_playready_license(*, challenge, title, track)\n
Get a PlayReady License message by sending a License Request (challenge).
This License message contains the encrypted content keys and will be read by the CDM and decrypted.
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.
:param challenge: The license challenge from the PlayReady CDM. :param title: The current Title 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 Track needing decryption. Provided for same reason as title. :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.
Source code in unshackle/core/service.py def get_playready_license(\n self, *, challenge: bytes, title: Title_T, track: AnyTrack\n) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.get_clearkey_license","title":"get_clearkey_license","text":"get_clearkey_license(*, challenge, title, track)\n
Get a W3C ClearKey License (JWK Set) by sending a License Request (challenge).
Used for DASH org.w3.clearkey tracks. unshackle uses no CDM here: the challenge is the W3C EME JSON license request, e.g. {\"kids\": [\"<base64url>\"], \"type\": \"temporary\"}, and the license is a JWK Set, e.g. {\"keys\": [{\"kty\": \"oct\", \"k\": \"...\", \"kid\": \"...\"}]}.
:param challenge: The JSON license request bytes to POST to the license server. :param title: The current Title 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 Track needing decryption. Provided for same reason as title. :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 content_keys in get_tracks.
Source code in unshackle/core/service.py def get_clearkey_license(\n self, *, challenge: bytes, title: Title_T, track: AnyTrack\n) -> 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\": [\"<base64url>\"], \"type\": \"temporary\"}``,\n and the license is a JWK Set, e.g. ``{\"keys\": [{\"kty\": \"oct\", \"k\": \"...\", \"kid\": \"...\"}]}``.\n\n :param challenge: The JSON license request bytes to POST to the license server.\n :param title: The current `Title` from get_titles that unshackle processes now. unshackle\n gives this in case it holds data you need, for example for an HTTP request.\n :param track: The current `Track` needing decryption. Provided for same reason as `title`.\n :return: The JWK Set license as a dict, JSON str, or raw bytes. Return None (the default)\n to let the framework POST the challenge to the manifest-provided Laurl, if any.\n Services with no license server can instead pre-populate the DRM object's\n `content_keys` in get_tracks.\n \"\"\"\n return None\n
"},{"location":"reference/api/service/#unshackle.core.service.Service.get_titles","title":"get_titles abstractmethod","text":"get_titles()\n
Get Titles for the provided title ID.
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.
You must return at least one object. If you do not, unshackle presumes an invalid Title ID.
You can use the data 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.
Source code in unshackle/core/service.py @abstractmethod\ndef get_titles(self) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.get_titles_cached","title":"get_titles_cached","text":"get_titles_cached(title_id=None)\n
Cached wrapper around get_titles() to reduce redundant API calls.
This method checks the cache before calling get_titles() and handles fallback to cached data when API calls fail.
Parameters:
Name Type Description Default title_id str Optional title ID for cache key generation. If not provided, will try to extract from service instance.
None Returns:
Type Description Titles_T Titles object (Movies, Series, or Album)
Source code in unshackle/core/service.py def get_titles_cached(self, title_id: str = None) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.apply_title_map","title":"apply_title_map","text":"apply_title_map(titles)\n
Rewrite service-provided titles using the per-service title_map config.
title_map lives under services.<TAG> in unshackle.yaml. Applied after the title cache so config edits take effect without a cache reset, and before any --enrich override so enrich wins. See remap_titles for the match rules.
Source code in unshackle/core/service.py def apply_title_map(self, titles: Titles_T) -> Titles_T:\n \"\"\"\n Rewrite service-provided titles using the per-service ``title_map`` config.\n\n ``title_map`` lives under ``services.<TAG>`` 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.get_tracks","title":"get_tracks abstractmethod","text":"get_tracks(title)\n
Get Track objects of the Title.
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.
Each Track in the Tracks should represent a Video/Audio track, Representation, or Adaptation, or a Subtitle file.
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.
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.
Make sure you correctly mark which Tracks have encryption, and which DRM System they use, with the drm property.
If you can get the Track's KID (Key ID) as a 32 char (16 bit) HEX string, give it to the Track's kid 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.
:param title: The current Title from get_titles that unshackle processes now. :return: Tracks object containing Video, Audio, Subtitles, and Chapters, if available.
Source code in unshackle/core/service.py @abstractmethod\ndef get_tracks(self, title: Title_T) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.get_chapters","title":"get_chapters abstractmethod","text":"get_chapters(title)\n
Get Chapters for the Title.
Parameters:
Name Type Description Default title Title_T The current Title from get_titles that unshackle processes now.
required You must return a Chapters object containing 0 or more Chapter objects.
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.
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 chapter_fallback_name. For example, \"Chapter {i:02}\" for \"Chapter 01\".
Source code in unshackle/core/service.py @abstractmethod\ndef get_chapters(self, title: Title_T) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.on_segment_downloaded","title":"on_segment_downloaded","text":"on_segment_downloaded(track, segment)\n
Called when one of a Track's Segments has finished downloading.
Parameters:
Name Type Description Default track AnyTrack The Track object that had a Segment downloaded.
required segment Path The Path to the downloaded Segment.
required Source code in unshackle/core/service.py def on_segment_downloaded(self, track: AnyTrack, segment: Path) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.on_track_downloaded","title":"on_track_downloaded","text":"on_track_downloaded(track)\n
Called when a Track has finished downloading.
Parameters:
Name Type Description Default track AnyTrack The downloaded Track object.
required Source code in unshackle/core/service.py def on_track_downloaded(self, track: AnyTrack) -> None:\n \"\"\"\n Called when a Track has finished downloading.\n\n Parameters:\n track: The downloaded Track object.\n \"\"\"\n
"},{"location":"reference/api/service/#unshackle.core.service.Service.on_track_decrypted","title":"on_track_decrypted","text":"on_track_decrypted(track, drm, segment=None)\n
Called when a Track has finished decrypting.
Parameters:
Name Type Description Default track AnyTrack The decrypted Track object.
required drm DRM_T The DRM object it decrypted with.
required segment Optional[Segment] The decrypted HLS segment information. None for DASH and ISM tracks and for an HLS track that merged during the download (merge_segments).
None Source code in unshackle/core/service.py def on_track_decrypted(self, track: AnyTrack, drm: DRM_T, segment: Optional[m3u8.Segment] = None) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.on_track_repacked","title":"on_track_repacked","text":"on_track_repacked(track)\n
Called when a Track has finished repacking.
Parameters:
Name Type Description Default track AnyTrack The repacked Track object.
required Source code in unshackle/core/service.py def on_track_repacked(self, track: AnyTrack) -> None:\n \"\"\"\n Called when a Track has finished repacking.\n\n Parameters:\n track: The repacked Track object.\n \"\"\"\n
"},{"location":"reference/api/service/#unshackle.core.service.Service.on_track_multiplex","title":"on_track_multiplex","text":"on_track_multiplex(track)\n
Called immediately before unshackle multiplexes a Track into a Container.
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.
Parameters:
Name Type Description Default track AnyTrack The repacked Track object.
required Source code in unshackle/core/service.py def on_track_multiplex(self, track: AnyTrack) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.grow_session_pool","title":"grow_session_pool","text":"grow_session_pool(session, size)\n
Grow a shared requests session's connection pool to size before track downloads start.
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 downloads * workers 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 get_adapter. RnetSession does not block on its idle-pool cap, so this function skips it.
Every mounted adapter grows in place, through its own init_poolmanager. A service can mount an :class:HTTPAdapter subclass, such as SSLCiphers, on any prefix. Mounting a new adapter over it would drop that subclass state, and its TLS context with it.
Source code in unshackle/core/service.py def grow_session_pool(session: Any, size: int) -> 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) >= size:\n continue\n adapter.init_poolmanager(size, size, block=True)\n adapter.proxy_manager.clear()\n
"},{"location":"reference/api/service/#unshackle.core.service.sanitize_proxy_for_log","title":"sanitize_proxy_for_log","text":"sanitize_proxy_for_log(uri, mask_host=False)\n
Sanitise a proxy URI for logs by masking any embedded userinfo (username/password).
serve sends these log lines to the client of a remote session, so the mask is unconditional and debug mode never lifts it. mask_host hides the hostname as well, for a proxy that came from the user-supplied Basic proxy provider.
Source code in unshackle/core/service.py def sanitize_proxy_for_log(uri: Optional[str], mask_host: bool = False) -> 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
"},{"location":"reference/api/titles/","title":"Titles API","text":"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.
"},{"location":"reference/api/titles/#unshackle.core.titles.Episode","title":"Episode","text":"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
Bases: Title
"},{"location":"reference/api/titles/#unshackle.core.titles.Episode.matches_wanted","title":"matches_wanted","text":"matches_wanted(wanted)\n
Whether a parsed -w key set selects this episode.
A part-ful episode answers to both its base key and its part key, so -w s1e1 takes every part. A dated episode also answers to its ISO air date. ! keys are part-qualified exclusions resolved here.
"},{"location":"reference/api/titles/#unshackle.core.titles.Episode.part_suffix","title":"part_suffix","text":"part_suffix()\n
.Part.2 / Part 2 in the series template's own separator style.
"},{"location":"reference/api/titles/#unshackle.core.titles.Episode.build_template_context","title":"build_template_context","text":"build_template_context(\n media_info, show_service=True, include_part=True\n)\n
Build template context dictionary from MediaInfo.
"},{"location":"reference/api/titles/#unshackle.core.titles.Episode.air_date_display","title":"air_date_display","text":"air_date_display()\n
Render air_date using the series template's own separator (dots or spaces).
"},{"location":"reference/api/titles/#unshackle.core.titles.Episode.folder_season","title":"folder_season","text":"folder_season()\n
Season folder label: air year when the air date parsed to a date, else SxxExx-style season.
"},{"location":"reference/api/titles/#unshackle.core.titles.Episode.part_label","title":"part_label","text":"part_label()\n
.2 selection-syntax suffix for console output, empty when part-less.
"},{"location":"reference/api/titles/#unshackle.core.titles.Movie","title":"Movie","text":"Movie(\n id_,\n service,\n name,\n year=None,\n language=None,\n data=None,\n description=None,\n)\n
Bases: Title
"},{"location":"reference/api/titles/#unshackle.core.titles.Movie.build_template_context","title":"build_template_context","text":"build_template_context(media_info, show_service=True)\n
Build template context dictionary from MediaInfo.
"},{"location":"reference/api/titles/#unshackle.core.titles.Album","title":"Album","text":"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
Bases: Music
Backward-compatible collection name for album-style music releases.
"},{"location":"reference/api/titles/#unshackle.core.titles.Music","title":"Music","text":"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
Bases: SortedKeyList, ABC
A grouped music release, such as an album, EP, single, compilation, or playlist.
"},{"location":"reference/api/titles/#unshackle.core.titles.Song","title":"Song","text":"Song(\n id_,\n service,\n name,\n artist,\n album,\n track,\n disc=1,\n year=None,\n language=None,\n data=None,\n album_artist=None,\n release_type=\"album\",\n total_tracks=None,\n total_discs=None,\n genre=None,\n explicit=None,\n isrc=None,\n upc=None,\n copyright=None,\n label=None,\n lyrics=None,\n artwork_url=None,\n)\n
Bases: Title
"},{"location":"reference/api/titles/#unshackle.core.titles.Song.matches_wanted","title":"matches_wanted","text":"matches_wanted(wanted)\n
Whether a parsed -w key set selects this song.
A song shares the episode key space, its disc reading as the season and its track as the episode, so -w 1-5 takes tracks 1 to 5 and -w 2x3 takes disc 2 track 3. A song has no parts and no air date, so it answers to its disc-and-track key only.
"},{"location":"reference/api/titles/#unshackle.core.titles.Song.build_template_context","title":"build_template_context","text":"build_template_context(media_info, show_service=True)\n
Build template context dictionary from MediaInfo.
"},{"location":"reference/api/titles/#unshackle.core.titles.remap_titles","title":"remap_titles","text":"remap_titles(titles, title_map)\n
Rewrite titles in-place using an exact-match title_map.
Some services name a title differently from how the user wants it stored, which can break library matching. title_map maps a source title string to the desired output title. Episodes are matched on their title (the show name), Movies and Songs on their name. Returns the same collection for convenient chaining.
"},{"location":"reference/api/tracks/","title":"Tracks API","text":"Auto-generated reference for the track model: Tracks, Track, and the media-specific subclasses. See Service Architecture for how these fit together.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Attachment","title":"Attachment","text":"Attachment(\n path=None,\n url=None,\n name=None,\n mime_type=None,\n description=None,\n session=None,\n)\n
Make a new Attachment.
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.
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.
Parameters:
Name Type Description Default path Union[Path, str, None] Path to an existing file.
None url Optional[str] URL to download the attachment from.
None name Optional[str] Name of the attachment.
None mime_type Optional[str] MIME type of the attachment.
None description Optional[str] Description of the attachment.
None session Optional[AnySession] Optional requests HTTP session to download the file with.
None"},{"location":"reference/api/tracks/#unshackle.core.tracks.Attachment.id","title":"id property","text":"id\n
Compute an ID from the attachment data.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Attachment.download","title":"download","text":"download(\n session=None,\n *,\n no_proxy_download=False,\n proxy_download=None,\n)\n
Download a URL-backed attachment to the temp directory.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Attachment.to_dict","title":"to_dict","text":"to_dict()\n
Serialise a URL-backed attachment for export/import.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Attachment.delete","title":"delete","text":"delete()\n
Delete the file only if it is in the temp directory. Files in other locations belong to the user.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Attachment.from_url","title":"from_url classmethod","text":"from_url(\n url,\n name=None,\n mime_type=None,\n description=None,\n session=None,\n)\n
Make an attachment from a URL.
Parameters:
Name Type Description Default url str URL to download the attachment from.
required name Optional[str] Name of the attachment.
None mime_type Optional[str] MIME type of the attachment.
None description Optional[str] Description of the attachment.
None session Optional[AnySession] Optional requests HTTP session to download the file with.
None Returns:
Name Type Description Attachment 'Attachment' A new attachment instance.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Audio","title":"Audio","text":"Audio(\n *args,\n codec=None,\n bitrate=None,\n channels=None,\n joc=None,\n descriptive=False,\n **kwargs,\n)\n
Bases: Track
Make a new Audio track object.
Parameters:
Name Type Description Default codec Optional[Codec] An Audio.Codec enum representing the audio codec. If not specified, unshackle uses MediaInfo to get the codec after it downloads the track.
None bitrate Optional[Union[str, int, float]] A number or float representing the average bandwidth in bits/s. unshackle rounds float values up to the nearest integer.
None channels Optional[Union[str, int, float]] 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.
None joc Optional[int] The number of Joint-Object-Coding Channels/Objects in the audio track.
None descriptive Union[bool, int] Mark this audio as being descriptive audio for the blind.
False 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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Audio.atmos","title":"atmos property","text":"atmos\n
Return True if the audio track contains Atmos.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Audio.parse_channels","title":"parse_channels staticmethod","text":"parse_channels(channels)\n
Converts a Channel string to a float representing the audio channel layout. E.g. \"3\" -> \"3.0\", \"2.1\" -> \"2.1\", \".1\" -> \"0.1\".
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.
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->6.0.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Audio.channel_total","title":"channel_total staticmethod","text":"channel_total(channels)\n
Total number of channels in either channel form, so a caller can compare both.
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\" -> 10.0.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Audio.to_music_container","title":"to_music_container","text":"to_music_container()\n
Remux the track into the container of its codec, as a standalone audio file.
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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Audio.get_track_name","title":"get_track_name","text":"get_track_name()\n
Return the base Track Name.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapter","title":"Chapter","text":"Chapter(timestamp, name=None)\n
Make a new Chapter with a Timestamp and optional name.
The timestamp may be in the following formats: - \"HH:MM:SS\" string, e.g., 25:05:23. - \"HH:MM:SS.mss\" string, e.g., 25:05:23.120. - a timecode integer in milliseconds, e.g., 90323120 is 25:05:23.120. - a timecode float in seconds, e.g., 90323.12 is 25:05:23.120.
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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapter.id","title":"id property","text":"id\n
Compute an ID from the Chapter data.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapter.named","title":"named property","text":"named\n
True if the Chapter has a name.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapters","title":"Chapters","text":"Chapters(iterable=None)\n
Bases: SortedKeyList, ABC
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapters.id","title":"id property","text":"id\n
Compute an ID from the Chapter data.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapters.loads","title":"loads classmethod","text":"loads(data)\n
Load chapter data from a string.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapters.load","title":"load classmethod","text":"load(path)\n
Load chapter data from a file.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapters.dumps","title":"dumps","text":"dumps(fallback_name='')\n
Return chapter data in OGM-based Simple Chapter format. https://mkvtoolnix.download/doc/mkvmerge.html#mkvmerge.chapters.simple
Parameters:
Name Type Description Default fallback_name str Name used for Chapters without a Name set.
'' The fallback name can use the following variables in f-string style:
- {i}: The Chapter number starting at 1. E.g.,
\"Chapter {i}\": \"Chapter 1\", \"Intro\", \"Chapter 3\". - {j}: A number starting at 1 that increments any time a Chapter has no name. E.g.,
\"Chapter {j}\": \"Chapter 1\", \"Intro\", \"Chapter 2\".
unshackle formats these with f-strings, so format directives work. For example, \"Chapter {i:02}\" will result in \"Chapter 01\".
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapters.dump","title":"dump","text":"dump(path, *args, **kwargs)\n
Write chapter data in OGM-based Simple Chapter format to a file.
Parameters:
Name Type Description Default path Union[Path, str] The file path to write the Chapter data to, overwriting any existing data.
required See Chapters.dumps for more parameter documentation.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Hybrid","title":"Hybrid","text":"Hybrid(videos, source, output_name=None)\n
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Hybrid.log","title":"log instance-attribute","text":"log = logging.getLogger('hybrid')\n
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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Hybrid.level_5","title":"level_5","text":"level_5(input_video)\n
Make Level 5 active area metadata through crop detection on the HDR10 track.
This resolves mismatches where DV has no black bars but HDR10 does (or vice versa) by telling the display the correct active area.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Hybrid.sanitize_l6","title":"sanitize_l6 staticmethod","text":"sanitize_l6(max_mdl, min_mdl, max_cll, max_fall)\n
Clamp static L6 values to a valid relationship.
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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Hybrid.level_6","title":"level_6","text":"level_6()\n
Edit RPU Level 6 values using the static L6 luminance data from the RPU.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Hybrid.extract_hdr10plus","title":"extract_hdr10plus","text":"extract_hdr10plus(video)\n
Extract HDR10+ metadata from the video track
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Hybrid.probe_hdr_metadata","title":"probe_hdr_metadata","text":"probe_hdr_metadata()\n
Extract mastering display and Content Light Level metadata from the HDR10 track with FFprobe.
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)
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Hybrid.convert_hdr10plus_to_dv","title":"convert_hdr10plus_to_dv","text":"convert_hdr10plus_to_dv()\n
Convert HDR10+ metadata to Dolby Vision RPU
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle","title":"Subtitle","text":"Subtitle(\n *args,\n codec=None,\n cc=False,\n sdh=False,\n forced=False,\n **kwargs,\n)\n
Bases: Track
Make a new Subtitle track object.
Parameters:
Name Type Description Default codec Optional[Codec] A Subtitle.Codec enum representing the subtitle format. If not specified, unshackle uses MediaInfo to get the format after it downloads the track.
None cc bool 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 - >>> (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.
False sdh bool 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.
False forced bool 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.
False Note: If codec is not specified, unshackle can skip some checks or assume a value. Give as much information as possible.
Information on Subtitle Types 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.
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)
More in-depth information, examples, and stuff to look for can be found in the Parameter explanation list above.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.get_track_name","title":"get_track_name","text":"get_track_name()\n
Return the base Track Name.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.strip_webvtt_cue_classes","title":"strip_webvtt_cue_classes staticmethod","text":"strip_webvtt_cue_classes(text)\n
Reduce a cue payload to the markup every target format shares: <i>, <b> and <u> without their class list. It removes class spans (<c.foo>), <v>, <lang>, <ruby>/<rt> and karaoke timestamps (<00:00:01.000>).
A class only selects a CSS ::cue 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 [0-9a-zA-Z_/]. The dot fails that test, so FFmpeg prints <i.loud> as cue text and then emits the closing italic-off with nothing opened. FFmpeg's WebVTT reader matches i/b/u 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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.strip_webvtt_timestamp_map","title":"strip_webvtt_timestamp_map staticmethod","text":"strip_webvtt_timestamp_map(text)\n
Remove X-TIMESTAMP-MAP header lines (RFC 8216 \u00a73.5, HLS only).
Cue times are already absolute, but SubtitleEdit reads the header and offsets every cue by it during conversion.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.sanitize_webvtt_timestamps","title":"sanitize_webvtt_timestamps staticmethod","text":"sanitize_webvtt_timestamps(text)\n
Fix invalid timestamps in WebVTT files, particularly negative timestamps.
Parameters:
Name Type Description Default text str The WebVTT text as string
required Returns:
Type Description str Sanitized WebVTT text
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.has_webvtt_cue_identifiers","title":"has_webvtt_cue_identifiers staticmethod","text":"has_webvtt_cue_identifiers(text)\n
Examine WebVTT text for cue identifiers that need removal.
Parameters:
Name Type Description Default text str The WebVTT text as string
required Returns:
Type Description bool True if the text has cue identifiers, False otherwise
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.sanitize_webvtt_cue_identifiers","title":"sanitize_webvtt_cue_identifiers staticmethod","text":"sanitize_webvtt_cue_identifiers(text)\n
Remove WebVTT cue identifiers that can confuse subtitle parsers.
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).
Parameters:
Name Type Description Default text str The WebVTT text as string
required Returns:
Type Description str Sanitized WebVTT text with cue identifiers removed
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.parse_vtt_time","title":"parse_vtt_time staticmethod","text":"parse_vtt_time(t)\n
Parse WebVTT timestamp to milliseconds. Returns 0 for malformed input.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.has_overlapping_webvtt_cues","title":"has_overlapping_webvtt_cues staticmethod","text":"has_overlapping_webvtt_cues(text)\n
Examine WebVTT text for overlapping cues that need merging.
Detects cues with start times within 50ms of each other and the same end time, which indicates multi-line subtitles split into separate cues.
Parameters:
Name Type Description Default text str The WebVTT text as string
required Returns:
Type Description bool True if the text has overlapping cues, False otherwise
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.merge_overlapping_webvtt_cues","title":"merge_overlapping_webvtt_cues staticmethod","text":"merge_overlapping_webvtt_cues(text)\n
Merge WebVTT cues that have overlapping/near-identical times but different line positions.
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).
Parameters:
Name Type Description Default text str The WebVTT text as string
required Returns:
Type Description str WebVTT text with overlapping cues merged
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.sanitize_webvtt","title":"sanitize_webvtt staticmethod","text":"sanitize_webvtt(text)\n
More thorough sanitization of WebVTT files that corrects multiple potential issues.
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.
Parameters:
Name Type Description Default text str The WebVTT text as string
required Returns:
Type Description str Sanitized WebVTT text
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.convert","title":"convert","text":"convert(codec, *, forced=False)\n
Convert this Subtitle to another format.
Backend selection is data-driven (see tracks/subtitle_convert.py): unshackle uses the best available backend that can convert source->target, and falls back through the capability chain on failure. The conversion_method config key (auto | subby | pysubs2 | subtitleedit | pycaption) pins the backend, and preferred_conversion_method nudges it per-service. An explicit config value always wins.
forced marks an explicit user request (--sub-format). unshackle skips lossy downconverts of styled formats (SSA/ASS -> SRT) unless forced is True.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.extract_fonts","title":"extract_fonts staticmethod","text":"extract_fonts(text)\n
Font names referenced by an ASS/SSA subtitle.
Covers both sources that need attaching for correct rendering: - the Fontname column of every Style: line in [V4+ Styles]/[V4 Styles] (column located from the section's Format: line, not assumed by index), and - inline \\fn font overrides inside Dialogue override blocks.
This method removes a leading @ (vertical-writing prefix), de-duplicates the names case-insensitively, and prefers a mixed-case spelling over an all-lowercase one.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.sanitize_broken_webvtt","title":"sanitize_broken_webvtt staticmethod","text":"sanitize_broken_webvtt(text)\n
Remove or fix corrupted WebVTT lines, particularly those with invalid timestamps.
Parameters:
Name Type Description Default text str The WebVTT text as string
required Returns:
Type Description str Sanitized WebVTT text with corrupted lines removed
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.space_webvtt_headers","title":"space_webvtt_headers staticmethod","text":"space_webvtt_headers(data)\n
Space out the WEBVTT Headers from Captions.
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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.merge_same_cues","title":"merge_same_cues staticmethod","text":"merge_same_cues(caption_set)\n
Merge captions with the same timecodes and text as one in-place.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.filter_unwanted_cues","title":"filter_unwanted_cues staticmethod","text":"filter_unwanted_cues(caption_set)\n
Filter out subtitle cues containing only \u00a0 or whitespace.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.merge_segmented_wvtt","title":"merge_segmented_wvtt staticmethod","text":"merge_segmented_wvtt(data, period_start=0.0)\n
Convert Segmented DASH WebVTT cues into a pycaption Caption List. Also returns an ISO 639-2 alpha-3 language tag if available.
Code ported originally by xhlove to Python from shaka-player. rlaphoenix has since improved it with pymp4 and pycaption functions.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.sample_slice","title":"sample_slice","text":"sample_slice(starts, timescale=1, window=None)\n
Return the segments of window plus one segment on each side.
Cue times in a segment are absolute, so sample_start stays zero and trim makes the cut. A track that ends before the window keeps only its last segment.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.trim","title":"trim","text":"trim(start, end)\n
Keep the cues between start and end seconds and move them to start at zero.
Returns False and leaves the file whole when pysubs2 cannot read or write its format.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.strip_hearing_impaired","title":"strip_hearing_impaired","text":"strip_hearing_impaired()\n
Remove the SDH captions.
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
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.reverse_rtl","title":"reverse_rtl","text":"reverse_rtl()\n
Reverse RTL (Right to Left) Start/End on Captions. Use this to fix the positioning of sentence-ending characters.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.DownloadContext","title":"DownloadContext dataclass","text":"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
Shared arguments passed to each manifest's download_track.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.DownloadContext.ensure_session","title":"ensure_session","text":"ensure_session()\n
Return the HTTP session, or a new Session if none was set.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track","title":"Track","text":"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
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.data","title":"data property writable","text":"data\n
Arbitrary track data dictionary.
This uses a defaultdict with a dict as the factory for easier nested saving and safer exists-checks.
Reserved keys:
- \"hls\" used by the HLS class.
- playlist: m3u8.model.Playlist - The primary track information.
- media: m3u8.model.Media - The audio/subtitle track information.
- segment_durations: list[int] - A list of each segment's duration.
- \"dash\" used by the DASH class.
- manifest: lxml.ElementTree - DASH MPD manifest.
- period: lxml.Element - The period of this track.
- adaptation_set: lxml.Element - The adaptation set of this track.
- representation: lxml.Element - The representation of this track.
- timescale: int - The timescale of the track's segments.
- segment_durations: list[int] - A list of each segment's duration.
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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.drm_preference","title":"drm_preference property writable","text":"drm_preference\n
DRM system this track must license with, one of the names in DRM_PREFERENCE_TYPES.
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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.sample_slice","title":"sample_slice","text":"sample_slice(starts, timescale=1, window=None)\n
Return the slice of segments that hold window, from the start time of each segment.
Sets sample_start to the start time of the first kept segment, in seconds. A video keeps sample_tail 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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.sample_byte_range","title":"sample_byte_range","text":"sample_byte_range(session)\n
Find the bytes of a one-file track that hold the sample window.
Reads the start of the file for a sidx 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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.can_sample","title":"can_sample","text":"can_sample(session)\n
Return False when a sample cannot cut this track, because it is one file with no segment index.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.add_init_drm","title":"add_init_drm","text":"add_init_drm(init_data, cdm)\n
Add the Widevine and PlayReady DRM that the init segment carries and the track does not have.
A track with a different DRM type stays as it is. The DRM system that agrees with the CDM comes first.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.prefers_playready","title":"prefers_playready","text":"prefers_playready(cdm)\n
Whether to try PlayReady before Widevine. The track's preference wins over the loaded CDM.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.download","title":"download","text":"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
Download and optionally Decrypt this Track.
For a URL-descriptor Video or Audio track with no drm set, unshackle probes the DRM from the track's init data and stores it on the track, so a service need not declare drm itself.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.move","title":"move","text":"move(target)\n
Move the Track's file from current location, to target location. This will overwrite anything at the target path.
Raises:
Type Description TypeError If the target argument is not the expected type.
ValueError If track has no file to move, or the target does not exist.
OSError If the file somehow failed to move.
Returns the new location of the track.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.to_dict","title":"to_dict","text":"to_dict()\n
Serialise the track for export/import (identity/URL/descriptor/language).
DRM is not serialised here. The export writer attaches the licensed DRM + keys. Subclasses add their own codec/quality fields.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.base_kwargs_from_dict","title":"base_kwargs_from_dict staticmethod","text":"base_kwargs_from_dict(data)\n
Assemble the shared Track constructor kwargs from a to_dict() payload.
DRM is not reconstructed here: to_dict does not serialise it, and the import flow attaches the licensed DRM + content keys separately.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.from_dict","title":"from_dict classmethod","text":"from_dict(data)\n
Reconstruct the correct Track subclass from a to_dict() payload.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.get_track_name","title":"get_track_name","text":"get_track_name()\n
Get the Track Name.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.get_drm_for_cdm","title":"get_drm_for_cdm","text":"get_drm_for_cdm(cdm)\n
Return the DRM matching the provided CDM, if available.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.get_key_id","title":"get_key_id","text":"get_key_id(init_data=None, *args, **kwargs)\n
Probe the DRM encryption Key ID (KID) for this specific track.
It can find the Key ID by probing the track with FFprobe for enc_key_id data, as well as for mp4 tenc (Track Encryption) boxes.
It explicitly ignores PSSH information like the PSSH box, as the box is likely to contain multiple Key IDs that may or may not be for this specific track.
To retrieve the initialization segment, this method calls :meth:get_init_segment with the positional and keyword arguments. This method then uses the return value of get_init_segment to find the Key ID.
Returns:
Type Description Optional[UUID] The Key ID as a UUID object, or None if unshackle cannot find the Key ID.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.load_drm_if_needed","title":"load_drm_if_needed","text":"load_drm_if_needed(service=None)\n
Load DRM information for this track if the parser deferred it.
Parameters:
Name Type Description Default service Service | None Service instance that can fetch track-specific DRM info
None Returns:
Type Description bool True if the DRM loaded or is already present, False if the load failed
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.load_drm_from_playlist","title":"load_drm_from_playlist","text":"load_drm_from_playlist()\n
Fallback method to load DRM by fetching this track's individual playlist.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.get_init_segment","title":"get_init_segment","text":"get_init_segment(\n maximum_size=20000,\n url=None,\n byte_range=None,\n session=None,\n)\n
Get the Track's initial segment data.
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.
If byte_range 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 maximum_size.
The default maximum_size of 20000 (20KB) is a tried-and-tested value that seems to work well across the board.
Parameters:
Name Type Description Default maximum_size int 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.
20000 url Optional[str] Explicit init map or file URL to probe from.
None byte_range Optional[str] Range of bytes to download from the explicit or implicit URL.
None session Optional[Session] HTTP session context, for example authorization and headers.
None"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.repackage","title":"repackage","text":"repackage(bsf_v=None)\n
Remux the track with FFmpeg -c copy.
A given bsf_v goes into the same pass as -bsf:v, 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 bsf_v so the remux still succeeds. Returns True if unshackle applied the requested bsf_v (always False when bsf_v is None, because the caller requested nothing).
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks","title":"Tracks","text":"Tracks(*args, manifest_url=None)\n
Video, Audio, Subtitle, Chapter, and Attachment Track Store. It provides convenience functions for listing, sorting, and selecting tracks.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.sample_base","title":"sample_base property","text":"sample_base\n
The earliest sample_start of the video and audio tracks, which a sample mux uses as time zero.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.exists","title":"exists","text":"exists(by_id=None, by_url=None)\n
Examine whether a track already exists, by various methods.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.add","title":"add","text":"add(tracks, warn_only=False)\n
Add a provided track to its appropriate array.
A track whose ID is already in the collection raises ValueError. With warn_only set, this method skips such a track and logs how many it skipped.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.sort_videos","title":"sort_videos","text":"sort_videos(by_language=None, exact_match=False)\n
Sort video tracks by resolution then bitrate, and optionally language.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.sort_audio","title":"sort_audio","text":"sort_audio(\n by_language=None, codec_priority=None, exact_match=False\n)\n
Sort audio tracks by bitrate, codec priority, Atmos, descriptive, and optionally language.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.sort_subtitles","title":"sort_subtitles","text":"sort_subtitles(\n by_language=None,\n type_priority=None,\n group_by=None,\n exact_match=False,\n)\n
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.
Section Order - by_language groups prioritized to top, and ascending alphabetically
- then rest ascending alphabetically after the prioritized groups (Each section ascending alphabetically, but separated)
Type Order - Forced
- Normal
- Hard of Hearing (SDH/CC) (Least to most captions expected in the subtitle)
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.
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.
exact_match makes a by_language entry sort only its own tag. By default \"en\" also sorts \"en-US\" and \"en-GB\".
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.filter","title":"filter","text":"filter(predicate)\n
Return a new Tracks with tracks filtered by predicate, preserving metadata.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.merge_video_selections","title":"merge_video_selections staticmethod","text":"merge_video_selections(*groups)\n
Concatenate video selections, dropping duplicates (by track id, order-preserving).
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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.partition_hybrid_videos","title":"partition_hybrid_videos staticmethod","text":"partition_hybrid_videos(videos, non_hybrid_ranges)\n
Split videos into hybrid-ingredient candidates and the standalone-deliverable pool.
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 -r HYBRID muxes only the hybrid while -r HYBRID,HDR10P also delivers HDR10+.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.flag_hybrid_ingredients","title":"flag_hybrid_ingredients staticmethod","text":"flag_hybrid_ingredients(\n hybrid_selected, non_hybrid_selected\n)\n
Mark tracks selected only as hybrid ingredients so the standalone mux loop skips them.
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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.mux","title":"mux","text":"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
Multiplex all the Tracks into a Matroska Container file.
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.
Parameters:
Name Type Description Default title str Set the Matroska Container file title. Usually displayed in players instead of the filename if set.
required delete bool Delete all track files after multiplexing.
True progress Optional[partial] Update a rich progress bar with completed=.... This must be the progress object's update() func, pre-set with task id by functools.partial.
None audio_expected bool Whether the output must have audio. unshackle uses this to decide if it adds embedded audio metadata.
True title_language Optional[Language] The title's intended language. Used to select the best video track for audio metadata when multiple video tracks exist.
None skip_subtitles bool Skip muxing subtitle tracks into the container.
False output_path Optional[Path] 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.
None"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video","title":"Video","text":"Video(\n *args,\n codec=None,\n range_=None,\n bitrate=None,\n width=None,\n height=None,\n fps=None,\n scan_type=None,\n closed_captions=None,\n dv_compatible_bitstream=False,\n **kwargs,\n)\n
Bases: Track
Make a new Video track object.
Parameters:
Name Type Description Default codec Optional[Codec] A Video.Codec enum representing the video codec. If not specified, unshackle uses MediaInfo to get the codec after it downloads the track.
None range_ Optional[Range] A Video.Range enum representing the video colour range. Defaults to SDR if not specified.
None bitrate Optional[Union[str, int, float]] A number or float representing the average bandwidth in bytes/s. unshackle rounds float values up to the nearest integer.
None width Optional[int] The horizontal resolution of the video.
None height Optional[int] The vertical resolution of the video.
None fps Optional[Union[str, int, float]] 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.
None 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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.Range","title":"Range","text":" Bases: str, Enum
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.Range.from_cicp","title":"from_cicp staticmethod","text":"from_cicp(primaries, transfer, matrix)\n
Convert CICP (Coding-Independent Code Points) values to Video Range.
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.
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)
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.
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
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.change_color_range","title":"change_color_range","text":"change_color_range(range_)\n
Change the Video's Colour Range to Limited (0) or Full (1).
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.vui_bsf","title":"vui_bsf","text":"vui_bsf()\n
Return the -bsf:v value that rewrites SPS VUI colour metadata to match self.range.
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 {h264,hevc}_metadata=... string suitable for FFmpeg -bsf:v.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.normalize_vui","title":"normalize_vui","text":"normalize_vui()\n
Rewrite SPS VUI colour metadata to match self.range.
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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.ccextractor","title":"ccextractor","text":"ccextractor(track_id, out_path, language, original=False)\n
Return a TextTrack object representing CC track extracted by CCExtractor.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.extract_c608","title":"extract_c608","text":"extract_c608()\n
Extract Apple-Style c608 box (CEA-608) subtitle using CCExtractor.
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.
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.
Need a test file with more than one c608 box, before unshackle can extract more than one CEA-608 track.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.remove_eia_cc","title":"remove_eia_cc","text":"remove_eia_cc()\n
Remove EIA-CC data from Bitstream while keeping SEI data.
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.
"},{"location":"reference/configuration/","title":"Configuration Reference","text":"Every config key you can set in unshackle.yaml, with its name, type, default value, and behaviour, split into one page per area. A worked config is on the annotated example page.
Where the file lives, how unshackle discovers it, and how to edit it: The Configuration File.
How defaults work
Every config key is optional except output_template, which dl requires. Without it, dl 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 yaml.safe_load. An empty or missing file means every other config key falls back to its default.
Two keys behave specially on load
curl_impersonate is a deprecated alias of network and emits a DeprecationWarning. scene_naming has been removed. If it is set to any value, unshackle exits immediately with an error telling you to use output_template instead.
See Deprecated & removed keys.
"},{"location":"reference/configuration/#quick-index","title":"Quick index","text":"Area Keys Directories directories, filenames, services_repo_force Services & authentication services, credentials, firefox_cookies, remote_services, serve Download & processing dl, continue_downloads, merge_segments, subtitle, audio, muxing, language_tags, dual_multi_mode Output & naming output_template, tag, tag_rules, tag_group_name, tag_imdb_tmdb, chapter_fallback_name, unicode_filenames DRM & CDM cdm, remote_cdm, decryption Network & proxy network, headers, proxy_providers Key vaults key_vaults, vault_timeout Post-scripts post_scripts External API keys omdb_api_key, tmdb_api_key, tvdb_api_key, tvdb_pin, tvdb_order, simkl_client_id, metadata_providers, anilist_title_language, disable_metadata, decrypt_labs_api_key, ipinfo_api_key Caching & updates title_cache_enabled, title_cache_time, title_cache_max_retention, update_checks, update_check_interval Appearance theme Logging, privacy & debug redact_paths, debug, debug_keys, debug_requests, set_terminal_bg Deprecated & removed curl_impersonate, downloader, scene_naming"},{"location":"reference/configuration/directories/","title":"Directories","text":"The directories 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 Path(...).expanduser(), so ~ works.
unshackle.yamldirectories:\n downloads: ~/Media/unshackle\n temp: /mnt/fast-scratch/unshackle-temp\n wvds: ~/.unshackle/WVDs\n prds: ~/.unshackle/PRDs\n
Key Type Default Overridable Purpose downloads path <repo>/downloads Yes Default output directory for finished files. temp path <repo>/temp Yes Temporary working files during download/decrypt/mux. cache path <data>/cache Yes Generic cache, title cache, and the update-check store. cookies path <data>/cookies Yes Per-service cookie files (and VPN cookie files). logs path <data>/logs Yes Log files. exports path <data>/exports Yes Export JSON files. wvds path <data>/WVDs Yes Widevine device files (.wvd). prds path <data>/PRDs Yes PlayReady device files (.prd). dcsl path <data>/DCSL Yes DCSL data. commands path unshackle/commands Yes CLI command modules. services list | path [unshackle/services] Yes Service search paths and/or remote repo specs (see below). vaults path unshackle/vaults Yes Vault backend modules. fonts path unshackle/fonts Yes Bundled fonts. user_configs path unshackle/ No protected Where unshackle.yaml lives. data path unshackle/ No protected Base for the data subdirectories above. core_dir path unshackle/core No protected Package core. namespace_dir path unshackle/ No protected Package root. app_dirs - AppDirs(\"unshackle\", False) No protected Internal AppDirs instance. The services directory is special
services may be a list, and each entry can be either a local directory or a repository spec: a git URL (https://..., ssh://..., git@..., or anything ending in .git) or owner/repo 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.
directories:\n services:\n - you/your-services # cloned from GitHub\n - https://example.com/private.git@stable\n - ~/my-services # local, lowest priority\n
How git-backed service repos are handled
unshackle's use of git is read-only on the remote: it only ever does a shallow clone, fetch, pull, and a local reset. unshackle never pushes anything. Your existing git credential helper authenticates private repos, and unshackle stores no tokens of its own. Clones live under <first-local-services-dir>/_repos/<host>__<owner>__<repo>/ (or the bundled unshackle/services), 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.
Automatic and manual refresh behave differently
The automatic 24 h-TTL refresh that happens during a normal dl/search 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, __pycache__) never block it. The manual unshackle util refresh-services command instead hard-resets the clone to upstream, discarding any local edits.
Set services_repo_force: true to make the automatic 24 h refresh behave like refresh-services. When a refresh is due, the run fetches and hard-resets every clone, and discards any local edits in _repos/. Runs between refreshes do not touch the network. Use it on unattended hosts where nobody edits the clones by hand.
services_repo_force: true\n
Refresh inside serve
A running server does not restart to pick up a refresh. Both the periodic refresh (serve.services_refresh_interval, see serve) and the manual POST /api/maintenance/refresh-services 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; GET /api/services marks it with pending_update in the meantime.
Read-only installs and reinstalls
If the services directory lives inside the installed package, a reinstall can delete the _repos clones. They are re-cloned on next use. On read-only installs you must point services at a writable path, or cloning will fail.
"},{"location":"reference/configuration/directories/#filenames","title":"Filenames","text":"The filenames config key is a dict of templated file/name patterns. unshackle uses each value verbatim (no path processing). It fills in braced fields like {time} and {service} at runtime.
Key Type Default Notes log str \"unshackle_{name}_{time}.log\" Written under directories.logs. debug_log str \"unshackle_debug_{service}_{time}.jsonl\" Structured debug log, under directories.logs. config str \"config.yaml\" Per-service config file, under that service's directory. root_config str \"unshackle.yaml\" The main config filename itself. chapters str \"Chapters_{title}_{random}.txt\" Under directories.temp. subtitle str \"Subtitle_{id}_{language}.srt\" Under directories.temp."},{"location":"reference/configuration/download/","title":"Download & processing","text":""},{"location":"reference/configuration/download/#dl","title":"dl","text":" - Type:
dict \u00a0\u00b7\u00a0 Default: {}
Persistent defaults for the dl command. unshackle uses the block as Click's default_map, so you can give any dl flag a default here. See Downloading and the CLI Reference for what each flag does.
Config key naming. A config key is the flag's long name with dashes replaced by underscores (--best-available \u2192 best_available, --sub-format \u2192 sub_format). A few config keys use the flag's internal destination and not its visible name. Set these exact config keys:
Flag Config key -r / --range range --list list --tmdb tmdb_id --imdb imdb_id --anilist anilist_id -naa / --noatmos no_atmos -o / --output output_dir --cdm-only / --vaults-only cdm_only Precedence (highest first): an explicit CLI flag \u2192 a per-service services.<TAG>.dl override \u2192 this global dl: block \u2192 the built-in default. In other words, config only fills in options you did not set on the command line.
Common config keys. This is a useful subset, and every dl flag works:
Key Type Default Sets lang list [\"orig\"] Video/audio language(s); orig = original language. A - prefix excludes, e.g. [all, -es]. a_lang / v_lang list [] Audio- / video-only language override. A - prefix excludes. s_lang list [\"all\"] Subtitle language(s). A - prefix excludes, e.g. [all, -es]. quality list [] (best) Resolution(s), e.g. [1080]. vcodec list [] (any) Video codec(s), e.g. [H265]. acodec list [] (any) Audio codec(s), e.g. [EC3]. range list [\"SDR\"] Colour range(s): SDR, HLG, HDR10, HDR10P, DV, HYBRID. channels float (unset) Audio channels, e.g. 6 for 5.1. sub_format str (unset) Convert subtitles to this format (srt, vtt, original, ...). forced_subs bool false Include forced subtitle tracks. forced_s_lang list [] Forced subtitle language(s); implies forced_subs. A - prefix excludes. forced_subs_only bool false Keep only forced subtitle tracks; implies forced_subs. audio_description bool false Include descriptive (audio-description) tracks. audio_description_only bool false Keep only descriptive (audio-description) tracks. no_subs / no_audio / no_chapters / no_attachments bool false Skip that track type. no_attachments also skips attaching subtitle fonts. downloads int 1 Tracks downloaded concurrently. workers int (downloader default) Threads per track. speed_limit str (unlimited) Total download speed cap across all downloads combined, e.g. 500k, 5M, 1.5G or plain bytes/sec. Values are bytes, not bits (5M = 5.0 MB/s). slow str (unset) Inter-title delay, e.g. \"20-40\". best_available bool false Warn instead of failing when a requested resolution, range, or language is missing, or when one DRM system does not license under --all-drm. The CLI flag is --best-available, also spelled --warn-only. proxy str (unset) Default proxy URI or 2-letter country. no_folder bool false Do not create a per-title folder. no and yes are language tags
YAML reads a bare no as false and a bare yes as true. unshackle puts both back to the tags no (Norwegian) and yes (Nyankpa) in every config key that takes a language: lang, v_lang, a_lang, s_lang, forced_s_lang, require_audio, require_video, require_subs, language_priority, muxing.default_language and the language_tags rules. Quotes (lang: \"no\") work as well.
Global download defaultsdl:\n lang: [en]\n quality: [1080]\n range: [HDR10]\n vcodec: [H265]\n sub_format: srt\n downloads: 2\n
Language exclusions in YAML
The language keys accept the same - exclusion tokens as the command line. Give them as a list or as one comma-separated string.
dl:\n s_lang: [all, -es]\n a_lang: \"orig,-es\"\n
See Excluding languages for the rules.
Per-service overrides
A dl block nested under a service in services takes the same keys and applies to that service only.
dl:\n lang: [en]\nservices:\n EXAMPLE1:\n dl:\n lang: [en, ja]\n range: [DV]\n
serve uses these same keys
The serve block accepts most of the same dl 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, speed_limit for example. serve has its own global_speed_limit.
"},{"location":"reference/configuration/download/#continue_downloads","title":"continue_downloads","text":" - Type:
bool \u00a0\u00b7\u00a0 Default: false
Keep a failed download's completed segment files so the next download resumes from where it stopped instead of restarting from byte zero.
unshackle reuses only whole, fully downloaded segments. It always discards partially written segments, and no partial-byte (Range) 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.
What can and cannot resume
- Segmented DASH, ISM, and HLS tracks resume.
- 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).
- 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.
- A track downloaded with
merge_segments or decrypt_segments never resumes. Both options consume or rewrite the segment files during the download.
For a one-off resume without changing config, pass dl --continue-downloads on the command line (the flag can only enable resume, never disable it).
Resume failed downloadscontinue_downloads: true\n
"},{"location":"reference/configuration/download/#merge_segments","title":"merge_segments","text":" - Type:
bool \u00a0\u00b7\u00a0 Default: false
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.
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 decrypt_segments also on, each segment is appended after its decryption completes, never before.
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.
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 EXT-X-KEY, with no EXT-X-DISCONTINUITY, 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.
No resume
A track that merges segment by segment always downloads from the start. continue_downloads cannot reuse its segments, because unshackle deletes each segment after it appends it.
merge_segments: true\n
"},{"location":"reference/configuration/download/#subtitle","title":"subtitle","text":" - Type:
dict \u00a0\u00b7\u00a0 Default: {}
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.
Sub-key Type Default Description strip_sdh bool true Strip SDH/CC cues (hearing-impaired annotations) into a clean track. sdh_method str \"auto\" SDH-stripping backend to use. preserve_formatting bool true Pass WebVTT cue text through as written. false re-encodes it through pycaption, which merges identical cues but flattens styling. unshackle removes WebVTT-only cue markup either way. convert_before_strip bool true Convert to the working format before stripping SDH. conversion_method str \"auto\" Subtitle conversion backend. output_mode str \"mux\" mux embeds subtitles in the MKV; sidecar writes separate files; both writes sidecars and still muxes. sidecar_format str \"srt\" Format for sidecar files when output_mode is sidecar or both. type_priority list (unset) Ordered ranking of subtitle types (forced, normal, sdh; CC counts as SDH). Types you leave out fall to the end. group_by str \"type\" Which key groups the subtitle tracks. type puts all forced tracks together, then all normal, then all SDH. language keeps each language next to its own variants. language_priority 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. subtitle:\n strip_sdh: true\n output_mode: sidecar\n sidecar_format: srt\n
group_by track order
group_by Result type Danish, Finnish, French, \u2026 Danish SDH, Finnish SDH, French SDH language Danish, Danish SDH, Finnish, Finnish SDH, French, French SDH type_priority still sets the order of the variants, so with group_by: language it controls the order inside each language.
language_priority sorts languages, it does not select them
subtitle:\n group_by: language\n language_priority: [en, es, fr]\n
Result for an English title Default English, Arabic, Bulgarian, Spanish, French, Japanese With the list above English, Spanish, French, Arabic, Bulgarian, Japanese unshackle removes nothing, unlike -sl, which drops every subtitle language it does not name.
Use orig in the list for the title's original language. A base tag also covers its regional forms, so en sorts en-US and en-GB, but zh does not cover zh-Hant, which you must name. The sort ignores entries that match no track, and it ignores entries that are not valid language tags.
--exact-lang applies here too: with it, en sorts only en, and en-US falls to the alphabetical tail with the rest. Name each tag you want when you use that flag.
type_priority picks the default subtitle only with muxing.default_language
At mux time the default flag goes to every forced subtitle whose language matches the first audio track, so a full dialogue track never becomes default on its own. type_priority alone does not change that. Name a subtitle language in muxing.default_language and the first track in that language gets the flag instead, which is where type_priority decides which track that is:
muxing:\n default_language:\n subtitle: en\nsubtitle:\n type_priority: [normal, sdh, forced]\n
"},{"location":"reference/configuration/download/#audio","title":"audio","text":" - Type:
dict \u00a0\u00b7\u00a0 Default: {}
Audio handling options. The most notable sub-key is codec_priority, an ordered list of audio codecs used to break ties in track selection. language_priority is an ordered list of languages that sort to the top of the audio tracks.
audio:\n codec_priority:\n - EAC3\n - AC3\n language_priority:\n - orig\n - en\n
codec_priority is a soft priority: nothing is dropped
codec_priority 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 codec_priority, and audio-description tracks are always forced to the end regardless of it. When codec_priority is unset, tracks sort by bitrate alone, with those same Atmos/descriptive rules still applied.
"},{"location":"reference/configuration/download/#muxing","title":"muxing","text":" - Type:
dict \u00a0\u00b7\u00a0 Default: {}
Matroska (MKV) muxing options.
Sub-key Type Default Description set_title bool true Write a human-readable title into the MKV container. default_language dict {} Force which language is flagged default per track type, e.g. {audio: en, subtitle: en}. merge_audio bool true Merge all audio into one file. --split-audio on the CLI flips this off. merge_video bool false Merge video tracks that share height, range, and codec into one file, so only language varies inside a file. --merge-video on the CLI flips this on. concurrency int 4 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 1 on a hard disk, where parallel writes are slower. muxing:\n set_title: true\n concurrency: 4\n default_language:\n audio: en\n subtitle: en\n
"},{"location":"reference/configuration/download/#language_tags","title":"language_tags","text":" - Type:
dict \u00a0\u00b7\u00a0 Default: {}
Language-tag remapping and the rule engine behind the {lang_tag} filename variable. When a rules list is present, unshackle evaluates each rule in order and uses the first match's tag. A rule can examine:
Condition Meaning audio At least one audio language matches. subs_contain At least one subtitle language matches. subs_contain_all Every listed language must be present. dual / multi / dubbed true matches when that filename variable is set, false when it is not. Each language condition takes one language tag or a list of them. A list matches when any entry matches, except subs_contain_all, which needs them all. An entry that is not a valid language tag (for example japanese) never matches. dual, multi and dubbed take a bare true or false, 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.
dual, multi and dubbed 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 DUAL, MULTi and DUBBED text. A rule that names dubbed: true and a language tags a localized dub without tagging a native release the same way.
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
Put {lang_tag} where you want the name
These rules fill {lang_tag}. To use your own name in place of the fixed text, keep {lang_tag?} in the template and leave out {dual?}, {multi?} and {dubbed?}.
"},{"location":"reference/configuration/download/#dual_multi_mode","title":"dual_multi_mode","text":" - Type:
str \u00a0\u00b7\u00a0 Default: strict
Rule set for the {dual}, {multi}, and {dubbed} filename variables.
strict (default)count (legacy) Variable Set when {dual} Exactly two audio languages and one is the title's original language. {multi} Three or more audio languages, even without the original. {dubbed} A single audio language that is not the title's original language (requires a known original). Variable Set when {dual} Exactly two audio languages (original language ignored). {multi} Three or more audio languages. {dubbed} Never set. dual_multi_mode: strict\n
Dialects count as one language
Regional variants of the same base language (e.g. en-US and en-GB) collapse to a single language in both modes, so they never trigger {dual} on their own.
"},{"location":"reference/configuration/drm/","title":"DRM & CDM","text":"These are the config keys. For concepts, device provisioning, and the wvd/prd commands see the DRM & CDM guide. Device files themselves live in directories.wvds (.wvd) and directories.prds (.prd).
"},{"location":"reference/configuration/drm/#cdm","title":"cdm","text":" - Type:
dict \u00a0\u00b7\u00a0 Default: {}
Maps a service tag to the CDM (Widevine/PlayReady device) to use, with a default fallback. Resolution is case-insensitive: an override (dl --cdm <name>, or the cdm field of an API job) wins, then the per-service entry, then default. An override pins one device for the whole run and skips any quality or Widevine/PlayReady sub-entries.
Over --remote, 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 widevine or playready sub-entry, or a profile or default 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 default entry, the server CDM licenses when the API key has it. See remote_services.
cdm:\n default: chromecdm_l3\n EXAMPLE2: android_l1\n
A value may also be a nested dict for advanced selection by quality, DRM system, or profile:
cdm:\n EXAMPLE1:\n \">=1080\": android_l1 # by track height\n \"<1080\": chromecdm_l3\n widevine: android_l1 # by DRM system\n playready: sl3000\n default: chromecdm_l3\n
Quality keys can hold 1080, >=1080, >720, <=576, <480 style comparisons. DRM keys are widevine / playready. 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 widevine/playready when present, or else the credential profile name, then default.
When an entry holds widevine and playready, 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 widevine / playready dict in a quality key does not set the order. The server CDM of a remote session follows the same order.
A quality key can also hold a dict of widevine / playready devices, and so can the top-level default entry:
cdm:\n default:\n widevine: chromecdm_l3\n playready: sl2000\n EXAMPLE1:\n \">=1080\": { widevine: android_l1, playready: sl3000 }\n \"<1080\": { widevine: chromecdm_l3, playready: sl2000 }\n
A quality key that holds one device name applies to both DRM systems. When a track needs the other system, unshackle uses the widevine / playready config key of the entry. dl --all-drm needs a device for each system from one of these shapes.
unshackle finds the resolved name in remote_cdm by name first. If no entry matches, unshackle loads it as a local device file, in this order: <name>.prd in directories.prds, <name>.prd in directories.wvds, then <name>.wvd in directories.wvds.
"},{"location":"reference/configuration/drm/#remote_cdm","title":"remote_cdm","text":" - Type:
list[dict] \u00a0\u00b7\u00a0 Default: []
A list of remote CDM definitions. unshackle matches each entry by its name (referenced from cdm), and its type selects the backend:
type Backend Key fields decrypt_labs Decrypt Labs KeyXtractor host, device_name, secret (fields) custom_api Fully YAML-configurable remote API host (required), device, auth, endpoints, request_mapping, response_mapping, caching, timeout (fields) (none), Device Type: PLAYREADY pyplayready RemoteCdm host, secret, device_name, security_level (default 3000) (none), otherwise pywidevine RemoteCdm host, secret, device_name, device_type, system_id, security_level (default 3000) 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
For the two pywidevine/pyplayready backends, field names are read case-insensitively in both styles: Device Type/device_type, System ID/system_id, Security Level/security_level, Host/host, Secret/secret, Device Name/device_name.
Serve APIs behind a proxy
unshackle does not send upstream's HEAD request or examine the Server response header, so the server can operate behind a reverse proxy or a CDN that removes or changes that header. Thus a host 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 secret from the request.
PlayReady host needs a /playready suffix
pyplayready's RemoteCdm treats host as a base URL and appends its own endpoint paths, so a PlayReady entry's host must include the trailing /playready segment (for example https://cdm.example.com/playready). Without it the server returns 404 rather than a configuration error.
"},{"location":"reference/configuration/drm/#remote-cdm-decrypt-labs","title":"decrypt_labs fields","text":"Field Default Notes host https://keyxtractor.decryptlabs.com device_name ChromeCDM ChromeCDM, L1, L2, L3 (Widevine) or SL2, SL3 (PlayReady). The host decides which of these names it serves. secret from decrypt_labs_api_key Sent as the decrypt-labs-api-key header. An error is raised if neither is set. system_id 26830 (Widevine), 0 (PlayReady) security_level Widevine 3; PlayReady 2000 for SL2, else 3000 unshackle uses PlayReady mode when device_type is PLAYREADY or device_name starts with SL.
"},{"location":"reference/configuration/drm/#remote-cdm-custom-api","title":"custom_api fields","text":"Field Type Notes host str Required. Base URL of the API. device dict name, type (CHROME, ANDROID, PLAYREADY), system_id, security_level auth dict type (default header): header uses header_name (default Authorization) and key; bearer uses bearer_token or key; basic uses username and password. custom_headers is merged in for any type. endpoints dict get_request and decrypt_response, each {path, method, timeout} request_mapping dict Per endpoint: param_names, static_params, conditional_params, transforms, nested_params, exclude_params response_mapping dict Per endpoint: fields, transforms, response_types, success_conditions, error_fields, key_fields caching dict enabled, use_vaults, check_cached_first legacy dict Legacy mode options. timeout int Default 30. Request timeout in seconds. Transforms cover base64/hex/JSON encoding and kid:key parsing. unshackle uses PlayReady mode when device.type is PLAYREADY or the device name is SL2/SL3.
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
"},{"location":"reference/configuration/drm/#decryption","title":"decryption","text":" - Type:
str or dict \u00a0\u00b7\u00a0 Default: \"shaka\"
Selects the tool that physically decrypts CENC-encrypted tracks. unshackle compares the value case-insensitively. \"mp4decrypt\" selects Bento4's mp4decrypt, and anything else (including \"shaka\") selects shaka-packager. When the value is a dict, unshackle compares the service tag case-insensitively and uses the default entry as the fallback.
unshackle decrypts HLS AES-128 ClearKey in-process and ignores this setting.
GlobalPer-service decryption: shaka\n
decryption:\n default: shaka\n EXAMPLE1: mp4decrypt\n
"},{"location":"reference/configuration/drm/#decrypt_segments","title":"decrypt_segments","text":" - Type:
bool \u00a0\u00b7\u00a0 Default: false
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.
This works with mp4decrypt only. Set decryption to mp4decrypt for the service (or as the default); with shaka 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 EXT-X-KEY and no EXT-X-DISCONTINUITY. Every other track keeps the whole-file decryption.
No resume
A track that decrypts segment by segment always downloads from the start. continue_downloads cannot reuse its segments, because a reused segment is already decrypted.
decrypt_segments: true\n
"},{"location":"reference/configuration/example/","title":"A complete annotated example","text":"The following config sets a handful of common config keys. Every config key not shown keeps its default.
unshackle.yamldirectories:\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
For how these interact at runtime, continue to Downloading, DRM & CDM, and Output & naming.
"},{"location":"reference/configuration/misc/","title":"Other Settings","text":"Smaller configuration areas: external metadata API keys, caching and update checks, logging and debug flags, and deprecated keys.
"},{"location":"reference/configuration/misc/#external-api-keys","title":"External API keys","text":"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.
Key Type Default Description omdb_api_key str \"\" OMDb API key for IMDb metadata lookups; a fallback for when the keyless imdb provider has no answer. Free keys are available on the OMDb site. tmdb_api_key str \"\" TMDB API key for metadata enrichment and external-ID tags. simkl_client_id str \"\" SIMKL client ID for metadata lookups; an alternative/fallback source to TMDB. tvdb_api_key str \"\" TheTVDB v4 API key; a fallback source to TMDB, strongest on TV series. Also the source --enrich --tvdb reads. Free keys are available on the TVDB site. tvdb_pin str \"\" Subscriber PIN, only needed for a user-supported TVDB key. Leave empty for a normal project key. tvdb_order str \"\" Default for --tvdb-order: renumber episodes to a TVDB season order (official, dvd, absolute, alternate, regional). Empty keeps the numbering the service gives. metadata_providers list or map (see below) Metadata providers to use, in the order they are tried. anilist_title_language str english Which AniList title variant to use: english, romaji, or native. disable_metadata bool false Set to true to stop all automatic metadata lookups. An ID you give yourself is still looked up. decrypt_labs_api_key str \"\" Global Decrypt Labs API key (used by remote CDM / vault). ipinfo_api_key str \"\" ipinfo.io API key for IP/region lookups. How metadata_providers is applied
A lookup goes to each metadata provider in turn and stops at the first good match, so the order decides which source wins. metadata_providers sets that order:
metadata_providers: [tvdb, tmdb, simkl]\n
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:
metadata_providers: [imdb, omdb, simkl, tmdb, tvdb, anilist]\n
Whatever the order, unshackle skips a metadata provider that has no API key. imdb and anilist need no API key, so they are always available. Available names are imdb, omdb, simkl, tmdb, tvdb, and anilist. The old name imdbapi still works and is read as imdb.
anilist 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.
The order applies to a title search and to a direct lookup of an ID you give with --tmdb, --imdb, --tvdb, or --anilist. A supplied ID always goes to the providers that read that kind of ID, and it never falls back to a title search.
Which AniList title anilist_title_language picks
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:
anilist_title_language: romaji\n
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.
What disable_metadata turns off
With disable_metadata: true, unshackle never contacts a metadata provider on its own. The title search is dead, and that includes the keyless imdb metadata provider. Titles, years and languages then come only from the service.
disable_metadata: true\n
An ID you give with --tmdb, --imdb, --tvdb, or --anilist 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 --enrich still reads that source. unshackle stops only the lookups you did not ask for.
The imdb provider needs no key
It replaces the earlier imdbapi metadata provider, which read a third-party mirror (api.tiffara.com) and needed the imdb_api_enabled switch. That option is gone: delete it from your config, where it is now ignored.
A different order per title kind
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, tv and movie, and this example sets both of them and names every metadata provider, so nothing is left to the default:
metadata_providers:\n tv: [tvdb, tmdb, simkl, imdb, omdb]\n movie: [tmdb, imdb, omdb, simkl, tvdb]\n
Each list is independent: it both orders and filters that kind on its own, so unshackle still uses for movie a metadata provider you leave out of tv. Here unshackle tries TVDB first for a series and last for a film.
You do not need to give both keys, or a full list in each. A kind you leave out uses the default order:
metadata_providers:\n tv: [tvdb, tmdb] # movies keep the default order\n
tv covers every episode and movie covers every film. unshackle only looks up metadata for those two kinds, so unshackle ignores any other config key, such as anime or music.
ipinfo_api_key never touches your service sessions
unshackle sends the token only to api.ipinfo.io, as a per-request Authorization 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 ip-api.in as a last resort.
"},{"location":"reference/configuration/misc/#caching-updates","title":"Caching & updates","text":""},{"location":"reference/configuration/misc/#title-cache","title":"Title cache","text":"unshackle caches fetched title metadata (region- and account-aware) to avoid repeat API calls.
Key Type Default Description title_cache_enabled bool true Master switch for the title cache. title_cache_time int (seconds) 1800 (30 min) Lifetime of fresh cached titles. title_cache_max_retention int (seconds) 86400 (24 h) Total retention window for a cached title, counted from when it was cached. Past title_cache_time 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 update_checks bool true Whether to check for new unshackle releases. update_check_interval int (hours) 24 Minimum hours between update checks. Note
Update checks query the GitHub releases API with a fixed 5-second timeout and cache the result in directories.cache/update_check.json.
"},{"location":"reference/configuration/misc/#appearance","title":"Appearance","text":"Key Type Default Description theme str catppuccin-mocha Named colour theme for all CLI output: banner, logs, progress bars, and help screens. One of catppuccin-mocha (aliases default, catppuccin, mocha), dracula, nord, gruvbox, one-dark (alias onedark), tokyo-night (alias tokyonight), monokai, flexoki, solarized-dark (alias solarized). Case-insensitive; underscores work in place of hyphens. Unknown names fall back to the default with a warning. Preview them all with unshackle env theme."},{"location":"reference/configuration/misc/#logging-privacy-debug","title":"Logging, privacy & debug","text":"Key Type Default Description redact_paths bool true Mask install-root / venv / home prefixes in logged paths (<unshackle>, <venv>, ~). Set false to show full paths. debug bool false Global debug mode. debug_keys bool false Log decryption keys. debug_requests bool false Log HTTP requests. set_terminal_bg bool false Append the theme's background colour to output styling. Effect of set_terminal_bg
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.
Key exposure
With debug_keys on, unshackle writes the content keys to the structured debug log at INFO level during the DRM handshake. Treat debug, debug_keys, and the unshackle_debug_*.jsonl files as sensitive, and keep redact_paths enabled when sharing logs.
debug_keys affects only content-encryption keys (the content_key/key 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.
"},{"location":"reference/configuration/misc/#deprecated-removed-keys","title":"Deprecated & removed keys","text":"Key Status Behaviour curl_impersonate Deprecated \u2192 use network Emits a DeprecationWarning; still honoured only if network is absent. downloader Deprecated Any value other than \"requests\" emits a DeprecationWarning; the value is otherwise ignored (the unified requests downloader is always used). scene_naming Removed If set to any non-null value, unshackle exits with an error directing you to configure output_template instead. imdb_api_enabled Removed Ignored. It gated the old imdbapi provider, which the keyless imdb provider replaces. Safe to delete from your config."},{"location":"reference/configuration/network/","title":"Network & proxy","text":""},{"location":"reference/configuration/network/#network","title":"network","text":" - Type:
dict \u00a0\u00b7\u00a0 Default: {}
TLS-fingerprinting and HTTP client settings for the rnet-based HTTP session.
Sub-key Type Default Description browser str \"Chrome131\" Impersonation preset. Must be an exact preset name (e.g. Chrome131, Firefox135, Edge101, Safari18, OkHttp4_12, OkHttp5, Opera118); unknown names raise an error. http1_only bool (unset) Force HTTP/1.1. http2_only bool (unset) Force HTTP/2. connect_timeout int 10 Connect timeout in seconds. read_timeout int 30 Read timeout in seconds (max gap between response chunks). timeout int (unset) Total request timeout in seconds. allow_redirects bool (unset) Follow redirects automatically (rnet client default when unset). pool_idle_timeout int 55 Seconds an idle pooled connection is kept (default stays under typical ~60s CDN idle kills). pool_max_idle_per_host int 64 Max idle connections kept per host. pool_max_size int (unset) Max total connections in the pool. tcp_keepalive int 30 TCP keepalive time in seconds. tcp_keepalive_interval int (unset) TCP keepalive probe interval in seconds. tcp_keepalive_retries int (unset) TCP keepalive probe retry count. tcp_nodelay bool (unset) Disable Nagle's algorithm. network:\n browser: Firefox135\n http2_only: true\n
Measured effect of http1_only
Both http1_only and http2_only 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.
Renamed from curl_impersonate
The old curl_impersonate section is a deprecated alias. If you still use it, unshackle honours it (only when network is absent) but emits a DeprecationWarning. Rename it to network.
"},{"location":"reference/configuration/network/#headers","title":"headers","text":" - Type:
dict \u00a0\u00b7\u00a0 Default: {}
Default HTTP headers merged into every HTTP session unshackle makes.
headers:\n Accept-Language: en-US,en;q=0.9\n
Don't set Accept-Encoding (and similar) here
Compatibility headers such as Accept-Encoding 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 Accept-Language, User-Agent). Per-service headers belong in that service's own config.
"},{"location":"reference/configuration/network/#proxy_providers","title":"proxy_providers","text":" - Type:
dict \u00a0\u00b7\u00a0 Default: {}
Proxy/VPN provider configuration. Each sub-key names a proxy provider, and unshackle passes its block straight to that provider's constructor. See Proxies & VPN for the full proxy provider guide. Recognised proxy providers and their exit ports:
Provider Config key Credentials Proxy scheme/port Basic (static) basic country \u2192 URI(s) as specified Control D controld Write API token (profile/resolver pairs optional) http://127.0.0.1:{port} (local forwarder) NordVPN nordvpn service credentials (48 chars combined) https://...:89 Surfshark surfsharkvpn service credentials (48 chars combined) https://...:443 Windscribe windscribevpn service credentials https://...:443 ExpressVPN expressvpn device login (enable: true) / token cache https://cat:...@...:443 ProtonVPN protonvpn TV login or exported cookies https://...:4443 (or :443 Secure Core) Gluetun gluetun per-VPN keys/creds http://localhost:{port} (local Docker) Hola (none, auto) none http://...:{peer} 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: <service username>\n password: <service password>\n
"},{"location":"reference/configuration/network/#controld","title":"controld","text":"Config keys of the Control D proxy provider. See Control D for how unshackle uses them.
Key Type Default Meaning token str required A Control D API token of type Write. profile str none Optional. The ID of a profile you made for unshackle. Give it together with resolver. Without it, unshackle creates unshackle-<region> profiles itself. resolver str none Optional. The resolver ID of an endpoint that uses profile, or its DoH URL https://dns.controld.com/<resolver>. profiles list [] Optional. More pairs, each a mapping with profile and resolver. max_profiles int 4 The most profiles unshackle uses: your pairs plus the unshackle-* endpoints on the account. It must be 1 or more. unshackle creates an unshackle-<region> profile and endpoint only while the total is lower. Provider loading differs between CLI and REST server
The dl CLI loads all providers, including gluetun. The REST API / remote-client path does not load gluetun, because it starts a local Docker container. ExpressVPN and ProtonVPN also auto-load when their cached session exists, and Hola auto-loads whenever the hola-proxy binary is present.
"},{"location":"reference/configuration/output/","title":"Output & naming","text":"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 & naming guide.
"},{"location":"reference/configuration/output/#output_template","title":"output_template","text":" - Type:
dict \u00a0\u00b7\u00a0 Required (no usable default; dl exits with an error if this is missing)
Filename templates keyed by media kind, using {variable} placeholders. Recognised kinds are movies, series, and songs (and albums for folder templates). A trailing ? on a variable (e.g. {quality?}) marks it optional: if empty, it and one adjacent separator are dropped.
unshackle.yamloutput_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
The nested folder sub-key controls output subfolders, and unshackle pops it out of output_template:
- A dict sets per-kind folder templates (kinds:
movies, series, songs, albums). - A str sets a single folder template for everything.
unshackle validates templates on load and emits warnings for unknown variables, non-string values, filesystem-unsafe characters (< > : \" / \\ | ? *), empty templates, and unknown folder-kind keys.
All valid template variables title, year, season, episode, season_episode, episode_name, part, absolute, date, quality, resolution, source, tag, track_number, artist, album_artist, album, disc, track_total, disc_total, release_type, genre, explicit, isrc, upc, label, audio, audio_channels, audio_full, atmos, dual, multi, dubbed, video, hdr, hfr, edition, repack, lang_tag, title_type.
{part?} is already inside {season_episode}
part holds the bare part index of a split episode (2) and is empty on every other title. unshackle folds it into {episode} and {season_episode}, so the shipped series template names split episodes correctly with no edit. Putting {part?} next to either of them renders the part twice (S01E01.Part.2.2). Use the standalone variable only in a template that names neither {episode} nor {season_episode}, and note that it is always empty in a folder template, since folders do not carry the part.
{absolute} counts episodes across seasons
absolute holds the absolute episode number, zero-padded to 3 digits (007), and is empty on titles that have none. You add it to the name yourself, and it never replaces {season} or {episode}. Any series with a TVDB absolute order can use it, anime most often. Services can supply it, and --enrich fills it in from TVDB. Use {absolute?} so the name stays clean when it is unknown.
"},{"location":"reference/configuration/output/#tagging-naming-keys","title":"Tagging & naming keys","text":"Key Type Default Description tag str \"\" Release-group tag. Fills the {tag} template variable and is written into MKV/audio tags. tag_group_name bool true Include the group name (tag) in the MKV Group tag. tag_imdb_tmdb bool true Write IMDb/TMDB/TVDB external-ID tags into the MKV (needs metadata providers). chapter_fallback_name str \"\" Fallback template for chapter names, e.g. \"Chapter {i:02}\". unicode_filenames bool false Allow Unicode in filenames; when false, names are ASCII-sanitised."},{"location":"reference/configuration/output/#tag_rules","title":"tag_rules","text":" - Type:
list \u00a0\u00b7\u00a0 Default: []
Conditionally replaces tag for a given download. Each rule pairs a when dict of conditions with the tag to use when they hold. unshackle evaluates the rules in order and the first match wins. If no rule matches, the global tag stays.
unshackle.yamltag_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
Rule semantics:
- Every condition in
when must hold (they are AND-ed). - A value can be a scalar or a list. A list matches if any entry matches.
- Comparison is case-insensitive string equality.
- The keys of
when are the filename template variables for the release itself: title_type, quality, resolution, source, video, hdr, hfr, audio, audio_channels, audio_full, atmos, dual, multi, dubbed, edition, repack, and lang_tag. Only these are available. unshackle adds the title's own fields (title, year, season, episode, and so on) after it evaluates the rules, so a condition cannot use them. - An unknown key in
when 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 tag, and skips it.
Put the more specific rules first, because unshackle stops at the first match.
Match hdr on the exact value
Matching is exact, and hdr is a composite label for Dolby Vision titles: a DV title with an HDR10 base layer gives DV.HDR, and with an HDR10+ base layer DV.HDR10P. Plain DV does not match those. Name every variant you want, as the example above does. Note also that HDR10 gives HDR, not HDR10. The full set of values is HDR, HDR10P, DV, DV.HDR, DV.HDR10P, and HLG, as listed in the variable table.
"},{"location":"reference/configuration/output/#operators","title":"Operators","text":"A condition value can start with a comparison operator, which unshackle applies to the rest of the value:
unshackle.yamltag_rules:\n - when: { resolution: \"<1080\" }\n tag: SDGROUP\n - when: { quality: \">=2160\" }\n tag: UHDGROUP\n - when: { video: \"!=H.265\" }\n tag: AVCGROUP\n
>, <, >=, <= compare numbers. unshackle reads the first number out of the actual value, so \">=2160\" matches a quality of 2160p. If the actual value has no number, the condition fails. =, ==, and != 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 \"!=2160\" holds for it and \"==2160\" does not. - An ordering operator with a text operand (for example
\">DV\") is a mistake: unshackle logs a warning and the condition fails. So does an operator with nothing after it (\">=\"). - A value with no operator keeps the plain equality behaviour described above.
Quote operator values in YAML
Two of these operators break an unquoted YAML value, and both stop the config from loading:
> opens a folded block scalar, so quality: >=2160 fails with a \"while scanning a block scalar\" error. ! starts a tag, so hdr: !=DV fails with a \"could not determine a constructor\" error.
Quote every operator value: quality: \">=2160\", resolution: \"<1080\", video: \"!=H.265\".
Keep a negation out of lists
A list matches if any entry matches, so two or more != entries in one list are always true. Give a negation as a single value, not as a list entry.
title_type is the media kind of the title: movie, series, or music. It is useful to give each kind its own group:
tag_rules:\n - when: { title_type: movie }\n tag: MOVIEGRP\n - when: { title_type: series }\n tag: TVGRP\n
The resolved tag applies to the {tag} filename variable only. The Group metadata tag written into MKV and music files always uses tag.
--tag wins
An explicit dl --tag on the command line disables the rules completely and uses the given tag.
"},{"location":"reference/configuration/post-scripts/","title":"Post-scripts","text":"Operate your own script when a download finishes, with unshackle's metadata passed in as {variable} placeholders. Use it to hand a finished file to an uploader, send a notification, or start a library scan.
"},{"location":"reference/configuration/post-scripts/#post_scripts","title":"post_scripts","text":" - Type:
list[dict] \u00a0\u00b7\u00a0 Default: [] (unshackle operates no scripts)
unshackle.yamlpost_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
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 {command: \"...\", event: success, mode: file}.
Key Default Meaning command required The command to run, with {variable} placeholders event success success when a file was written, failure when the download failed mode file file, season, or run. See Modes wait false true makes unshackle wait for the script to exit before carrying on. See Waiting for a script unshackle skips an entry whose event or mode 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 command it cannot split into arguments, such as one with an unbalanced quote, and logs a warning. Neither stops the download or the other entries.
"},{"location":"reference/configuration/post-scripts/#how-the-command-runs","title":"How the command runs","text":"unshackle splits the command into arguments first, and then substitutes the variables into those arguments. The process runs without a shell.
This is what keeps a title like Bob\"; rm -rf ~ 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.
Prefix your variables
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 {title} whose value is --upload-file=/etc/passwd would arrive as an option to your script, not as text. Write --title={title}, not a bare {title}, 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 -), and logs a warning instead.
No shell features, and name your interpreter
Pipes, &&, > redirection, ~ and globs do not work, because unshackle uses no shell. If you want them, make the shell explicit: bash -c \"...\".
For the same reason there is no interpreter lookup. Write python /opt/upload.py rather than /opt/upload.py. unshackle will not guess whether you meant the system Python or the one in its own virtual environment.
On Windows, when a fixed part of an argument contains a space, quote the whole argument (\"--out=C:\\My Dir\\{filename}\"), not only the value. Substituted values never need quoting on any OS.
On Windows, do not target a .bat or .cmd file directly. Windows runs batch files through cmd.exe, 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 (python upload.py, pwsh -File upload.ps1) instead.
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.
One process per file
In file mode a large season pack starts one process per episode with nothing throttling them. If your script is heavy, set wait: true, queue the work inside the script, or use mode: season.
"},{"location":"reference/configuration/post-scripts/#wait","title":"Waiting for a script","text":"unshackle.yamlpost_scripts:\n - command: \"python /opt/upload.py --file={filepath}\"\n wait: true\n
With wait: true, unshackle waits until the script exits, then writes the exit code to the debug log and carries on. Because the file 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. --postscript entries never wait.
"},{"location":"reference/configuration/post-scripts/#variables","title":"Variables","text":"Metadata comes from the same naming context that produced the file's name, built per output file. So {quality} and {hdr} always give the values for the file unshackle passes in. Downloading -q 1080,2160 -r HDR10,SDR produces four files, each with its own invocation and its own values.
Variable Value {filepath} Absolute path of the output file {filename} Its filename, with extension {folder} Absolute path of its parent folder {ext} Its extension, including the dot {sidecars} Sidecar subtitle files written for this output, newline separated {title} Show, movie or track name, sanitized {title_raw} Exactly what the service returned, untouched {title_id} The service's ID for the title {service} Service tag {year} {season} {episode} {episode_name} Season and episode are plain numbers (1, 5) {part} Part number of a split episode as a plain number (1 for Part.1). Empty when the episode has no part {season_episode} {absolute} {date} As in the filename template: {season_episode} keeps the part suffix (S01E05.Part.1) while {episode} drops it {quality} {resolution} {hdr} {hfr} {vcodec} {acodec} {edition} {tag} {lang_tag} As in the filename template, for this file {tmdb} {imdb} {tvdb} The tagging IDs in use, otherwise empty. See Tagging IDs {error} Failure message. Empty on success Every variable from your output_template is available here as well, including {video} and {audio}, of which {vcodec} and {acodec} are aliases.
Empty variables become an empty string
--tmdb={tmdb} with no ID resolved hands your script --tmdb=, so treat an empty string as absent. Write your script to accept an empty value for every variable.
Empty is common, and not only when data is missing:
- No metadata provider found an ID.
{tmdb} 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. - The title has no such field. Movies have no
{season}, {episode} or {part}, and music has none of them. - The naming context renders it empty on purpose.
{hdr} is empty for an SDR file, because SDR is the absence of an HDR tag in a filename rather than a tag that reads SDR. {edition}, {atmos}, {multi}, {dual} and {hfr} behave the same way. If your script needs the word SDR, derive it from an empty {hdr} yourself. - The post-script is a
failure one. A failed download has no output file to read metadata from, so everything that comes from the output file is empty. See Events.
There is no {variable?} conditional here, unlike output_template. 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.
Season and episode are the plain numbers, not the S01E05 form used in filenames. The padding and the separator belong to the filename template rather than to the data.
"},{"location":"reference/configuration/post-scripts/#music-variables","title":"Music variables","text":"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. {season}, {episode}, {part} and {episode_name} are always empty for music.
Variable Value {artist} Track artist {album_artist} Album artist, falling back to the track artist {album} Album name {track_number} {disc} Zero padded. {disc} is empty on a single-disc release {track_total} {disc_total} Zero padded totals, empty when the service did not give them {isrc} {upc} {label} {genre} As the service reported them, empty when absent {release_type} album, single, ep, and so on. A service that reports nothing gives album {explicit} The word Explicit when the track is flagged, otherwise empty In a file post-script {title} is the track name. See Modes for what an album post-script puts in {title}.
{year} is empty when the service gives the release no year. {ext} is the container the track arrived in, such as .flac, because a music download is not muxed.
"},{"location":"reference/configuration/post-scripts/#tagging-ids","title":"Tagging IDs","text":"{tmdb}, {imdb} and {tvdb} 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.
They hold an ID you passed with --tmdb, --imdb or --tvdb, 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.
"},{"location":"reference/configuration/post-scripts/#sidecar-files","title":"Sidecar files","text":"{sidecars} 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 {sidecars} to be empty unless subtitle.output_mode is sidecar or both, which is not the default. A music download writes no sidecars at all.
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.
When one download writes several outputs (-q 1080,720), each output's folder gets its own copy of the sidecar files, and each invocation lists the copies sitting beside its own {filepath}.
Reading {sidecars} in Pythonsubs = [p for p in sys.argv[i].removeprefix(\"--subs=\").split(\"\\n\") if p]\n
"},{"location":"reference/configuration/post-scripts/#modes","title":"Modes","text":"mode Runs {filepath} {sidecars} file Once per output file That file That output's sidecars season Once per season folder, after that season's last queued title Empty Empty run Once per folder written, at the end of the run Empty Empty season means everything this run asked for
A season post-script fires when the last title this run queued for that season finishes. With -w S01-S02 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.
A title that fails stops the whole run. unshackle dispatches the failure post-script for that title and then returns. It downloads no further title, and no season or run 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.
unshackle attaches the post-script to the folder, not to the season, so one season landing in several folders (-q 1080,720 with a quality-dependent folder template) fires it once per folder, each with its own {folder}. A movie is a group of its own: a season post-script fires for a movie's folder as soon as the movie finishes.
In run mode every variable except {folder} is empty, because one run can cover several shows. Only {folder} is meaningful, which makes it useful for starting a library scan once.
"},{"location":"reference/configuration/post-scripts/#music","title":"Music","text":"Music uses the same three modes, with the album standing in for the season.
mode Runs file Once per track, after its metadata has been written season Once per album folder, after every queued track of that album has landed run Once per folder written, at the end of the run In a file post-script {title} and {title_raw} are the track name. In an album post-script they are the album name, and the per-track variables {track_number}, {disc} and {isrc} are empty, in the same way that {episode} is empty in a season post-script.
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.
"},{"location":"reference/configuration/post-scripts/#events","title":"Events","text":"success runs after the file has moved to its final path. failure runs when the download fails, with {filepath} empty and {error} set. Each track of an album is its own title. A music failure post-script therefore describes the track that failed, not the release.
failure only fires in file mode
A failure entry with mode: season or mode: run never runs. Leave mode at its default on a failure entry.
A failure post-script has no output file to read metadata from, so it carries only what the title object already knew: {title}, {title_raw}, {title_id}, {year}, {season}, {episode}, {part}, {season_episode}, {absolute}, {date}, {episode_name}, the music release fields such as {artist} and {album}, {service}, the tagging IDs and {error}. Everything that comes from the output file, such as {quality}, {hdr}, {vcodec} and {acodec}, is empty.
A resumed --continue-downloads download that finishes runs success as usual. unshackle sees your script's exit code only when that entry sets wait: true, 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.
A success post-script always names a file this run wrote. There is no skip-if-exists path in dl today, so nothing fires for a title that was not downloaded.
"},{"location":"reference/configuration/post-scripts/#-postscript","title":"--postscript","text":"dl accepts --postscript \"<command>\", repeatable. Every command given this way runs with event: success and mode: file.
$ unshackle dl --postscript \"python /opt/upload.py {filepath}\" SERVICE TITLE_ID\n
It replaces the post_scripts config for that run rather than adding to it, so no configured entry runs while it is in use. That includes your season, run and failure entries, which have no --postscript equivalent.
"},{"location":"reference/configuration/post-scripts/#-no-postscript","title":"--no-postscript","text":"dl --no-postscript operates the run with no post-script. It silences every configured entry and every --postscript command, for each event and mode. Use it to skip an uploader or a notifier for one run without an edit to unshackle.yaml.
$ unshackle dl --no-postscript SERVICE TITLE_ID\n
"},{"location":"reference/configuration/post-scripts/#the-rest-api","title":"The REST API","text":"The API never accepts a post-script command. postscript, post_script and post_scripts in a POST /api/download body get 400 INVALID_PARAMETERS. A command that arrives from an HTTP caller would be remote code execution.
unshackle does operate the scripts defined in unshackle.yaml for API jobs, music jobs included. Only the command itself may not cross the network.
"},{"location":"reference/configuration/post-scripts/#logging","title":"Logging","text":"unshackle logs the command it operated twice: at DEBUG level on the console, and as a post_script_dispatch entry in the structured JSON debug log when that log is on.
unshackle masks both the same way, and honours redact_paths, which is on by default. Debug logs get shared in issue reports, and a post-script command line is mostly paths. URL credentials and token= / api_key= query parameters are also masked.
Do not hardcode secrets in the command
unshackle cannot recognise an arbitrary secret in the command line, such as -H \"Authorization: Bearer <key>\", and logs it verbatim. Read the secret from a file or an environment variable inside your script rather than putting it in the command.
"},{"location":"reference/configuration/post-scripts/#limitations","title":"Limitations","text":" - No
success post-script operates under --no-mux or --skip-dl, because neither writes a muxed output. A failure post-script still runs under --no-mux if the download itself fails. failure post-scripts only operate in file mode. - There is no webhook sender. Call
curl from a script instead. - Script output is not captured. Redirect it inside your own script if you want a log.
"},{"location":"reference/configuration/services/","title":"Services & authentication","text":""},{"location":"reference/configuration/services/#services","title":"services","text":" - Type:
dict keyed by service tag \u00a0\u00b7\u00a0 Default: {}
Per-service configuration, keyed by the canonical service tag (for example EXAMPLE1, EXAMPLE2, EXAMPLE3). unshackle reads several well-known sub-keys out of each service's block:
proxy_map: remaps the region query you passed to -p/--proxy for this service. A config key is that query, or \"provider:query\" 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 -p a full proxy URL. title_map: 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. dl: per-service download defaults, using the same keys as the global dl block.
Individual services may read any additional keys they define. unshackle hands the merged result (the service's own config.yaml with this block layered on top) to the service as self.config.
User- or device-specific values (API keys, account IDs, device attributes) belong in this block rather than in the service's own config.yaml, which holds shared defaults. See creating a service.
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
"},{"location":"reference/configuration/services/#credentials","title":"credentials","text":" - Type:
dict keyed by service tag \u00a0\u00b7\u00a0 Default: {}
Per-service login credentials. Each value is a username:password[:extra] string, the same data as a [username, password] (or [username, password, extra]) list, or a dict of profile name to either of those. With the dict form, -p/--profile selects the entry, and unshackle uses the default config key when you give no profile, or when the named profile is missing. unshackle parses these into Credential objects. It also uses the credential's SHA-1 as an account hash for cache keys.
credentials:\n EXAMPLE2: user@example.com:hunter2\n EXAMPLE1:\n default: primary@example.com:pw1\n second: secondary@example.com:pw2\n
Cookies vs credentials
unshackle stores cookies as files under directories.cookies, not in this config key. A service's authenticate() accepts cookies, credentials, or both.
"},{"location":"reference/configuration/services/#firefox_cookies","title":"firefox_cookies","text":" - Type:
dict keyed by service tag \u00a0\u00b7\u00a0 Default: {}
Settings for extracting cookies directly from a local Firefox profile. A service block must give hosts, 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 local_storage boolean, unshackle also pulls matching entries from webappsstore.sqlite, which only services that keep auth tokens in localStorage rather than in HTTP cookies need. Extraction is read-only.
Firefox does not need to be closed
The extractor copies both cookies.sqlite and its WAL file into a 0700 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.
Extraction falls back silently to file cookies
If extraction yields no cookies or fails for any reason, unshackle silently falls back to the normal file-based cookie path (cookies/<SERVICE>.txt or cookies/<SERVICE>/<profile>.txt), with no error reported.
"},{"location":"reference/configuration/services/#remote_services","title":"remote_services","text":" - Type:
dict \u00a0\u00b7\u00a0 Default: {}
Definitions of remote unshackle service servers, used by the --remote mode. Each entry is named by you (pick it with --server, or do not write that flag when you configure only one) and gives the server's url (required), an optional api_key, an optional auth_headers list, an optional server_cdm boolean, an optional timeout in seconds, and an optional services sub-dict of per-service local overrides such as title_map.
Leave server_cdm 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. true asks for the server CDM and falls back to the local CDM when the server refuses; false always uses the local CDM. dl --cdm <name> on a remote run has the same effect as false for that run: the device you name licenses the remote session. A cdm entry for the service has the same effect for that service when it names the device that unshackle loaded. Both take priority over server_cdm: true. Remove the entry to use the server CDM for that service. The default entry does not count.
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.
auth_headers lists extra header names to send the API key in, tried before the defaults X-Secret-Key and X-Api-Key, which unshackle always appends as fallbacks. It sends the first name. If the server answers 401, 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 auth_headers: [\"Authorization\", \"x-secret-key\"] as Authorization, x-secret-key, X-Api-Key.
timeout is the time in seconds that the client waits for data from the server. The default is 120. 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 timeout 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. 0 means the default.
In --remote mode unshackle turns the server's service list into synthetic CLI commands that operate against it, falling back to the tags in that services sub-dict when unshackle cannot fetch the list. Each synthetic command carries the server-side service's options and documentation, so unshackle dl --remote <TAG> -h 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.
"},{"location":"reference/configuration/services/#serve","title":"serve","text":" - Type:
dict \u00a0\u00b7\u00a0 Default: {}
Configuration for the serve command (the built-in REST API server). The full server guide is the REST API section. These are the config keys.
Sub-key Type Default Description api_secret str (unset) Master secret the server accepts in the X-Secret-Key header. Required unless you start the server with --no-key. users dict {} Per-user API keys and their allowlists (see below). tiers dict {} Named settings that users entries reference by name (see below). services list (unset) Global service allowlist. Omit to allow all. remote_only bool false Expose only the remote service session endpoints (health, services, search, session) and disable the rest of the REST API. dashboard dict (unset) Developer dashboard: key is the API key for the read-only /api/dashboard/ endpoints (status, remote sessions, remote session logs, jobs, keys, services, health, logs, SSE events). Unset leaves those routes unregistered. See dashboard endpoints. session_ttl int (s) 300 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. max_sessions int or null 100 Maximum concurrent remote sessions; at the cap the server evicts the oldest. Set it to null or 0 for no limit, which is also what /api/dashboard/status then reports, so a dashboard can tell \"no cap\" from a cap that happens to sit at the default. history_limit int 100 How many finished jobs to retain in history. compression_level int 1 gzip level for responses. services_refresh_interval int (s) 0 How often the server pulls the git-backed service repositories in directories.services and hot-reloads the services that changed. 0 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. services_staged_max_age int (s) 0 How long a staged service waits for its jobs and sessions before the server swaps it in anyway. 0 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. global_speed_limit str (unlimited) Server-wide download speed cap, e.g. 10M, 1.5G or plain bytes/sec (same format as speed_limit). One shared budget across all concurrent jobs; the server ignores per-job speed limits while it is set. cdm_overrides list or bool (unset) Allowed per-request CDM overrides: a list of permitted device names, or true for any. Unset rejects every override. allow_job_credentials bool false Permit clients to supply credentials per job. server_accounts dict {} Services whose remote sessions use the server's own credentials and cookie files instead of the client's (see below). devices list (auto) Widevine devices offered; auto-filled from directories.wvds. playready_devices list (auto) PlayReady devices; auto-filled from directories.prds. Each entry under users uses that user's API key as its name, and can set its own services, devices, and playready_devices allowlists, narrowing the global ones, plus an optional username used as the log label for that API key (defaults to a truncated form of the API key). A user with no playready_devices config key gets no PlayReady access at all, not the global list.
Reload serve settings without a restart
Send SIGHUP to a running server (systemctl reload with ExecReload=kill -HUP $MAINPID 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 users, tiers, services and device lists in one step. Open CDM sessions and remote sessions continue; an API key you removed gets 401 on its next request. A file that does not parse or validate keeps the running settings and logs the reason. A change to remote_only, services_refresh_interval, the first PlayReady device, or any command-line flag needs a restart, and the log says so. Windows has no SIGHUP: restart the server there.
server_cdm decides whether the server runs the CDM licensing for that API key. Set it to true to enable every service, or to a list of service tags to enable only those. It is false unless the entry sets it. For a service the API key does not cover, the server tells a remote client configured with server_cdm: true to license with its own local CDM instead, and a client that asks anyway gets a FORBIDDEN error. Because a download job always licenses with the server's CDM, an API key without server_cdm for that service also cannot submit or retry /api/download jobs. Keys that have no users entry, such as api_secret, keep server CDM access.
A remote client that picks its own device licenses the remote session with that device. It picks with dl --cdm, with a cdm entry for the service, or with server_cdm: false in its remote_services 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.
server_cdm_max_height 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 default entry. A service the map does not name or sets to null gets the default, and with no default it has no limit. The server compares the limit with the lowest -q 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 -q when the remote session starts:
- With no
-q, or a -q 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. - With a
-q 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 SERVER_CDM_CAPPED error. - A download job must pass a
quality at or below the limit, and must not set best_available or a HYBRID range. HYBRID always keeps the lowest Dolby Vision track, at any quality. A job with no quality, with a higher one, with best_available, or with HYBRID gets a SERVER_CDM_CAPPED error. The server checks the values the job runs with, after it applies the service defaults and the serve: download defaults.
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.
server_vault lets a remote session that the client's own device licenses take content keys from the server vault. Set it to true for every service, or to a list of service tags. It is false unless the entry sets it, and server_cdm 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.
admin is a boolean that lets the API key run the maintenance endpoints (clear-cache, clear-temp, refresh-services). It is false unless the entry sets it. Keys that have no users entry, such as api_secret, keep that access.
A tier names an entry under serve.tiers, which holds the settings that several API keys share. Today a tier carries rate_limit, the requests per hour that API key may make; an API key can also set its own rate_limit, which wins over its tier's. An API key with neither has no limit. Going over the limit answers 429 with a Retry-After header. The server keeps a fixed window rather than a sliding one: it opens on the first request and resets an hour later. A tier that names no entry under serve.tiers, or a rate_limit 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 /api/health.
server_accounts 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 credentials. For a service that is not listed the server never uses its own accounts: a client that sends nothing authenticates with nothing.
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
Each entry under a service names a profile from credentials, or a cookie file cookies/<TAG>/<profile>.txt 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 global. Quote no (Norway), because YAML reads the bare word as false.
The region of a remote session is the country the client asked for with --proxy (ca, ca1, provider:ca), the server's own region with --no-proxy, or the client's own region otherwise. A full proxy URI carries no country, so with one only a global account matches. The server picks the profiles that cover that region (or are global) 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 -p/--profile.
Cookies come only from the profile's own file (cookies/EXAMPLE1/ca_main.txt; the server does not read a bare cookies/EXAMPLE1.txt), and each account keeps its own persistent cache under cache/_accounts/EXAMPLE1/<profile>/, so refreshed tokens survive the remote session but never cross accounts. serve refuses to start when a listed profile has neither an entry under credentials nor a cookie file. /api/search, /api/list-titles and /api/list-tracks use the same pool, matched on the client's reported region, and return FORBIDDEN 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.
A users entry opts in to those accounts with server_accounts: true (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 /api/services does not advertise the server's accounts to it. API keys with no users entry, such as api_secret, keep access.
server_proxy decides whether that API key may use the proxy providers the server has configured. There is no implicit access: only the boolean true on the API key's users entry grants it, and an API key without a users 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 proxy, not to match the client's region, and not for a service geofence. This applies to remote sessions, search, title lists, and /api/download jobs alike. Such a client must send a full proxy URI, or no_proxy to accept the server's own connection. Set server_proxy: true to let that API key send a country code or a provider:country 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.
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
dl keys inside serve
Most dl flag keys (downloads, workers, best_available, and so on) can be set directly inside serve, 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.
"},{"location":"reference/configuration/vaults/","title":"Key vaults","text":"The full guide is at Vaults. Two keys configure them.
"},{"location":"reference/configuration/vaults/#key_vaults","title":"key_vaults","text":" - Type:
list[dict] \u00a0\u00b7\u00a0 Default: []
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 type (the backend module name) and a name, plus backend-specific keys.
type Purpose Required keys Notes SQLite Local SQLite database name, path Loaded critically; a failure aborts the run. MySQL Remote MySQL database name, host, database, username Extra keys (e.g. password, port) forwarded to pymysql. connect_timeout defaults to vault_timeout. API RESTful JSON API name, uri, token Optional headers map is sent with every request. Honours vault_timeout. HTTP HTTP API with modes name, host, one of password/api_key, and username in query mode api_mode: query (default), json, decrypt_labs. Honours vault_timeout. 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
Per-entry options
no_push: true makes a vault read-only (unshackle fetches content keys from it but never writes to it). - A vault of
type: API whose name contains decrypt_labs auto-fills its token from decrypt_labs_api_key when not set inline. Vault type values are case-sensitive module names. - unshackle treats an all-zero content key (32 zeros) as \"no key\" everywhere and never stores it.
Bad content keys
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 bad_keys table of every SQLite vault with the name of the vault that supplied it, and every vault lookup skips a flagged pair from then on. A SQLite vault also refuses to store a flagged pair again. Only the SQLite backend stores flags; an API vault that supplied the pair gets a report. A serve instance with server_cdm flags a pair the same way when a remote client reports it, so a server whose key_vaults hold no SQLite entry cannot remember a bad content key.
"},{"location":"reference/configuration/vaults/#vault_timeout","title":"vault_timeout","text":" - Type:
float \u00a0\u00b7\u00a0 Default: 10.0
Timeout in seconds for vault operations. Injected automatically into any backend whose constructor accepts a timeout parameter (a per-vault timeout still wins). The MySQL backend uses it as the default connect_timeout.
"}]}
\ No newline at end of file
+{"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":"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.
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.
Use responsibly
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.
"},{"location":"#what-it-does","title":"What it does","text":"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:
- Fetch the title metadata (movies, full series, seasons, episodes, albums, tracks).
- Parse the streaming manifest: DASH, HLS, or Smooth Streaming (ISM).
- Select the tracks you asked for by resolution, codec, bitrate, range, language, and channel layout.
- 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.
- Decrypt, extract closed captions, repack, and mux the result into a Matroska (
.mkv) file with correct language, forced, and default flags. - Tag and name the output using configurable filename templates.
"},{"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; 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":"A git clone with the install script is the recommended way to install unshackle.
Linux (recommended)Windows (recommended)Advanced: uv tool git clone https://github.com/unshackle-dl/unshackle.git\ncd unshackle\nsh install.sh\nuv run unshackle env check\n
git clone https://github.com/unshackle-dl/unshackle.git\ncd unshackle\n.\\install.bat\nuv run unshackle env check\n
uv tool install git+https://github.com/unshackle-dl/unshackle.git\nunshackle setup\n
This installs unshackle into the tool folder of uv, not a folder that you choose. unshackle setup then puts the tools, config, and data in your user data and config directories.
The install script installs uv and unshackle, then runs unshackle setup. In a clone, run every command as uv run unshackle .... The examples on this site use the bare unshackle command.
External tools
unshackle shells out to FFmpeg, MKVToolNix, shaka-packager, Bento4, and dovi_tool for decryption, repacking, muxing, and Dolby Vision work. unshackle setup downloads them when a portable build exists for your system. See Installation for the full list and recommended versions.
"},{"location":"#a-first-download","title":"A first download","text":"Every download is three parts: the dl command, a service tag, and the service's title argument (a URL, ID, or slug).
Download a 1080p title with English audiounshackle dl -q 1080 -l en EXAMPLE 81234567\n
The dl command carries all the quality, language, and output flags. The service tag (EXAMPLE 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.
"},{"location":"#where-to-go-next","title":"Where to go next","text":" - Installation. Install unshackle and the external tools it depends on.
- Quickstart. Configure
unshackle.yaml and do your first download. - Downloading. The full
dl command guide: quality, codecs, languages, track selection, and output. - Configuration. Where
unshackle.yaml lives, the directory layout, and how to edit values. Full config key list in the Configuration Reference. - REST API. Operate the
serve HTTP server and drive downloads programmatically.
Getting help
Operate unshackle --help or unshackle dl --help at any time. The community Discord is the fastest place to ask questions.
"},{"location":"dev/creating-a-service/","title":"Creating a Service","text":"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).
Who this page is for
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.
unshackle ships two reference services. EXAMPLE, at unshackle/services/EXAMPLE/, 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 unshackle/services/MUSIC_EXAMPLE/, is the same kind of showcase for a music service. If your platform has songs, read that one too.
"},{"location":"dev/creating-a-service/#how-unshackle-finds-a-service","title":"How unshackle finds a service","text":"At startup unshackle scans every path in the directories.services config key (a list). Each entry is either a local directory of services or a remote repo spec (a git URL or owner/repo shorthand, which unshackle clones for you). The default is the bundled unshackle/services directory.
Within a services directory, every subfolder that contains an __init__.py is a service, and the folder name is the service tag:
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
Two rules the loader enforces:
- The class name must match the folder/tag name exactly. Folder
EXAMPLE must define class EXAMPLE. A mismatch raises a RuntimeError. - 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.
After installation, you call a service as a subcommand of dl:
unshackle dl EXAMPLE 20914\nunshackle dl EX 20914 # via an ALIAS\n
Config lives next to the code
A service's own settings go in config.yaml inside the service folder (directories.services/<TAG>/config.yaml). This is separate from the global unshackle.yaml. Access it in code as self.config[...]. Never hardcode URLs, user agents, or certificates. Put them here.
config.yaml is shared: keep secrets out of it
Treat config.yaml 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 unshackle.yaml under services.<TAG>, which is merged into self.config at runtime. That checked-in-defaults / per-user-overrides split is exactly why every URL lives in config.yaml with {}/{name} placeholders while the secrets that fill them stay out of it. Both halves read back through the same self.config[...].
Split across files? Use relative imports
If your service grows beyond a single __init__.py, import your own modules relatively:
from .helpers import parse_manifest # correct\nfrom unshackle.services.TAG.helpers import parse_manifest # breaks from a repo\n
A service loaded from a remote repo lives outside the unshackle package, so Python cannot find the absolute unshackle.services.<TAG>.* path and the import fails with no known parent package. Relative imports work both locally and from a cloned repo.
"},{"location":"dev/creating-a-service/#the-service-base-class","title":"The Service base class","text":"Every service subclasses unshackle.core.service.Service. The minimum is a Click cli entry point plus three abstract methods.
"},{"location":"dev/creating-a-service/#class-variables","title":"Class variables","text":"Declared at class level to configure framework behaviour:
Variable Type Purpose ALIASES tuple[str, ...] Extra tags that resolve to this service (e.g. (\"EX\", \"DOMAIN\")). Case does not matter. Default (). GEOFENCE tuple[str, ...] IP region codes the service requires. Empty = no geofence. unshackle treats the first entry as the main region for auto-proxy. GEOBLOCK tuple[str, ...] IP region codes where the service refuses to work. Every other region is allowed. Default (). VAULT_TAG Optional[str] Overrides the key-vault namespace so sibling services can share one vault. Default None (use the service's own tag). AUTH_METHODS Optional[tuple[str, ...]] Auth methods accepted (\"cookies\" / \"credentials\"). When None, the REST /services endpoint infers them from authenticate(). ANONYMOUS_SEARCH bool Set True when search() needs no login and no state from authenticate(). A search then skips the cookie load, authenticate() and the cookie save. Default False. NO_SUBTITLES bool Set True on a service with no subtitle tracks to skip subtitle handling entirely. ANIME bool Set True when the catalogue is anime, so metadata lookups prefer AniList. A title's own anime flag overrides it. DAILY bool Set True when the catalogue is daily/date-based (talk shows, news, sports), so unshackle names episodes by air date. A title's own daily flag overrides it. NO_SUBTITLES is a convention, not a base-class attribute
dl.py uses hasattr to find NO_SUBTITLES, and the Service base class deliberately does not declare it, so it only exists if your service defines it. Setting NO_SUBTITLES = True is what makes the pipeline skip subtitle work for services that never carry subtitles. Leave it off otherwise.
GEOFENCE drives an automatic proxy: on startup, if you did not pass an explicit --proxy, the base class does a live IP check and, if your region is blocked, fetches a proxy to GEOFENCE[0] from your configured proxy providers.
GEOBLOCK is the negative form: the service works everywhere except the listed regions. With no GEOFENCE to name a main region, a GEOBLOCK hit stops the run with a \"not available in your region\" error; pass --proxy yourself.
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
"},{"location":"dev/creating-a-service/#what-service__init__-wires-up","title":"What Service.__init__ wires up","text":"When you call super().__init__(ctx), the base class sets up the attributes you will use throughout the service:
Attribute What it is self.config This service's config.yaml contents (a dict), or None if absent. self.log A logging.Logger named after your class. self.session A prepared requests.Session with config headers and a retry adapter (5 retries, backoff 0.2, retries on 429/500/502/503/504). self.cache A Cacher for arbitrary key/value data, for example authentication tokens. self.title_cache A region/account-aware TitleCacher used by get_titles_cached. self.cache_dir config.directories.cache / <ClassName>. self.track_request A TrackRequest built from the CLI --vcodec / --range / --best-available flags. self.credential None until authenticate() runs. self.current_region The two-letter region resolved from proxy/IP. self.track_request is a small dataclass you can read and rewrite before fetching tracks:
@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
Read the request, don't second-guess the user
Services may narrow track_request 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 get_tracks returns.
Override get_session() to defeat TLS-fingerprint bot detection
The base get_session() returns a plain requests.Session (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 session(\"Chrome131\") (any rnet.Impersonate preset). RnetSession is a drop-in requests.Session replacement (same .get/.post/cookie-jar interface), so nothing else in the service changes. If instead you need specific SSL cipher behaviour, mount unshackle.core.utils.sslciphers.SSLCiphers onto a plain requests.Session.
"},{"location":"dev/creating-a-service/#the-methods-you-write","title":"The methods you write","text":"unshackle calls the methods in the order shown. Only the three abstract ones are mandatory.
graph LR\n A[cli] --> B[__init__] --> C[authenticate] --> D[get_titles] --> E[get_tracks] --> F[get_chapters]
"},{"location":"dev/creating-a-service/#cli-the-click-entry-point","title":"cli: the Click entry point","text":"A static method decorated as a Click command. It defines the CLI arguments and returns an instance of your service. Keep the command name= matching the tag.
name= is cosmetic: the directory name is what resolves the command
unshackle chooses the command from the folder/class name, not from the name= in @click.command. A mismatched name= still loads and runs. It only produces confusing --help/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.
@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) -> 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
Your docstring becomes the CLI --help text (help=__doc__), so document the accepted URL/ID formats and options there.
CDM-aware behaviour
The resolved CDM is on ctx.obj.cdm (may be None for DRM-free runs). Use is_widevine_cdm() / is_playready_cdm() from unshackle.core.cdm.detect to classify it. These work correctly for local and remote CDMs, so never hand-roll an isinstance check. Services often pick a device profile or manifest endpoint based on which DRM the CDM speaks.
"},{"location":"dev/creating-a-service/#authenticate-optional-login","title":"authenticate: optional login","text":"Override to log in with cookies and/or credentials. Call super().authenticate() first: the base implementation loads the cookie jar into self.session.cookies and stores self.credential. Do all token fetching here. It runs before get_titles.
def authenticate(self, cookies=None, credential=None) -> 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) > 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
Cookies come from files under directories.cookies. Credentials come from the credentials map in unshackle.yaml. For interactive prompts (OTP, captcha) use self.request_input(prompt), never a bare input(). Under serve mode there is no local terminal, so a bare input() would hang the server waiting on stdin that never arrives. request_input instead relays the prompt to the client: a remote-dl session gets it through the attached InputBridge, and a REST download job shows it as input_prompt. Locally it routes through the shared Rich console (prompt_user) so the prompt renders correctly alongside progress and log output.
For a login that the user approves on another device (a pair code, a QR code), use self.wait_for_approval(message, check, timeout), never a hand-written loop. It shows the message, then calls check at each interval until check returns a value. check returns None while the approval is pending.
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
It raises TimeoutError after timeout seconds. Under serve 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 notice field until the wait ends.
The wait sees a cancel only between two check calls, so check must return within a few seconds. A check that reads a socket keeps the socket open across calls and returns None after each short idle wait.
Make each token cache entry unique
The cache above uses tokens_{device}_{profile} on purpose. A token cache must include every dimension that changes the token (device, profile, or credential.sha1), 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.
Use the credential carefully
Use the Credential only inside authenticate() to get tokens. Do not stash it or the raw cookie jar elsewhere. The base class already caches identity for you.
"},{"location":"dev/creating-a-service/#get_titles-required","title":"get_titles: required","text":"Return a titles collection for the given ID. The return type depends on the kind of title:
Return Contains Use for Movies Movie objects Films Series Episode objects Shows (flatten seasons into episodes) Album Song objects Music Every title carries a language (its original recorded language) and an arbitrary data 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.
def get_titles(self) -> 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
Common constructor fields:
MovieEpisodeSong Movie(id_, service, name, year=None, language=None, data=None, description=None)\n
Episode(id_, service, title, season, number, name=None, year=None,\n language=None, data=None, description=None, air_date=None,\n part=None)\n
Pass air_date for daily and sports titles to name by date instead of SxxExx. Return a Series([...]) of episodes. Pass part only when the service splits one episode into several videos, see Split episodes.
Song(id_, service, name, artist, album, track, disc=1, year=None,\n language=None, data=None, ...)\n
Return an Album([...]) of songs. disc defaults to 1 and year is optional. Optional metadata keywords such as album_artist, genre, isrc, label, lyrics and artwork_url feed the tagger and the naming templates. Read the class for the current list.
From get_tracks(), give one Audio track for each codec and bitrate you offer for the song. The framework then selects one with its usual audio options. A Song skips the muxer, so restore the real container suffix on the track path in on_track_downloaded. The MUSIC_EXAMPLE service shows the full music surface.
The ID must be unique and stable
id_ must be truthy and, if it has a length, at least 4 characters, to avoid clashes. Use the service's own stable IDs.
Title caching
You can call self.get_titles_cached() instead of get_titles() 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 title_map config.
"},{"location":"dev/creating-a-service/#split-episodes","title":"Split episodes","text":"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). Episode.number stays an int. The optional part carries the index.
Episode(..., season=1, number=1, part=1, name=\"The Reckoning\")\nEpisode(..., season=1, number=1, part=2, name=\"The Reckoning\")\n
part counts from 1, contiguous. unshackle rejects part=0, and -w can only address parts up to 99. - Every part of one episode shares the same
season and number. - Each part is a separate
Episode with its own unique id_. - Unsplit episode: leave
part unset. Never pass part=1 for a whole episode. - Do not put the part in
name or number. Pass a clean name (or None) and set part. part 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.
part accepts an int or a digit string. A value that is not an integer raises TypeError. A value of 0 or less raises ValueError.
The framework never infers a part from the episode name
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 part argument.
Clean the part out of the name
Episode discards any name that starts with Episode <number>, so a raw \"Episode 1 (Part 2): The Reckoning\" leaves you with no episode name at all. Remove the prefix before you pass it, or pass None.
Once part is set, the filename gains a part token (S01E01.Part.2, see Output & naming), -w S01E01.2 selects a single part while a bare -w S01E01 selects them all, and the --list-titles tree labels the episode 01.2. The REST API reports it as an extra part field on the serialized title, described in Endpoints.
Opt-in and additive
Leaving part unset costs you nothing: filenames, sort order, -w matching and the API JSON are identical to a plain episode, so a service that does not split episodes has nothing to adopt.
"},{"location":"dev/creating-a-service/#get_tracks-required","title":"get_tracks: required","text":"Given one title, return a Tracks object holding Video, Audio, and Subtitle tracks. In almost all cases you assemble these by parsing a manifest, not by hand.
The manifest parsers live in unshackle.core.manifests:
from unshackle.core.manifests import DASH, HLS, ISM\n
Each exposes from_url(url, session=...) (or from_text(text, url)) and then .to_tracks(language=...):
DASH (.mpd)HLS (.m3u8)ISM (Smooth Streaming) def get_tracks(self, title: Title_T) -> Tracks:\n return DASH.from_url(manifest_url, session=self.session) \\\n .to_tracks(language=title.language)\n
def get_tracks(self, title: Title_T) -> Tracks:\n return HLS.from_url(manifest_url, session=self.session) \\\n .to_tracks(language=title.language)\n
The URL must be a variant (master) playlist, not a media playlist.
def get_tracks(self, title: Title_T) -> Tracks:\n return ISM.from_url(manifest_url, session=self.session) \\\n .to_tracks(language=title.language)\n
Always pass language=
Pass the title's original language to to_tracks(language=...). For DASH and HLS this is required as a fallback. If to_tracks cannot derive a track's language and you gave no valid fallback, it raises ValueError. It is also what lets the parser flag is_original_lang on each track (through is_close_match), which drives -l best/all selection and the filename language token.
Some services deliver a separate manifest per codec/range. The base class provides get_tracks_for_variants(title, fetch_fn) to fan out over every codec\u00d7range in the TrackRequest, including HYBRID (fetch HDR10 + DV and merge) and --best-available skip-on-error handling:
def get_tracks(self, title: Title_T) -> Tracks:\n def fetch_variant(title, codec, range_) -> 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
After parsing, you may correct track metadata the manifest gets wrong: stamp the real video.range, fix odd audio channel counts, mark descriptive audio, add hand-built subtitles or an Attachment (e.g. cover art). Do not filter for resolution/bitrate. See fetch_dash_manifest in the EXAMPLE service for a thorough demonstration.
Flip HDR10 \u2192 HDR10+ by hand when you know the platform embeds it
HDR10+ is a bitstream (SEI) feature. The HLS parser intentionally does not sniff it from the bitstream, so a manifest that embeds HDR10+ SEI but labels the variant plain HDR10 will parse as HDR10. The label is the only signal the parser has, and it is wrong. Only the service author knows the platform embeds HDR10+, so it is on you to correct video.range to HDR10+ here for those services.
get_tracks is your only chance to capture license inputs
The license callbacks (get_widevine_license and the others) fire much later, in the download/decrypt step, long after get_tracks has returned, and they receive only challenge, title, and track. Nothing else from the manifest response reaches them. So you must stash anything a license call needs (the license URL, dt-custom-data, a session token) now, during get_tracks, onto self.license_data or title.data. This is a lifecycle-timing consequence you cannot infer from the callback signatures.
Give the KID if you cheaply can
If you can get a track's Key ID (32-char hex) without downloading the track data, set track.kid. It speeds up the decryption and key-lookup path. And be sure encrypted tracks carry the correct drm so the core licenses them.
"},{"location":"dev/creating-a-service/#get_chapters-required","title":"get_chapters: required","text":"Return a Chapters object of 0 or more Chapters. It sorts by timestamp, numbers the chapters at mux time, and adds a 00:00:00.000 chapter if none exists. Timestamps take \"HH:MM:SS[.mmm]\", int milliseconds, or float seconds.
def get_chapters(self, title: Title_T) -> 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
Sort by timestamp before you build the Chapters
Chapters.add() adds its own unnamed Chapter(0) once you add a chapter that is not at 0, and a duplicate timestamp raises ValueError. Sort first, so yours lands before it.
You never need to add Chapter(0). An API chapter at 0 keeps its name. Drop duplicate timestamps.
Close a named range with an unnamed chapter
An unnamed Chapter ends the range before it: Chapter(name=\"Intro\") at the start, an unnamed one where the intro ends.
Don't invent chapter names
Never write \"Chapter 1\"; leave unnamed chapters unnamed. Users set chapter_fallback_name in their config (for example, \"Chapter {i:02}\").
"},{"location":"dev/creating-a-service/#handling-drm","title":"Handling DRM","text":"The core drives licensing. Your job is to answer the license challenges the CDM produces. Mark encrypted tracks with the right DRM in get_tracks (the manifest parsers do this automatically for PSSH/EXT-X-KEY found in the manifest), then write the license callbacks you need. Each receives the challenge plus the current title and track:
Method For Returns get_widevine_service_certificate Widevine privacy mode The service certificate (bytes or base64 str), or None. get_widevine_license Widevine The raw license response (bytes or base64 str), unmodified. get_playready_license PlayReady The license response. Defaults to delegating to get_widevine_license. get_clearkey_license DASH org.w3.clearkey The JWK Set (dict/JSON/bytes), or None to let the framework POST the challenge to the manifest's Laurl. 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
Return the license untouched
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.
ClearKeyCENC (org.w3.clearkey) has three escalating integration levels
Pick the lowest level that works for the platform:
- The manifest carries a
<Laurl>: write nothing. The framework POSTs the challenge to that URL itself. - Your service needs a custom endpoint or extra headers: override
get_clearkey_license to do the POST yourself. - Keys arrive obfuscated or through a bespoke channel: fetch and unwrap the content key in
get_tracks and pre-populate drm.content_keys[kid] = key_hex on the track's ClearKeyCENC. The non-obvious payoff: when every KID is already keyed, the framework skips the license round-trip entirely.
Things the service does not do:
- HLS AES-128 (
ClearKey) tracks and DRM-free tracks have no license callback. The content key comes from the manifest, and unshackle applies it directly. - Key vaults cache
KID:KEY pairs across runs, so repeat downloads skip the license round-trip entirely. - Decryption tooling (shaka-packager or mp4decrypt) and the choice of local vs remote CDM are user configuration, not service concerns.
See the DRM & CDM reference for the full picture.
"},{"location":"dev/creating-a-service/#optional-event-hooks","title":"Optional event hooks","text":"Override any of these to react to pipeline stages (all no-ops by default): on_segment_downloaded, on_track_downloaded, on_track_decrypted, on_track_repacked, on_track_multiplex. Also override search() to yield SearchResult objects for unshackle search.
Set ANONYMOUS_SEARCH only for a search that needs no account
With ANONYMOUS_SEARCH = True, search() operates on an HTTP session with no cookies, and authenticate() does not run. Set it only when the search results do not depend on the account, and when search() does its own setup. A search() that reads a token, a header or a region from authenticate() fails or gives results for the wrong region.
def search(self) -> 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
"},{"location":"dev/creating-a-service/#minimal-service-skeleton","title":"Minimal service skeleton","text":"A complete, minimal single-manifest service. Save as services/MYSVC/__init__.py (class name MYSVC), with an optional services/MYSVC/config.yaml beside it.
services/MYSVC/__init__.pyfrom __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 <title-id-or-url>\n \"\"\"\n\n ALIASES = (\"MY\",)\n GEOFENCE = (\"US\",)\n TITLE_RE = r\"^(?:https?://myservice\\.com/watch/)?(?P<id>[\\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) -> \"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) -> None:\n super().authenticate(cookies, credential)\n # obtain any tokens here, e.g. self.token = ...\n\n def get_titles(self) -> 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) -> 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) -> 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
services/MYSVC/config.yamlendpoints:\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
Try it with:
unshackle dl MYSVC https://myservice.com/watch/abc123\n
"},{"location":"dev/creating-a-service/#checklist","title":"Checklist","text":" - Folder name, class name, and Click
name= all match the tag exactly. -
cli is a @staticmethod that returns an instance. __init__ calls super().__init__(ctx). -
get_titles, get_tracks and get_chapters written. Titles carry the original language. - Tracks come from a manifest parser with
to_tracks(language=title.language). No filtering by quality or language. - Encrypted tracks carry their DRM. The license callbacks you need return responses unmodified.
- URLs, user agents, and certificates live in
config.yaml, read through self.config[...]. - Multi-file services import their own modules relatively (
from .helpers import x), so they work when loaded from a repo.
Read unshackle/services/EXAMPLE/ end to end. It annotates every feature touched above in one place. For a music service, read unshackle/services/MUSIC_EXAMPLE/ too.
"},{"location":"dev/service-architecture/","title":"Service Architecture","text":"This page is the conceptual map of the internal object model that a service author works against. It ties together the moving parts: the Service base class, the Title hierarchy a service returns, the Track 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.
Who this page is for
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.
"},{"location":"dev/service-architecture/#the-shape-of-a-download","title":"The shape of a download","text":"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 dl command drives the whole flow and only ever calls three required methods on your service, in order:
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
get_titles() returns a Titles collection: the movies, episodes, or songs the platform exposes for the requested ID. get_tracks(title) returns a Tracks object for a single chosen title. In practice this means fetching a manifest and handing it to a parser, which builds the Video/Audio/Subtitle objects. get_chapters(title) returns any chapter markers.
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 Title and Track objects. The framework does the rest.
"},{"location":"dev/service-architecture/#the-service-base-class","title":"The Service base class","text":"Every service subclasses unshackle.core.service.Service, an abstract base class. Two kinds of members matter: class variables that give the details of the service, and methods that the pipeline calls.
"},{"location":"dev/service-architecture/#class-variables","title":"Class variables","text":"Declared at the top of your service class, these are static descriptors:
Class variable Type Purpose ALIASES tuple[str, ...] Alternate tags the service answers to, in any case (resolved by Services.get_tag). GEOFENCE tuple[str, ...] ISO region codes the service requires; empty means no geofence. unshackle treats the first entry as the \"main region\" for automatic proxy selection. GEOBLOCK tuple[str, ...] 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. VAULT_TAG Optional[str] Overrides the key-vault namespace; defaults to the service's own tag. AUTH_METHODS Optional[tuple[str, ...]] Accepted auth methods (\"cookies\" / \"credentials\"). When None, the REST /services endpoint infers them from authenticate(). ANONYMOUS_SEARCH bool search() needs no login and no state from authenticate(). A search then skips the cookie load, authenticate() and the cookie save. Default False. ANIME bool The catalogue is anime, so metadata lookups prefer AniList. A title's own anime flag overrides it. DAILY bool The catalogue is daily/date-based, so unshackle names episodes by air date. A title's own daily flag overrides it."},{"location":"dev/service-architecture/#required-methods","title":"Required methods","text":"These are abstract. A service will not load unless it defines all three:
get_titles() -> Titles_T: find the title collection for the requested ID. get_tracks(title) -> Tracks: assemble the track set for one title. get_chapters(title) -> Chapters: return chapter markers (may be empty).
"},{"location":"dev/service-architecture/#optional-methods-and-hooks","title":"Optional methods and hooks","text":" authenticate(cookies=None, credential=None): the base implementation loads a CookieJar into self.session.cookies and stores self.credential. Override it to do a real login handshake. search(): raises NotImplementedError by default. Write it so that the search command can operate. unshackle calls authenticate() first, unless the service sets ANONYMOUS_SEARCH. - DRM license hooks:
get_widevine_service_certificate, get_widevine_license, get_playready_license (delegates to Widevine by default), and get_clearkey_license (returns None by default). See DRM hooks below. request_input(prompt): prompts the user. It goes through the remote-dl input bridge, the REST download job relay, or the rich console. wait_for_approval(message, check, timeout, interval=3.0): shows a message, then calls check 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 notice. - Event callbacks:
on_segment_downloaded, on_track_downloaded, on_track_decrypted, on_track_repacked, on_track_multiplex let a service react to pipeline events (for example, MonaLisa decrypts each segment in on_segment_downloaded). resolve_server_keys(title): 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 Service base class at all: dl.py probes for it with hasattr 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.
"},{"location":"dev/service-architecture/#what-__init__-wires-up-for-you","title":"What __init__ wires up for you","text":"You rarely override __init__. The base constructor takes the Click context and sets up the objects your methods rely on:
Attribute What it is self.config The per-service config slice (see Request and HTTP session objects). self.log A logging.Logger named after your class. self.session A ready-to-use HTTP session (headers, retries, and proxy applied). self.cache A generic key/value Cacher namespaced to the service. self.title_cache A region- and account-aware TitleCacher. self.cache_dir config.directories.cache / <ServiceName>. self.credential The active Credential, or None until authenticated. self.track_request A TrackRequest describing the requested codecs, ranges, and best-available flag (see below). The constructor also resolves proxies: it reads --proxy and the proxy_query and proxy_provider context params that dl derives from it, consults the per-service proxy_map, and, if GEOFENCE is set and you did not give an explicit proxy, does a live IP check and auto-fetches a proxy to GEOFENCE[0] when it detects a geoblock. A GEOBLOCK hit with no GEOFENCE stops the run with a \"not available in your region\" error, because there is no main region to fetch a proxy for; pass --proxy yourself. A proxy whose exit is in a GEOBLOCK region stops the run the same way. See Proxies and VPN.
TrackRequest
self.track_request is a small dataclass built from the CLI: codecs (from --vcodec, empty means \"accept any\"), ranges (from --range, default [Video.Range.SDR]), and best_available. Use it in get_tracks to decide which variants to fetch.
"},{"location":"dev/service-architecture/#titles-and-the-title-hierarchy","title":"Titles and the Title hierarchy","text":"get_titles() returns a title collection, one of the Titles_T types. Each collection holds one or more Title objects (Title_T). There are three parallel families, one per media kind:
Media kind Item (Title_T) Collection (Titles_T) Movies Movie Movies TV Episode Series Music Song Album, and Music (the base collection) All items subclass Title, which carries the shared identity: a unique id, the originating service class, an optional original language, arbitrary data, and a freshly-constructed self.tracks = Tracks() that get_tracks will fill. Collections use sorted lists, so titles stay in a stable order.
The unique ID is validated
Title.__init__ rejects a falsy id_, and rejects any ID shorter than 4 characters (\"The unique ID is not large enough, clash likely.\"). Pick a stable, sufficiently unique identifier from the platform.
"},{"location":"dev/service-architecture/#constructors-at-a-glance","title":"Constructors at a glance","text":"Each subclass adds its own required fields on top of id_ and service:
MovieEpisodeSong Movie(id_, service, name, year=None, language=None, data=None, description=None)\n
You must give name. year is optional, but it must be a positive integer if you give it.
Episode(id_, service, title, season, number,\n name=None, year=None, language=None, data=None,\n description=None, air_date=None)\n
title is the show name. You must give season and number, and 0 is a valid value. unshackle converts an air_date to a date so the {date} naming token stays clean, and it discards a placeholder episode name like \"Episode 4\" automatically.
Song(id_, service, name, artist, album, track, disc=1, year=None,\n language=None, data=None, ...)\n
You must give name, artist, album, and track, and unshackle validates them. disc defaults to 1, and year is optional. A single therefore needs no disc, and an undated release needs no year.
A Song also takes optional metadata keywords that the tagger and the naming templates read: album_artist, release_type, total_tracks, total_discs, genre, explicit, isrc, upc, copyright, label, lyrics, and artwork_url. Read the class for the current list.
The tagger also falls back to Song.data 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 metadata sub-dict, with the nested keys winning, so either shape works.
From get_tracks(), a music service gives one Audio track for each codec and bitrate it offers for a Song. The framework then selects one with its usual audio options, -a/--acodec and --abitrate, and its usual audio sorting. A movie or an episode uses the same options. -q/--quality sets the video height only and does not apply to music. Audio has no bit_depth or sample_rate field. Therefore bitrate separates a hi-res FLAC from a CD FLAC, and the audio sort already ranks it.
A Song is an ordinary Title on the one generic download path. unshackle has no music-specific service API and no separate music download loop. The GROUP_AUDIO_DOWNLOADS flag, get_music_track_options and get_music_collection_label no longer exist, and a music service does not need them.
Restore the container in on_track_downloaded
Every track downloads to a temp file named Audio_<id>.mp4 whatever it holds, and the final move keeps that suffix. A Song 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 on_track_downloaded, or a FLAC lands as an untaggable .mp4. The event fires twice, once before decryption and once at the end, so wait until track.drm is clear before you rename.
The MUSIC_EXAMPLE reference service, at unshackle/services/MUSIC_EXAMPLE/, shows the full music surface.
"},{"location":"dev/service-architecture/#title-remapping","title":"Title remapping","text":"After the service fetches the titles (and after any cache), the framework applies remap_titles(titles, title_map) with the per-service title_map config. This does an exact-string rename (it compares Episodes on their show title, and Movies and Songs on their name), so you can change a platform's odd naming to what your library expects. get_titles_cached() also cache-wraps the titles, and it is region- and account-aware. See the TitleCacher notes.
The ordering here is deliberate on both sides. The framework applies title_map after the title cache so that editing the map takes effect immediately, without forcing a cache reset, and before metadata enrichment (--enrich) so that an explicit enrich override still wins over a mapped name.
"},{"location":"dev/service-architecture/#tracks-and-the-track-model","title":"Tracks and the Track model","text":"A Tracks object is the container get_tracks returns. It has typed buckets (videos, audio, subtitles, chapters, and attachments) plus a manifest_url. Iterating a Tracks 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.
Track IDs must be deterministic
Tracks.add 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 add will raise.
"},{"location":"dev/service-architecture/#the-base-track","title":"The base Track","text":"Track is the base for Video, Audio, and Subtitle. (Chapter, Chapters, and Attachment are standalone classes, not Track subclasses.) Every track records its delivery method in Track.Descriptor, which tells unshackle how to download it:
Descriptor Delivery URL A single direct URL. HLS HTTP Live Streaming. DASH Dynamic Adaptive Streaming over HTTP. ISM Smooth Streaming. The main attributes include url (a string or list of strings), language (a langcodes.Language), drm (an optional iterable of DRM objects), needs_repack, and descriptor-specific state stashed in track.data[\"hls\"] / track.data[\"dash\"]. If you do not give a name, unshackle derives a human-readable name from the language.
"},{"location":"dev/service-architecture/#video","title":"Video","text":"Video adds codec, range, bitrate, width, height, fps, scan_type, and closed-caption descriptors. The relevant enums:
Video.Codec: AVC (H.264), HEVC (H.265), VC1, VP8, VP9, AV1. Video.Range: SDR, HLG, HDR10, HDR10P (HDR10+), DV (Dolby Vision), and HYBRID. HYBRID 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 dovi_tool (see Dolby Vision hybrid).
Bitrate units
Both Video and Audio store bitrate in bits per second (rounded up). The string form displays kb/s, and --vbitrate and --abitrate compare in kb/s.
"},{"location":"dev/service-architecture/#audio","title":"Audio","text":"Audio adds bitrate, channels, joc (Joint Object Coding, the Atmos indicator), and descriptive. Audio.Codec covers AAC, AC3 (DD), EC3 (DD+), AC4, OPUS, OGG (Vorbis), DTS, DTSX, ALAC, and FLAC. The atmos property is True when joc is set (or when extra flags it).
"},{"location":"dev/service-architecture/#subtitle","title":"Subtitle","text":"Subtitle adds three mutually-constrained flags: cc (closed captions), sdh (subtitles for the deaf and hard-of-hearing), and forced. A track cannot be both cc and sdh, and forced cannot combine with either. Subtitle.Codec includes SubRip (SRT), WebVTT (VTT), SubStationAlpha/SubStationAlphav4 (SSA/ASS), TimedTextMarkupLang (TTML), SAMI, and the box-encapsulated DASH formats fTTML (STPP) and fVTT (WVTT). Subtitles receive post-download normalization (segment merging, WebVTT sanitization, format conversion, and optional SDH stripping), all documented for users in Subtitles.
"},{"location":"dev/service-architecture/#chapters-and-attachments","title":"Chapters and attachments","text":" Chapter(timestamp, name=None): a single marker. The timestamp accepts HH:MM:SS[.mmm], integer milliseconds, or float seconds. Chapters: a sorted collection that auto-inserts a 00:00:00.000 chapter and reads/writes OGM Simple format. Attachment: a font or image attached to the mux (for example, fonts an ASS subtitle references), built from a local path or a url.
"},{"location":"dev/service-architecture/#selection-sorting-and-muxing","title":"Selection, sorting, and muxing","text":"Tracks is also the selection engine the dl command uses. It offers sort_videos / sort_audio / sort_subtitles (P2P-standard ordering), predicate-based select_* filters, by_resolutions, and by_language. When downloads finish, the same object multiplexes everything: Tracks.mux(title, ...) builds and runs an mkvmerge command, applying language, default-track, forced, and hearing-impaired flags, attaching chapters and fonts, and writing a .muxed.mkv (or .mka / .mks for audio- or subtitle-only sets). As a service author you never call mux yourself. You only return correct tracks.
"},{"location":"dev/service-architecture/#manifest-parsers","title":"Manifest parsers","text":"Most services do not assemble tracks by hand. They give a manifest to one of three parsers in unshackle.core.manifests. Each parser has the same three-part contract:
Format Class Notes MPEG-DASH (.mpd) DASH Parses <MPD>; enumerates tracks from the first content period. HLS (.m3u8) HLS Requires a variant (master) playlist, not a media playlist. Smooth Streaming (.ism) ISM Synthesizes init segments from CodecPrivateData."},{"location":"dev/service-architecture/#the-parser-contract","title":"The parser contract","text":" - Construct:
DASH.from_url(url, session=...) or DASH.from_text(text, url) (and likewise for HLS / ISM). Always pass a url, even to from_text, because the parser needs it to make relative segment paths absolute. to_tracks(...): parses the manifest into a Tracks container of Video, Audio, and Subtitle objects, each carrying descriptor-specific state. download_track(...): 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.
A typical get_tracks therefore looks like fetching the manifest text with self.session and returning DASH.from_text(mpd, url).to_tracks(language=title.language).
Pass the original language
DASH and HLS to_tracks raise ValueError if they cannot derive a track's language and you gave no valid fallback. Always pass the title's original recorded language. For HLS, to_tracks uses this fallback directly for the primary track, because HLS variants carry no language.
"},{"location":"dev/service-architecture/#segment-filtering-hooks","title":"Segment-filtering hooks","text":" - HLS: set
track.OnSegmentFilter(segment) to drop unwanted segments (ads/bumpers). A dropped segment is invisible to the whole download: unshackle ignores its EXT-X-KEY and its EXT-X-DISCONTINUITY, so a clear ad break inside an encrypted track does not disturb decryption. - DASH: pass a
period_filter callable to to_tracks to drop whole periods. unshackle automatically drops the caching-breadth periods that some services send, and the non-content segment types.
"},{"location":"dev/service-architecture/#format-gotchas-worth-knowing","title":"Format gotchas worth knowing","text":" - DASH enumerates tracks from only the first content period, but downloads segments from all content periods matching the representation. The parser reads
SegmentTemplate, SegmentList, and SegmentBase addressing, and $Number%0Nd$ padding. - HLS re-fetches the media playlist at download time, recovers
SUPPLEMENTAL-CODECS 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. - ISM has no list of segments and no init segments: the parser synthesizes segment URLs from the
<c> fragment timeline, and rebuilds a moov/ftyp init box from CodecPrivateData (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: Tracks.add no longer reads the second manifest's tracks as duplicates of the first.
"},{"location":"dev/service-architecture/#drm-hooks","title":"DRM hooks","text":"If a track carries DRM, the framework licenses and decrypts it, but it needs your service to talk to the platform's license server. unshackle recognizes five DRM systems:
DRM class System License flow Widevine Widevine CDM challenge \u2192 license server \u2192 content keys (.wvd device) PlayReady PlayReady CDM challenge (WRM header) \u2192 license server \u2192 content keys (.prd device) ClearKeyCENC W3C org.w3.clearkey over CENC JSON KID request \u2192 JWK set; no CDM ClearKey HLS AES-128 content key fetched directly from a URI; no CDM, no challenge MonaLisa Proprietary WASM DRM keys extracted locally; no license server ClearKey vs ClearKeyCENC
Despite the shared prefix these are entirely different systems. ClearKey is HLS AES-128, decrypted in-process. ClearKeyCENC is the W3C EME JWK flow over MPEG-CENC, decrypted with shaka-packager or mp4decrypt like Widevine.
"},{"location":"dev/service-architecture/#the-service-side-hooks","title":"The service-side hooks","text":"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:
Hook Return Purpose get_widevine_service_certificate(title, track, challenge) cert bytes Optional privacy-mode service certificate. get_widevine_license(title, track, challenge) license bytes POST the Widevine challenge to the license server, return the response. get_playready_license(title, track, challenge) license Same for PlayReady; defaults to delegating to Widevine. get_clearkey_license(title, track, challenge) dict / str / bytes / None For ClearKeyCENC; return None to let the framework POST to the manifest Laurl. You do not open CDM sessions or operate shaka-packager yourself. The Widevine/PlayReady classes drive the CDM handshake and call the decryption backend. Your hook is only the \"send this challenge, give me back the license\" step.
"},{"location":"dev/service-architecture/#how-unshackle-chooses-a-cdm-and-finds-keys","title":"How unshackle chooses a CDM and finds keys","text":"CDM selection is config-driven: the cdm map resolves a service tag (and optionally the track quality or DRM type) to a device name, which load_cdm instantiates as a local .wvd/.prd 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.
"},{"location":"dev/service-architecture/#dolby-vision-and-hybrid","title":"Dolby Vision and hybrid","text":"Two DV mechanisms sit on top of the track model. DV fixup re-exposes DV signalling on HLS streams that carry a valid DV RPU but advertise plain HEVC (dv_compatible_bitstream). Hybrid processing (Video.Range.HYBRID) selects an HDR10(+) base and a DV donor, extracts the RPU with dovi_tool, 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.
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.
"},{"location":"dev/service-architecture/#request-and-http-session-objects","title":"Request and HTTP session objects","text":"Everything a service does over the network flows through objects the base constructor prepared, all derived from the Click context (ctx) that dl passes in.
self.config: your service's slice of unshackle.yaml, i.e. config.services[<ServiceName>]. This is a plain dict. Use it for per-service settings like base URLs, an API key, or a title_map. See Configuration. self.session: a requests.Session with config.headers applied, a retry policy (total=5, 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 session() factory uses and that the network config key configures.) self.credential: the active Credential (username:password[:extra]), populated by authenticate. unshackle uses its sha1 as the account hash for cache keys. self.cache: a generic Cacher: JSON key/value storage under the service's cache dir, with CRC32 integrity checks, versioning, and optional expiry (auto-derived from a JWT exp claim when present). Good for auth tokens and API responses. self.title_cache: a TitleCacher that wraps get_titles results, keyed by title ID, region, and account hash. It serves fresh data within title_cache_time, falls back to stale data within title_cache_max_retention when an API call fails, and --no-cache bypasses it. self.track_request: the TrackRequest describing what the user asked for (codecs, ranges, best-available), for use inside get_tracks.
A minimal service skeleton
services/EXMP/__init__.pyfrom 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) -> 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) -> \"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
The directory name (EXMP) must match the class name exactly. That stem is the service tag. Put your service in one of the directories.services paths.
"},{"location":"dev/service-architecture/#where-to-go-next","title":"Where to go next","text":" - Creating a Service: a guided walkthrough that builds on this model.
- Service API: exact signatures for the
Service base class. - Titles API and Tracks API: the full object reference.
- DRM API: the DRM and CDM classes in detail.
- Downloading: how the flags a user passes map onto track selection.
"},{"location":"dev/rest-api/","title":"REST API Overview","text":"unshackle ships with a built-in HTTP server. Alongside the command-line tool, you can operate unshackle serve 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.
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.
Who this section is for
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.
"},{"location":"dev/rest-api/#what-the-api-is-for","title":"What the API is for","text":"The server exposes the same capabilities as the dl command, but as discrete HTTP calls you can script against:
- Discovery: show the services available on the server, use a service's search, and enumerate the titles and tracks behind a title ID.
- 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.
- 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.
- 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.
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.
"},{"location":"dev/rest-api/#running-the-server","title":"Running the server","text":"Start the server with the serve command:
Start the REST API on the default host and portunshackle serve\n
By default the server binds to 127.0.0.1:8786 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.
An API key is required by default
Unless you pass --no-key, the server needs an API secret configured under the serve section of your config. If none is set, unshackle serve refuses to start. See Authentication for how to set api_secret and how the X-Secret-Key header works.
"},{"location":"dev/rest-api/#common-options","title":"Common options","text":"The serve command accepts the following flags:
Option Default Effect -h, --host 127.0.0.1 Address to bind to. Use 0.0.0.0 to accept connections from other machines. -p, --port 8786 Port to bind to. --api-only off Serve only the REST API, without the Widevine/PlayReady CDM HTTP endpoints. --cdm-only off Serve only the Widevine/PlayReady CDM HTTP endpoints, plus /api/health and the dashboard. No REST API, no remote sessions, no Swagger UI. Cannot be combined with --api-only or --remote-only. --no-widevine off Disable the Widevine CDM endpoints. Cannot be combined with --api-only. --no-playready off Disable the PlayReady CDM endpoints. Cannot be combined with --api-only. --no-key off Disable API-key authentication entirely; every request is allowed. --remote-only off Expose only the remote-session subset of routes. Implies --api-only. --debug-api off Include tracebacks and worker stderr in error responses. --debug off Enable debug-level logging. --caddy off Also launch Caddy as a reverse proxy, using the Caddyfile in your user-config directory. Serve the REST API only, on all interfacesunshackle serve --api-only --host 0.0.0.0 --port 8786\n
Binding to a public interface
--no-key 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 127.0.0.1, or keep the default key-based auth when binding to 0.0.0.0. Put a TLS-terminating reverse proxy (Caddy, nginx) in front for anything internet-facing.
"},{"location":"dev/rest-api/#server-modes","title":"Server modes","text":"The routes the server mounts depend on how you start the server:
Default (CDM + REST)--api-only--remote-only--cdm-only The server mounts both the pywidevine/pyplayready CDM endpoints and the full REST API. This is the mode you get when you operate unshackle serve with no mode flags.
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 --no-key).
The server mounts only the remote-session subset of routes (health, services, search, and everything under /api/session/*). This mode implies --api-only, and the interactive Swagger UI is not mounted.
The server mounts only the pywidevine and pyplayready CDM endpoints. Under /api/ it answers /api/health and, when serve.dashboard.key 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.
"},{"location":"dev/rest-api/#base-url","title":"Base URL","text":"All REST endpoints live under the /api prefix. With the default bind address the base URL is:
http://127.0.0.1:8786/api\n
Every path in this documentation is relative to the host and port. For example, the health check is GET http://127.0.0.1:8786/api/health.
Interactive API docs
Unless you started the server with --remote-only, an interactive Swagger UI is available at /api/docs/. The server generates it from the same route table it serves, so it always matches the version you operate. Note that in --api-only mode the docs page is itself behind the API key. Only /api/health is exempt from authentication.
A quick smoke test that needs no API key:
Confirm the server is upcurl http://127.0.0.1:8786/api/health\n
Response{\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
"},{"location":"dev/rest-api/#endpoint-map","title":"Endpoint map","text":"Every REST path uses JSON request and response bodies and lives under /api. The table below is a map of the surface. The Endpoints page gives each request and response in full.
"},{"location":"dev/rest-api/#discovery","title":"Discovery","text":"Method Path Purpose GET /api/health Liveness and version check. Never requires an API key. GET /api/services List the services available on this server. POST /api/search Run a service's search for a query. POST /api/list-titles List the titles behind a service title ID. POST /api/list-tracks 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 POST /api/download Queue a download; returns a job_id. GET /api/download/jobs List jobs, with filtering and sorting. POST /api/download/jobs/clear-finished Remove all finished jobs. GET /api/download/jobs/{job_id} Full detail for one job. GET /api/download/jobs/{job_id}/events Stream one job's progress as Server-Sent Events. DELETE /api/download/jobs/{job_id} Cancel a running job, or remove a finished one. POST /api/download/jobs/{job_id}/retry Re-queue a finished job's parameters as a new job. POST /api/download/jobs/{job_id}/priority Move a queued job to the front. POST /api/download/jobs/{job_id}/input 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 GET /api/history Read the persisted log of finished jobs. DELETE /api/history/{job_id} Delete a history entry. GET /api/profiles Named credential profiles per service. GET /api/config The server's effective, redacted configuration. GET /api/env/check Presence and versions of external tools."},{"location":"dev/rest-api/#maintenance","title":"Maintenance","text":"Method Path Purpose POST /api/maintenance/clear-cache Clear the cache directory. POST /api/maintenance/clear-temp Clear the temp directory. POST /api/maintenance/refresh-services git pull 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 POST /api/session/create Start a server-side, authenticated service session. GET /api/session/{session_id} Remote session info and time-to-live. DELETE /api/session/{session_id} Tear down a session. GET /api/session/{session_id}/titles Titles for the session's title ID. POST /api/session/{session_id}/tracks Tracks (with URLs) for a chosen title. POST /api/session/{session_id}/segments Per-track segment/download details. POST /api/session/{session_id}/segment_filter Server-side HLS segment filter results for one track. POST /api/session/{session_id}/license Proxy or server-side DRM licensing. POST /api/session/{session_id}/keys/bad Report a server-vault content key that did not decrypt. GET /api/session/{session_id}/logs Drain the service's server-side log output. GET /api/session/{session_id}/prompt Poll for interactive auth status/prompt. POST /api/session/{session_id}/prompt Submit an answer to an auth prompt. Remote-only routes
The health, services, search, and /api/session/* routes are the ones exposed when the server runs with --remote-only. Everything else (downloads, jobs, history, config, maintenance) is only available in the full or --api-only modes.
"},{"location":"dev/rest-api/#authentication-in-one-line","title":"Authentication in one line","text":"With the default configuration, send your API secret in the X-Secret-Key header on every request except /api/health:
An authenticated requestcurl -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
A missing or unknown API key returns 401. Authentication gives the full model, including per-key service allowlists.
"},{"location":"dev/rest-api/#where-to-go-next","title":"Where to go next","text":" - Quick Start: start the server, set an API key, and operate your first end-to-end download over the API.
- Authentication: the
X-Secret-Key header, --no-key, per-key service allowlists, and CORS. - Endpoints: every request body, query parameter, and response shape, endpoint by endpoint.
- Job Lifecycle: how a download moves from
queued to a terminal state, live progress, cancellation, and retries. - Remote Sessions: the
/api/session/* flow for driving a service from a thin remote client. - Error Responses: the standard error envelope, error codes, and their HTTP statuses.
"},{"location":"dev/rest-api/authentication/","title":"REST API Authentication","text":"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.
You start the API with the unshackle serve command. Authentication is on by default: if you start the server without an API key configured, it refuses to launch.
Which server am I running?
unshackle serve can operate in two shapes, and each uses a slightly different piece of code to examine your API key:
- The integrated server (the default) exposes the REST API and the pywidevine / pyplayready CDM HTTP endpoints.
- The API-only server (
--api-only, also implied by --remote-only) exposes only the REST API.
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.
"},{"location":"dev/rest-api/authentication/#the-short-version","title":"The short version","text":" - Add an
api_secret to the serve section of your unshackle.yaml. - Start the server with
unshackle serve. - Send that secret in the
X-Secret-Key header on every request except GET /api/health.
A minimal authenticated requestcurl -H \"X-Secret-Key: your-secret-key-here\" \\\n http://127.0.0.1:8786/api/services\n
"},{"location":"dev/rest-api/authentication/#configuring-authentication","title":"Configuring authentication","text":"All authentication settings live under the serve section of your unshackle config file (unshackle.yaml).
"},{"location":"dev/rest-api/authentication/#a-single-api-key","title":"A single API key","text":"The simplest setup defines one shared secret with api_secret:
unshackle.yamlserve:\n api_secret: \"a-long-random-secret-string\"\n
This value becomes the one and only API key that the server accepts. The server allows requests that present it in the X-Secret-Key header. The server rejects everything else.
The server will not start without a key
If you start unshackle serve with no api_secret configured, and you have not passed --no-key, the command fails immediately with:
API secret key is not configured. Please add 'api_secret' to the 'serve' section in your config.\n
Choose a long, unpredictable value. The API key is the only thing standing between the internet and your CDM and download endpoints.
"},{"location":"dev/rest-api/authentication/#multiple-keys-with-users","title":"Multiple keys with users","text":"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:
unshackle.yamlserve:\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
The config key of each entry under users (for example a-secret-key-for-alice) is the secret that client sends in X-Secret-Key. The username is a human-readable label used in logs and in job/history metadata.
How api_secret and users combine (integrated server)
On the integrated server, the server automatically adds the configured api_secret as an extra accepted API key alongside everyone in users. It gives that API key access to all loaded Widevine and PlayReady devices, and labels it api_user. So api_secret behaves as an admin-level API key in addition to any named users you define.
On the API-only server, the server accepts only api_secret: the single-key model. (See the developer notes for the exact difference.)
"},{"location":"dev/rest-api/authentication/#cdm-device-access-per-api-key","title":"CDM device access per API key","text":"Under the integrated server, an API key can do DRM licensing only through a CDM device that its user entry lists:
Config key Grants access to devices Widevine .wvd devices, by name playready_devices PlayReady .prd devices, by name PlayReady access is opt-in per user
If a user entry omits playready_devices, 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.
Grants decide whether the server returns content keys
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 (KID:KEY) for a remote session. server_cdm lets the server license with those devices. server_vault 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 serve for both grants.
"},{"location":"dev/rest-api/authentication/#disabling-authentication","title":"Disabling authentication","text":"The --no-key flag turns authentication off entirely. The server allows every request, ignores X-Secret-Key, and needs no API key in your configuration.
unshackle serve --no-key\n
Only use --no-key on a trusted, isolated network
With --no-key, any client that can reach the port can show your services, start downloads, and use your CDM devices. Never put a --no-key server on an untrusted network.
"},{"location":"dev/rest-api/authentication/#how-clients-present-credentials","title":"How clients present credentials","text":"Clients authenticate by sending the secret in a single HTTP request header on every call:
X-Secret-Key: <your-secret>\n
The value must match one of the configured API keys exactly (api_secret, or one of the keys under users). 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.
One route also accepts the key as a query parameter
The job event stream, GET /api/download/jobs/{job_id}/events, also accepts the API key in a secret_key query parameter. This is for browsers: the EventSource API cannot set request headers. The exception applies to that one route only, and it works in both server modes.
new EventSource(`http://127.0.0.1:8786/api/download/jobs/${jobId}/events?secret_key=${key}`);\n
The header always wins. If the request has an X-Secret-Key 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.
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.
curlPython (requests)JavaScript (fetch) curl -H \"X-Secret-Key: your-secret-key-here\" \\\n http://127.0.0.1:8786/api/services\n
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
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
The reference client sets it for you
unshackle's own remote download client (RemoteService) sends X-Secret-Key automatically, reading the API key from your remote_services config. It also sends a User-Agent of unshackle/<version>. You only deal with the header directly when writing your own client.
"},{"location":"dev/rest-api/authentication/#the-health-check-is-always-open","title":"The health check is always open","text":"One endpoint is exempt from authentication: GET /api/health. It never requires an API key, so you can use it for liveness and version probes without embedding a secret in your monitoring:
No key neededcurl http://127.0.0.1:8786/api/health\n
Response{\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
Every other endpoint (including the Swagger UI at /api/docs/ on the API-only server) requires a valid API key.
"},{"location":"dev/rest-api/authentication/#authentication-failures","title":"Authentication failures","text":"When the server rejects a request for authentication reasons, the response has an HTTP 401 Unauthorized status and a small JSON body.
Missing headerWrong key Sending a request with no X-Secret-Key header:
{\n \"status\": 401,\n \"message\": \"Secret Key is Empty.\"\n}\n
Sending an API key that is not in your config:
{\n \"status\": 401,\n \"message\": \"Secret Key is Invalid.\"\n}\n
Auth errors use a different JSON shape than other errors (developer note)
The rest of the API reports errors with a structured body containing error_code, message, timestamp, and other fields (see Errors). The authentication middleware is different: it returns {\"status\": 401, \"message\": \"...\"}, where status is an integer, and there is no error_code or timestamp.
In your client, treat any 401 as an authentication problem and parse both shapes, because the standard error body is not always present.
"},{"location":"dev/rest-api/authentication/#rate-limit-rejections","title":"Rate limit rejections","text":"An API key that carries a rate limit gets 429 Too Many Requests once it goes over, from the same middleware and in the same shape as the 401 bodies above, with a Retry-After header in seconds:
{\n \"status\": 429,\n \"message\": \"Rate limit exceeded.\"\n}\n
A limit comes from serve.tiers.<name>.rate_limit or from the API key's own serve.users.<key>.rate_limit, in requests per hour. An API key with neither has no limit, and GET /api/health is never limited. See dashboard rate limits for the config and the counters, and services configuration for the keys themselves.
429 is not the RATE_LIMITED error body
RATE_LIMITED in Errors is a service rate limit that a handler raises, and it arrives in the standard envelope with an error_code. The 429 here comes from the middleware before any handler runs, and has the integer-status shape shown above. A client that reads error_code to classify a 429 must cope with it being absent.
"},{"location":"dev/rest-api/authentication/#access-controls-on-top-of-the-api-key","title":"Access controls on top of the API key","text":"After the server authenticates a request, several additional controls decide what that specific API key can do.
"},{"location":"dev/rest-api/authentication/#per-key-service-allowlists","title":"Per-key service allowlists","text":"You can restrict which services an API key may use. Two layers combine:
- Global allowlist:
serve.services, applied to every API key. - Per-key allowlist:
services inside that key's users entry.
The effective allowlist for a request is:
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 servicesserve:\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
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.
"},{"location":"dev/rest-api/authentication/#cdm-overrides-and-per-job-credentials","title":"CDM overrides and per-job credentials","text":"The server config gates two download-time capabilities. Unless you enable them, the server refuses them with 403 Forbidden, even for an authenticated API key:
Config key Default Controls serve.cdm_overrides off Whether a request may pick a specific CDM device via the cdm field. Set to true to allow any, or to a list/set of device names to allow only those. serve.allow_job_credentials off Whether a request may pass its own credential / credentials login details for a download job. Opting in to per-request CDM and credentialsserve:\n api_secret: \"admin-key\"\n cdm_overrides: [\"my_widevine_device\"] # or true to allow any configured device\n allow_job_credentials: true\n
When to enable these gates
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 403, 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.
Client-supplied credentials get isolated token caches
When you enable allow_job_credentials and a download job supplies its own credential / credentials, 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.
See Downloads for how the download endpoint uses these fields.
"},{"location":"dev/rest-api/authentication/#session-ip-binding-remote-sessions","title":"Session IP binding (remote sessions)","text":"The remote-download session endpoints (/api/session/*) 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 403 Forbidden. Thus the server binds a remote session both to the API key that created it and to the address it came from.
"},{"location":"dev/rest-api/authentication/#transport-security-https","title":"Transport security (HTTPS)","text":"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 serve command can launch Caddy for you:
unshackle serve --caddy\n
With --caddy, unshackle also starts caddy run using the Caddyfile 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 Caddyfile.
"},{"location":"dev/rest-api/authentication/#quick-reference","title":"Quick reference","text":"Item Value Auth header X-Secret-Key Query-parameter alternative ?secret_key= on GET /api/download/jobs/{job_id}/events only Default bind address 127.0.0.1:8786 Exempt endpoint GET /api/health Failure status 401 Unauthorized, or 429 Too Many Requests for a key over its rate limit Missing-header body {\"status\": 401, \"message\": \"Secret Key is Empty.\"} Invalid-key body {\"status\": 401, \"message\": \"Secret Key is Invalid.\"} Over-limit body {\"status\": 429, \"message\": \"Rate limit exceeded.\"}, plus a Retry-After header Rate limit config serve.tiers.<name>.rate_limit, overridden by serve.users.<key>.rate_limit Disable auth --no-key (all requests allowed) Config location serve.api_secret and serve.users in unshackle.yaml"},{"location":"dev/rest-api/authentication/#developer-notes-how-the-server-does-the-check","title":"Developer notes: how the server does the check","text":"This section is for people writing or debugging the server, not for API consumers.
"},{"location":"dev/rest-api/authentication/#two-middlewares-one-header","title":"Two middlewares, one header","text":"The header and config are identical between modes, but the code that enforces them differs:
-
API-only server (--api-only, or --remote-only which forces API-only). An api_key_authentication middleware runs on every request. It lets GET /api/health through unconditionally, then reads X-Secret-Key. 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 api_secret (labelled api_user, with no devices) plus every key under serve.users. A per-user key therefore authenticates here exactly as it does on the integrated server, and that user's services allowlist applies as usual. With --no-key, this middleware is not installed and the users map is empty.
-
Integrated server (default). A serve_authentication middleware wraps pywidevine's authentication (and pyplayready's for /playready* paths), and the REST routes live in the same application, guarded by the same check. Here the accepted-keys map is your full serve config: api_secret (auto-added with access to all loaded devices) plus every entry under users, each with its declared devices / playready_devices.
Because the API-only middleware guards all non-health paths, the Swagger UI at /api/docs/ is also behind X-Secret-Key there. In --remote-only mode the Swagger UI is not mounted at all.
Both middlewares read the caller's API key through the shared request_secret_key() helper in unshackle/core/api/handlers.py. That helper returns the X-Secret-Key header, and falls back to the secret_key query parameter only when the matched route is the job event stream. The integrated server needs one extra branch for this. pywidevine's authentication is header-only. So serve_authentication 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.
"},{"location":"dev/rest-api/authentication/#cors-and-the-authorization-header","title":"CORS and the Authorization header","text":"A cors_middleware runs on every response in both modes (and answers OPTIONS preflight requests with an empty response). It emits:
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
The REST API authenticates with X-Secret-Key. The middleware advertises Authorization because the co-hosted pywidevine / pyplayready CDM endpoints use it. PUT appears in the allowed-methods list, but no REST route uses it. Only GET, POST, and DELETE have routes.
"},{"location":"dev/rest-api/authentication/#where-device-access-is-read","title":"Where device access is read","text":"The map of accepted API keys lives at request.app[\"config\"][\"users\"]. For DRM operations, an API key's permitted Widevine devices come from its devices list, and PlayReady devices from playready_devices. The server uses the first configured device when a request does not (or may not) override it. A server-wide config.cdm[<service>] mapping, if present, takes precedence over the API key's device list when the server chooses which device to use.
"},{"location":"dev/rest-api/dashboard/","title":"Developer Dashboard","text":"The dashboard endpoints show the operator of a serve 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 (serve --quiet) from a web page instead of a terminal.
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.
"},{"location":"dev/rest-api/dashboard/#enable","title":"Enable","text":"Set a dashboard key under serve.dashboard in unshackle.yaml:
serve:\n api_secret: ...\n dashboard:\n key: a-long-random-string\n
Without dashboard.key the server does not register the routes, and they answer 404. serve --no-key turns off user authentication only; the dashboard key stays required. Once the dashboard key is set, every /api/dashboard/ request must carry it in X-Secret-Key. Every other endpoint refuses the dashboard key, and the dashboard refuses user keys. The routes are available in --remote-only mode too.
Run the server headless with --quiet: no banner, no Rich output, one plain log line per event on stderr, and api.* loggers stay at INFO so remote session activity reaches the log ring. Add --debug to raise the level to DEBUG and also write the full log to directories.logs as unshackle_serve_<time>.log. 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.
unshackle serve --remote-only --quiet\n
"},{"location":"dev/rest-api/dashboard/#endpoints","title":"Endpoints","text":"All are GET.
Path Returns /api/dashboard/status Version, code_hash, bind host and port, mode (full, api_only, remote_only), uptime, requests_total, requests_rejected (401s), requests_by_key (label \u2192 count), configured service count (the same services as /api/dashboard/services), session count, max_sessions (null when the operator configured no limit), session_ttl, job counts by status. The service count includes services that failed to import - use /api/dashboard/services for the number that loaded. /api/dashboard/sessions Every live remote session: id, owner (username or masked key), creator_ip, service, title_id, titles, tracks, title (the display name of the title the client is on: the last one it asked tracks for, else the first resolved title), auth_status, auth_error, server_account (the server profile lent to the remote session, else null), server_cdm (false when the client's own device licenses the remote session), server_cdm_max_height (the tallest video the server CDM licenses live, else null), client, actions, created_at and last_accessed (ISO 8601) with created_ts and last_accessed_ts (Unix epoch, the same clock as log ts), age_seconds, idle_seconds, log_seq. client is whatever the remote client sent as client in its session create request. The CLI sends version, code_hash (the commit the client runs, null when its source cannot be read), platform and argv. argv is the command line the user ran: proxy and URL userinfo, secret query parameters and credential values become ***, 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 {}. log_seq is the last sequence number in the remote session's service log - poll /api/dashboard/sessions/{id}/logs when it changes. actions is the session's request log, newest last, capped at 500: ts, method, action (titles, tracks, segments, license, prompt, \u2026), query, status, ms, bytes_in, bytes_out. /api/dashboard/jobs Every download job with full detail, regardless of owner. Empty in --remote-only mode. /api/dashboard/logs {\"seq\": N, \"records\": [...]}: the last 1000 log records. ?since=<seq> returns only newer records; ?level=WARNING sets the minimum level; ?logger=serve keeps one logger and its children (aiohttp.access is the noisiest). ts is a Unix epoch in seconds. /api/dashboard/cdm-logs {\"seq\": N, \"records\": [...], \"sessions\": [...]}: the last 5000 calls to the Widevine and PlayReady CDM device routes, and the open sessions of each device. ?since=<seq> returns only newer records. See CDM calls. /api/dashboard/sessions/{id}/logs One remote session's service log: {\"session_id\", \"last_seq\", \"records\": [...]}. Each record has seq, ts, level, message. ?since=<seq> returns only newer records. 404 when the remote session is unknown. /api/dashboard/keys Every configured API key: what it may do and what it has done. One row per key in serve.users, plus serve.api_secret when it is set. /api/dashboard/services Every service configured on this server and its load state, including the ones that failed to import. See Services for what configured means. /api/dashboard/health Preflight: whether this instance could finish a download. Cached 30 seconds. /api/dashboard/events Server-Sent Events stream. With ?since=<seq> it returns {\"seq\", \"stats\", \"events\": [...]} instead: every event after seq (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. requests_rejected counts 401 responses; those never appear in requests_by_key. The label is the username from the users entry when one is set, else the first four characters of the API key.
"},{"location":"dev/rest-api/dashboard/#event-stream","title":"Event stream","text":"/api/dashboard/events sends a stats event (the same body as /status) on connect and then every 5 seconds, so the connection stays alive and the counters stay current. Between those it sends:
Event Data log One log record: seq, ts, level, logger, msg. session action (create, update on every request the session makes and when titles or tracks load, or delete) plus the full remote session summary, so each event is a complete snapshot. A delete also carries reason: closed (the client ended it), expired (TTL sweep) or evicted (max_sessions reached). A session opened by --skip-dl can live only a few seconds, so a UI that wants history must keep its own record of these events. job event (queued, progress, status, or the terminal status) plus the full job object. service action (staged, applied or failed) and tags, the services it applies to. A failed action carries errors and an empty tags. Refetch /api/dashboard/services when one arrives, instead of polling for a reload. Every frame carries an id: (the event seq). After a dropped connection an EventSource reconnects with Last-Event-ID and the server replays the events it missed. The connection never closes on its own.
A browser EventSource cannot set headers, so this route also accepts the dashboard key as ?secret_key=. The dashboard key then appears in proxy and access logs and in browser history, so use the query parameter only for /events and send the header everywhere else.
const es = new EventSource(`${server}/api/dashboard/events?secret_key=${key}`);\nes.addEventListener(\"log\", (e) => console.log(JSON.parse(e.data).msg));\n
CORS is open (Access-Control-Allow-Origin: *), so a dashboard page served from another origin works without a proxy.
"},{"location":"dev/rest-api/dashboard/#remote-session-logs","title":"Remote session logs","text":"A remote session mirrors the service's own self.log into a 500-record buffer at INFO, whatever level the server prints at. The remote session summary carries only a truncated auth_error; the buffer holds the real reason a login failed.
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
The field name is records, the same one /api/dashboard/logs uses, so one dashboard reads both logs the same way. Each record has the shape the client route /api/session/{id}/logs returns. last_seq is the buffer's own last sequence number, so an empty page still reports the true value.
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.
log_seq is a poll trigger, not a push
A remote session summary reaches the dashboard only when something publishes a session event - a request the remote session makes, or an auth transition. A log line on its own publishes nothing. Poll this route when log_seq changes, and on a timer while a drawer is open.
"},{"location":"dev/rest-api/dashboard/#cdm-calls","title":"CDM calls","text":"A server in full mode also mounts the Widevine CDM device routes at /{device}/... and the PlayReady ones at /playready/{device}/.... The server records each call to these routes in a 5000-record buffer of its own, apart from the log records of /api/dashboard/logs.
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
since and seq work as they do for /api/dashboard/logs: records holds the calls with a seq above since, oldest first. seq starts again at 1 when the server restarts, so a seq below your cursor means a restart: read again from 0.
Field Meaning ts Unix epoch in seconds, when the call arrived. drm widevine, or playready for a route below /playready/. op open, close, set_service_certificate, get_service_certificate, get_license_challenge, parse_license or get_keys. The licence type or content key type that follows in the path is not part of it. device The device name from the path, cut at 255 characters. key_id, user The id and label of the caller's row in /api/dashboard/keys. Both are anonymous when the API key is missing or unknown. session_id The CDM session, lowercase hexadecimal, so the calls of one licence exchange group together. null when there is none, for example a refused open. status, ok The HTTP status of the reply. ok is true below 400. error null when ok. Otherwise the message of the reply, cut at 300 characters. A handler that raised an error gives the error's class name only. ms Time the server took to answer, in milliseconds. A record never holds the API key, init_data, 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.
sessions 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: open is the number of sessions open now, and max 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 open. The list is [] until the first open, and on a server that mounts no CDM device routes.
Polled only
The event stream does not carry these records. One licence exchange is five calls, and that volume would push session events out of the stream's history.
"},{"location":"dev/rest-api/dashboard/#keys","title":"Keys","text":"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
id is a hash of the API key, so it stays stable across restarts and carries no key material. Two API keys with no username merge into one label in requests_by_key but stay separate here, so use id as the identity and label only for display.
Field Meaning role Which key this is: user (a serve.users entry), admin (serve.api_secret) or dashboard (serve.dashboard.key). Identity, not capability - read the grant fields for what the API key may do. services The effective allowlist, the global list intersected with the API key's. null means unrestricted; [] means the API key reaches no service route at all. server_cdm, server_accounts false, true, or the list of service tags the grant covers. server_cdm_max_height The configured limit on live server CDM licences: a height, a map of service tag to height, or null for no limit. server_proxy Boolean. Only a literal true grants it, and an API key with no users entry does not get it. rate_limit Requests per hour, from the API key's own value or its tier's. null means no limit. window_used Requests counted in the current hourly window. rejected Responses of 400 or worse that the server attributes to this API key, 429s included. The global requests_rejected stays 401-only. bytes_out Response bodies only. An event stream reports no body length, so it counts as zero. last_seen null until the API key makes its first request. Only a configured API key gets a row of counters. A request on an open route such as /api/health with an unknown key counts as anonymous, so an unauthenticated caller cannot grow the table.
Every API key the server counts has a row here, the dashboard key included, so a requests_by_key bucket other than anonymous always matches one. A \"traffic by key\" panel reads the rows here, which are unambiguous, and takes anonymous from requests_by_key. Read role before you draw the bars: the dashboard row is the panel measuring its own polling.
The dashboard key gets services: [] and no grants unless the operator also gave it a serve.users entry, because it reaches nothing outside /api/dashboard/. An API key listed in more than one place still gets exactly one row.
"},{"location":"dev/rest-api/dashboard/#rate-limits","title":"Rate limits","text":"An API key over its limit gets 429 with a Retry-After header:
serve:\n tiers:\n bot: { rate_limit: 600 } # requests per hour\n users:\n \"<api key>\":\n username: bot-relay\n tier: bot\n # rate_limit: 900 # optional, wins over the tier\n
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 tier that names no entry under serve.tiers, or a rate_limit 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 /api/health.
"},{"location":"dev/rest-api/dashboard/#services","title":"Services","text":"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
The list holds only the services configured on this server:
- The global
serve.services list, when it is set. - Else, the union of the
services lists of all keys in serve.users. - Else, every installed service.
The union does not show what every API key can reach
An API key with no services list can use every service, but it does not add to the union. The api_secret API key is the same. So with k1: {services: [A]} and a k2 with no list, the list shows only A. To list every service, remove the services lists or set serve.services.
GET /api/dashboard/services?all=1 lists every installed service. /status always counts only the configured services.
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.
state is loaded, staged or failed. A service that failed to import keeps its error here instead of disappearing, and /status still counts it in the service total - count the state values here for the number that loaded.
A staged service has an update on disk that a busy service blocks from the import: the repo pull already happened, so commit (what runs now) and staged_commit (what waits) differ. It swaps in when the last job and the last remote session for that tag finish. Both commits are null for a service from a plain local directory rather than a git repo.
Watch the service event rather than polling for the swap.
"},{"location":"dev/rest-api/dashboard/#health","title":"Health","text":"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
An instance can answer every request and still fail every download, because mp4decrypt is missing or a vault's credentials expired. This finds that before a job does.
status is ok, degraded (an optional dependency is missing) or failing (a required one is). Player binaries are not checked: a headless server never has one and it plays nothing. Each check is ok, warn or fail. Check ids are the binary names, cdm, vault:<name> (the vault's configured name, so two vaults of the same type stay apart), bad_keys and proxies. bad_keys warns when the vaults hold no SQLite 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.
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 detail 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.
An unreachable vault costs a slow, partial answer
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 probe check with the status fail 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.
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.
Proxy providers are only checked at construction
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 ok.
"},{"location":"dev/rest-api/dashboard/#counters-reset-on-restart","title":"Counters reset on restart","text":"Stats, the log ring and the event history are all in memory. A restart drops every number to zero. started_at in the stats frame (with version and code_hash) 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.
"},{"location":"dev/rest-api/endpoints/","title":"REST API Endpoints","text":"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.
Start the server with unshackle serve. By default it binds to 127.0.0.1:8786, and every route lives under the /api/ prefix. The Authentication page gives authentication, server modes, and the X-Secret-Key header in detail. Read that first if you have not already. For an end-to-end walkthrough, see the Quickstart.
Base URL
All examples below assume a base URL of http://127.0.0.1:8786. Replace the host and port so that they match your own unshackle serve -h <host> -p <port> invocation.
Interactive docs
The server mounts a live Swagger UI at /api/docs/ whenever it does not operate in --remote-only 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 X-Secret-Key. Only /api/health is exempt.
"},{"location":"dev/rest-api/endpoints/#conventions","title":"Conventions","text":" - Authentication. Every request except
GET /api/health requires the X-Secret-Key header when you configure an API key. --no-key disables the check entirely. See Authentication. - Content type. Request bodies are JSON (
Content-Type: application/json). All success responses are JSON unless this page documents a 204 No Content. - CORS. Every response carries permissive CORS headers, and the server answers
OPTIONS preflight requests automatically. - Compression. JSON responses of 256 bytes or more are gzip-compressed when the client sends
Accept-Encoding: gzip. A slow response is not compressed. - Service allowlist. The effective allowlist for your API key filters the service-facing endpoints (the intersection of the global
serve.services list and your per-key list). The server treats services you cannot use as unknown.
Error responses have two shapes
Structured application errors (raised inside a handler) return {\"status\": \"error\", \"error_code\": \"...\", \"message\": \"...\", \"timestamp\": \"...\"}. The authentication middleware, however, returns a different shape: {\"status\": 401, \"message\": \"...\"} with an integer status and no error_code. The same middleware answers 429 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.
"},{"location":"dev/rest-api/endpoints/#general-endpoints","title":"General endpoints","text":"These endpoints report server state and enumerate what is available. GET /api/health, GET /api/services, and POST /api/search are also exposed in --remote-only mode.
"},{"location":"dev/rest-api/endpoints/#get-apihealth","title":"GET /api/health","text":"Health check. This is the only route exempt from authentication: you can call it without an X-Secret-Key header. It reports the running version and a best-effort update check.
RequestResponse 200 curl http://127.0.0.1:8786/api/health\n
{\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_hash 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 unshackle/core, unshackle/commands, unshackle/utils, or unshackle/vaults. Service modules are not included. unshackle sets the value to null only when it cannot read the source files.
If the update check fails (for example, no network), update_available and latest_version are null while current_version still reports the installed version.
Status Meaning 200 Server is healthy."},{"location":"dev/rest-api/endpoints/#get-apiservices","title":"GET /api/services","text":"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). load_errors 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 pending_update has newer code staged: it keeps its current code until its running or queued jobs and its live remote sessions finish.
RequestResponse 200 curl -H \"X-Secret-Key: $KEY\" http://127.0.0.1:8786/api/services\n
{\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
Field notes:
Field Description tag Canonical service tag; use this as the service value on other endpoints. aliases Alternate tags the service also answers to. geofence Region codes the service is geofenced to (may be empty). geoblock Region codes where the service refuses to work (may be empty). title_regex URL/ID pattern the service matches, as a string or list of strings (or null). url Service URL, taken from the service's CLI short help. help The service module's docstring. cli_params Array of parameter descriptors. Arguments have {name, kind: \"argument\", required}; options have {name, kind: \"option\", opts, is_flag, default, help, type, multiple} and, for choice options, a choices list. needs_auth Whether the service overrides authenticate(). has_search Whether the service supports POST /api/search. anonymous_search Whether POST /api/search operates with no login for this service. The server then ignores credentials and cookies on a search. has_drm Whether the service overrides a Widevine or PlayReady license hook. pending_update Set to true while a service repository refresh waits for this service's jobs to finish before it swaps in the new code. Absent otherwise. server_accounts Present when the server lends its own accounts for this service: {regions: [\"ca\", \"gb\"], global: bool}, the regions those accounts cover. A client sends no credentials, cookies, or cache for such a service. auth_methods Declared or inferred auth methods, e.g. [\"cookies\"], [\"credentials\"]. Status Meaning 200 Service list returned. 500 Unexpected server error (INTERNAL_ERROR)."},{"location":"dev/rest-api/endpoints/#post-apisearch","title":"POST /api/search","text":"Find titles in a service by query string. The service must have a search() method (see has_search above).
For a service with anonymous_search, the server does not log in and ignores credentials and cookies. The server account check still applies.
Request body
Field Type Required Default Description service string yes - Service tag. query string yes - Search query. profile string no null Credential/cookie profile to use. proxy string no null Full proxy URI, a Control D resolver as controld://<resolver>@dns.controld.com, or a country code when the API key has server_proxy. no_proxy boolean no false Force-disable all proxy use. credentials, cookies, cache - no null Your own login material, on a --remote-only server only. See Client cache on a remote-only server. RequestResponse 200 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
{\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
Status Error code Meaning 200 - Search completed. 400 INVALID_PARAMETERS Missing query. 400 INVALID_SERVICE Unknown or disallowed service. 400 INVALID_PROXY Proxy could not be resolved. 502 SERVICE_ERROR Service failed to initialise, or does not support search."},{"location":"dev/rest-api/endpoints/#post-apilist-titles","title":"POST /api/list-titles","text":"Get the list of titles behind a title ID, for example episodes or a movie, without downloading anything.
Request body
Field Type Required Description service string yes Service tag. title_id string yes Title identifier. profile string no Credential/cookie profile. proxy string no Full proxy URI, a Control D resolver as controld://<resolver>@dns.controld.com, or a country code when the API key has server_proxy. no_proxy boolean no Force-disable proxy. cdm_type string no Preferred CDM type. credentials, cookies, cache - no Your own login material, on a --remote-only server only. See Client cache on a remote-only server. You can also pass service-specific CLI options as additional keys.
"},{"location":"dev/rest-api/endpoints/#logins-that-need-the-user","title":"Logins that need the user","text":"search, list-titles and list-tracks have no channel to the user. A login that asks for input or waits for an approval on another device fails at once with AUTH_FAILED on these endpoints. Complete that login in a download job or a remote session, then send the saved login with the request.
"},{"location":"dev/rest-api/endpoints/#client-cache-on-a-remote-only-server","title":"Client cache on a remote-only server","text":"A --remote-only server keeps nothing that a client sends. When the request does not use a server account, the server runs search, list-titles and list-tracks on a new service cache directory for that request only, and removes the directory when the request ends, on success and on error. A --remote-only server exposes only search of these three endpoints, so the rule applies to list-titles and list-tracks only if a later release exposes them in that mode.
credentials ({username, password, extra?}) and cookies (base64 of a zlib-compressed Netscape cookie file) are the same as on POST /api/session/create. cache is a map of cache files in the same form: each cache key is the file path relative to the service cache directory, with / separators and no .json 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.
When you send credentials, cookies or cache, a successful response also has a cache field in the same form, with the updated files (for example a refreshed token), but no titles_ 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 cache field.
RequestResponse 200 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
{\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
Each serialized title carries type (\"episode\", \"movie\", or \"other\"), name, id, language, description, date, and cover_url. Episodes and movies add year. Episodes also add series_title, season, and number.
A song serializes as \"other\"
A song has no type of its own. The server sends it as \"other\", and the response carries none of its music fields: no artist, no album, no track or disc number, and no year. name holds the song name. To read the disc and track numbers of a release, operate the CLI with --list-titles. You can still select songs over the API, through the wanted parameter.
These keys are sent only when the title carries them, so a title without them serializes exactly as before:
Key Type On Meaning part integer episode Part index of a split episode, counting from 1. air_date string episode ISO air date of daily and date-based content. unshackle names the episode by date instead of SxxExx. absolute integer episode Absolute episode number across all seasons. daily boolean episode The episode is daily/date-based. Set from the title, or from the service's DAILY class attribute. anime boolean episode, movie The title is anime, so metadata lookups prefer AniList. Set from the title, or from the service's ANIME class attribute. part on a split episode
A service that splits one episode into several separately playable videos reports each one as its own episode. Those titles share a season and number and add a part integer counting from 1. No other title carries the part field, so a client can ignore it safely. See Split episodes.
Status Error code Meaning 200 - Titles returned. 400 INVALID_INPUT Missing service or title_id. 400 INVALID_SERVICE Unknown or disallowed service. 401 AUTH_FAILED Authentication with the service failed. 404 NOT_FOUND Title not found. 500 INTERNAL_ERROR Unexpected error."},{"location":"dev/rest-api/endpoints/#post-apilist-tracks","title":"POST /api/list-tracks","text":"Show the video, audio, and subtitle tracks for a title. For series, you can scope to specific episodes.
Spotting the original-language audio
Each audio track carries is_original, which marks the track the default lang of orig 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 (pt marks pt-BR rather than pt-PT). Services need not report a title's language, so every track can legitimately come back false.
Request body
Field Type Required Description service string yes Service tag. title_id string yes Title identifier. wanted string / string[] no Episode/season range (e.g. \"S01E01-S01E03\"), or a song selector (e.g. \"1-5\", \"1,3,7\", or \"2x3\" for disc 2 track 3). A list of selectors is accepted too. season int/string no Season number (combined with episode). episode int/string no Episode number (combined with season). part int/string no Part index of a split episode (combined with season and episode). profile, proxy, no_proxy, cdm_type - no As on list-titles. credentials, cookies, cache - no As on list-titles. dl_params object no The dl track selection that the service reads from ctx.parent.params: lang, v_lang, a_lang, acodec, forced_subs and exact_lang, as on POST /api/session/create. Some services select the manifests they fetch from these values. When you give both season and episode, the server combines them into a \"{season}x{episode}\" selector. part narrows that to \"{season}x{episode}.{part}\", one part of a split episode. Without part you get every part of the episode. The server reads part only when you give both season and episode, and wanted takes precedence over all three. To scope a part by range, put it in wanted instead (\"S01E01.2\").
Single title / movie: Response 200Multiple episodes: Response 200 {\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, \"language\": \"en\", \"is_original_lang\": true,\n \"name\": null, \"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, \"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, \"needs_repack\": false, \"edition\": [], \"data\": null,\n \"drm\": [], \"descriptor\": \"DASH\" }\n ]\n}\n
{\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
The server sorts tracks by bitrate, descending. Episodes the server cannot get go into unavailable_episodes, rather than failing the whole request. Track objects here do not include a download url. Only the remote session endpoints give segment URLs.
The drm array on a track is a list of {type, pssh?, kids?, content_keys?, license_url?} objects.
Every track carries the same fields as a local track: is_original_lang, name, needs_repack, edition, and data. bitrate is in kb/s, and bitrate_bps gives the exact bits/s. data holds the part of the service-set track.data that fits in JSON, without the hls, dash, and ism parser keys. Audio keeps is_original and atmos for clients that read them, and adds the exact joc object count.
Status Error code Meaning 200 - Tracks returned. 400 INVALID_INPUT Missing service or title_id. 400 INVALID_PARAMETERS Invalid wanted range. 400 INVALID_SERVICE Unknown or disallowed service. 404 NO_CONTENT No matching episodes, or all matches failed."},{"location":"dev/rest-api/endpoints/#download-jobs","title":"Download jobs","text":"Downloads are asynchronous. POST /api/download enqueues a job and returns immediately with a job_id. The server runs each job in a background job worker subprocess. You then poll the job endpoints for progress and results.
Job states
A job moves through queued \u2192 downloading \u2192 one of the terminal states completed, failed, or cancelled. You can prioritise only queued jobs. You can retry or remove only terminal jobs.
"},{"location":"dev/rest-api/endpoints/#post-apidownload","title":"POST /api/download","text":"Make a download job. It requires service and title_id. Every other field is an optional download parameter with a server-side default. On success this returns 202 Accepted, not 200.
RequestResponse 202 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
{\n \"job_id\": \"b0f7c8e2-4a1d-4e9c-9b7e-2f3a1c0d5e6f\",\n \"status\": \"queued\",\n \"created_time\": \"2026-07-03T12:00:00+00:00\"\n}\n
Common parameters (all optional). These mirror the dl command flags:
Field Type Default Notes profile string null Credential/cookie profile. quality int[] [] Target resolution(s); best available if empty. vcodec string/string[] null Video codec filter. acodec string/string[] null Audio codec filter. vbitrate / abitrate int null Video / audio bitrate in kbps (positive). vbitrate_range / abitrate_range string null \"MIN-MAX\" bitrate window. range string[] [\"SDR\"] Dynamic range(s). channels number null Audio channel layout. no_atmos boolean false Exclude Atmos tracks. wanted string / string[] [] Episode/season selectors, as a list or as one comma-separated string. Accepts the part form, \"S01E01.2\", and the air-date form, \"2026-08-11\" or \"2026-08-01:2026-08-31\". For a music release, a selector is a track number, \"1-5\" or \"1,3,7\", or \"{disc}x{track}\" such as \"2x3\". latest_episode boolean false Only the newest episode. latest_episodes integer null Only the N newest episodes. A positive integer. When set, it overrides latest_episode. lang / v_lang / a_lang / s_lang string[] [\"orig\"] / [] / [] / [\"all\"] Language filters. require_audio string[] [] Audio languages that must exist. The job fails if one is missing, even with best_available. require_video string[] [] Video languages that must exist. The job fails if one is missing, even with best_available. require_subs string[] [] Subtitle languages that must exist. The job fails if one is missing. s_lang still decides what to keep. forced_subs boolean false Include forced subtitles. forced_subs_only boolean false Download forced subtitles and no other subtitle; implies forced_subs. Not valid with no_subs, video_only, audio_only or chapters_only. forced_s_lang string[] [] Forced subtitle language(s); implies forced_subs. exact_lang boolean false Exact language matching. sub_format string null Output subtitle format. video_only / audio_only / subs_only / chapters_only boolean false Track-type restriction (at most one). no_subs / no_audio / no_chapters / no_video / no_attachments boolean false Skip a track type. audio_description boolean false Download audio description. audio_description_only boolean false Download audio description and no standard audio. Not valid with no_audio, video_only, subs_only or chapters_only. slow boolean/string null Randomized delay between downloads. split_audio boolean null Separate files per audio codec. skip_dl boolean false Only fetch keys, do not download. all_drm boolean false License each track with both Widevine and PlayReady. Needs a CDM for each DRM system. Key vaults are read first; cdm_only: true sends a challenge for each system. The server refuses it with cdm, which selects one device. export boolean false Export manifest/keys/subs to JSON. cdm_only boolean null Force CDM-only (true) or vault-only (false) key retrieval. proxy / no_proxy / no_proxy_download / proxy_download string / bool / bool / string null / false / false / null Proxy controls. proxy and proxy_download must be full proxy URIs unless the API key has server_proxy. A Control D resolver, controld://<resolver>@dns.controld.com, counts as a full proxy URI: the server runs a forwarder for it. no_folder / no_source / no_mux boolean false Output/mux controls. sample boolean/string null Download a short sample and write it with a SAMPLE tag on the filename in a Sample folder inside the output folder. true is 60 seconds from 2 minutes in; \"0-60\" is a window in seconds. include_sample boolean false Download the full title, then also cut a 60 second sample from each muxed file into a Sample folder next to it. workers int null Threads per track. adaptive_workers boolean false Scale segment workers to measured CDN throughput, up to the workers cap. download_processes int 1 Split a track's segments across this many processes. Only engages for large batches. downloads int 1 Concurrent tracks. worst boolean false Lowest bitrate within quality. best_available boolean false Fall back to best available. With all_drm, a DRM system that does not license is a warning. repack boolean false Add REPACK tag. tag string null Release group tag. tmdb_id / imdb_id / tvdb_id / anilist_id - null External ID overrides. Each resolves its metadata directly instead of by a title search, and is used for tagging. Set enrich to also take the title, year and original language. Give at most one of tmdb_id, imdb_id and tvdb_id, since unshackle resolves the others from it. Sending two returns 400. anilist_id still combines with one of them. tmdb_id and tvdb_id must be positive integers, imdb_id must look like tt1375666, and anilist_id must be a positive integer or a string like mal:12345, or the request returns 400. An ID whose provider is unconfigured, such as tmdb_id with no tmdb_api_key, fails the job rather than returning 400. anilist_id needs no API key. tvdb_order official, dvd, absolute, alternate, regional null Renumber episodes to a TVDB season order. Falls back to the tvdb_order config option. enrich boolean false Overwrite title, year and original language with the external source's. Needs one of tmdb_id, imdb_id, tvdb_id or anilist_id. Without one the job fails instead of returning 400. daily boolean false Treat the title as daily/date-based content and fill missing episode air dates from TVDB. The fill needs enrich and a TVDB ID. An air date the service already set is kept. output_dir string null Output directory, relative to the server's downloads directory. The server rejects a path that resolves outside it with 400. no_cache / reset_cache boolean false Title cache controls. Validation. Invalid values return 400 INVALID_PARAMETERS. vcodec, acodec and sub_format take the same spellings as the CLI options of the same name (unshackle dl --help prints each list). The API and the CLI read one list, so they cannot disagree. range must be one of SDR/HDR10/HDR10P/DV/HLG/HYBRID, and HDR10+ is also valid. The bitrate, download worker, and download counts must be positive integers. You may set at most one of the *_only flags. You cannot combine no_subs with subs_only, or no_audio with audio_only.
Service options. A service's own CLI options travel in the same body. Send them in a nested service_params object, or as flat top-level keys. service_params wins over a flat key of the same name. An option you leave out takes the default declared on the service's cli command, so the job matches the equivalent dl run. profile at the top level always means the credential profile, never a service's own --profile option.
Request 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
Rejected parameters
postscript, post_script and post_scripts are never accepted. A body containing any of them gets 400 INVALID_PARAMETERS, because a command string that arrives from an HTTP caller would be remote code execution. You configure post-scripts only in unshackle.yaml, where they still operate for API jobs. See Post-scripts.
Gated parameters (developer)
The server accepts a few keys, but permits them only when the server config opts in. Otherwise the server rejects the request with 403 FORBIDDEN:
cdm (per-request CDM device name): allowed only if serve.cdm_overrides is true or a list containing that device name. credential (\"user:pass\") and credentials (a map): allowed only if serve.allow_job_credentials is truthy (off by default).
On the server, unshackle merges the effective parameters in this order: defaults \u2192 serve: config overrides \u2192 service-specific defaults \u2192 your request body.
Status Error code Meaning 202 - Job queued. 400 INVALID_INPUT Missing service/title_id or malformed JSON. 400 INVALID_PARAMETERS A parameter failed validation. 400 INVALID_SERVICE Unknown or disallowed service. 403 FORBIDDEN A gated parameter is not permitted. 403 SERVER_CDM_CAPPED The API key has a server_cdm_max_height for the service, and the job has no quality at or under it, sets best_available, or has HYBRID in range."},{"location":"dev/rest-api/endpoints/#get-apidownloadjobs","title":"GET /api/download/jobs","text":"Show download jobs, with optional filtering and sorting.
Query parameters
Param Values Default Description status queued, downloading, completed, failed, cancelled - Filter by status. service service tag - Filter by service. sort_by created_time, started_time, completed_time, progress, status, service created_time Sort field. sort_order asc, desc desc Sort direction. full true, false false Include full per-job details. RequestResponse 200 curl -H \"X-Secret-Key: $KEY\" \\\n \"http://127.0.0.1:8786/api/download/jobs?status=downloading&sort_by=progress&sort_order=desc\"\n
{\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
With full=true, each job additionally includes parameters (with secrets redacted), started_time, completed_time, output_files, error_message, error_details, and error_code. When you start the server with --debug-api, each job also includes error_traceback and worker_stderr.
Status Error code Meaning 200 - Jobs returned. 400 INVALID_PARAMETERS Invalid sort_by or sort_order."},{"location":"dev/rest-api/endpoints/#get-apidownloadjobsjob_id","title":"GET /api/download/jobs/{job_id}","text":"Fetch a single job with full details (equivalent to a full=true list entry).
Status Error code Meaning 200 - Job returned. 404 JOB_NOT_FOUND No such job."},{"location":"dev/rest-api/endpoints/#get-apidownloadjobsjob_idevents","title":"GET /api/download/jobs/{job_id}/events","text":"Stream the job's progress as Server-Sent Events. Use this instead of polling GET /api/download/jobs/{job_id}.
The response has the content type text/event-stream. Each event has this format:
event: <name>\ndata: <job JSON>\n
The data field of every event is the same job object that GET /api/download/jobs/{job_id} returns.
Event When it is sent snapshot Immediately, as the first event. Gives the job's current state. status The job leaves the queue and starts to download. progress 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. completed The job finished. The server then closes the event stream. failed The job failed. The server then closes the event stream. cancelled The job was cancelled. The server then closes the event stream. The server sends a : keep-alive comment each 15 seconds while the job is quiet, to keep proxies from closing an idle connection. Ignore these lines.
If the job is already in a terminal state, the server sends the snapshot event, then the terminal event, and closes the event stream immediately.
Authentication from a browser
EventSource cannot set headers. For this endpoint only, the server also accepts the API key in the secret_key query parameter. This works in both server modes, the default integrated server and --api-only:
const events = new EventSource(\n `http://127.0.0.1:8786/api/download/jobs/${jobId}/events?secret_key=${key}`\n);\nevents.addEventListener(\"progress\", (e) => console.log(JSON.parse(e.data).progress));\nevents.addEventListener(\"completed\", () => events.close());\n
The header always wins. Send the API key in the query parameter or in the header, not both. If an X-Secret-Key header is present, the server examines that header and ignores the query parameter. See Authentication.
RequestResponse 200 curl -N -H \"X-Secret-Key: $KEY\" \\\n \"http://127.0.0.1:8786/api/download/jobs/b0f7c8e2-.../events\"\n
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
Status Error code Meaning 200 - Event stream started. 404 JOB_NOT_FOUND No such job."},{"location":"dev/rest-api/endpoints/#delete-apidownloadjobsjob_id","title":"DELETE /api/download/jobs/{job_id}","text":"Cancel or remove a job. The behaviour depends on the job's current state:
- Terminal job (completed/failed/cancelled): removed from the manager, returning
204 No Content with an empty body. - Queued or downloading job: cancelled, returning
200 {\"status\": \"success\", \"message\": \"Job cancelled\"}.
Warning
A 204 response has no body. Do not try to parse JSON from it.
Status Error code Meaning 200 - Job cancelled. 204 - Terminal job removed (empty body). 400 INVALID_PARAMETERS Job is in a state that cannot be cancelled. 404 JOB_NOT_FOUND No such job."},{"location":"dev/rest-api/endpoints/#post-apidownloadjobsclear-finished","title":"POST /api/download/jobs/clear-finished","text":"Remove every terminal (completed/failed/cancelled) job from the manager. No request body.
Response 200 { \"removed\": 3 }\n
"},{"location":"dev/rest-api/endpoints/#post-apidownloadjobsjob_idretry","title":"POST /api/download/jobs/{job_id}/retry","text":"Enqueue a new job that reuses a terminal job's service, title, and parameters. The service allowlist and parameter gates are re-checked. Returns 202 with the new job's ID.
Retry reuses the original, unredacted parameters
A retry replays the finished job's stored parameters exactly as the original client submitted them, including any secrets such as credential/credentials. It does not use the redacted parameters view that GET /api/download/jobs and GET /api/history 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.
Response 202 {\n \"job_id\": \"9c1e2f3a-...\",\n \"status\": \"queued\",\n \"created_time\": \"2026-07-03T12:05:00+00:00\"\n}\n
Status Error code Meaning 202 - New job queued. 404 JOB_NOT_FOUND No such job. 409 CONFLICT Job is not in a terminal state. 400 INVALID_SERVICE Service is no longer allowed. 403 FORBIDDEN A gated parameter is no longer permitted. 403 SERVER_CDM_CAPPED The job is no longer inside the server_cdm_max_height of the API key."},{"location":"dev/rest-api/endpoints/#post-apidownloadjobsjob_idpriority","title":"POST /api/download/jobs/{job_id}/priority","text":"Move a queued job to the front of the download queue.
Response 200 { \"job_id\": \"b0f7c8e2-...\", \"position\": \"front\" }\n
Status Error code Meaning 200 - Job moved to front. 404 JOB_NOT_FOUND No such job. 409 CONFLICT Job is not queued."},{"location":"dev/rest-api/endpoints/#post-apidownloadjobsjob_idinput","title":"POST /api/download/jobs/{job_id}/input","text":"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 input_prompt field and in its progress events. Show the prompt to the user and send the answer here.
A job that waits for an approval on another device, such as a pair code login, shows the message in its notice field instead. A notice needs no answer: show it to the user and keep polling.
RequestResponse 200 { \"response\": \"123456\" }\n
{ \"status\": \"accepted\" }\n
Status Error code Meaning 200 - Answer sent to the job. The input_prompt field goes back to null. 400 INVALID_INPUT The body is not JSON, or it has no response. 404 JOB_NOT_FOUND No such job. 409 CONFLICT The job does not wait on a prompt. Warning
The job keeps its download slot while it waits. It fails with AUTH_FAILED if nobody answers the prompt within 10 minutes.
"},{"location":"dev/rest-api/endpoints/#server-management","title":"Server management","text":"Endpoints for profiles, effective configuration, download history, environment checks, and maintenance actions.
"},{"location":"dev/rest-api/endpoints/#get-apiprofiles","title":"GET /api/profiles","text":"Show the named credential profiles configured per service (usable as the profile 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.
Response 200 {\n \"profiles\": {\n \"EXAMPLE\": [\"default\", \"premium\"],\n \"OTHER\": [\"us-account\"]\n }\n}\n
"},{"location":"dev/rest-api/endpoints/#get-apiconfig","title":"GET /api/config","text":"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 (secret, password, passwd, token, api_key, credential, auth, cookie, bearer, private) and any userinfo in proxy URLs. The directories block holds the server's absolute paths and reaches only an admin key (admin: true or the api_secret); a plain key gets the response without it.
Response 200 {\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
"},{"location":"dev/rest-api/endpoints/#get-apihistory","title":"GET /api/history","text":"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 DELETE /api/history/{job_id} and POST /api/download/jobs/clear-finished. unshackle stores the history in api_history.jsonl in the cache directory. It skips corrupt lines, and a missing file yields an empty list.
Query parameters
Param Type Default Description limit int (\u2265 1) 100 Maximum entries to return. service string - Case-insensitive service filter. Response 200 {\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
Status Error code Meaning 200 - History returned. 400 INVALID_PARAMETERS Invalid limit."},{"location":"dev/rest-api/endpoints/#delete-apihistoryjob_id","title":"DELETE /api/history/{job_id}","text":"Remove a single persisted history entry. Returns 204 No Content (empty body) on success.
Status Error code Meaning 204 - Entry removed (empty body). 404 NOT_FOUND No such entry (or outside your allowlist)."},{"location":"dev/rest-api/endpoints/#post-apimaintenanceclear-cache-and-post-apimaintenanceclear-temp","title":"POST /api/maintenance/clear-cache and POST /api/maintenance/clear-temp","text":"Delete and recreate the cache or temp directory. Both, and refresh-services, need admin: true on the API key or the api_secret itself; any other key gets 403 FORBIDDEN. Neither takes a request body. The server blocks both with 409 CONFLICT if any job is currently downloading (the details include the offending active_jobs).
The 409 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.
clear-cache also wipes download history
The persistent history read by GET /api/history lives in api_history.jsonl 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 DELETE /api/history/{job_id} instead.
Response 200 { \"cleared\": true, \"freed_bytes\": 1048576 }\n
Status Error code Meaning 200 - Directory cleared. 409 CONFLICT A download is currently active."},{"location":"dev/rest-api/endpoints/#post-apimaintenancerefresh-services","title":"POST /api/maintenance/refresh-services","text":"git-pull every service repository configured under directories.services and re-import the services that changed, without a restart. refreshed becomes true when all repos updated successfully, or when you configure no repository. deferred lists the services that have a running or queued job: they keep their current code until that job finishes, then swap. load_errors lists the services whose new code failed to import; the server drops them until the next successful refresh.
Response 200 {\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
"},{"location":"dev/rest-api/endpoints/#get-apienvcheck","title":"GET /api/env/check","text":"Report the install status of the external binaries unshackle depends on (the same set unshackle env check inspects), with best-effort version detection.
Response 200 {\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
"},{"location":"dev/rest-api/endpoints/#remote-dl-sessions","title":"Remote-dl sessions","text":"Developer feature
The /api/session/* 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 --remote-only mode, and they are what the built-in RemoteService client drives. Most end users never call them directly.
The server holds remote sessions in memory. They expire after serve.session_ttl (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 403 FORBIDDEN.
"},{"location":"dev/rest-api/endpoints/#remote-session-lifecycle-overview","title":"Remote session lifecycle overview","text":"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}/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
"},{"location":"dev/rest-api/endpoints/#slow-responses","title":"Slow responses","text":"The titles, tracks and license routes can take minutes on a large catalogue. When the answer is not ready after 30 seconds, the route sends status 200 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.
A late failure has status 200
The server sent the status before the work ended. A failure after the first 30 seconds arrives as the standard error body with status 200. Check status in the body, not only the HTTP status. The body has no HTTP status field. Use error_code and retryable to decide what to do.
A slow response is not gzip-compressed. Gzip output cannot start before the body is ready, and the newlines must go out at once.
"},{"location":"dev/rest-api/endpoints/#post-apisessioncreate","title":"POST /api/session/create","text":"Make a remote session for a service and title. Authentication runs asynchronously in the background. This call returns immediately with status: \"authenticating\", and you then poll the prompt endpoint. The body accepts service and title_id (both required). It also accepts a broad set of optional keys, because the body allows additionalProperties. These are credentials ({username, password, extra?}), cookies (base64 of zlib-compressed Netscape cookie file), proxy, no_proxy, profile, cache (map of forwarded cache files, keyed by the file path relative to the service cache directory with / separators and no .json suffix, so a nested key such as session_web/<sha1> lands in a subdirectory), client_region, proxy_region, cdm_type, range_, vcodec, quality, best_available, dl_params, client, and any service CLI options. proxy_region is the country code the client resolved proxy from; the server matches it against its own accounts. client is a freeform object the dashboard shows as sent (the CLI puts version, code_hash, platform and a redacted argv in it); the server ignores it above 4096 bytes of JSON.
dl_params is an object with the dl track selection: lang, v_lang and a_lang (arrays of language strings), acodec (an array of audio codec names or dl -a aliases such as ddp), and forced_subs and exact_lang (booleans). The service reads these values from ctx.parent.params. The server uses the dl default for each absent or malformed value, and drops an unknown codec name.
Service CLI options also travel in a nested service_params object, which wins over a flat key with the same name. profile at the top level always means the credentials profile, never a service's own --profile option.
The proxy value must be a full proxy URI, unless the operator gives your API key server_proxy in the serve.users config. Without server_proxy, the server does not resolve country codes with its own proxy providers. It rejects the request with INVALID_PROXY when no proxy is set and the reported client_region differs from the server's region. A request that reports no client_region is not blocked. Pass proxy with your own proxy, or no_proxy to accept the server's own connection. With server_proxy, the server resolves a country code and picks a proxy for your client_region itself. A Control D resolver, controld://<resolver>@dns.controld.com, counts as a full proxy URI: the server runs a forwarder for it and needs no Control D configuration of its own.
Response 200 {\n \"session_id\": \"d4e5f6a7-...\",\n \"service\": \"EXAMPLE\",\n \"status\": \"authenticating\",\n \"server_account\": false\n}\n
server_account is true when the server authenticated with one of its own accounts (serve.server_accounts). 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.
Status Error code Meaning 200 - Session created; authentication in progress. 400 INVALID_INPUT Missing service or title_id. 400 INVALID_SERVICE Unknown or disallowed service."},{"location":"dev/rest-api/endpoints/#get-apisessionsession_idprompt","title":"GET /api/session/{session_id}/prompt","text":"Poll for the authentication status and any pending interactive prompt (OTP, PIN, device code). Response variants:
AuthenticatingPending inputAuthenticatedFailed { \"status\": \"authenticating\" }\n
{ \"status\": \"pending_input\", \"prompt\": \"Enter the code sent to your email:\" }\n
{ \"status\": \"authenticated\" }\n
{ \"status\": \"failed\", \"error\": \"Invalid credentials\" }\n
Status Error code Meaning 200 - Status returned. 403 FORBIDDEN Request IP differs from the remote session creator. 404 SESSION_NOT_FOUND No such session."},{"location":"dev/rest-api/endpoints/#post-apisessionsession_idprompt","title":"POST /api/session/{session_id}/prompt","text":"Submit a response to a pending prompt. Body: { \"response\": \"...\" } (required).
Response 200 { \"status\": \"accepted\" }\n
Status Error code Meaning 200 - Response accepted. 400 INVALID_INPUT Missing response, or no prompt is pending. 404 SESSION_NOT_FOUND No such session."},{"location":"dev/rest-api/endpoints/#get-apisessionsession_idlogs","title":"GET /api/session/{session_id}/logs","text":"Drain the service's server-side log output for this remote session. The server mirrors every log call the service makes (self.log.info, warnings, errors) into a bounded per-session buffer, so a remote client can see why an auth, title, or license step failed. Pass since=<seq> to get only records newer than the last drained sequence number. Works in every auth state, including failed.
Response 200 {\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
Status Error code Meaning 200 - Records returned (empty list when nothing new). 404 SESSION_NOT_FOUND No such session. 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.
"},{"location":"dev/rest-api/endpoints/#get-apisessionsession_idtitles","title":"GET /api/session/{session_id}/titles","text":"Fetch the titles for an authenticated remote session. A slow answer arrives as a slow response.
Response 200 {\n \"session_id\": \"d4e5f6a7-...\",\n \"titles\": [ { \"type\": \"episode\", \"name\": \"Pilot\", \"id\": \"ep-1\" } ]\n}\n
Requires an authenticated remote session. Otherwise it returns 404 SESSION_NOT_FOUND.
"},{"location":"dev/rest-api/endpoints/#post-apisessionsession_idtracks","title":"POST /api/session/{session_id}/tracks","text":"Get tracks and chapters for a specific title within the remote session. Body: { \"title_id\": \"...\" } (required). Unlike list-tracks, 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.
manifests holds each served DASH/ISM manifest once. A service can build an AdaptationSet of its own that the served manifest does not contain. track_manifests holds a one-AdaptationSet MPD for each such track, and the client re-parses that in place of the whole manifest.
Response 200 {\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\": \"<base64 zlib xml>\" } ],\n \"track_manifests\": [ { \"track_id\": \"s-1\", \"type\": \"dash\", \"url\": \"https://...\", \"data\": \"<base64 zlib xml>\" } ],\n \"session_headers\": { \"User-Agent\": \"...\" },\n \"session_cookies\": { \"sid\": \"...\" },\n \"server_cdm_type\": \"widevine\"\n}\n
Status Error code Meaning 200 - Tracks returned. 400 INVALID_INPUT Missing or unknown title_id. 404 SESSION_NOT_FOUND No such session."},{"location":"dev/rest-api/endpoints/#post-apisessionsession_idsegments","title":"POST /api/session/{session_id}/segments","text":"Get the download URL, DRM info, headers, cookies, and raw track data for the selected tracks. Body: { \"track_ids\": [\"v-1\", \"a-1\"] } (required).
Response 200 {\n \"tracks\": {\n \"v-1\": { \"descriptor\": \"DASH\", \"url\": \"https://...\", \"drm\": [ ... ], \"headers\": { ... }, \"cookies\": { ... }, \"data\": { ... } }\n }\n}\n
Status Error code Meaning 200 - Segment info returned. 400 INVALID_INPUT Missing track_ids. 404 TRACK_NOT_FOUND An unknown track ID was requested."},{"location":"dev/rest-api/endpoints/#post-apisessionsession_idsegment_filter","title":"POST /api/session/{session_id}/segment_filter","text":"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: { \"track_id\": \"v-1\" } (required). unwanted is null when the track has no filter. The client keeps every segment when the server does not have this route.
Response 200 { \"unwanted\": [\"https://cdn.example/hls/ad1.ts\"] }\n
Status Error code Meaning 200 - Unwanted segment URIs, or null. 400 INVALID_INPUT Missing track_id. 404 TRACK_NOT_FOUND An unknown track ID was requested. 500 SERVICE_ERROR The playlist request or the filter failed."},{"location":"dev/rest-api/endpoints/#post-apisessionsession_idlicense","title":"POST /api/session/{session_id}/license","text":"Get the content keys for the DRM. The mode field selects one of two modes. A slow answer arrives as a slow response.
Proxy mode (mode: \"proxy\", the default) forwards the client's CDM challenge to the service's license endpoint and returns the raw license bytes:
RequestResponse 200 { \"track_id\": \"v-1\", \"challenge\": \"<base64 CDM challenge>\", \"drm_type\": \"widevine\" }\n
{ \"license\": \"<base64 license bytes>\" }\n
Server-CDM mode (mode: \"server_cdm\") runs the full CDM flow on the server using the device configured for your API key, returning content keys directly. Use track_id for a single track or track_ids for a batch:
Single: Response 200Batch: Response 200 { \"keys\": { \"<kid_hex>\": \"<key_hex>\" }, \"vault_keys\": [\"<kid_hex>\"], \"drm_type\": \"widevine\" }\n
{ \"keys\": { \"v-1\": { \"<kid_hex>\": \"<key_hex>\" } }, \"vault_keys\": [\"<kid_hex>\"], \"drm_type\": \"widevine\" }\n
Field Description track_id / track_ids Single track, or a batch of tracks. challenge Base64 CDM challenge (proxy mode). pssh Base64 PSSH (server-CDM mode). drm_type widevine (default) or playready. In server-CDM mode the server's cdm mapping for the service decides the DRM system and the response drm_type names the system that licensed. The client's value decides only when the server has no mapping for the service. mode proxy (default) or server_cdm. clear_tracks (response) Requested track ids that carry no DRM, so they have no keys. Absent when every requested track is encrypted. vault_keys (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 200 - License/keys returned. 400 INVALID_INPUT Missing challenge/PSSH, or no CDM device configured for the API key. 400 INVALID_PARAMETERS Unsupported drm_type. 404 TRACK_NOT_FOUND Unknown track ID. 404 NO_CONTENT Server CDM produced no keys. 502 SERVICE_ERROR The service aborted during licensing."},{"location":"dev/rest-api/endpoints/#post-apisessionsession_idkeysbad","title":"POST /api/session/{session_id}/keys/bad","text":"Report a content key from vault_keys 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. The client never learns the server vault names.
{ \"kid\": \"<kid_hex>\", \"key\": \"<key_hex>\" }\n
Status Error code Meaning 200 - The pair is flagged. 400 INVALID_INPUT This remote session was not served that pair. 404 SESSION_NOT_FOUND Unknown remote session."},{"location":"dev/rest-api/endpoints/#get-apisessionsession_id","title":"GET /api/session/{session_id}","text":"Return remote session metadata and validity.
Response 200 {\n \"session_id\": \"d4e5f6a7-...\",\n \"service\": \"EXAMPLE\",\n \"valid\": true,\n \"expires_in\": 300,\n \"track_count\": 4,\n \"title_count\": 10\n}\n
404 SESSION_NOT_FOUND if the remote session does not exist or has expired.
"},{"location":"dev/rest-api/endpoints/#delete-apisessionsession_id","title":"DELETE /api/session/{session_id}","text":"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.
Response 200 {\n \"status\": \"ok\",\n \"cache\": { \"tokens\": \"<base64 zlib bytes>\", \"session_web/<sha1>\": \"<base64 zlib bytes>\" }\n}\n
The cache 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 / separators and no .json 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 .. segment, or an empty segment, and so does the client. 404 SESSION_NOT_FOUND if the remote session does not exist.
"},{"location":"dev/rest-api/endpoints/#error-responses","title":"Error responses","text":"The server serialises every structured error raised inside a handler to the same JSON envelope:
{\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
details appears only when non-empty. retryable appears only when the error is retryable (e.g. network errors, rate limiting). debug_info appears only when you start the server with --debug-api.
Authentication errors differ
Errors raised by the API-key middleware use a distinct shape ({\"status\": 401, \"message\": \"Secret Key is Empty.\"}, {\"status\": 401, \"message\": \"Secret Key is Invalid.\"}, or {\"status\": 429, \"message\": \"Rate limit exceeded.\"} with a Retry-After header) with an integer status and no error_code, timestamp, or details. A 429 from the middleware therefore carries no error_code, unlike the RATE_LIMITED 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 error_code: \"INVALID_INPUT\".
"},{"location":"dev/rest-api/endpoints/#error-codes-and-default-status","title":"Error codes and default status","text":"Error code HTTP status INVALID_INPUT 400 INVALID_SERVICE 400 INVALID_PROXY 400 INVALID_PARAMETERS 400 AUTH_FAILED 401 FORBIDDEN 403 SERVER_CDM_CAPPED 403 GEOFENCE 403 NOT_FOUND 404 NO_CONTENT 404 JOB_NOT_FOUND 404 SESSION_NOT_FOUND 404 TRACK_NOT_FOUND 404 CONFLICT 409 RATE_LIMITED 429 INTERNAL_ERROR 500 DOWNLOAD_ERROR 500 WORKER_ERROR 500 SERVICE_ERROR 502 DRM_ERROR 502 NETWORK_ERROR 503 SERVICE_UNAVAILABLE 503 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 NETWORK_ERROR (503, retryable), \"rate limit\" or \"429\" become RATE_LIMITED (429, retryable), and anything unrecognized collapses to INTERNAL_ERROR (500).
"},{"location":"dev/rest-api/endpoints/#see-also","title":"See also","text":" - REST API overview. What the server is and when to use it.
- Authentication. Keys, server modes, and the
X-Secret-Key header. - Quickstart. A first end-to-end request walkthrough.
- Downloading. The
dl flags mirrored by POST /api/download.
"},{"location":"dev/rest-api/errors/","title":"Error Responses","text":"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.
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.
Where this comes from
unshackle/core/api/errors.py defines the error format, and the wrapper that turns raised errors into responses lives in unshackle/core/api/routes.py. Nothing on this page is invented. It reflects the actual server behaviour.
"},{"location":"dev/rest-api/errors/#the-standard-error-shape","title":"The standard error shape","text":"A structured error is always a JSON object with status set to the literal string \"error\". The full set of fields:
Error response body{\n \"status\": \"error\",\n \"error_code\": \"INVALID_PARAMETERS\",\n \"message\": \"vcodec must be one of: H264, H265, ...\",\n \"timestamp\": \"2026-07-03T12:34:56.789012+00:00\",\n \"details\": { \"field\": \"vcodec\" },\n \"retryable\": true,\n \"debug_info\": {\n \"exception_type\": \"APIError\",\n \"traceback\": \"...\"\n }\n}\n
Field Type Always present? Meaning status string Yes Always the literal \"error\". Lets a client distinguish an error body from a success body at a glance. error_code string Yes A stable, machine-readable code from the catalogue below. Match on this, not on message. message string Yes A human-readable description of what went wrong. Wording may change between versions, so do not parse it. timestamp string Yes ISO 8601 timestamp (UTC) of when the error response was built. details 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). retryable boolean Only when true Present and set to true when retrying the same request may succeed later (network blips, rate limiting, transient outages). Absent otherwise. debug_info object Only with --debug-api Technical diagnostics; see Debug information. Match on error_code, branch on HTTP status
Treat error_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.
"},{"location":"dev/rest-api/errors/#the-details-object","title":"The details object","text":"When present, details carries extra context specific to the error. It is only included when it is non-empty, so a client must treat a missing details as \"no extra information\". Some concrete examples you may encounter:
- A validation failure may include the offending field or the list of valid values.
- A \"title not found\" error on a remote session includes
available_titles. - A maintenance conflict includes
active_jobs, the jobs blocking the operation. - Categorised exceptions add a
reason tag, such as \"network_connectivity\" or \"geofence_restriction\".
"},{"location":"dev/rest-api/errors/#the-retryable-hint","title":"The retryable hint","text":"The retryable field appears only when it is true. 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.
A retryable network error
{\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
"},{"location":"dev/rest-api/errors/#error-code-catalogue","title":"Error code catalogue","text":"Every code below is a member of the APIErrorCode enumeration. The Status column is the default HTTP status the server returns for that code. A handler can override the status in special cases (for example, a network error is always forced to 503), but the defaults hold for the overwhelming majority of responses.
"},{"location":"dev/rest-api/errors/#client-errors-4xx","title":"Client errors (4xx)","text":"Code Status Meaning INVALID_INPUT 400 A required field is missing, or the request body could not be parsed. Also used as the generic \"your input was malformed\" code. INVALID_SERVICE 400 The named service is unknown, or is not permitted for your API key. INVALID_PROXY 400 The supplied proxy specification could not be resolved or is malformed, or the proxy failed the exit check. INVALID_PARAMETERS 400 One or more download or query parameters failed validation (bad codec, bitrate, sort field, and so on). AUTH_FAILED 401 Authentication with the streaming service failed (bad credentials or cookies). FORBIDDEN 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. SERVER_CDM_CAPPED 403 The server CDM does not license live above the server_cdm_max_height of the API key. details.reason is server_cdm_max_height (with details.max_height), client_device, for a remote session where the client's own device licenses, or server_device, for a remote session that runs on the server's device. A remote client licenses the track with its own device, except for server_device: then only its own vaults can supply the key. GEOFENCE 403 The title is not available in the applicable region. NOT_FOUND 404 A requested resource (title, history entry, and so on) does not exist. NO_CONTENT 404 The request was valid but produced nothing: no matching titles, tracks, episodes, or keys. JOB_NOT_FOUND 404 The referenced download job does not exist. SESSION_NOT_FOUND 404 The remote-dl session does not exist or has expired. TRACK_NOT_FOUND 404 A referenced track ID is not present in the remote session. CONFLICT 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). RATE_LIMITED 429 The streaming service is rate-limiting requests. Retryable. Not every 429 is RATE_LIMITED
The server has a rate limit of its own. An API key over serve.tiers.<name>.rate_limit or serve.users.<key>.rate_limit gets a 429 from the authentication middleware, before any handler runs, so it carries no error_code and is not the RATE_LIMITED code above. It is the shape {\"status\": 429, \"message\": \"Rate limit exceeded.\"} with a Retry-After header. Read Retry-After 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.
"},{"location":"dev/rest-api/errors/#server-errors-5xx","title":"Server errors (5xx)","text":"Code Status Meaning INTERNAL_ERROR 500 An unexpected server-side error. This is the fallback for any exception the server could not categorise. DOWNLOAD_ERROR 500 The download process itself failed. WORKER_ERROR 500 The download worker subprocess errored out. SERVICE_ERROR 502 The streaming service's API returned an error, or the service does not support the requested operation. DRM_ERROR 502 DRM or license acquisition failed. Retryable. NETWORK_ERROR 503 A network connectivity problem (connection, timeout, DNS, TLS). Retryable. SERVICE_UNAVAILABLE 503 The service is temporarily unavailable or under maintenance. Retryable. Fallback status
If a code is ever emitted without a mapped status, the server falls back to 500. In practice every code above has an explicit mapping.
"},{"location":"dev/rest-api/errors/#how-the-server-produces-errors","title":"How the server produces errors","text":"Understanding where an error comes from helps interpret it.
Explicitly raised errors. Most endpoints raise a structured APIError directly. For example, a missing service field yields INVALID_INPUT, and a disallowed service yields INVALID_SERVICE. These carry a precise code, message, and often a populated details object.
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:
If the error mentions... It becomes Retryable auth, login, credential, unauthorized, forbidden, token AUTH_FAILED (401) no connection, timeout, network, unreachable, socket, dns, resolve (or ConnectionError, TimeoutError, URLError, SSLError) NETWORK_ERROR (503) yes geofence, geoblock, region, not available in, territory GEOFENCE (403) no not found, 404, does not exist, invalid id NOT_FOUND (404) no rate limit, too many requests, 429, throttle RATE_LIMITED (429) yes drm, license, widevine, playready, decrypt DRM_ERROR (502) no service unavailable, 503, maintenance, temporarily unavailable SERVICE_UNAVAILABLE (503) yes invalid, malformed, validation (or ValueError, ValidationError) INVALID_INPUT (400) no anything else INTERNAL_ERROR (500) no Categorised errors include a reason tag inside details (such as \"network_connectivity\" or \"drm_failure\") so a client can react without parsing the message text.
Invalid JSON bodies. If a POST endpoint receives a body that is not valid JSON, the server returns INVALID_INPUT (400) with the parse error in details.error:
Malformed request body{\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
"},{"location":"dev/rest-api/errors/#the-authentication-error-exception","title":"The authentication error exception","text":"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 X-Secret-Key header, the middleware short-circuits with a legacy body that uses an integer status and no error_code or timestamp.
Missing keyInvalid key { \"status\": 401, \"message\": \"Secret Key is Empty.\" }\n
{ \"status\": 401, \"message\": \"Secret Key is Invalid.\" }\n
Handle both shapes
A client must expect two error formats: the standard structured error (string status of \"error\", with error_code), and this authentication error (integer status, no error_code). The GET /api/health endpoint is exempt from authentication, so it never returns the key-error shape.
"},{"location":"dev/rest-api/errors/#late-failures-with-status-200","title":"Late failures with status 200","text":"The remote session titles, tracks and license routes send status 200 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 200. The body has no field for the HTTP status that the error would otherwise have. error_code and retryable stay in the body.
Check the body on these routes
On these routes a 200 does not always mean success. Parse the body and treat \"status\": \"error\" with an error_code as a failure.
"},{"location":"dev/rest-api/errors/#responses-with-no-body","title":"Responses with no body","text":"Not every failure or completion has a JSON body. Some endpoints answer with 204 No Content and an empty body, notably deleting a terminal download job and deleting a history entry.
Do not parse 204 bodies
A 204 response has no body. Clients must examine the status code before they decode JSON, or the decode will fail on an empty string.
"},{"location":"dev/rest-api/errors/#debug-information","title":"Debug information","text":"By default, error responses never include tracebacks or internal diagnostics. If you start the server with the --debug-api flag, every structured error gains a debug_info object:
Error with --debug-api enabled{\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
The debug_info object always carries exception_type and, for exception-derived errors, a formatted traceback. Some endpoints add extra diagnostics such as captured job worker stderr.
Developer use only
--debug-api exposes internal tracebacks in responses. Enable it only for local debugging, never on a server reachable by untrusted clients.
"},{"location":"dev/rest-api/errors/#client-handling-recommendations","title":"Client handling recommendations","text":"For anyone writing a consumer of the API, a durable strategy is:
- Read the HTTP status first. It tells you the broad class of outcome, and it lets you find the
204/no-body and authentication-error cases before you read the body. - Branch on
error_code. For structured errors, this is the stable identifier to switch on. Do not use message as the identifier. - Respect
retryable. When it is true, back off and try the request again. The reference client retries 429, 500, 502, 503, and 504 with exponential backoff. When absent, fix the request rather than repeating it. - Fall back gracefully. For an unrecognised code, show the
message and the HTTP status.
Reference consumer
unshackle's own remote-download client treats any status of 400 or above as fatal, and a 200 body with \"status\": \"error\" and an error_code too: it logs Server error [<error_code>]: <message> and exits. It also wraps requests in a retry adapter (five attempts, backing off on 429, 500, 502, 503, and 504). This is a reasonable template for your own client's error handling.
"},{"location":"dev/rest-api/job-lifecycle/","title":"Download Job Lifecycle","text":"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.
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.
Who this page is for
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.
For the full request and response shape of each endpoint, see Endpoints. For how the server reports errors, see Error Responses.
"},{"location":"dev/rest-api/job-lifecycle/#the-five-states","title":"The five states","text":"A job is always in exactly one of five states, exposed as the status field:
Status Meaning queued Created and waiting for a free job worker. No download has started yet. downloading A job worker has picked the job up and the download is in progress. completed The download finished successfully; output_files lists the results. failed The download stopped with an error; error_message and error_code explain why. cancelled The job was cancelled before it could finish, from either the queued or downloading state. The last three (completed, failed, and cancelled) 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.
"},{"location":"dev/rest-api/job-lifecycle/#how-a-job-moves-between-states","title":"How a job moves between states","text":"stateDiagram-v2\n [*] --> queued: POST /api/download\n queued --> downloading: a worker picks it up\n queued --> cancelled: DELETE (while queued)\n downloading --> completed: download succeeds\n downloading --> failed: download errors\n downloading --> cancelled: DELETE (while downloading)\n completed --> [*]\n failed --> [*]\n cancelled --> [*]\n\n completed --> queued: POST .../retry (as a NEW job)\n failed --> queued: POST .../retry (as a NEW job)\n cancelled --> queued: POST .../retry (as a NEW job)
The transitions in prose:
queued \u2192 downloading 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. downloading \u2192 completed is the happy path: the download engine wrote all the requested files and reported success. downloading \u2192 failed is any error during the download: a service failure, a network problem, a DRM error, and so on. The job records what went wrong. queued/downloading \u2192 cancelled happens when you send a DELETE for a job that has not finished (see Cancelling a job). - Retry does not move a terminal job back to
queued. 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).
Priority does not change status
Moving a job to the front of the queue with the priority endpoint reorders when it will start, but it stays queued until a job worker picks it up. It is not a state change.
"},{"location":"dev/rest-api/job-lifecycle/#creating-a-job","title":"Creating a job","text":"You queue a download with POST /api/download. The request needs at least a service and a title_id, plus any download options you want to set. On success the server replies with 202 Accepted and the new job's identity:
Queue a downloadcurl -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
202 Accepted{\n \"job_id\": \"b1e6c7de-6d0a-4f2f-9d1e-3a2b4c5d6e7f\",\n \"status\": \"queued\",\n \"created_time\": \"2026-07-03T12:00:00.000000\"\n}\n
The job starts in queued. The job workers auto-start on the first job you submit, so you switch nothing else on. Keep the job_id. Every later call uses it.
The full parameter set
POST /api/download accepts the same download options as the dl command (quality, codecs, language selection, wanted 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.
"},{"location":"dev/rest-api/job-lifecycle/#reading-a-jobs-status-and-progress","title":"Reading a job's status and progress","text":"There are two ways to look at jobs.
One job in fullAll jobs (summaries) GET /api/download/jobs/{job_id} returns the complete detail for a single job, including parameters (with secrets redacted), timing, output files, and error information if it failed.
curl http://127.0.0.1:8786/api/download/jobs/b1e6c7de-6d0a-4f2f-9d1e-3a2b4c5d6e7f \\\n -H \"X-Secret-Key: your-api-secret\"\n
GET /api/download/jobs lists every job the manager currently holds. By default each entry is a summary. Pass full=true to get the same full detail as the single-job endpoint for every job.
curl \"http://127.0.0.1:8786/api/download/jobs?status=downloading&sort_by=progress&sort_order=desc\" \\\n -H \"X-Secret-Key: your-api-secret\"\n
You can filter the list by status and service, and order it with sort_by (created_time, started_time, completed_time, progress, status, or service) and sort_order (asc / desc). See Endpoints for the query-parameter reference.
"},{"location":"dev/rest-api/job-lifecycle/#the-progress-fields","title":"The progress fields","text":"While a job is downloading, 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:
Field Type Meaning progress number 0 to 100 Overall percent complete. phase string Human-readable phase, e.g. downloading video 1080p HDR10, audio en 5.1. title string Title being processed. current_title string The specific episode/movie in progress (for a batch). completed_tracks int Number of tracks finished so far. total_tracks int Total tracks selected for the download. active_tracks list of strings Labels of the tracks downloading right now. track_progress list Per-active-track {label, progress, speed} entries. segments_done number Segments downloaded for the track in progress. segments_total number Total segments for the track in progress. speed string Transfer speed of the track in progress, e.g. 4.20 MB/s. skipped_subtitles list Subtitles that were skipped as non-fatal failures (when skip_subtitle_errors is set). input_prompt string or null The prompt the service waits on. Answer it with POST /api/download/jobs/{job_id}/input. notice string or null A message the service shows while it waits for an approval on another device, such as a pair code. It needs no answer. The full detail adds started_time, completed_time, output_files, the redacted parameters, and, for failed jobs, error_message, error_details, and error_code. With --debug-api, it also adds error_traceback and worker_stderr.
A typical polling loop
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
Or subscribe instead of polling
GET /api/download/jobs/{job_id}/events pushes the same job object as Server-Sent Events, and closes the event stream when the job ends. See Endpoints.
What the percentage means
progress climbs from 0 toward 90 while tracks download, then the final stretch to 100 covers post-download work such as decryption cleanup, repackaging, and muxing. A job that has finished downloading but is still muxing can sit near 90 for a moment before completing. On success the manager sets it to exactly 100.
For a batch, progress is per-episode, not whole-batch
A multi-episode request (a wanted range) is a single job that processes its episodes sequentially. As each new episode begins, progress and the track counts (completed_tracks / total_tracks) 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 output_files array against parameters.wanted rather than trusting progress.
"},{"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":"A completed job has its output_files populated with the paths of the muxed results, and progress is 100. This is the state you want.
"},{"location":"dev/rest-api/job-lifecycle/#failed","title":"Failed","text":"A failed job carries the error. error_message is the short human message, error_code is one of the API's structured error codes (for example NETWORK_ERROR, DRM_ERROR, AUTH_FAILED, or DOWNLOAD_ERROR), and error_details gives more context. When you start the server with --debug-api, error_traceback and worker_stderr are also filled in, to help you find the cause.
Secrets are scrubbed from error text
A service can echo a credential or a proxy URL into its output. The server masks any known secret values out of error_message, error_details, error_traceback, and worker_stderr before returning them, so it is safe to log these fields.
The error-code catalogue and how each maps to an HTTP status is on the Error Responses page.
"},{"location":"dev/rest-api/job-lifecycle/#cancelled","title":"Cancelled","text":"The server stopped a cancelled job on request, before it finished. It may have partial output, but it is not considered complete. See below.
"},{"location":"dev/rest-api/job-lifecycle/#cancelling-a-job","title":"Cancelling a job","text":"Send DELETE /api/download/jobs/{job_id}. The behaviour depends on the job's current state, and this is important because the response differs:
Job state when you DELETE What happens Response queued or downloading The job is cancelled. A running download's worker process is terminated. 200 with {\"status\": \"success\", \"message\": \"Job cancelled\"} completed, failed, or cancelled (terminal) The job is removed from the manager entirely. 204 No Content, empty body Not found - 404 with error code JOB_NOT_FOUND In other words, DELETE on a live job cancels it, while DELETE 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.
Do not parse the body of a 204
Removing a terminal job returns 204 No Content with an empty body. A client must not try to decode JSON from it. Examine the status code first.
Cancel a running jobcurl -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
To remove all terminal jobs at once, use POST /api/download/jobs/clear-finished, which returns {\"removed\": <count>}.
"},{"location":"dev/rest-api/job-lifecycle/#retrying-a-job","title":"Retrying a job","text":"POST /api/download/jobs/{job_id}/retry 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 202.
- You can retry only terminal jobs. A retry of a
queued or downloading job returns 409 with error code CONFLICT. - A missing job returns
404 (JOB_NOT_FOUND). - 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
INVALID_SERVICE or FORBIDDEN if permissions changed.
202 Accepted, a fresh job{\n \"job_id\": \"c2f7d8ef-7e1b-5a3a-ae2f-4b3c5d6e7f80\",\n \"status\": \"queued\",\n \"created_time\": \"2026-07-03T12:30:00.000000\"\n}\n
"},{"location":"dev/rest-api/job-lifecycle/#prioritising-a-job","title":"Prioritising a job","text":"POST /api/download/jobs/{job_id}/priority moves a queued job to the front of the line, so it will be the next one a free job worker picks up.
- The job must be
queued. Prioritising a job in any other state returns 409 (CONFLICT). A missing job returns 404. - On success the response is
{\"job_id\": \"<id>\", \"position\": \"front\"}.
This only reorders the queue. The job's status stays queued until a job worker starts it.
"},{"location":"dev/rest-api/job-lifecycle/#history-and-retention","title":"History and retention","text":"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.
- Read it with
GET /api/history (newest first, with limit and service filters). - Delete a single entry with
DELETE /api/history/{job_id} (returns 204).
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.
Why the history file lives under the cache directory
unshackle puts api_history.jsonl 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.
"},{"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":"Developer section
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.
"},{"location":"dev/rest-api/job-lifecycle/#the-manager-and-its-queue","title":"The manager and its queue","text":"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.
- Concurrency:
max_concurrent_downloads (default 2) caps it. That many jobs can be in downloading at once. The rest wait in queued. - Retention:
job_retention_hours (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.
Two concurrency knobs that are easy to conflate
max_concurrent_downloads caps how many separate download jobs operate at once. The separate serve.downloads setting controls how many tracks download in parallel within a single job. They are independent, and raising one does not affect the other.
Concurrency and retention config keys
The manager reads these as top-level config attributes (config.max_concurrent_downloads and config.download_job_retention_hours). Those keys are not part of the standard config schema, so in practice the built-in defaults of 2 and 24 apply. GET /api/config gives the live values. The related serve.history_limit (default 100) instead controls how many entries the on-disk history file keeps.
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 downloading, stamps started_time, does the download, and on finish stamps completed_time and records history.
"},{"location":"dev/rest-api/job-lifecycle/#each-job-runs-in-its-own-subprocess","title":"Each job runs in its own subprocess","text":"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:
python -m unshackle.core.api.download_worker <payload.json> <result.json> <progress.json>\n
Three temporary files bridge the parent and the job worker:
payload.json: the manager writes it before launch. It contains the job ID, service, title ID, and merged parameters. progress.json: the job worker writes it continuously as the download proceeds. result.json: the job worker writes it at the end.
The job worker has no terminal. When a service asks the user for input, the job worker writes the prompt to progress.json as input_prompt and waits. The answer from POST /api/download/jobs/{job_id}/input 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 notice and sets it back to null when the wait ends.
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.
The job worker's exit codes are 0 for success, 1 for a download error, and 2 for bad arguments. Its result.json is either {\"status\": \"success\", \"output_files\": [...]} or {\"status\": \"error\", \"message\", \"error_details\", \"error_code\", \"traceback\"}. If the process exits non-zero, or the result is missing or not a success, the parent marks the job failed and adopts the job worker's error_code (or derives one by categorising the exception).
"},{"location":"dev/rest-api/job-lifecycle/#how-progress-reaches-the-api","title":"How progress reaches the API","text":"While the job worker operates, the manager polls progress.json every 0.5 s and copies the fields it finds onto the live DownloadJob. That is what the GET endpoints return.
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 0 to 90. The download engine drives the remaining 90 to 100 as it repackages and muxes. A track counts as done when it reaches a terminal state such as Downloaded, Decrypted, or a skipped subtitle.
"},{"location":"dev/rest-api/job-lifecycle/#how-cancellation-works","title":"How cancellation works","text":"Each job carries a cancellation event. When you DELETE a live job:
- If it is
queued, it flips straight to cancelled, 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. - If it is
downloading, the manager sets the cancellation event and flips the job to cancelled. The polling loop notices the event, terminate()s the job worker subprocess (escalating to kill() 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.
"},{"location":"dev/rest-api/job-lifecycle/#secret-handling-in-serialized-jobs","title":"Secret handling in serialized jobs","text":"Job parameters may carry secrets: a raw user:pass 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 (credential, credentials, password, token, api_key) and strips userinfo from proxy URLs. The manager also scrubs free-text fields that a service might have leaked a secret into (error_message, error_details, error_traceback, worker_stderr, 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.
"},{"location":"dev/rest-api/job-lifecycle/#see-also","title":"See also","text":" - Endpoints: the full request/response reference for every job endpoint.
- Error Responses: the error envelope, codes, and HTTP statuses a failed job reports.
- Authentication: the
X-Secret-Key header and per-key service allowlists that gate job creation and retry. - Downloading: the equivalent options on the
dl command line.
"},{"location":"dev/rest-api/quickstart/","title":"REST API Quick Start","text":"Unshackle ships with a built-in REST API that exposes the same download engine you drive from the command line. The unshackle serve command serves it and lets you queue downloads, poll their progress, browse services, and manage history over HTTP instead of the terminal.
The full loop runs end to end: start the server, authenticate, submit a download job, and poll it to completion. The curl commands here come directly from the API routes.
Who this page is for
This is a developer guide. It assumes you are comfortable with HTTP, JSON, and a tool like curl. 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.
"},{"location":"dev/rest-api/quickstart/#before-you-begin","title":"Before you begin","text":"You need a working unshackle install with services and CDM devices already configured, exactly as you would for a normal command-line download. If unshackle dl works for you, the API will too, since it runs the identical download pipeline.
If you have no install yet, follow Installation. Then check your tools:
From a cloneInstalled as a uv tool uv run unshackle env check\n
unshackle env check\n
This page uses the bare unshackle command. From a git clone, the recommended install, run each command as uv run unshackle ....
"},{"location":"dev/rest-api/quickstart/#step-1-configure-an-api-secret","title":"Step 1: Configure an API secret","text":"The server authenticates every request (except the health check) with an API key that you send in the X-Secret-Key header. The server reads this API key from the serve section of your unshackle.yaml config.
At minimum you must set api_secret:
unshackle.yamlserve:\n api_secret: \"choose-a-long-random-secret\"\n
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 serve.users, keyed by the secret:
unshackle.yamlserve:\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
The secret must exist
If api_secret is not set and you do not pass --no-key, unshackle serve refuses to start and raises an error. Treat the secret like a password. Anyone who has it can queue downloads on your machine.
Disabling auth for local testing
--no-key turns authentication off entirely: the server allows every request and ignores the X-Secret-Key header. This is convenient for a throwaway local test, but never put a --no-key server on a network you do not fully trust.
"},{"location":"dev/rest-api/quickstart/#step-2-start-the-server","title":"Step 2: Start the server","text":"Start the REST API with the serve command:
unshackle serve --api-only\n
By default the server binds to 127.0.0.1:8786. The --api-only flag serves only the REST API and omits the Widevine/PlayReady CDM HTTP endpoints. Drop it when you also want those endpoints.
Common options:
Option Default Effect -h, --host 127.0.0.1 Address to bind to -p, --port 8786 Port to bind to --api-only off Serve only the REST API, no CDM endpoints --no-key off Disable API-key authentication (allow all requests) --debug-api off Include tracebacks and stderr in error responses --debug off Enable DEBUG-level logging --remote-only off Expose only the remote-session subset of routes --caddy off Also launch Caddy as a reverse proxy (for HTTPS) Once it is up you will see the API mounted under /api/ and, unless you started in remote-only mode, an interactive Swagger UI:
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
Swagger UI is also behind auth
In --api-only mode (without --no-key), the Swagger UI at /api/docs/ requires the X-Secret-Key header, the same as every other route. Only /api/health is exempt from authentication.
For the rest of this page we will assume the server is reachable at http://127.0.0.1:8786 and store the secret in an environment variable:
export SECRET=\"choose-a-long-random-secret\"\nexport BASE=\"http://127.0.0.1:8786\"\n
"},{"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":"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:
curl \"$BASE/api/health\"\n
200 OK{\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
The update_check block is best effort. If unshackle cannot reach the update source, update_available and latest_version come back as null rather than failing the request.
"},{"location":"dev/rest-api/quickstart/#step-4-authenticate-a-real-request","title":"Step 4: Authenticate a real request","text":"Every other endpoint needs the X-Secret-Key header. A quick way to prove your API key works is to show the services the server can see:
curl \"$BASE/api/services\" \\\n -H \"X-Secret-Key: $SECRET\"\n
200 OK (truncated){\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
If the API key is missing or wrong, you get a 401 with a plain body:
401 Unauthorized{ \"status\": 401, \"message\": \"Secret Key is Invalid.\" }\n
Two error shapes exist
The authentication middleware returns the short {\"status\": 401, \"message\": \"...\"} shape shown above. Every other error the API produces uses the richer structured shape (error_code, timestamp, details, ...) described in Error handling. Parse both shapes in your client.
The tag value for the service you want is the identifier you pass as service in the calls below.
"},{"location":"dev/rest-api/quickstart/#step-5-submit-a-download-job","title":"Step 5: Submit a download job","text":"Downloads are asynchronous. You POST a job to /api/download, the server immediately hands back a job_id, and the actual download runs in the background so your request never blocks.
The only required fields are service and title_id. Everything else mirrors the flags of the dl command and has a sensible default, so a minimal job looks like this:
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
A more realistic job pins the quality and codecs and asks for specific episodes:
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
On success the server responds with 202 Accepted and the identifier you will poll:
202 Accepted{\n \"job_id\": \"3f9c1e0a-8d2b-4e6f-9a1c-77b0f2a1c4d5\",\n \"status\": \"queued\",\n \"created_time\": \"2026-07-03T12:00:00.000000+00:00\"\n}\n
Capture the job_id for the next step:
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
"},{"location":"dev/rest-api/quickstart/#frequently-used-download-fields","title":"Frequently used download fields","text":"The request body accepts the full download parameter set. A few of the most useful:
Field Default Meaning service - Service tag (required) title_id - Title identifier (required) profile null Named credential/cookie profile to use quality [] Resolution(s), e.g. [1080]; empty means best available vcodec null Video codec, e.g. \"H265\" acodec null Audio codec, e.g. \"EC3\" range [\"SDR\"] Dynamic range: SDR, HDR10, HDR10+, DV, HLG, HYBRID wanted [] Episodes to fetch, e.g. [\"S01E01\"], or music tracks, e.g. [\"1-5\"]. Empty means all lang [\"orig\"] Video/audio language(s) s_lang [\"all\"] Subtitle language(s) downloads 1 Number of tracks to download concurrently proxy null Proxy URI or country code Validation is strict: invalid codecs, subtitle formats, dynamic-range names, non-positive counts, or mutually exclusive flags (for example both video_only and audio_only) come back as 400 with error code INVALID_PARAMETERS. See the full reference on the download reference page for every accepted field.
Gated fields
The server refuses a per-request CDM (cdm) or inline credentials (credential / credentials) with 403 FORBIDDEN, unless the server operator has explicitly opted in with serve.cdm_overrides and serve.allow_job_credentials. Both are off by default.
"},{"location":"dev/rest-api/quickstart/#step-6-poll-the-job-to-completion","title":"Step 6: Poll the job to completion","text":"A job moves through these states:
queued \u2192 downloading \u2192 completed | failed | cancelled\n
The last three are terminal. Poll the job detail endpoint until you reach one of them. This endpoint always returns the full job record:
curl \"$BASE/api/download/jobs/$JOB\" \\\n -H \"X-Secret-Key: $SECRET\"\n
While the download runs you will see status: \"downloading\" and a progress value climbing from 0 toward 100:
200 OK (in progress){\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
When it finishes you will see status: \"completed\" and the produced files under output_files:
200 OK (completed){\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
A simple polling loop in shell:
poll.shwhile 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
Polling cadence
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.
Or let the server push the updates
GET /api/download/jobs/{job_id}/events 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.
curl -N \"$BASE/api/download/jobs/$JOB/events\" \\\n -H \"X-Secret-Key: $SECRET\"\n
If a job ends in failed, the full record includes error_message, error_code, and (when you start the server with --debug-api) error_traceback and worker_stderr to help you find the cause. The server scrubs sensitive values in these fields before it returns them.
"},{"location":"dev/rest-api/quickstart/#step-7-clean-up","title":"Step 7: Clean up","text":"Once you have collected the output you can remove the finished job. DELETE on a job has two behaviors depending on its state:
curl -X DELETE \"$BASE/api/download/jobs/$JOB\" \\\n -H \"X-Secret-Key: $SECRET\"\n
- If the job is terminal (completed/failed/cancelled), the manager removes it. You get
204 No Content with an empty body. - If the job is still queued or downloading, the manager cancels it instead. You get
200 with {\"status\": \"success\", \"message\": \"Job cancelled\"}.
Do not parse JSON on 204
A 204 response has no body. This applies to terminal-job removal here and to deleting history entries. Examine the status code before you decode JSON.
To clear every finished job at once instead of one at a time:
curl -X POST \"$BASE/api/download/jobs/clear-finished\" \\\n -H \"X-Secret-Key: $SECRET\"\n
200 OK{ \"removed\": 3 }\n
"},{"location":"dev/rest-api/quickstart/#managing-the-queue","title":"Managing the queue","text":"A handful of endpoints round out job control. All require the X-Secret-Key header.
Method Path Purpose GET /api/download/jobs List all jobs, with optional filtering and sorting GET /api/download/jobs/{job_id} Full detail for one job DELETE /api/download/jobs/{job_id} Cancel a running job, or remove a terminal one POST /api/download/jobs/{job_id}/retry Re-queue a new job from a terminal one POST /api/download/jobs/{job_id}/priority Move a queued job to the front of the queue POST /api/download/jobs/clear-finished Remove all terminal jobs Listing supports query parameters for filtering by status or service, sorting with sort_by (created_time, started_time, completed_time, progress, status, service) and sort_order (asc / desc), and requesting full per-job detail with full=true:
curl \"$BASE/api/download/jobs?status=downloading&sort_by=progress&sort_order=desc\" \\\n -H \"X-Secret-Key: $SECRET\"\n
200 OK{\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
A retry reuses the original job's service, title, and parameters to enqueue a brand new job, and returns 202 with a fresh job_id. A retry works only on terminal jobs, and returns 409 CONFLICT otherwise. A priority change works only on jobs still in the queued state.
"},{"location":"dev/rest-api/quickstart/#beyond-a-single-download","title":"Beyond a single download","text":"The download loop above is the core of the API, but the same server exposes more:
- Discovery:
POST /api/search finds titles by query, and POST /api/list-titles / POST /api/list-tracks inspect what a title offers before you commit to downloading it. See titles and tracks. - History:
GET /api/history reads a persisted log of jobs that reached a terminal state (newest first), and DELETE /api/history/{job_id} removes a single entry. See history. - Introspection:
GET /api/profiles lists configured credential profiles per service, GET /api/config returns a redacted view of the effective server config, and GET /api/env/check reports which external binaries the machine has. - Maintenance:
POST /api/maintenance/clear-cache, .../clear-temp, and .../refresh-services do housekeeping (the server blocks the cache and temp clears with 409 while a download is active). - Remote sessions: the
/api/session/* endpoints drive the thin-client \"remote download\" flow, where the server authenticates and licenses on behalf of a local client. See remote sessions.
The interactive Swagger UI at /api/docs/ documents every route and lets you try them in the browser (send your X-Secret-Key there too).
"},{"location":"dev/rest-api/quickstart/#error-handling","title":"Error handling","text":"Apart from the auth middleware's short form, every error the API returns uses a single structured envelope:
{\n \"status\": \"error\",\n \"error_code\": \"INVALID_PARAMETERS\",\n \"message\": \"Human-readable description\",\n \"timestamp\": \"2026-07-03T12:00:00Z\",\n \"details\": { }\n}\n
details appears only when the server has more to add. retryable: true appears only for transient failures. The server includes a debug_info block (exception type and traceback) only when it runs with --debug-api.
The error_code maps to an HTTP status. The ones you will meet most often:
Error code HTTP Typical cause INVALID_INPUT 400 Malformed JSON body or missing required field INVALID_SERVICE 400 Unknown or disallowed service tag INVALID_PARAMETERS 400 A download field failed validation AUTH_FAILED 401 Service login/credential failure FORBIDDEN 403 A gated field was used without server opt-in NOT_FOUND 404 Title or resource does not exist JOB_NOT_FOUND 404 No job with that job_id CONFLICT 409 Illegal state transition (e.g. retry a running job) RATE_LIMITED 429 Upstream throttling (retryable) INTERNAL_ERROR 500 Unexpected server-side failure SERVICE_ERROR 502 The service raised an error NETWORK_ERROR 503 Connection/timeout reaching the service (retryable) Retry politely
Codes marked retryable (NETWORK_ERROR, RATE_LIMITED, SERVICE_UNAVAILABLE) reflect transient conditions. Back off and retry rather than hammering the server.
"},{"location":"dev/rest-api/remote-sessions/","title":"Remote Service Sessions","text":"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.
This is the mechanism behind unshackle's client/server \"remote download\" workflow. A thin local client (RemoteService) talks to an unshackle serve 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.
Why you'd use this
- The server has service accounts, cookies, or a CDM you do not want to copy to every machine.
- You want to do downloads on a fast/local machine but keep credentials and licensing centralised.
- A service is region-locked to where the server lives, and the client is not.
"},{"location":"dev/rest-api/remote-sessions/#the-big-picture","title":"The big picture","text":"\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
The client implements the same interface dl 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.
Migration: remote_dl is gone
The RemoteService adapter lives inside the ordinary dl command and replaces the old standalone remote_dl command. If you have prior scripts or docs that invoke remote_dl, use dl with a configured remote server instead. The functionality now rides on dl through RemoteService.
For the auth-facing endpoints, header format, and error shapes referenced below, see Authentication and the endpoint reference in the REST API index.
"},{"location":"dev/rest-api/remote-sessions/#configuring-a-remote-server-client-side","title":"Configuring a remote server (client side)","text":"On the client, add a remote_services block to your unshackle.yaml. Each entry names a server and provides its URL and API key.
unshackle.yaml (client)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
Key Required Meaning url yes Base URL of the unshackle serve instance (no trailing slash needed) api_key no Sent as the X-Secret-Key header on every request server_cdm no When true, DRM keys are resolved by the server's CDM rather than a local device (default false) services no Per-service local config overrides, keyed by service tag Port default
The unshackle serve default port is 8786 (not 8080). Use the port your server binds. Some older example snippets show 8080, which is not the default.
"},{"location":"dev/rest-api/remote-sessions/#selecting-a-server","title":"Selecting a server","text":"If you configure exactly one server, unshackle uses it implicitly:
unshackle dl EXAMPLE 0ABCDEF\n
If you configure more than one server, you must pick one with --server:
unshackle dl --server my_server EXAMPLE 0ABCDEF\n
With no remote_services configured at all, unshackle raises a clear error telling you to add the block shown above.
"},{"location":"dev/rest-api/remote-sessions/#what-happens-during-a-download","title":"What happens during a download","text":"From your point of view the command looks like an ordinary download. Under the hood the client walks a remote session through its lifecycle.
1. Create + authenticate2. Interactive prompts (if needed)3. Titles + tracks4. Licensing5. Download + close The client calls POST /api/session/create, forwarding whatever it can so the server does not have to prompt:
- Local credentials for the service/profile (
{username, password, extra?}) - Local cookies, compressed and base64-encoded
- 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
server_proxy. Without server_proxy 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 --proxy with its own proxy, or --no-proxy to accept the server's own connection. With server_proxy the server picks a proxy that matches the client region itself. For --proxy controld:ca the client points its Control D profile at the region and sends only the resolver, as controld://<resolver>@dns.controld.com. 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. --no-proxy-download and --proxy-download change that for downloads only. - Track-selection hints (
range_, vcodec, quality, best_available) so the server fetches the right manifests - Your language and audio codec selection (
-l, -vl, -al, -a, -fs) in a dl_params object. Some services fetch one manifest for each audio language, and pick the languages from these values - 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
The server uses its own accounts only when the operator lists the service in serve.server_accounts and gives your API key server_accounts in serve.users. 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. --proxy ca picks a ca account.
GET /api/services advertises the regions those accounts cover. When your own region is not one of them and you set no --proxy, 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 controld:// resolver from the client.
The server responds immediately with a session ID and a status. Authentication runs in the background on the server.
Some services need a one-time code, PIN, or device confirmation. When the server's auth flow asks for input, the remote session enters pending_input. 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.
Enter the 6-digit code sent to your email: 483920\n
A client older than the service_params change sends service options as flat body keys only. A flat key that shares a name with a transport field (such as profile, 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 service_params.
The server also mirrors the service's own log output (self.log) into a per-session buffer. The client drains it through GET /api/session/{id}/logs after each step and prints the records locally, so you see the server-side reason when a step fails.
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 track_manifests, and the client re-parses that instead. Any session_headers / session_cookies the server used are merged into the client's local HTTP session.
The tracks response repeats the title. A service can rewrite title fields inside get_tracks, 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 track.data, 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.
For a DRM-protected title the client either proxies its CDM challenge through the server, or, if server_cdm: true, asks the server to do the full CDM flow and return the content keys directly. See Server-side vs. proxied CDM below.
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 session_ttl, so a long download does not let the remote session expire. On completion, and also when dl exits early (--list, Ctrl+C, an error), it deletes the remote session. If the login belongs to the client, the DELETE 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.
Renaming remote titles locally
You can rename titles for a remote service you do not have installed locally by adding a title_map under that service in your client remote_services.<name>.services config. The server sends raw titles. Your local map wins.
This is deliberate: the server does no title_map 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.
"},{"location":"dev/rest-api/remote-sessions/#server-side-vs-proxied-cdm","title":"Server-side vs. proxied CDM","text":"There are two ways DRM keys get resolved, chosen by the client's server_cdm flag.
Proxied CDM (default)Server-side CDM (server_cdm: true) Your local CDM builds the license challenge. The client sends that challenge to POST /api/session/{id}/license, the server forwards it to the service, and the raw license bytes come back for your local CDM to parse.
- Keeps your CDM local. The server only relays the license request.
- Used when
server_cdm is false (the default). - Also used for a run with
dl --cdm <name>, and for a service whose own entry in your cdm config named the loaded device. In each case the client sends server_cdm: false when it creates the remote session, and the server builds the service on your device even when the API key has the server CDM. - A service option that the service lists in
SERVER_DEVICE_OPTIONS keeps the server CDM. The server reads the option from service_params, then from the top level of the request. The create response gives the result in server_cdm, and the client shows a warning when the server did not apply its choice. - 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
cdm_call, and your local CDM answers it. See Your own device identity.
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 KID:KEY pairs directly. The client needs no CDM.
- Enable with
server_cdm: true in the server entry. - The server tells the client which DRM type it used (
widevine or playready). - A content key the server took from its own vault is unproven. The response lists its KID in
vault_keys, the client decrypts and checks that the output decodes, and a wrong pair goes back to POST /api/session/{id}/keys/bad. 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. 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. The client never learns the server vault names. - 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.
A height limit on the server CDM
An API key with server_cdm_max_height gets the server CDM only up to that height. The session create response tells the client who licenses the session in server_cdm and gives the limit in server_cdm_max_height. In a server CDM session, the batch licence response lists each track the server refused to license live under capped_tracks. A single-track server CDM licence answers 403 SERVER_CDM_CAPPED for such a track. In both cases the client licenses those tracks in proxy mode with its own local CDM. See server_cdm_max_height.
"},{"location":"dev/rest-api/remote-sessions/#your-own-device-identity","title":"Your own device identity","text":"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:
- 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.
- CDM calls. When the service calls the CDM, the server sends a
cdm_call 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 close 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. - Session keys only. A
keys call returns Widevine OPERATOR_SESSION and SIGNING keys. It never returns a content key, and the client refuses a PlayReady keys call. So a server cannot use your device to license titles for itself. - Identity config. A service names the config keys a client may send (for example
esn, Kpe, Kph, esn_map). The server lists them in the service listing as client_config. The client sends only those keys, from its own services: <TAG>: block in unshackle.yaml. 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 esn_map) 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.
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 server_device to true 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 server_vault grant (or server_cdm); 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: DELETE returns no cache files, and the HTTP session headers and track.data lose their secret-looking keys, as for a server login.
The server vault in a session your device licenses
With the server_vault grant (or server_cdm) 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 server_vault.
"},{"location":"dev/rest-api/remote-sessions/#remote-session-lifecycle-and-expiry","title":"Remote session lifecycle and expiry","text":"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.
Behavior Value Notes Idle session TTL 300s (5 min) default Refreshed on every request to the session and when a titles or tracks 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 Auth is never rushed
A remote session that is still authenticating or waiting on pending_input 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.
The TTL and max-session limits are read from server config:
unshackle.yaml (server)serve:\n session_ttl: 300 # seconds a session may sit idle\n max_sessions: 100 # cap on concurrent sessions\n
"},{"location":"dev/rest-api/remote-sessions/#security-properties-worth-knowing","title":"Security properties worth knowing","text":" - API key required. Every remote session request carries
X-Secret-Key. The server rejects requests without a valid API key (health check aside). See Authentication. - 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
403 FORBIDDEN. Remote sessions are not portable between hosts. - 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 (
serve.server_accounts) gets a persistent per-account cache instead, so the account's tokens outlive the remote session. - The server redacts secrets in logs. It redacts remote session IDs, service tags, and other user values before it writes them to the log.
"},{"location":"dev/rest-api/remote-sessions/#developer-reference","title":"Developer reference","text":"This section is for developers
The material below documents the server-side implementation and the HTTP contract. End users configuring a client can stop at the sections above.
"},{"location":"dev/rest-api/remote-sessions/#remote-session-endpoints","title":"Remote session endpoints","text":"The server mounts all these routes, even in --remote-only mode. Paths use the session_id that create returns.
Why --remote-only exists
--remote-only 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 --api-only 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.
Method Path Purpose POST /api/session/create Build + authenticate a service instance; returns a session ID immediately GET /api/session/{id}/titles Fetch and cache the title list POST /api/session/{id}/tracks Resolve tracks, manifests, chapters, headers/cookies for a title POST /api/session/{id}/segments Resolve per-segment/track download descriptors POST /api/session/{id}/segment_filter Unwanted HLS segment URIs for one track (ads, bumpers) POST /api/session/{id}/license DRM licensing (proxy or server CDM) POST /api/session/{id}/keys/bad Report a server-vault content key that did not decrypt GET /api/session/{id}/logs Drain the service's server-side log output GET /api/session/{id}/prompt Poll interactive auth status / pending prompt POST /api/session/{id}/prompt Submit an answer to a pending prompt GET /api/session/{id} Session info (validity, TTL, counts) DELETE /api/session/{id} 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":"POST /api/session/create requires service and title_id. It also accepts credentials, cookies (base64 of zlib-compressed Netscape cookie file), proxy, no_proxy, profile, cache (a map of filename \u2192 base64(zlib(bytes))), client_region, server_cdm (false when the user picked the local CDM), cdm_type, cdm_security_level, cdm_relay (true when the client answers CDM calls), cdm_system_id and cdm_device_type (Widevine only), service_config (the identity config keys the service lists in client_config), client (a freeform identity object the dashboard shows as sent), and the track-selection hints range_, vcodec, quality, best_available, plus arbitrary service CLI options (additionalProperties: true).
dl_params holds the dl track selection: lang, v_lang and a_lang (arrays of language strings), acodec (an array of audio codec names, such as EC3), and forced_subs and exact_lang (booleans). The server gives these values to the service in ctx.parent.params, never as service options, so a service option with the same name, such as an own --lang, does not get them. The server uses the dl default for each absent or malformed value: lang is [\"orig\"], v_lang, a_lang and acodec are [], and forced_subs and exact_lang are false. The server drops an unknown codec name. An empty array is a valid value and stays empty.
The server does not forward the dl mode flags: video_only, audio_only, subs_only, chapters_only, list_, skip_dl, sub_format, no_attachments, audio_description, audio_description_only and forced_subs_only. A service that reads one of them to skip work fetches more on the server, but the result is the same.
In a client-login session (not a server account), the server gives the service the client's profile in ctx.parent.params, 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.
The response returns before authentication finishes:
{ \"session_id\": \"...uuid4...\", \"service\": \"EXAMPLE\", \"status\": \"authenticating\",\n \"server_cdm\": false, \"server_cdm_max_height\": null, \"server_vault\": true, \"server_device\": false }\n
server_vault tells the client that the server vault serves a remote session its own device licenses. server_device tells it that the service runs on the server's device, so every content key comes from a vault.
Authentication runs on a background thread (asyncio.to_thread(authenticate, ...)). The remote session starts in AUTHENTICATING. The client must poll the prompt endpoint until it reaches authenticated (or failed).
"},{"location":"dev/rest-api/remote-sessions/#interactive-auth-the-inputbridge","title":"Interactive auth: the InputBridge","text":"When the service calls its input function during authenticate() on the server thread, an InputBridge pauses that thread and exposes the prompt to the HTTP layer.
AuthStatus values: authenticating, pending_input, authenticated, failed. InputBridge.request_input(prompt, timeout=600) blocks the sync auth thread on a threading.Event until submit_response() or cancel() fires. - A timeout raises
TimeoutError and marks the remote session FAILED. - A prompt after authentication (in
get_titles(), get_tracks() or licensing) raises RuntimeError at once. The client polls for prompts only during authentication, so no answer can come. - A CDM call (
InputBridge.request_cdm) 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. AUTH_INPUT_TIMEOUT = 600.0 seconds. This is also the TTL granted to AUTHENTICATING / PENDING_INPUT sessions in the store.
GET /api/session/{id}/prompt returns one of:
{ \"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
A cdm_call comes first, in any auth state. The client answers it with a JSON object in response: {\"session\": \"...\", \"challenge\": \"<base64>\"} for challenge, {\"keys\": [{\"kid\", \"type\", \"key\", \"permissions\"}]} for keys, {} for close, or {\"error\": \"...\"} when its CDM refuses. An older client refuses close, 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.
A missing remote session returns 404 SESSION_NOT_FOUND. An IP mismatch returns 403 FORBIDDEN. POST /api/session/{id}/prompt takes { \"response\": \"...\" } and returns { \"status\": \"accepted\" }. A post with no pending prompt is an INVALID_INPUT error.
"},{"location":"dev/rest-api/remote-sessions/#sessionstore-internals","title":"SessionStore internals","text":"Source: unshackle/core/api/session_store.py. A singleton you get from get_session_store().
- Config-driven limits.
serve.session_ttl (default 300) and serve.max_sessions (default 100) are read as properties, so config changes take effect without recreating the store. create() evicts the least-recently-accessed remote session when at capacity, then stores a new SessionEntry. It defaults auth_status to AUTHENTICATED, and the create handler overrides it to AUTHENTICATING. get() refreshes last_accessed through touch(). It returns None (and deletes the entry) if an authenticated remote session has been idle longer than the TTL. Remote sessions in AUTHENTICATING / PENDING_INPUT are exempt from TTL expiry. cleanup_expired() runs every 60s: authenticated remote sessions expire at ttl, in-flight-auth remote sessions expire at AUTH_INPUT_TIMEOUT. The removal of a remote session cancels its InputBridge and deletes its cache directory (pruning empty parent dirs up to, but not including, the cache root). - The server calls
cancel_all_bridges() on shutdown, to unblock any waiting auth threads.
SessionEntry fields:
Field Description session_id UUID4 string service_tag Normalized service tag service_instance The authenticated service object kept alive between calls titles / title_map Result of get_titles() and a title_id \u2192 Title map tracks / tracks_by_title / chapters_by_title Cached resolved tracks and chapters creator_ip IP recorded at create time for IP-binding checks cache_tag Per-session cache directory tag input_bridge InputBridge for interactive auth, if any auth_status / auth_error Current AuthStatus and last error message created_at / last_accessed Timestamps; last_accessed drives TTL and LRU eviction"},{"location":"dev/rest-api/remote-sessions/#per-session-cache-namespacing","title":"Per-session cache namespacing","text":"The create handler builds a Cacher namespaced as:
_sessions/<pbkdf2_hmac(sha256, X-Secret-Key, \"unshackle-session-ns\", 100000)[:12]>/<session_id>/<service>\n
The handler writes forwarded cache files into that directory before authentication. On DELETE, when the login belongs to the client (client_auth) 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 titles_* files) and returns them under a cache field, so the client can keep refreshed tokens. Each cache key is the file path relative to that directory, with / separators and no .json suffix, which is the Cacher cache key the service reads it with:
{\n \"status\": \"ok\",\n \"cache\": {\n \"tokens\": \"...base64(zlib(bytes))...\",\n \"session_web/<sha1>\": \"...base64(zlib(bytes))...\"\n }\n}\n
Both sides reject a cache key with a drive letter, a root, a .. 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 cache 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.
"},{"location":"dev/rest-api/remote-sessions/#remote-session-info-response","title":"Remote session info response","text":"GET /api/session/{id}:
{\n \"session_id\": \"...\",\n \"service\": \"EXAMPLE\",\n \"valid\": true,\n \"expires_in\": 300,\n \"track_count\": 12,\n \"title_count\": 40\n}\n
expires_in is the configured TTL, not time remaining
The expires_in value reports the store's configured session_ttl, not the seconds left before this specific remote session expires.
"},{"location":"dev/rest-api/remote-sessions/#reference-client-remoteservice","title":"Reference client: RemoteService","text":"Source: unshackle/core/remote_service.py. This is the canonical consumer of the remote session API and a good template for any client.
RemoteClient.request sets X-Secret-Key and User-Agent: unshackle/<version>, uses the server's timeout from remote_services (default 120s) as the read timeout, and treats any status_code >= 400 as fatal: it logs Server error [<error_code>]: <message> and raises SystemExit(1). A 200 body with \"status\": \"error\" is also fatal (see the heartbeat below). - Heartbeat. The
titles, tracks and license 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 200, so a failure after that time arrives as the usual error body with status 200. Your client must check status 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. - Retries. The download-side HTTP session mounts an adapter with
Retry(total=5, backoff_factor=0.2, status_forcelist=[429, 500, 502, 503, 504]). - Flow.
authenticate() \u2192 create (+ poll prompt every 2s up to a 600s deadline, answering pending_input prompts. With stdin closed the client logs an error and raises SystemExit(1) instead of posting an empty answer) \u2192 get_titles() \u2192 get_tracks() (merging returned session_headers/session_cookies, re-parsing manifests) \u2192 get the licence in proxy mode or server_cdm mode \u2192 close() (DELETE, saving any returned cache). - Server resolution.
resolve_server() reads config.remote_services.<name> into {url, api_key, services, server_cdm}, injecting the server_cdm flag into the services map as _server_cdm.
"},{"location":"dev/rest-api/remote-sessions/#troubleshooting","title":"Troubleshooting","text":"\\\"Could not connect to remote server ... Is it running?\\\"
The client could not reach the URL. Make sure that unshackle serve operates on the server, the url/port in remote_services are correct (default port 8786), and any firewall or reverse proxy allows the connection.
403 FORBIDDEN mid-download
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.
Auth times out or the prompt never resolves
Interactive auth allows up to 600s. If you miss that window, the server marks the remote session failed 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.
\\\"Multiple remote services configured. Use --server ...\\\"
You have more than one entry under remote_services. Pass --server <name> to pick one.
"},{"location":"getting-started/configuration-file/","title":"The Configuration File","text":"A single configuration file named unshackle.yaml 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.
Where the exhaustive key list lives
This page is an overview. For the complete, key-by-key breakdown of every setting, its type, and its default, see the Configuration Reference.
"},{"location":"getting-started/configuration-file/#the-config-filename","title":"The config filename","text":"The main configuration file is always named unshackle.yaml. It uses plain YAML. You can open and edit it in any text editor, or manage individual values with the unshackle cfg command.
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.
"},{"location":"getting-started/configuration-file/#where-the-config-file-lives","title":"Where the config file lives","text":"When unshackle starts, it searches a fixed list of locations and uses the first one that exists. In order of priority:
# Location Typical path 1 The unshackle package folder <clone>/unshackle/unshackle.yaml (a uv tool install: .../site-packages/unshackle/unshackle.yaml) 2 The parent of the package folder <clone>/unshackle.yaml (a uv tool install: .../site-packages/unshackle.yaml) 3 Your OS user-config directory see the table below Where the file belongs depends on how you installed unshackle:
- Git clone (recommended). Keep the file at
unshackle/unshackle.yaml inside the clone, which is location 1. unshackle setup writes a new config there, and it stays with the clone when you update it. uv tool install. Use location 3, your per-user config directory. A uv tool upgrade replaces the package folder, so a file at location 1 or 2 is lost. unshackle setup writes a new config there.
The path of the per-user config directory depends on your operating system:
LinuxWindowsmacOS ~/.config/unshackle/unshackle.yaml\n
%LOCALAPPDATA%\\unshackle\\unshackle.yaml\n
~/Library/Application Support/unshackle/unshackle.yaml\n
Not sure which file is being used?
Operate unshackle env info. It prints the path unshackle loaded the config from, or tells you that it found none. It also prints every directory unshackle currently uses.
The config is read exactly once, when unshackle starts. If you edit the file, the change takes effect on the next command.
"},{"location":"getting-started/configuration-file/#top-level-structure","title":"Top-level structure","text":"unshackle.yaml 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.
Here is a small, realistic example that sets a download location, a release tag, a default CDM, and one service's credentials:
unshackle.yaml# 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 -> \"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
The top-level keys group loosely into these areas:
Area Example keys Downloading & DRM dl, cdm, remote_cdm, decryption Networking network, headers Credentials & cookies credentials, firefox_cookies Tracks & muxing subtitle, audio, muxing, language_tags Key vaults key_vaults, vault_timeout Proxies & remote proxy_providers, remote_services, serve, services Naming & tagging tag, output_template, chapter_fallback_name External API keys tmdb_api_key, tvdb_api_key, simkl_client_id, ipinfo_api_key, metadata_providers Behaviour & logging update_checks, redact_paths, debug, unicode_filenames Post-scripts post_scripts Paths directories, filenames For the full list with types and defaults, see the Configuration Reference.
Unknown keys are silently ignored
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.
"},{"location":"getting-started/configuration-file/#setting-download-defaults-dl","title":"Setting download defaults (dl:)","text":"If you always pass the same dl flags (a language, a resolution, a codec), put them under a dl: 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 (--best-available \u2192 best_available).
unshackle.yamldl:\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
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 dl: block under it:
Per-service defaultsdl:\n lang: [en] # default for everything\nservices:\n EXAMPLE:\n dl:\n lang: [en, ja] # Example downloads English + Japanese\n
A few keys are named after the flag's internal name
Most keys are obvious, but set these exact ones: range (-r), list (--list), tmdb_id (--tmdb), imdb_id (--imdb), tvdb_id (--tvdb), no_atmos (--noatmos), and output_dir (-o). The Configuration Reference has the full list and every available config key.
"},{"location":"getting-started/configuration-file/#the-directory-layout","title":"The directory layout","text":"The directories 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 ~ for your home directory.
unshackle.yamldirectories:\n downloads: ~/Videos/unshackle\n temp: /mnt/fast/unshackle-temp\n cache: ~/.cache/unshackle\n
The directories unshackle uses:
Name Purpose Overridable downloads Default output folder for finished downloads Yes temp Temporary working files during a download Yes cache Cache store (title cache, update checks, service caches) Yes cookies Per-service cookie files Yes logs Log files Yes exports Export JSONs Yes wvds Widevine devices (.wvd files) Yes prds PlayReady devices (.prd files) Yes dcsl DCSL data Yes services Search paths for service code (see below) Yes commands CLI command modules Yes vaults Vault modules Yes fonts Bundled fonts Yes Some directories cannot be moved
unshackle protects five internal entries: app_dirs, core_dir, namespace_dir, user_configs, and data. If you write any of them under directories, unshackle ignores the override. This is intentional. Those paths come from the package location and your OS user directories.
"},{"location":"getting-started/configuration-file/#the-services-directory-is-special","title":"The services directory is special","text":"Unlike the other entries, services 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:
unshackle.yamldirectories:\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
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.
"},{"location":"getting-started/configuration-file/#the-filenames-config-key","title":"The filenames config key","text":"Alongside directories, the filenames 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.
"},{"location":"getting-started/configuration-file/#editing-the-config-with-unshackle-cfg","title":"Editing the config with unshackle cfg","text":"You do not have to edit unshackle.yaml by hand. The unshackle cfg command reads and writes individual values for you, creating the config file (and its parent directory) if it does not exist yet.
Read a single value by passing its config key. Nested config keys use dot notation:
$ unshackle cfg tag\n$ unshackle cfg cdm.default\n
Set a value by passing a config key and a value:
$ unshackle cfg tag MYGRP\n$ unshackle cfg cdm.default my_device_l3\n
unshackle parses the value as a Python literal, so write booleans as True/False and quote the strings inside a list (\"['en']\"). unshackle stores anything that is not valid Python literal syntax as a plain string:
$ unshackle cfg update_checks False\n$ unshackle cfg vault_timeout 30\n
Remove a value with --unset:
$ unshackle cfg cdm.default --unset\n
Show everything currently set with --list:
$ unshackle cfg --list\n
When it writes, unshackle cfg targets the config file that unshackle loaded. If none exists yet, it makes unshackle.yaml in the unshackle package folder (location 1 above):
- Git clone. That is
unshackle/unshackle.yaml in the clone, which is the correct place. uv tool install. A tool upgrade replaces the package folder and deletes that file. Run unshackle setup first, which writes the config to your user config directory, or make the file there yourself. Then unshackle cfg writes to it.
Editing with cfg strips comments
Because unshackle cfg rewrites the whole file when it saves, a write removes any comments in unshackle.yaml. If you keep important notes as comments, edit the file by hand instead, or keep those notes elsewhere.
"},{"location":"getting-started/configuration-file/#next-steps","title":"Next steps","text":" - Browse the Configuration Reference for every config key and default.
- Set up your first download in Downloading.
- Learn how unshackle discovers and updates services in Creating a Service.
"},{"location":"getting-started/installation/","title":"Installation","text":"unshackle is a modular archival tool for movies, TV, and music. It ships as a single Python package named unshackle that installs one console command, also called unshackle. This page covers the install script, the unshackle setup command, the Python version unshackle needs, and the external command-line tools it expects to find.
What you get
Installing the package registers a single entry point, the unshackle command. It covers everything: downloading, key-vault management, device provisioning, the REST server, and the helper utilities.
"},{"location":"getting-started/installation/#install-from-a-git-clone-recommended","title":"Install from a git clone (recommended)","text":"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.
The repository has an install script for Linux (install.sh) and for Windows (install.bat). The script installs uv if it is not found, installs unshackle, and then runs unshackle setup.
LinuxWindows git clone https://github.com/unshackle-dl/unshackle.git\ncd unshackle\nsh install.sh\n
git clone https://github.com/unshackle-dl/unshackle.git\ncd unshackle\n.\\install.bat\n
In a clone, the script runs uv sync and then uv run unshackle setup. The last lines of setup tell you to check your tools with uv run unshackle env check. Run unshackle from the clone with uv run unshackle ....
To install without a clone, see Advanced: install as a uv tool.
"},{"location":"getting-started/installation/#what-unshackle-setup-does","title":"What unshackle setup does","text":"unshackle setup prepares a new installation. The install script runs it for you, and you can run it yourself at any time:
From a cloneInstalled as a uv tool uv run unshackle setup\n
unshackle setup\n
The command does these steps:
- It shows which external tools are missing, and where to get the ones that it cannot download.
- It asks once for each tool or group of tools to download. The required tools come first. shaka-packager and
mp4decrypt share one DRM question, so mp4decrypt comes with the required tools, but env check 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 binaries folder (see Where setup puts files). - If no
unshackle.yaml exists, it asks for a downloads folder and writes a minimal config file. - It makes the data folders for cookies, WVDs, PRDs, and services.
- It asks for
.wvd and .prd 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 cdm.default to the imported device. If you imported more than one, it asks which one is the default. - 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
env check next.
You can run the command again. It skips the tools that it finds and never overwrites an existing config.
Not every tool has a download
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.
On Linux, setup cannot download MKVToolNix, which is a required tool. Install the mkvtoolnix package with your package manager (for example apt, dnf, or pacman).
CCExtractor on Linux needs FUSE
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 ccextractor package instead.
"},{"location":"getting-started/installation/#where-setup-puts-files","title":"Where setup puts files","text":"Item From a git clone From a uv tool install External tools unshackle/binaries in the clone binaries in the user data directory New config (unshackle.yaml) unshackle/unshackle.yaml 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 On Windows, CCExtractor and its libraries go into their own ccextractor subfolder of the tools folder.
On Linux, the user data directory is usually ~/.local/share/unshackle and the user config directory is usually ~/.config/unshackle. On Windows, both are %LOCALAPPDATA%\\unshackle. Run uv run unshackle env info to see the paths that unshackle uses. Its User_Binaries row shows the binaries folder in the user data directory.
Setup writes a new config only when it finds no unshackle.yaml in any of the config locations. It keeps an existing config where it is. In a clone, the new config sets only directories.downloads, so the data folders stay at their defaults in the clone.
A uv tool upgrade replaces the package folder. For a uv tool install, setup puts the tools in the user data directory and writes a directories block that moves the data folders there, so an upgrade keeps them. If an existing config keeps data folders inside the package of a uv tool install, setup shows a warning and prints the directories lines to add.
"},{"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 (mp4decrypt) dovi_tool \u2265 2.1 Dolby Vision handling SubtitleEdit \u2265 5.0 Subtitle conversion (optional) The sections below tell you about each of these, and how to make sure that your setup is complete.
"},{"location":"getting-started/installation/#python-versions","title":"Python versions","text":"unshackle requires Python 3.11 or newer, up to and including 3.14 (requires-python = \">=3.11,<3.15\"). Anything older than 3.11 or 3.15 and later is unsupported, and the installer refuses to assemble the environment.
You do not usually need to install a matching Python interpreter by hand, since uv can download and manage one for you. If you work inside an existing virtual environment, make sure that it is on a supported version.
"},{"location":"getting-started/installation/#installing-by-hand","title":"Installing by hand","text":"If you do not use the install script, install unshackle with uv and then run unshackle setup, or install the external tools yourself.
"},{"location":"getting-started/installation/#running-from-a-clone","title":"Running from a clone","text":"Use uv run 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.
Run from a git clonegit clone https://github.com/unshackle-dl/unshackle.git\ncd unshackle\nuv run unshackle setup\n
Every command shown elsewhere in these docs works the same way from a clone. Prefix it with uv run:
uv run unshackle env check\n
"},{"location":"getting-started/installation/#advanced-install-as-a-uv-tool","title":"Advanced: install as a uv tool","text":"This way is for users who know uv tools and want the unshackle command on their PATH without a clone.
Where a uv tool install keeps files
uv tool install puts unshackle into the tool folder of uv, not into a folder that you choose. unshackle setup 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 uv tool install, unshackle setup tells you this and asks if you want to continue.
Install the tool and run setup:
Install as a uv tooluv tool install git+https://github.com/unshackle-dl/unshackle.git\nunshackle setup\n
The install scripts also do this when you run one alone, without a clone: when the script does not find the unshackle pyproject.toml next to it, it runs uv tool install and then unshackle setup. When it finishes, it tells you to open a new terminal, because the PATH change only applies to new terminals. Run unshackle env check there.
Upgrading and removing
Because you installed it from a git URL, re-run the same uv tool install command (uv will update in place) to get a newer version, and use uv tool uninstall unshackle to remove it.
Developer note
Contributors will also want the development and test dependency groups. The project defines dev (linters, type checkers) and test (pytest and friends) groups in pyproject.toml. Install them with uv sync --group dev --group test inside the clone. End users can ignore these entirely.
"},{"location":"getting-started/installation/#external-tools-on-your-path","title":"External tools on your PATH","text":"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 binaries/ folder inside the installed package, then in the binaries folder of your user data directory, and then on your system PATH. unshackle setup installs tools into the first folder in a clone and into the second for a uv tool install. Installing a tool system-wide or putting it into one of those folders both work.
unshackle setup installs the required tools and some optional ones for you. Use the tables below when you install a tool by hand.
"},{"location":"getting-started/installation/#required-tools","title":"Required tools","text":"These must be present for core downloading, decryption, and muxing to work:
Tool Binary looked up Why it is needed FFmpeg ffmpeg Media processing: remuxing, conversion, track handling FFprobe ffprobe Media analysis: inspecting tracks and container details MKVToolNix mkvmerge Muxing downloaded tracks into a final MKV mkvpropedit mkvpropedit Editing MKV metadata after muxing shaka-packager shaka-packager / packager Decrypting DRM-protected content (the default decryptor) shaka-packager is the default decryptor
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 decryption config key if you want to switch to mp4decrypt.
Do not use shaka-packager 3.0 through 3.9.x
These versions stop with a segmentation fault on a single-track MP4 whose internal track_id is 2 or more. A track that unshackle downloads from a DASH or HLS manifest usually has such a track_id.
"},{"location":"getting-started/installation/#recommended-and-optional-tools","title":"Recommended and optional tools","text":"These extend unshackle's capabilities. Install the ones relevant to what you download. For example, dovi_tool only matters if you download Dolby Vision video.
Tool Binary looked up Why it is needed Bento4 (mp4decrypt) mp4decrypt Alternative DRM decryptor to shaka-packager MP4Box (GPAC) MP4Box Muxing DTS:X Profile 2 (DTS-UHD) audio dovi_tool dovi_tool Dolby Vision metadata handling HDR10Plus_tool hdr10plus_tool HDR10+ metadata handling SubtitleEdit seconv, SubtitleEdit Subtitle conversion (the SeConv CLI from 5.x) CCExtractor ccextractor, ccextractorwin, ccextractorwinfull Extracting closed captions FFplay ffplay Simple preview player MPV mpv Advanced preview player (used by util crop/util range previews) HolaProxy hola-proxy Hola proxy provider support Caddy caddy Optional reverse proxy for unshackle serve --caddy Docker docker Gluetun VPN proxy support Git git Fetching and updating remote service repositories MP4Box is only used for DTS:X Profile 2
Titles with DTS:X Profile 2 (DTS-UHD) audio mux to MP4; everything else muxes to MKV with mkvmerge. Install with apt install gpac.
SubtitleEdit specifics
unshackle looks for seconv first, the batch CLI shipped with SubtitleEdit 5.x, before falling back to a SubtitleEdit (4.x) binary. The 5.0 GUI has no batch mode, so the SeConv CLI is what you want for automated subtitle conversion.
"},{"location":"getting-started/installation/#verifying-your-installation","title":"Verifying your installation","text":"After installation, make sure that unshackle can see the tools it depends on.
"},{"location":"getting-started/installation/#examine-the-external-dependencies","title":"Examine the external dependencies","text":"The env check subcommand is the first check. It inspects your environment and reports which tools it found:
From a cloneInstalled as a uv tool uv run unshackle env check\n
unshackle env check\n
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 All required tools installed \u2713 or Missing required: <names>.
If a required tool shows as missing, env check tells you to run unshackle setup. You can also install the tool by hand and put it on your PATH (or in one of the binaries folders), then re-run the check.
unshackle is not found after a uv tool install
The bin directory of uv tools is probably not on your PATH. Run uv tool update-shell and open a new terminal.
"},{"location":"getting-started/installation/#inspect-environment-paths","title":"Inspect environment paths","text":"To see where unshackle will read its configuration from and where it stores downloads, caches, cookies, and devices, use:
uv run unshackle env info\n
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.
"},{"location":"getting-started/installation/#next-steps","title":"Next steps","text":" - Set up your configuration file (
unshackle.yaml), or let unshackle setup write a first one. - Start downloading titles when
env check finds every required tool.
"},{"location":"getting-started/quickstart/","title":"Quick Start","text":"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 unshackle dl command, and learn where the finished file lands.
Before you start
This guide assumes that you installed unshackle as Installation describes. The examples use the bare unshackle command. From a git clone, the recommended install, run each one as uv run unshackle ..., for example uv run unshackle env check.
unshackle includes no services
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). EXAMPLE in this guide stands in for the tag you give yours.
"},{"location":"getting-started/quickstart/#1-run-setup","title":"1. Run setup","text":"unshackle drives several external tools (FFmpeg, MKVToolNix, shaka-packager, and others) to decrypt, repack, and mux media, and it needs a config file. The unshackle setup command prepares both. If you used the install script, setup has already run. You can run it again at any time:
unshackle setup\n
Setup downloads the missing required tools and, if you agree, groups of optional tools. If no unshackle.yaml exists, it writes a minimal one with your downloads folder. It also makes the data folders and lets you import .wvd and .prd devices, one file or a whole folder at a time. Installation tells you what each step does and where the files go.
Then make sure that unshackle finds the tools:
unshackle env check\n
The required tools (FFmpeg, FFprobe, MKVToolNix, mkvpropedit, and shaka-packager) must show a green check. Optional tools such as dovi_tool (Dolby Vision) and CCExtractor (closed captions) only matter for the features that use them.
Set up by hand
To do these steps yourself, install the tools from the tables in Installation. Then run unshackle env info to see where unshackle looks for unshackle.yaml, and make the file in one of those locations. The configuration guide gives the details.
"},{"location":"getting-started/quickstart/#2-check-the-output-template","title":"2. Check the output template","text":"unshackle refuses to start a download unless it knows how to name the output file. That means output_template is the one setting a first run genuinely requires. Everything else has a sensible default. The config that setup writes copies tag and output_template from the example config. A minimal, working config looks like this:
unshackle.yamloutput_template:\n movies: \"{title} ({year}) {quality} {source}\"\n series: \"{title} {season_episode} {episode_name?} {quality} {source}\"\n
unshackle fills in each {variable} from the title and the tracks you downloaded. Output and Naming gives the full set of valid variables, including resolution, video, audio, hdr, edition, tag, and more.
Spaces or dots?
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 Title.S01E01.1080p names. Write the template in the style you want the filenames to look.
Editing config from the CLI strips comments
You can read and set keys with unshackle cfg (for example unshackle cfg tag MYGROUP or unshackle cfg --list), 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.
"},{"location":"getting-started/quickstart/#3-write-a-service","title":"3. Write a service","text":"The service tag you pass to dl (like EXAMPLE) 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.
Put the finished module in your directories.services folder (unshackle env info shows the path). The tag then works with dl, search, and the other service commands.
"},{"location":"getting-started/quickstart/#4-add-a-cdm-for-drm","title":"4. Add a CDM for DRM","text":"Most streaming services encrypt their titles. To fetch content keys, unshackle needs a CDM, a Widevine device (.wvd) or a PlayReady device (.prd). If you imported devices during unshackle setup, they are already in place. If setup also wrote your config, it set cdm.default to the device that you chose. Otherwise, add a Widevine device you already have with:
unshackle wvd add /path/to/device.wvd\n
This validates the file and moves it into your WVDs directory. Then point services at it in your config. The cdm map uses the service tag as its config key, with a default that covers everything else:
unshackle.yamlcdm:\n default: my_device # the .wvd file's name, without the extension\n EXAMPLE: my_other_device # override for a specific service\n
PlayReady works the same way with .prd files created and managed by the prd command. If a title is DRM-free, unshackle needs no CDM.
Tip
Operate unshackle wvd parse my_device to inspect a device's security level and contents, and unshackle env info to show where unshackle stores WVDs and PRDs.
"},{"location":"getting-started/quickstart/#5-supply-authentication","title":"5. Supply authentication","text":"Services that require a login read either cookies or credentials.
-
Cookies: export the service's cookies to a Netscape-format text file and place it in your cookies directory. unshackle looks for, in order: cookies/{SERVICE}.txt, then cookies/{SERVICE}/{profile}.txt, then cookies/{SERVICE}/default.txt. So unshackle finds a file at cookies/EXAMPLE.txt automatically for the EXAMPLE service.
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.
-
Credentials: store a username and password per service in your config:
unshackle.yamlcredentials:\n EXAMPLE: \"email@example.com:your-password\"\n
Use the -p/--profile 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.
"},{"location":"getting-started/quickstart/#6-find-a-title-optional","title":"6. Find a title (optional)","text":"If you have a URL or ID already, skip this. Otherwise, find a title on the service and note the id it prints, because that is what you feed to dl:
unshackle search EXAMPLE \"My Show\"\n
You can also show what a service gives for a given title without downloading:
unshackle dl --list-titles EXAMPLE 81234567 # show seasons/episodes\nunshackle dl --list EXAMPLE 81234567 # show available tracks\n
"},{"location":"getting-started/quickstart/#7-do-your-first-download","title":"7. Do your first download","text":"A download always has three parts:
unshackle dl <FLAGS> <SERVICE-TAG> <TITLE>\n
dl carries every quality, language, track, and output flag. <SERVICE-TAG> picks which service to talk to (e.g. EXAMPLE). <TITLE> is the URL, ID, or slug the service understands.
A good first command asks for 1080p with English audio:
Your first downloadunshackle dl -q 1080 -l en EXAMPLE 81234567\n
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.
"},{"location":"getting-started/quickstart/#handy-first-flags","title":"Handy first flags","text":"Flag Meaning -q, --quality Target resolution(s), e.g. -q 1080 or -q 1080,720. Defaults to best available. -l, --lang Language(s) for video and audio, e.g. -l en or -l orig,en. orig = the title's original language. Defaults to orig. -sl, --s-lang Subtitle language(s); defaults to all. -v, --vcodec Video codec, e.g. -v H.265. Defaults to any. -r, --range Dynamic range, e.g. -r HDR10 or -r DV. Defaults to SDR. -w, --wanted Which episodes, e.g. -w S01 or -w S01E01-S01E03. For music, which tracks, e.g. -w 1-5 or -w 2x3 for disc 2 track 3. -o, --output Override the output directory for this run. --list List the tracks that would be downloaded, then stop. A few realistic variations
# 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
See Downloading for the complete flag reference, including codec, bitrate, channel-layout, and track-type selection.
"},{"location":"getting-started/quickstart/#8-where-the-output-lands","title":"8. Where the output lands","text":"By default, unshackle writes finished files to the downloads directory. unshackle env info shows its exact path. A config from unshackle setup uses the folder that you gave at its prompt. Without that setting, the default is a downloads folder one level above the installed unshackle package. Override it for one command with -o:
unshackle dl -q 1080 -o /mnt/media/incoming EXAMPLE 81234567\n
- unshackle writes movies as a single
.mkv file named from your movies template. - unshackle groups TV episodes into a per-show / per-season folder (from your
series template) unless you pass --no-folder. - unshackle builds the filename from your
output_template and adds IMDb/TMDB/TVDB IDs to the file's metadata tags when available.
To change the default output location permanently, set it in your config:
unshackle.yamldirectories:\n downloads: /mnt/media/incoming\n
"},{"location":"getting-started/quickstart/#where-to-go-next","title":"Where to go next","text":" - Downloading. The full
dl command: quality, codecs, languages, track selection, hybrid Dolby Vision, and output control. - Configuration. Every
unshackle.yaml config key, plus directories, key vaults, proxies, and naming templates. - REST API. Operate the
serve server to drive downloads over HTTP.
You are never far from help
unshackle --help, unshackle dl --help, and unshackle <command> --help show every option. When in doubt, add --list to a dl command to preview what it would do before it downloads anything.
"},{"location":"guide/cli-reference/","title":"CLI Reference","text":"A complete reference for every unshackle command, subcommand, and flag. This page groups the commands by purpose:
dl: the download pipeline (the command you use most). search: find titles on a service. import: rebuild a download from an export file. setup: install the external tools and make a first config. cfg, env: manage configuration and the environment. kv: Key Vault operations. wvd, prd: Widevine / PlayReady device management. serve: operate the local CDM and REST API server. util: helper media utilities.
Running commands from a clone
This page uses the bare unshackle command. From a git clone, the recommended install, run each command as uv run unshackle ....
Getting help on any command
Every command accepts -h, --help, or -?. For example unshackle dl --help or unshackle wvd new --help. Each service defines its own arguments for dl and search (such as a title ID or a query), so examine unshackle dl SERVICE --help for those.
"},{"location":"guide/cli-reference/#root-command","title":"Root command","text":"unshackle [OPTIONS] COMMAND [ARGS]...\n
unshackle: Modular Movie, TV, and Music Archival Software.
Every invocation prints a banner and, when you enable update_checks in your config, checks for a newer release.
Option Description -v, --version Print version information and exit. -d, --debug Enable DEBUG-level logs and JSON debug logging. Silences noisy HTTP libraries unless debug_requests is set in config. -h, --help, -? Show help and exit. Commands are auto-discovered, so third-party command modules dropped into the commands directory appear automatically.
"},{"location":"guide/cli-reference/#dl","title":"dl","text":"The download command. It is itself a group whose subcommands are the installed streaming services, so an invocation always has three layers:
unshackle dl [OPTIONS] SERVICE [SERVICE ARGS...]\n
OPTIONS: every flag below, parsed at the dl level. SERVICE: a service tag (for example EXAMPLE1 or EXAMPLE2). Tags are case-insensitive and honour each service's aliases (example+, EXAMPLE2, and the other alias forms all give the same tag). SERVICE ARGS: the title, URL, or ID, plus any service-specific options. These belong to the service, not to dl.
Typical downloads
# 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
Config-driven defaults
You can give any dl flag a default under the dl: section of unshackle.yaml, and per-service under services.<TAG>.dl. 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.
"},{"location":"guide/cli-reference/#quality-codec-bitrate-range","title":"Quality, codec, bitrate & range","text":"Flag Default Description -p, --profile - Profile for credentials and cookies. -q, --quality best Resolution(s), comma-separated, e.g. 1080,720. -q 1080 also matches anamorphic tracks by 16:9 canvas. -v, --vcodec any Video codec(s). Accepts names or values: AVC/H.264/H264, HEVC/H.265/H265, VC1/VC-1, VP8, VP9, AV1. -a, --acodec any Audio codec(s), comma-separated. Accepts AAC, AC3/DD, EC3/DD+/eac3/ddp, AC4/AC-4, OPUS, OGG/VORB/vorbis, DTS, DTSX/DTS-X, ALAC, FLAC. -vb, --vbitrate highest Exact video bitrate in kbps. -ab, --abitrate highest Exact audio bitrate in kbps. -vb-range, --vbitrate-range - Video bitrate range in kbps, e.g. 6000-7000; picks highest within. Mutually exclusive with --vbitrate. -ab-range, --abitrate-range - Audio bitrate range in kbps, e.g. 128-256. Mutually exclusive with --abitrate. -r, --range SDR Colour range(s): SDR, HLG, HDR10, HDR10P (HDR10+), DV, HYBRID. -c, --channels - Audio channels; matches sub-layouts (5.1 \u2248 6.0). -naa, --noatmos off Exclude Dolby Atmos audio tracks. --worst off Pick the lowest bitrate within the requested quality. Requires -q. --best-available, --warn-only off Warn and continue when a requested resolution, range, or language is absent, instead of failing. With --all-drm, also when one DRM system does not license. -rvb, --real-video-bitrate off Probe real media size for true video bitrates, overriding the manifest. -rab, --real-audio-bitrate off Same for audio (slower). HYBRID range
-r HYBRID fetches both HDR10/HDR10+ and Dolby Vision and merges them with dovi_tool. It requires the dovi_tool binary on your PATH.
"},{"location":"guide/cli-reference/#language-subtitles","title":"Language & subtitles","text":"Flag Default Description -l, --lang orig Language(s) for both video and audio. orig = the title's original language; e.g. orig,en. A - prefix excludes, e.g. all,-es. -vl, --v-lang - Video-only language (overrides -l for video). A - prefix excludes. -al, --a-lang - Audio-only language (overrides -l for audio). A - prefix excludes. -sl, --s-lang all Subtitle language(s). A - prefix excludes, e.g. all,-es. --require-audio - Audio langs that must exist. The title fails even with --best-available. Does not select tracks. --require-video - Video langs that must exist. The title fails even with --best-available. Does not select tracks. --require-subs - Subtitle langs that must exist. Fails the title if one is missing. --s-lang still decides what to keep. -fs, --forced-subs off Include forced subtitle tracks. -fso, --forced-subs-only off Keep only forced subtitle tracks; drop the other subtitles. Implies -fs. -fsl, --forced-s-lang none Language(s) wanted for forced subtitles; implies -fs. A - prefix excludes. --exact-lang off Exact matching only: -l es-419 matches es-419, not es-ES. Applies to selection and to sort order. --sub-format - Output subtitle format (SRT/srt, VTT/webvtt, ASS/ssa, TTML, SMI, ...), or original to keep the source format. These flags select languages, they do not order them
Naming languages with -l or -sl removes the others. To keep every language but put your preferred ones first, use audio.language_priority and subtitle.language_priority in your configuration file.
unshackle honours the special language tokens orig, all, and best everywhere it expects a language.
"},{"location":"guide/cli-reference/#title-episode-selection","title":"Title & episode selection","text":"Flag Description -w, --wanted Wanted episodes, e.g. S01-S05,S07, S01E01-S02E03. Supports exclusions with a leading - (e.g. -S03). For a split episode, .N picks one part (S01E01.2), a range must stay inside the episode (S01E01.1-S01E01.3), and S01E01 on its own takes every part. For a dated episode, a token can also be an ISO air date (2026-08-11) or a date range with a colon (2026-08-01:2026-08-31). For a music release, a token is a track number (1-5, 1,3,7), or {disc}x{track} (2x3) when the release has more than one disc. --select-titles Interactively select what to download: episodes of a series, or films when a title has more than one. Cannot combine with -w. --latest-episode Download only the single most recent episode. --latest-episodes N Download only the N most recent episodes. --list-titles List titles only; do not download."},{"location":"guide/cli-reference/#track-type-inclusion-exclusion","title":"Track-type inclusion / exclusion","text":"Keep only certain track types, or skip certain track types.
Include-only Skip -V, --video-only -nv, --no-video -A, --audio-only -na, --no-audio -S, --subs-only -ns, --no-subs -C, --chapters-only -nc, --no-chapters -nt, --no-attachments (cover art, subtitle fonts, and files the service attaches) Flag Description -ad, --audio-description Include descriptive (audio-description) tracks. -ado, --audio-description-only Keep only descriptive (audio-description) tracks; drop the standard audio. Does not need -ad. --skip-subtitle-errors Skip a failed subtitle instead of aborting the title. Video/audio failures remain fatal."},{"location":"guide/cli-reference/#output-muxing-files","title":"Output, muxing & files","text":"Flag Description --split-audio Write a separate output file per audio codec instead of merging. Defaults to config muxing.merge_audio. --merge-video Mux video tracks that share a height, range, and codec into one file, so only language varies inside a file. Defaults to config muxing.merge_video. -o, --output Override the output directory for this run. --no-folder Disable folder creation for TV shows. --no-source Remove the source tag from the filename/path. --no-mux Do not mux; keep individual track files. --sample Download a short sample and write it with a SAMPLE tag on the filename in a Sample folder inside the output folder. Bare --sample = 60 seconds from 2 minutes in; --sample 0-60 = a custom window in seconds. --include-sample Download the full title, then also cut a 60 second sample from each muxed file into a Sample folder next to it. --tag Group tag override. --repack Add a REPACK tag to the filename. --postscript Run a command after each output file, with {variable} placeholders substituted. Repeatable. Replaces the post_scripts config for this run. See Post-scripts. --no-postscript Run no post-script for this run, neither the configured ones nor --postscript."},{"location":"guide/cli-reference/#metadata-tagging","title":"Metadata & tagging","text":"Flag Description --tmdb TMDB ID (integer). Used for the tags. Skips the title search. --enrich reads it too. Needs tmdb_api_key. --imdb IMDb ID, e.g. tt1375666. Used for the tags. Skips the title search. --enrich reads it too. Needs no API key. --tvdb TVDB ID (integer). Used for the tags. Skips the series lookup that --tvdb-order would otherwise do. --enrich reads it too. Needs tvdb_api_key. --anilist AniList ID (integer), e.g. --anilist 21. A MyAnimeList ID is accepted as mal:12345 and resolved to the AniList entry. Used for the tags. Skips the title search. --enrich reads it too. Needs no API key. --enrich Overwrite show title, year and original language with the external source's. Requires one of --tmdb, --imdb, --tvdb, or --anilist. --daily Treat the title as daily/date-based content and fill missing episode air dates from TVDB. The fill needs --enrich and a TVDB ID. See Daily and date-based content. --tvdb-order Renumber episodes to a TVDB season order: official (aired), dvd, absolute, alternate, or regional. Needs tvdb_api_key. One ID at a time
You cannot combine --tmdb, --imdb and --tvdb. Give one and unshackle finds the others from it, and writes all three to the tags. --anilist 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 --tmdb with no tmdb_api_key, fails before the download starts. --anilist needs no API key, so it never fails this check.
"},{"location":"guide/cli-reference/#episode-ordering","title":"Episode ordering","text":"A service does not always number a series the way TVDB's aired order does. Some services use TVDB's alternate (Streaming) order for Futurama, for example. --tvdb-order works out which order the service used, then renumbers the episodes into the order you asked for.
Orders that do not cover the whole series
An order can ignore episodes the service carries. TVDB's dvd 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.
"},{"location":"guide/cli-reference/#drm-keys-decryption","title":"DRM, keys & decryption","text":"Flag Description --cdm-only / --vaults-only Use only the CDM, or only Key Vaults, for key acquisition. --cdm <name> Use the named CDM device from the cdm config mapping for this run, ignoring the service/default mapping. Over --remote, that device licenses the remote session, not the server CDM. --skip-dl Skip the download but still retrieve keys. --all-drm License each track with both Widevine and PlayReady. Needs a CDM for each DRM system. Key Vaults are read first; --cdm-only sends a challenge for each system. Not for use with --cdm. --export Export track info and keys to a mediaexport JSON file in the exports directory."},{"location":"guide/cli-reference/#network-proxy","title":"Network & proxy","text":"Flag Description --proxy Proxy URI, a country or location code resolved from configured providers, or provider:region (e.g. nordvpn:ca, gluetun:us, protonvpn:de:berlin, controld:yul). --no-proxy Force-disable all proxy use. --no-proxy-download Bypass the proxy for all downloads (manifest, licence, and auth stay proxied). --proxy-download Use a different proxy for all downloads, in the same forms as --proxy (manifest, licence, and auth stay on --proxy). --remote Use a remote unshackle server. --server Name a remote server from the remote_services config."},{"location":"guide/cli-reference/#concurrency-caching-listing","title":"Concurrency, caching & listing","text":"Flag Default Description --workers downloader default Per-track download threads. --adaptive-workers off Scale per-track segment workers dynamically (up to the --workers cap) based on measured CDN throughput and errors. --download-processes 1 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. --continue-downloads off Keep completed segment files across runs and resume a previously failed download. One-off enable of the continue_downloads config option. --downloads 1 Number of tracks downloaded concurrently. --speed-limit unlimited Cap total download speed across all threads and tracks, e.g. 500k, 5M, 1.5G or plain bytes/sec. Values are bytes, not bits (5M = 5.0 MB/s). off disables a configured limit. --no-cache off Bypass the title cache. --reset-cache off Clear the title cache. --list off List available/would-be-downloaded tracks; do not download. --slow - Inter-title delay. Bare --slow = 60-120s; --slow 20-40 = custom range (minimum 20s). Some flags cannot be combined
--select-titles and --wanted are mutually exclusive. --worst needs --quality. --vbitrate and --vbitrate-range (and the audio equivalents) are mutually exclusive.
"},{"location":"guide/cli-reference/#search","title":"search","text":"Find titles on a service. Like dl, search is a group whose subcommands are the installed services, and it reuses dl's authentication, cookie, and proxy machinery.
unshackle search [OPTIONS] SERVICE [QUERY...]\n
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 dl.
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 --profile has no effect.
Option Description -p, --profile Profile for credentials and cookies. --proxy Proxy URI, country or location code, or provider:region (e.g. controld:ca). --no-proxy Force-disable all proxy use. Example
unshackle search EXAMPLE \"My Show\"\nunshackle search -p myprofile EXAMPLE \"Another Show\"\nunshackle search --proxy nordvpn:ca SERVICE \"query\"\n
"},{"location":"guide/cli-reference/#import","title":"import","text":"Reconstruct a download (download \u2192 decrypt \u2192 mux) from an --export JSON file without re-contacting the service. It re-fetches the manifest, injects the stored keys, and then runs the normal dl pipeline. The service tag is read from the export file, not passed by you.
unshackle import EXPORT_FILE [DL_ARGS...]\n
unshackle forwards any dl options after the file verbatim, so you can override quality, range, proxy, and so on.
Example
unshackle import export.json\nunshackle import export.json -r HDR10 --proxy US\n
The export file can be a mediaexport file from dl --export, an export from an older version of unshackle, or an export from unidl. The file must name the service it came from.
"},{"location":"guide/cli-reference/#setup","title":"setup","text":"Install the external tools and make a first config.
unshackle setup\n
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 binaries folder, in the package folder of a git clone or in your user data directory for a uv tool install. If no unshackle.yaml exists, it writes a first one: inside the clone, or to your user config directory for a uv tool install. It then makes the data folders and imports .wvd and .prd 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 env check. 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.
Example
uv run unshackle setup # from a git clone\nunshackle setup # from a uv tool install\n
"},{"location":"guide/cli-reference/#cfg","title":"cfg","text":"Read, set, delete, or show configuration values in unshackle.yaml without hand-editing YAML.
unshackle cfg [KEY] [VALUE] [OPTIONS]\n
Argument / Option Description KEY Dotted path into the config, e.g. tag, serve.api_secret, directories.downloads. VALUE Value to set. Parsed as a Python literal when possible, so true, 123, ['a','b'], and {'k':1} become real types; bare words stay strings. --unset Remove the configuration value. --list List all set configuration values. Comments are stripped
Writing a value through cfg 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 --unset together is an error.
Example
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
"},{"location":"guide/cli-reference/#env","title":"env","text":"Inspect and manage the project environment.
unshackle env COMMAND [ARGS]...\n
"},{"location":"guide/cli-reference/#env-check","title":"env check","text":"unshackle env check\n
Prints a dependency table (Category / Tool / Status / Required / Purpose) that shows which external tools unshackle finds on your PATH. It also gives a summary of how many required tools are present. If a required tool is missing, it tells you to run unshackle setup.
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 * required. All others are optional.
"},{"location":"guide/cli-reference/#env-info","title":"env info","text":"unshackle env info\n
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).
"},{"location":"guide/cli-reference/#env-theme","title":"env theme","text":"unshackle env theme\n
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 theme config key.
"},{"location":"guide/cli-reference/#env-clear","title":"env clear","text":"Clear an environment directory. unshackle empties the directory, makes it again, and reports the number of files and bytes it freed.
Command Description unshackle env clear cache [SERVICE] Clear the cache directory, or only one service's cache subdirectory. unshackle env clear temp Clear the temp directory. Example
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
"},{"location":"guide/cli-reference/#kv","title":"kv","text":"Manage Key Vaults. You configure vaults under key_vaults in unshackle.yaml, each with a name, a type (sqlite, mysql, http, api), and type-specific options. unshackle normalises service tags automatically.
unshackle kv COMMAND [ARGS]...\n
"},{"location":"guide/cli-reference/#kv-copy-to_vault-from_vault","title":"kv copy TO_VAULT FROM_VAULT...","text":"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.
Option Description -s, --service Only copy data for a specific service. -l, --local-only Only copy data for services installed locally. Mutually exclusive with --service."},{"location":"guide/cli-reference/#kv-sync-vault","title":"kv sync VAULT...","text":"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 --service / --local-only options as copy.
"},{"location":"guide/cli-reference/#kv-add-file-service-vault","title":"kv add FILE SERVICE VAULT...","text":"Add content keys to one or more vaults for a service. FILE contains one KID:KEY pair per line (32 hex : 32 hex, UTF-8). unshackle skips every line that does not match that form.
"},{"location":"guide/cli-reference/#kv-search-kid","title":"kv search KID","text":"Find a KID (32 hex characters, no dashes) in the configured vaults and report its content key.
Option Description -s, --service Limit the search to a specific service tag. -v, --vault Limit the search to a specific configured vault by name. Note
unshackle cannot enumerate remote vaults without a service, so pass --service when you examine them.
"},{"location":"guide/cli-reference/#kv-prepare-vault","title":"kv prepare VAULT...","text":"Make service tables on vaults that use tables, for every installed service, where they do not already exist.
Example
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
"},{"location":"guide/cli-reference/#wvd","title":"wvd","text":"Manage Widevine Device (.wvd) files. Devices live in the configured WVDs directory.
unshackle wvd COMMAND [ARGS]...\n
Command Description wvd add PATHS... Validate and move one or more .wvd files into the WVDs directory. wvd delete NAMES... Delete .wvd files by name (without extension). Prompts for confirmation. wvd parse PATH Parse a .wvd and print its System ID, security level, type, flags, and client info. Relative paths resolve against the WVDs directory. wvd dump WVD_PATHS... OUT_DIR Extract a device's contents (metadata, private key, client ID, VMP) into OUT_DIR/<name>/. With no paths, dumps every WVD in the WVDs directory. wvd new NAME PRIVATE_KEY CLIENT_ID [FILE_HASHES] Create a new .wvd from a PEM private key and a ClientIdentification blob, optionally with a VMP (FileHashes) blob. wvd new options:
Option Default Description -t, --type Android Device type. -l, --level 1 Security level (1-3). -o, --output WVDs dir Output directory. Example
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
"},{"location":"guide/cli-reference/#prd","title":"prd","text":"Manage PlayReady Device (.prd) files. Devices live in the configured PRDs directory. Built on pyplayready.
unshackle prd COMMAND [ARGS]...\n
"},{"location":"guide/cli-reference/#prd-new-paths","title":"prd new PATHS...","text":"Make a new .prd. Give either a single folder that contains zgpriv.dat (group key) and bgroupcert.dat (group certificate), or two file paths (group key, then group certificate).
Option Description -e, --encryption_key Optional device ECC private encryption key (generated if omitted). -s, --signing_key Optional device ECC private signing key (generated if omitted). -o, --output Output directory or .prd file path. prd new will not overwrite an existing file.
"},{"location":"guide/cli-reference/#prd-reprovision-prd_path","title":"prd reprovision PRD_PATH","text":"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 -e / -s / -o options. By default it overwrites the device in place.
"},{"location":"guide/cli-reference/#prd-test-device","title":"prd test DEVICE","text":"Do a test of a device against the Microsoft PlayReady demo server and print the returned content keys.
Option Default Description -c, --ckt aesctr Content key encryption type: aesctr or aescbc. -sl, --security-level 2000 Minimum security level: 150, 2000, or 3000. Example
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
"},{"location":"guide/cli-reference/#serve","title":"serve","text":"Serve your local Widevine/PlayReady devices and the REST API for remote access. Built on aiohttp.
unshackle serve [OPTIONS]\n
Option Default Description -h, --host 127.0.0.1 Host to serve from. -p, --port 8786 Port to serve from. --caddy off Also serve through Caddy (requires the caddy binary and a Caddyfile). --api-only off Serve only the REST API, not the CDM endpoints. Incompatible with --no-widevine/--no-playready. --no-widevine off Disable the Widevine CDM endpoints. --no-playready off Disable the PlayReady CDM endpoints. --no-key off Disable API-key authentication (allows all requests). --debug-api off Include tracebacks/stderr in API error responses. --debug off Enable debug logging for API operations. --remote-only off Expose only the remote service session endpoints (health, services, search, session). Implies --api-only. WVD files in the WVDs directory and PRD files in the PRDs directory are auto-loaded. The REST API lives under http://<host>:<port>/api/, with Swagger UI at /api/docs/ and a health check at /api/health (exempt from auth).
Configure api_secret first
Unless you pass --no-key, serve.api_secret must be set in your config. Requests authenticate with the X-Secret-Key header. --no-key disables authentication entirely. Only use it on a trusted, private network.
unshackle.yamlserve:\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
Example
unshackle serve\nunshackle serve -h 0.0.0.0 -p 8080\nunshackle serve --api-only\nunshackle serve --remote-only\nunshackle serve --caddy\n
"},{"location":"guide/cli-reference/#util","title":"util","text":"Various helper media utilities. When you give a command a directory, it processes every .mkv/.mp4 inside it in natural (S01E01 before S01E10) order.
unshackle util COMMAND [ARGS]...\n
"},{"location":"guide/cli-reference/#util-refresh-services","title":"util refresh-services","text":"unshackle util refresh-services\n
Force a refresh (git pull / hard reset) of all service repos configured under directories.services. This updates the clones on disk. A server that is already running reloads the changed services through POST /api/maintenance/refresh-services or serve.services_refresh_interval instead.
"},{"location":"guide/cli-reference/#util-crop-path-aspect","title":"util crop PATH ASPECT","text":"Losslessly crop H.264/H.265 video at the bitstream level. ASPECT is a W:H target such as 2.39:1.
Option Default Description --letter / --pillar --letter Crop top/bottom (--letter) or the sides (--pillar). -o, --offset 0 Fine-tune the computed crop area if not perfectly centred. -p, --preview off Preview the crop in MPV (or FFplay) instead of writing a file."},{"location":"guide/cli-reference/#util-range-path","title":"util range PATH","text":"Losslessly set the video range flag to full or limited at the bitstream level.
Option Default Description --full / --limited - Full (0-255) or limited (16-235) range. -p, --preview off Preview instead of writing a file."},{"location":"guide/cli-reference/#util-test-path","title":"util test PATH","text":"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.
Option Default Description -m, --map 0 Do a test of specific tracks with FFmpeg's -map, for example 0:v:0 or 0:a. Example
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
"},{"location":"guide/cli-reference/#see-also","title":"See also","text":" - Installation: install unshackle and its dependencies.
- Quickstart: your first download.
- Configuration file: set defaults for any
dl flag and configure vaults, proxies, and directories.
"},{"location":"guide/downloading/","title":"Downloading","text":"unshackle dl 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.
Where the full flag list lives
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 unshackle dl --help. Every flag shown here can also be given a default in your configuration file. See Configuration file.
"},{"location":"guide/downloading/#command-shape","title":"Command shape","text":"A download is always three layers: the root CLI, the dl command (which is where unshackle parses all the flags below), and a service tag subcommand that carries the title argument.
unshackle dl [OPTIONS] SERVICE [SERVICE ARGUMENTS]\n
unshackle: the root command. dl: the download command. unshackle parses all of the options on this page here, so they go before the service tag. SERVICE: a service tag such as EXAMPLE1, EXAMPLE2, EXAMPLE3. Service tags are case-insensitive and honour each service's aliases (for example example+ resolves to its real tag). SERVICE ARGUMENTS: usually a title ID or URL. This positional argument belongs to the service, not to dl, so it comes after the tag.
A minimal downloadunshackle dl EXAMPLE 81234567\n
Flags belong to dl, the title belongs to the serviceunshackle dl -q 1080 -v H.265 -r HDR10 --lang en EXAMPLE 'https://www.example.com/...'\n
See what a service accepts
Because each service defines its own positional argument, use unshackle dl SERVICE --help (for example unshackle dl EXAMPLE --help) to see that service's own argument and any service-specific options.
"},{"location":"guide/downloading/#the-download-flow","title":"The download flow","text":"When you start a download, dl moves through the pipeline below. The order tells you why, for example, --list stops early, and why unshackle fetches the content keys even with --skip-dl.
- Setup: load the DRM CDM, key vaults, proxy providers, cookies, and credentials.
- Authenticate: sign in to the service with your profile's cookies/credentials.
- Fetch titles: retrieve the movie, episode list, or album (cached unless
--no-cache/--reset-cache). - Filter titles: apply
--wanted, --latest-episode, --latest-episodes, or --select-titles. - Get tracks: parse the manifest into video, audio, subtitle, and chapter tracks.
- Select tracks: narrow each type down using your quality, codec, range, language, and bitrate flags.
- Download: pull segments for the selected tracks (concurrently per
--downloads). - License & decrypt: get the content keys (vault \u2192 CDM), decrypt each track.
- Post-process: extract closed captions, convert subtitles, repack, mux with
mkvmerge, and move the finished file to your downloads directory.
--list prints the tracks a title exposes and stops before selection. --list-titles prints every title the service returned and stops before --wanted/--latest-episode/--latest-episodes filtering. --skip-dl runs the license step but skips the actual segment download.
"},{"location":"guide/downloading/#choosing-quality","title":"Choosing quality","text":""},{"location":"guide/downloading/#resolution","title":"Resolution","text":"-q / --quality takes one or more target resolutions (heights) as a comma-separated list. Without it, unshackle picks the best available resolution.
Single resolutionunshackle dl -q 1080 EXAMPLE 81234567\n
Multiple resolutions in one rununshackle dl -q 2160,1080,720 EXAMPLE 81234567\n
16:9 canvas matching
Resolution matching is by track height first. If no track height matches exactly, unshackle falls back to a 16:9-canvas match, so -q 1080 also selects an anamorphic 1920\u00d7804 track (computed as int(width \u00d7 9 / 16)). unshackle applies the fallback to each range and codec on its own. A service that crops only its HDR10 tracks therefore keeps its 3840\u00d71920 HDR10 track, even when another range has an exact 2160 height match.
"},{"location":"guide/downloading/#best-available-and-worst","title":"Best-available and worst","text":"By default a missing requested resolution is an error. Two flags change that:
Flag Behaviour --best-available (--warn-only) 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 --all-drm a DRM system that does not license. --worst Within the specified quality, pick the lowest bitrate rendition. Requires -q/--quality. Never fail on a missing resolutionunshackle dl -q 2160 --best-available EXAMPLE 0ABC123\n
"},{"location":"guide/downloading/#video-codec-and-colour-range","title":"Video codec and colour range","text":""},{"location":"guide/downloading/#codec","title":"Codec","text":"-v / --vcodec selects one or more video codecs. The default is any codec. It accepts either enum names or their values, comma-separated.
Name Value AVC H.264 HEVC H.265 VC1 VC-1 VP8 VP8 VP9 VP9 AV1 AV1 H264 and H265 are aliases of AVC and HEVC.
Either spelling worksunshackle dl -v HEVC EXAMPLE 81234567\nunshackle dl -v H.265 EXAMPLE 81234567\nunshackle dl -v hevc,avc EXAMPLE 81234567\n
"},{"location":"guide/downloading/#colour-range","title":"Colour range","text":"-r / --range selects one or more colour ranges. The default is SDR.
Range Meaning SDR Standard dynamic range (default) HLG Hybrid Log-Gamma HDR10 HDR10 HDR10P HDR10+ DV Dolby Vision HYBRID Fetch both an HDR10/HDR10+ base and a DV track, then merge them Grab HDR10 and Dolby Vision in one rununshackle dl -q 2160 -r HDR10,DV EXAMPLE '...'\n
HYBRID requires dovi_tool
-r HYBRID makes a single hybrid track by injecting the Dolby Vision RPU metadata onto an HDR10/HDR10+ base layer with dovi_tool. It requires the dovi_tool binary, resolved from unshackle's binaries/ folder, the binaries folder of your user data directory, or your PATH. The normal case is a DV track plus an HDR10 or HDR10+ base. With HDR10+ and no DV, unshackle converts the HDR10+ metadata to DV instead, which also needs hdr10plus_tool. With no DV and no HDR10+, the title fails. When HDR10+ is present, unshackle prefers it over HDR10 as the base layer.
To keep an HDR10+ deliverable alongside the hybrid, request both ranges: -r HYBRID,HDR10P. -r HYBRID on its own muxes only the merged hybrid.
"},{"location":"guide/downloading/#bitrate-selection","title":"Bitrate selection","text":"By default unshackle keeps the highest-bitrate rendition for each selected resolution/codec/range/language combination. You can constrain this.
Flag Purpose -vb / --vbitrate Exact video bitrate in kbps. -ab / --abitrate Exact audio bitrate in kbps. -vb-range / --vbitrate-range Video bitrate range in kbps, e.g. 6000-7000; picks the highest within it. -ab-range / --abitrate-range Audio bitrate range in kbps, e.g. 128-256. Exact vs range are mutually exclusive
You cannot combine --vbitrate with --vbitrate-range, and likewise for the audio pair. Pick one form.
"},{"location":"guide/downloading/#real-bitrate-probing","title":"Real bitrate probing","text":"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 --vbitrate/--vbitrate-range 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:
-rvb / --real-video-bitrate: probe real video bitrates (per codec/range). -rab / --real-audio-bitrate: probe real audio bitrates (per codec/channels/ language). Slower than the video variant because there are more renditions to probe.
Reading the probed numbers
unshackle measures a single-file track (DASH SegmentBase/BaseURL) 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.
Why not every rendition is probed
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 ffprobe. A probe failure is non-fatal: the manifest value stays in place.
"},{"location":"guide/downloading/#audio-codec-channels-and-atmos","title":"Audio codec, channels, and Atmos","text":""},{"location":"guide/downloading/#codec_1","title":"Codec","text":"-a / --acodec selects one or more audio codecs (comma-separated). The default is any.
Name Value Codec AAC AAC Advanced Audio Coding AC3 DD Dolby Digital EC3 DD+ Dolby Digital Plus AC4 AC-4 Dolby AC-4 OPUS OPUS Opus OGG VORB Vorbis DTS DTS DTS DTSX DTS-X DTS:X Profile 2 (DTS-UHD) ALAC ALAC Apple Lossless FLAC FLAC FLAC unshackle accepts names, values, and a few aliases: eac3 and ddp both give EC3, and vorbis gives OGG.
Prefer Dolby Digital Plus, fall back to AACunshackle dl -a EC3,AAC EXAMPLE 81234567\n
"},{"location":"guide/downloading/#channels-and-atmos","title":"Channels and Atmos","text":" -c / --channels: desired channel layout, for example 5.1 or 2.0. Matching is by ceiling, so 5.1 implicitly matches a 6.0-reported layout. An immersive layout such as 5.1.4 matches on its total number of channels, so -c 10 selects it. -naa / --noatmos: exclude Atmos audio tracks from selection.
5.1 audio, no Atmosunshackle dl -c 5.1 --noatmos EXAMPLE 0ABC123\n
"},{"location":"guide/downloading/#music-quality","title":"Music quality","text":"A music service gives one Audio track for each codec and bitrate it offers for a song. The audio options above choose between them: -a picks the codec and -ab or -ab-range picks the bitrate. If you set neither, unshackle takes the best track.
-q / --quality is a video height. It has no effect on a music download.
Take the lossless trackunshackle dl -a FLAC EXAMPLE 81234567\n
Take the lossy track at 320 kb/sunshackle dl -a AAC -ab 320 EXAMPLE 81234567\n
Two FLAC tracks in one release
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 --list to read the bitrates, then give -ab the one you want.
"},{"location":"guide/downloading/#languages","title":"Languages","text":""},{"location":"guide/downloading/#video-and-audio-language","title":"Video and audio language","text":"-l / --lang sets the wanted language(s) for both video and audio. The default is orig, the title's original language.
Original language plus Englishunshackle dl -l orig,en EXAMPLE 81234567\n
unshackle changes the special token orig to the title's own original language everywhere you use it. You can override each track type independently:
-vl / --v-lang: language for video only (overrides -l for video). Useful when the burned-in video language differs from the audio you want. -al / --a-lang: language for audio only (overrides -l for audio).
English audio over the original videounshackle dl -al en EXAMPLE 81234567\n
"},{"location":"guide/downloading/#excluding-languages","title":"Excluding languages","text":"Put a - in front of a language to remove it from the selection. This works on -l, -vl, -al, -sl, and -fsl, in the same way as it works on -w / --wanted.
Every subtitle language except Spanishunshackle dl -sl all,-es EXAMPLE 81234567\n
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: -sl -es is the same as -sl all,-es, and -l -es is the same as -l orig,-es.
Only exclusions# 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
-vl and -al have no default of their own: they cascade to -l. An override that names a language replaces -l for that track type, exclusions included. An override that gives only exclusions adds them to the ones from -l.
Cascade# video keeps the Japanese track; only the audio drops Spanish\nunshackle dl -l en,-es -vl ja EXAMPLE 81234567\n
Rules for exclusion tokens
orig becomes the title's own original language, so -sl -orig drops the subtitles in that language. --exact-lang applies to exclusions with the same matching rules as selection: -es removes exactly the tracks that es would select. Without it, -es also removes es-419 and es-ES. - Tracks with no language tag are never excluded.
- unshackle rejects
-all. Name the languages you do not want instead. - The comma form is the documented style.
-sl -es also works, but a shell can read a lone -es as another option.
"},{"location":"guide/downloading/#sort-order","title":"Sort order","text":"-l and -sl 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:
unshackle.yamlaudio:\n language_priority: [orig, en]\nsubtitle:\n group_by: language\n language_priority: [en, es, fr]\n
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.
See subtitle.language_priority for the details.
"},{"location":"guide/downloading/#exact-vs-fuzzy-matching","title":"Exact vs fuzzy matching","text":"By default language matching is fuzzy: -l en also accepts en-US, en-GB, and the other regional forms (up to a small distance). Pass --exact-lang when only an exact match is acceptable: with it, -l es-419 selects only es-419, not es-ES.
The all and best tokens
For audio, the tokens all and best bypass the usual one-track-per-language pick and instead select the best track for each language present. For subtitles, all keeps every subtitle language.
"},{"location":"guide/downloading/#subtitles","title":"Subtitles","text":""},{"location":"guide/downloading/#selecting-subtitle-languages","title":"Selecting subtitle languages","text":"-sl / --s-lang sets the wanted subtitle language(s). The default is all, so unshackle downloads every available subtitle language.
Only English and Spanish subtitlesunshackle dl -sl en,es EXAMPLE 81234567\n
To keep the default and drop one language, use the - prefix described in Excluding languages. -sl all,-es keeps every subtitle language except Spanish, forced Spanish subtitles included.
"},{"location":"guide/downloading/#requiring-subtitles","title":"Requiring subtitles","text":"--require-subs takes a list of languages that must exist. If any is missing, the title fails, even under --best-available / --warn-only. Use it when a download is only worth keeping if a specific subtitle track is present.
It gates the title. It does not select tracks: --s-lang still decides what to keep, and it defaults to all:
# 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
"},{"location":"guide/downloading/#requiring-audio-and-video-languages","title":"Requiring audio and video languages","text":"--require-audio and --require-video take a list of languages that must exist. If one is missing, the title fails, even under --best-available / --warn-only. Like --require-subs, they gate the title without selecting tracks: -l / -al / -vl still decide what unshackle downloads.
This matters most with -l best or -l all, which accept whatever the service offers and so never report a missing language on their own:
# 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
The check runs against the full track list, before any language selection or exclusion. orig resolves to the title language, and --exact-lang applies. Audio carried inside the video track counts. --no-audio and --no-video drop the matching requirement.
"},{"location":"guide/downloading/#forced-subtitles-and-output-format","title":"Forced subtitles and output format","text":" -fs / --forced-subs: include forced subtitle tracks (signs/foreign dialogue). Without this flag, unshackle drops forced subtitle tracks from the selection. -fsl / --forced-s-lang: keep forced subtitles only in these languages (implies -fs). Works independently of --s-lang, so -sl all -fsl en grabs every full subtitle but only the English forced track. It accepts exclusions too: -fsl all,-es keeps every forced subtitle except the Spanish one, and -fsl -es means the same. -fso / --forced-subs-only: keep only the forced subtitle tracks and drop every other subtitle (implies -fs). --s-lang and -fsl still select the languages. --sub-format: set the output subtitle format, converting only when necessary. Accepts codec names/values and common aliases (srt, vtt, ass, ssa, ttml, and the other codec aliases), or the literal original to keep the source format.
Value Format SRT / srt SubRip VTT / vtt WebVTT ASS / ass Advanced SubStation Alpha SSA / ssa SubStation Alpha TTML / ttml Timed Text Markup original Keep the source format, no conversion Convert subtitles to SRTunshackle dl --sub-format srt EXAMPLE 81234567\n
SDH stripping happens by default
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 subtitle.strip_sdh config option controls this behaviour (default on).
"},{"location":"guide/downloading/#selecting-episodes-and-tracks","title":"Selecting episodes and tracks","text":"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.
"},{"location":"guide/downloading/#wanted-ranges","title":"Wanted ranges","text":"-w / --wanted accepts season and episode ranges, comma-separated. Prefix a token with - to exclude it. For a music release, the same option takes track numbers. Read music tracks below.
Whole seasonsSpecific episodesExclusionsSplit episodesAir dates unshackle dl -w S01 EXAMPLE 81234567\nunshackle dl -w S01-S03 EXAMPLE 81234567\nunshackle dl -w S01,S03,S05 EXAMPLE 81234567\n
unshackle dl -w S01E01 EXAMPLE 81234567\nunshackle dl -w S01E01-S01E05 EXAMPLE 81234567\nunshackle dl -w S01E01-S02E03 EXAMPLE 81234567\n
# Seasons 1 through 5, but not season 3\nunshackle dl -w S01-S05,-S03 EXAMPLE 81234567\n
# 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
# 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
"},{"location":"guide/downloading/#music-tracks","title":"Music tracks","text":"-w 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 {disc}x{track} 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.
TracksMore than one discExclusions # 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
# 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
# Tracks 1 through 8, but not track 4\nunshackle dl -w 1-8,-4 EXAMPLE 81234567\n
Read the track list first
--list-titles prints the release with its disc and track numbers, so you can see which numbers to give -w.
"},{"location":"guide/downloading/#daily-and-date-based-content","title":"Daily and date-based content","text":"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 Show.YYYY.MM.DD instead of SxxExx, the {date} token holds the ISO date, and the season folder becomes the year.
A service that only carries this kind of title sets DAILY = True on its class, and a service can set air_date on each episode itself. Add --daily to mark any other title as date-based:
unshackle dl --daily --tvdb 73871 --enrich EXAMPLE 81234567\n
With --enrich and a TVDB ID, --daily 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 --enrich unshackle has no source to fill from, and says so.
A dated episode answers to its air date in -w, as well as to its SxxExx token. A date token is a plain ISO date (2026-08-11). A date range uses a colon (2026-08-01:2026-08-31), 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 SxxExx tokens in one -w.
"},{"location":"guide/downloading/#split-episodes","title":"Split episodes","text":"A few services split one episode into several separately playable videos. Where a service reports that, add .N after the episode to pick one part.
Token Selects S01E01 All parts of episode 1. S01E01.2 Part 2 of episode 1, and nothing else. S01E01.1-S01E01.3 Parts 1 to 3 of episode 1. S01,-S01E01.2 All of season 1 except episode 1 part 2. Parts 1 and 3 are kept. A season token such as S01 covers every episode and every part, so you only need .N when you want a part on its own.
A part range stays inside one episode
S01E01.1-S01E01.3 is valid. unshackle rejects S01E01.1-S01E02.3, 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: -w S01E01.2,S01E02.1.
A part of an unsplit episode selects nothing
-w S01E02.2 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 --list-titles to see which episodes carry parts.
"},{"location":"guide/downloading/#other-selection-flags","title":"Other selection flags","text":"Flag Behaviour --select-titles Interactively pick episodes of a series, or films when a title has more than one. Cannot combine with -w. --latest-episode Download only the single most recent episode. --latest-episodes N 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. --list-titles List every title the service returned, then stop. -w, --latest-episode and --latest-episodes are not applied to this listing. When --latest-episode or --latest-episodes is set, -w has no effect.
Grab just the newest episodeunshackle dl --latest-episode EXAMPLE 81234567\n
Grab the three newest episodesunshackle dl --latest-episodes 3 EXAMPLE 81234567\n
"},{"location":"guide/downloading/#including-and-excluding-track-types","title":"Including and excluding track types","text":"You can restrict a download to certain track categories, either positively (only these) or negatively (everything but these).
Only these types (*-only flags):
-V / --video-only -A / --audio-only -S / --subs-only -C / --chapters-only
Skip these types (no-* flags):
-nv / --no-video -na / --no-audio -ns / --no-subs -nc / --no-chapters -nt / --no-attachments (cover art, subtitle fonts, and files the service attaches)
Additional track-type flags:
-ad / --audio-description: include descriptive (audio-description) tracks, which unshackle drops by default. -ado / --audio-description-only: keep only the descriptive tracks and drop the standard audio. It does not need -ad. Add -A to download no video or subtitles. --skip-subtitle-errors: if a subtitle fails to download, skip it and continue rather than aborting the whole title. Video and audio failures remain fatal.
The -only kind flags
-ado and -fso each keep one kind of track inside its track type. They do not drop the other track types: -ado still downloads the video, and -fso still downloads video and audio. Add -A or -S for that.
- The language flags still apply. With the default
-l orig, -ado fails when the descriptive track is not in the original language. Select the language with -al. - A flag that drops the same tracks is an error, for example
-ado with --no-audio or -fso with -A. - 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.
- 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.
Audio description only, in Englishunshackle dl -A -ado -al en EXAMPLE 81234567\n
Subtitles onlyunshackle dl -S -sl en EXAMPLE 81234567\n
Everything except chaptersunshackle dl -nc EXAMPLE 81234567\n
Note
You can combine an *-only flag with no-* flags to fine-tune: *-only chooses the starting set of categories, then no-* subtracts from it. Attachments (for example fonts) are always kept.
"},{"location":"guide/downloading/#listing-and-dry-runs","title":"Listing and dry runs","text":"Before committing to a long download, inspect what unshackle would do:
Flag Effect --list List the tracks the service exposes for each title, then stop. No selection, no download. --list-titles List every title the service returned, then stop. -w, --latest-episode and --latest-episodes are not applied to this listing. --skip-dl Skip downloading but still acquire the decryption keys. --all-drm License each track with both Widevine and PlayReady. See Widevine and PlayReady on the same title. See the track selection without downloadingunshackle dl -q 1080 -v H.265 -r HDR10 --list EXAMPLE 81234567\n
"},{"location":"guide/downloading/#output-and-muxing","title":"Output and muxing","text":""},{"location":"guide/downloading/#output-location-and-folders","title":"Output location and folders","text":" -o / --output: override the output directory for this run (otherwise unshackle uses the configured downloads directory). --no-folder: do not make a per-show folder for TV downloads. --no-source: remove the service source tag from the filename and path.
Send this download somewhere specificunshackle dl -o ~/Videos/incoming EXAMPLE 81234567\n
"},{"location":"guide/downloading/#muxing-behaviour","title":"Muxing behaviour","text":"By default, mkvmerge muxes the tracks of a movie or an episode into a single Matroska (.mkv) file. These flags change how unshackle assembles the output:
Flag Behaviour Default source --no-mux Do not mux; keep the individual track files. - --sample Download a short sample: 60 seconds from 2 minutes in, or --sample START-END for a window in seconds. - --include-sample Download the full title, then also cut a 60 second sample from each muxed file into a Sample folder. - --split-audio Write a separate output file per audio codec instead of merging all audio. config muxing.merge_audio (on) --merge-video Mux video tracks that share a height, range, and codec into one file, so only language varies inside a file. config muxing.merge_video (off) --sample needs a segmented track
--sample downloads only the segments that hold the window, and mkvmerge 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.
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.
A sidecar subtitle file with sidecar_format: original is not trimmed. It holds the segments around the window, or the whole file when the track is one file.
Music is never muxed
A song skips the muxer. unshackle keeps the container that the service delivered, such as .flac, .m4a, or .mp3, and writes the metadata into that file. Read Music output files.
"},{"location":"guide/downloading/#after-the-download","title":"After the download","text":"--postscript \"<command>\" runs your own command once per output file, with unshackle's metadata substituted into {variable} placeholders. It is repeatable, and it replaces the post_scripts config for that run. No success post-script operates under --no-mux, because that run writes no muxed output. A failure post-script still operates if the download fails.
Hand each finished file to an uploaderunshackle dl --postscript \"python /opt/upload.py {filepath} --service={service}\" EXAMPLE 81234567\n
--no-postscript operates the run with no post-script at all. It silences the post_scripts config and --postscript together, for every event and mode.
Skip the uploader for one rununshackle dl --no-postscript EXAMPLE 81234567\n
For post-scripts that continue across runs, for the season and run modes, for failure post-scripts and for the full variable list, see Post-scripts.
"},{"location":"guide/downloading/#naming-tags","title":"Naming tags","text":" --tag: set the release group tag (overrides the configured tag). --repack: add a REPACK tag to the output filename.
Custom group tag and a REPACK labelunshackle dl --tag MYGRP --repack EXAMPLE 81234567\n
"},{"location":"guide/downloading/#proxies","title":"Proxies","text":"--proxy accepts a full proxy URI, a country or location code (resolved through your configured proxy providers), or a provider:region form. See Proxies & VPN for the exact grammar.
Proxy formsunshackle 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
Three related flags:
--no-proxy: force-disable all proxy use for this run. --no-proxy-download: 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. --proxy-download: use a different proxy for all downloads. The manifest, license, and authentication requests still go through --proxy. Takes the same forms as --proxy.
"},{"location":"guide/downloading/#performance-and-caching","title":"Performance and caching","text":"Flag Purpose --workers N Threads used per track for segment downloads. Default depends on the downloader. --adaptive-workers Opt-in: start the per-track worker count at --workers, reduce it when the CDN returns errors, then raise it again while the extra workers add measured throughput. The count never goes above --workers. Off by default (fixed worker count). --download-processes N Opt-in: split a large segment batch across N download processes, each with its own worker pool. A single process tops out around 1.3 Gb/s (Python interpreter limit); 2 reaches 2.5GbE line rate on fast CDNs. Only engages for batches of 24+ segments. Ignored while --speed-limit (or serve's global_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. The download stays in a single process instead of running with the wrong settings. Default 1. --continue-downloads 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 continue_downloads config option, which documents what can and cannot resume. --downloads N Number of tracks downloaded concurrently. Default 1. --slow [MIN-MAX] Add a delay between titles to look more like a real device. --slow alone means 60-120s; --slow 20-40 sets a custom range. Minimum 20s. --no-cache Bypass the title cache for this download. --reset-cache Clear the title cache before fetching. Two tracks at a time, eight threads eachunshackle dl --downloads 2 --workers 8 EXAMPLE 81234567\n
Space out a season downloadunshackle dl -w S01 --slow 30-60 EXAMPLE 81234567\n
"},{"location":"guide/downloading/#keys-vaults-and-export","title":"Keys, vaults, and export","text":"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:
--cdm-only: only use the CDM (skip vaults). Over a server_cdm 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. --cdm <name>: use the named CDM device for this run, ignoring the cdm config mapping (including its quality and Widevine/PlayReady sub-entries). Over --remote, that device licenses the remote session, not the server CDM. --vaults-only: only use key vaults and never license through the CDM. A missing content key fails.
Fetch keys only, no downloadunshackle dl --skip-dl EXAMPLE 81234567\n
--export writes a mediaexport 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. unshackle import 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 version: 2 files and unidl's own export files.
Export track info and keysunshackle dl --skip-dl --export EXAMPLE 81234567\n
Add --all-drm 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 --cdm-only to send a challenge for each DRM system.
License with Widevine and PlayReady, no downloadunshackle dl --skip-dl --all-drm --export EXAMPLE 81234567\n
The file name tells what the file holds, in the form {title}.{scope}.{resolutions}.{codecs}.{ranges}.{manifests}.{audio}-{SERVICE}.json:
Export File name A movie Example.Movie.2024.1080p.h264.sdr.hls.aac2.0-EXAMPLE.json A whole season Example.Show.S01.2160p.h265.sdr.hdr10.dash.dd5.1-EXAMPLE.json Episodes 5 to 9 and 12 Example.Show.S01E05-E09.S01E12.1080p.h264.sdr.dash.aac2.0-EXAMPLE.json - A dot separates each part and each word of the title. The name has no spaces or underscores. It does not follow your
output_template: a template with spaces does not change the export name. - The scope is
S01 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 S01-S03. After three parts, +N counts the parts left out. A movie has no scope. - The quality parts come from the video and audio tracks selected for the titles in the file. Each value shows once.
- 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.
- When another file already has the name, unshackle adds
-2, -3, and so on. It never writes over another export.
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.
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 -a AAC,EC3 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, orig has no value: select the languages with -l and -vl.
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.
The export file is a secret
It holds the content keys and usually a signed manifest URL. Hand it over on purpose, not by accident.
The mediaexport package specifies the mediaexport format and is the reader and writer unshackle uses.
Region is recorded only with a proxy
When you use --proxy, the export records the region so an import can reproduce the correct geofence. Without a proxy, the export stores no region.
Some DASH and Smooth exports need a title language
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 Title.language 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.
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.
"},{"location":"guide/downloading/#metadata-and-tagging","title":"Metadata and tagging","text":"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 --enrich. Give at most one of --tmdb, --imdb and --tvdb, and unshackle works the rest out from it. To stop the automatic lookups but keep the IDs you give, set disable_metadata in your config.
Flag Example Purpose --tmdb --tmdb 27205 Use this TMDB ID instead of an automatic search. Needs tmdb_api_key. --imdb --imdb tt1375666 Use this IMDb ID instead of an automatic search. Needs no API key. --tvdb --tvdb 73871 Use this TVDB ID instead of looking the series up. Needs tvdb_api_key. --anilist --anilist 21 Use this AniList ID instead of an automatic search. mal:12345 is also accepted. Needs no API key. --enrich - Overwrite the show title, year and original language with the external source's. Requires one of --tmdb, --imdb, --tvdb, or --anilist. --tvdb-order --tvdb-order dvd Renumber episodes to a TVDB season order. Needs tvdb_api_key. Force the right IMDb match, and keep the service's own namingunshackle dl --imdb tt1375666 EXAMPLE 81234567\n
Force the match and take IMDb's title, year and language toounshackle dl --imdb tt1375666 --enrich EXAMPLE 81234567\n
"},{"location":"guide/downloading/#what-each-metadata-provider-supplies","title":"What each metadata provider supplies","text":"Metadata providers differ in what they answer with, so the fields --enrich can replace depend on which ID you gave. Every metadata provider except imdb and anilist only operates when you set its config key:
Provider Config key Title and year Original language External IDs it returns TMDB tmdb_api_key yes yes, alpha-2 such as ko IMDb, TMDB, TVDB TVDB tvdb_api_key yes yes, alpha-3 such as kor TMDB, TVDB, sometimes IMDb OMDb omdb_api_key yes yes, as an English name such as Korean IMDb IMDb (no config key needed) yes yes, alpha-2 such as ko IMDb SIMKL simkl_client_id 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 ja AniList Whatever the tag looks like, unshackle normalises it before use, so ko, kor and Korean all end up as the same language.
AniList only answers for anime
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 anilist earlier in metadata_providers if you mostly download anime. anilist_title_language sets which of the three AniList title variants unshackle uses.
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.
Each ID goes to the providers that read that kind of ID, in metadata_providers order:
--tmdb reads TMDB. --imdb 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. --tvdb reads TVDB. It needs tvdb_api_key. --anilist 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 --tmdb, --imdb or --tvdb when you want those tags as well.
Give one of --tmdb, --imdb and --tvdb. 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. --anilist is the exception and still pairs with one of the three, which is how you tag an anime title with a western ID.
The ID you give must have a metadata provider that can find it, so unshackle makes sure of that before it downloads anything. --tmdb without tmdb_api_key, or an ID whose metadata providers your metadata_providers list leaves out, fails immediately with a message naming what to set. --imdb needs no API key, because the imdb metadata provider is keyless and in the default order.
With --enrich, 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.
--enrich 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 {absolute} naming variable. --enrich never changes the season and episode numbers.
With --daily, --enrich also fills in the air date of each episode from TVDB. See Daily and date-based content.
--enrich replaces the original language, which affects more than the filename
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 --enrich, unshackle keeps the service's own value and does not change track selection.
"},{"location":"guide/downloading/#episode-ordering","title":"Episode ordering","text":"A service does not always number a series the way TVDB's aired order does. Some services use TVDB's alternate (Streaming) order for Futurama, for example, while TVDB's official order holds back four season-one episodes to the start of season two. --tvdb-order works out which order the service used, then renumbers the episodes into the order you asked for:
Download Futurama in DVD orderunshackle dl --tvdb-order dvd EXAMPLE 81234567\n
Available orders are official (aired), dvd, absolute, alternate, and regional. Set tvdb_order in your config to apply one by default.
Orders that do not cover the whole series
An order can leave out episodes the service carries. TVDB's dvd 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.
"},{"location":"guide/downloading/#configuration-defaults","title":"Configuration defaults","text":"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 dl: block and per-service overrides.
Explicit flags always win
A value you pass on the command line (or through an environment variable) always takes precedence over both the global dl: defaults and any per-service dl: overrides. Config only fills in options you did not set explicitly.
"},{"location":"guide/downloading/#quick-reference","title":"Quick reference","text":"A condensed lookup of the most-used options. Use unshackle dl --help for the complete, authoritative list.
Flag Short Meaning --quality -q Target resolution(s), e.g. 1080,720. --vcodec -v Video codec(s). --acodec -a Audio codec(s). --range -r Colour range(s). Default SDR. --channels -c Audio channel layout. --noatmos -naa Exclude Atmos audio. --lang -l Video + audio language(s); default orig. - excludes, e.g. all,-es. --a-lang -al Audio-only language override. - excludes. --v-lang -vl Video-only language override. - excludes. --s-lang -sl Subtitle language(s); default all. - excludes, e.g. all,-es. --forced-subs -fs Include forced subtitles. --forced-s-lang -fsl Forced subtitle language(s); implies -fs. - excludes. --sub-format Output subtitle format. --wanted -w Episode/season range, an air date, or a track number for a music release (1-5, 2x3). --daily Fill missing air dates from TVDB during --enrich. --select-titles Interactively pick episodes or films. --latest-episode Only the newest episode. --latest-episodes N Only the N newest episodes. --video-only / --audio-only / --subs-only -V / -A / -S Restrict track types. --no-video / --no-audio / --no-subs / --no-chapters / --no-attachments -nv / -na / -ns / -nc / -nt Skip track types. --worst Lowest bitrate within -q. --require-audio Audio languages that must exist. The title fails if one is missing. --require-video Video languages that must exist. The title fails if one is missing. --best-available Degrade gracefully instead of failing. --output -o Output directory for this run. --split-audio / --merge-video / --no-mux Muxing behaviour. --postscript / --no-postscript Run a command after each output file, or run none. --proxy / --no-proxy / --no-proxy-download / --proxy-download Proxy control. --workers / --downloads / --slow Concurrency and pacing. --list / --list-titles / --skip-dl Dry runs. --cdm-only / --vaults-only Content key source control. --cdm <name> Pin one CDM device, bypassing the cdm config mapping. --export Export track info and keys to JSON. --tmdb / --imdb / --tvdb / --anilist / --enrich Metadata overrides. --tvdb-order Renumber episodes to a TVDB season order."},{"location":"guide/drm-and-cdm/","title":"DRM & CDM Setup","text":"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.
Who this page is for
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.
"},{"location":"guide/drm-and-cdm/#key-concepts","title":"Key concepts","text":"Before configuring anything, it helps to know the vocabulary. unshackle draws a firm line between two things:
- 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.
- 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.
A handful of other terms show up throughout:
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. 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.
"},{"location":"guide/drm-and-cdm/#supported-drm-systems","title":"Supported DRM systems","text":"unshackle implements five DRM systems. Only the first two need a device file and a license-server handshake. The rest are special cases.
System Device file License flow Decryption Widevine (Google) .wvd CDM challenge \u2192 license server \u2192 CDM parses \u2192 keys shaka-packager / mp4decrypt PlayReady (Microsoft) .prd CDM challenge (WRM header) \u2192 license server \u2192 CDM parses \u2192 keys shaka-packager / mp4decrypt ClearKey (CENC), W3C EME org.w3.clearkey none JSON {\"kids\":[...],\"type\":\"temporary\"} \u2192 license server returns a JWK Set. No CDM. shaka-packager / mp4decrypt ClearKey (HLS), AES-128 EXT-X-KEY none Key fetched directly from a URI or data: URL. No CDM, no challenge. in-process AES-CBC MonaLisa (proprietary, WASM) .mld Ticket from the service API; keys extracted locally via WASM. No license server. ML-Worker binary + AES-ECB, per segment Two different ClearKeys
\"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 EXT-X-KEY tag references, and unshackle decrypts it in-process. The CENC variant is the W3C EME org.w3.clearkey scheme. It delivers keys as a JWK Set, and shaka-packager or mp4decrypt decrypts it like Widevine. Neither involves a device file.
"},{"location":"guide/drm-and-cdm/#widevine-vs-playready","title":"Widevine vs PlayReady","text":"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:
- Device file: Widevine uses a
.wvd. PlayReady uses a .prd. - 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).
To download a Widevine-protected title you need a .wvd device. For PlayReady you need a .prd device. You can hold both, and unshackle automatically selects the appropriate one for each track.
Obtaining device files
A .wvd or .prd 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 wvd and prd commands below manage and provision device files once you have the raw cryptographic material.
"},{"location":"guide/drm-and-cdm/#providing-a-device-with-the-wvd-and-prd-commands","title":"Providing a device with the wvd and prd commands","text":"Device files live in dedicated directories, by default:
Kind Default directory Widevine .wvd data/WVDs PlayReady .prd data/PRDs You can move these with the directories section of your unshackle.yaml:
unshackle.yamldirectories:\n wvds: /home/george/unshackle-data/WVDs\n prds: /home/george/unshackle-data/PRDs\n
"},{"location":"guide/drm-and-cdm/#widevine-devices-the-wvd-command","title":"Widevine devices: the wvd command","text":"The wvd command group manages .wvd files.
Add an existing deviceInspect a deviceCreate from raw materialDelete / dump $ unshackle wvd add ./nexus_6p.wvd\n
unshackle validates the file and moves it into the WVDs directory. You can add several at once by passing multiple paths.
$ unshackle wvd parse nexus_6p\n
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.
$ unshackle wvd new \"Nexus 6P\" ./private_key.pem ./client_id.bin ./vmp.bin -t ANDROID -l 3\n
Builds a .wvd from a PEM private key, a Client ID blob, and an optional FileHashes (VMP) blob. -t/--type is the device type (default Android) and -l/--level is the security level 1 to 3 (default 1). The VMP argument is optional.
$ unshackle wvd delete nexus_6p\n$ unshackle wvd dump nexus_6p ./out\n
delete removes a device (with a confirmation prompt). dump extracts a device's contents (metadata, private key, Client ID, VMP) into a folder.
v1 WVD files must be migrated
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:
$ pywidevine migrate --help\n
"},{"location":"guide/drm-and-cdm/#playready-devices-the-prd-command","title":"PlayReady devices: the prd command","text":"The prd command group creates and maintains .prd files.
Create a new deviceReprovisionTest against Microsoft's demo server $ unshackle prd new ./zgpriv.dat ./bgroupcert.dat\n
Provision a new device from a group key and group certificate. You can instead point at a single folder that contains zgpriv.dat and bgroupcert.dat:
$ unshackle prd new ./device_folder/\n
unshackle makes a fresh leaf certificate and writes the device to the PRDs directory (or to -o/--output). Use -e/--encryption_key and -s/--signing_key to supply your own ECC keys instead of generating them.
$ unshackle prd reprovision ./data/PRDs/mydevice.prd\n
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).
$ unshackle prd test ./data/PRDs/mydevice.prd -sl 2000 -c aesctr\n
Runs a full challenge/license/keys cycle against Microsoft's public PlayReady test server and prints the returned keys, confirming the device works. -sl/--security-level accepts 150, 2000, or 3000 (default 2000). -c/--ckt accepts aesctr or aescbc.
"},{"location":"guide/drm-and-cdm/#selecting-which-device-to-use-the-cdm-config","title":"Selecting which device to use: the cdm config","text":"A device on disk is not enough. You must tell unshackle which device to use for which service. That is the job of the cdm section, which maps a service tag to a device name (the file's name without extension). A default entry acts as the fallback:
unshackle.yamlcdm:\n default: nexus_6p_26830_l3\n EXAMPLE1: chromecdm_l3\n EXAMPLE2: sm_g935f_l1\n
Lookups are case-insensitive.
The device name is the file name
A device named chromecdm_l3 in the config resolves to chromecdm_l3.wvd in the WVDs directory (or chromecdm_l3.prd in the PRDs directory). It may also be the name of a remote CDM defined in remote_cdm. See Remote CDMs below.
"},{"location":"guide/drm-and-cdm/#advanced-selection-by-quality-drm-or-profile","title":"Advanced selection: by quality, DRM, or profile","text":"Instead of a plain name, a cdm 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.
By qualityBy DRM systemBy profile unshackle compares each config key against the video height. You can use exact heights or comparisons (>=1080, >720, <=576, <480). The most specific one wins.
cdm:\n SOMESERVICE:\n \">=1080\": sm_g935f_l1\n default: chromecdm_l3\n
Keys widevine and playready select a device per system. unshackle applies these automatically, using the widevine device for Widevine tracks and the playready device for PlayReady tracks.
cdm:\n SOMESERVICE:\n widevine: sm_g935f_l1\n playready: mydevice_sl3\n
unshackle compares each config key against the active profile, with a default fallback.
cdm:\n SOMESERVICE:\n premium: sm_g935f_l1\n default: chromecdm_l3\n
"},{"location":"guide/drm-and-cdm/#local-vs-remote-cdms","title":"Local vs remote CDMs","text":"A CDM can operate in two places:
- A local CDM loads a
.wvd or .prd device from your machine and performs the challenge/license/keys handshake locally. This is what the cdm mapping above resolves to by default. - 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.
The device name in your cdm mapping resolves to a remote CDM whenever it matches the name of an entry in the remote_cdm list. Otherwise it falls back to a local .prd/.wvd file of that name.
"},{"location":"guide/drm-and-cdm/#remote-cdms","title":"Remote CDMs","text":"You declare remote CDMs as a list under remote_cdm. Each entry has a name (which you then reference from the cdm mapping) and a shape that depends on its type. There are four kinds.
"},{"location":"guide/drm-and-cdm/#widevine-remote-cdm-pywidevine-serve","title":"Widevine remote CDM (pywidevine serve)","text":"With no type field and a non-PlayReady device type, unshackle treats the entry as a standard pywidevine \"serve\" endpoint:
unshackle.yamlremote_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
security_level defaults to 3000 if omitted. unshackle reads field names case-insensitively, so Device Type/device_type, System ID/system_id, and the other field names are all accepted.
"},{"location":"guide/drm-and-cdm/#playready-remote-cdm","title":"PlayReady remote CDM","text":"If the device type is PLAYREADY, unshackle routes the entry to the pyplayready remote CDM:
unshackle.yamlremote_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
The host must end in /playready
For a PlayReady remote CDM the host URL has to include the trailing /playready path segment (e.g. https://cdm.example.com/playready). pyplayready's RemoteCdm treats host 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 404 responses from the server rather than an obvious configuration error.
A pywidevine or pyplayready serve API can operate behind a reverse proxy or a CDN. Refer to Serve APIs behind a proxy.
"},{"location":"guide/drm-and-cdm/#decrypt-labs-hosted-keyxtractor-api","title":"Decrypt Labs (hosted KeyXtractor API)","text":"Set type: decrypt_labs to use Decrypt Labs' hosted KeyXtractor service, which includes an intelligent key-caching layer:
unshackle.yamlremote_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
unshackle sends the API key as the decrypt-labs-api-key header. If you do not write secret on the entry, unshackle falls back to the global decrypt_labs_api_key value. If neither is present it raises an error. The host defaults to https://keyxtractor.decryptlabs.com. PlayReady devices (SL2/SL3) default to security level 2000/3000 respectively. Widevine devices default to system_id: 26830, security_level: 3.
"},{"location":"guide/drm-and-cdm/#custom-api-custom_api","title":"Custom API (custom_api)","text":"For an arbitrary CDM HTTP API, type: custom_api provides a fully configurable client that adapts to almost any request/response shape through YAML alone. A minimal example:
unshackle.yamlremote_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
The custom_api type supports much more: request/response field remapping, transforms (base64/hex/JSON encoding, kid:key 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.
Developer: full custom_api schema
A custom_api entry accepts these sub-objects:
device (name, type, system_id, security_level) auth (type of header/bearer/basic with the matching credential fields, plus custom_headers) endpoints (get_request and decrypt_response, each {path, method, timeout}) - per-endpoint
request_mapping (param_names, static_params, conditional_params, transforms, nested_params, exclude_params) and response_mapping (fields, transforms, response_types, success_conditions, error_fields, key_fields) caching (enabled, use_vaults, check_cached_first) legacy and timeout
unshackle infers PlayReady mode when device.type == PLAYREADY or the device name is SL2/SL3.
"},{"location":"guide/drm-and-cdm/#decryption-backends","title":"Decryption backends","text":"Once unshackle knows the content keys, one of two external tools decrypts the encrypted file (for Widevine, PlayReady, and ClearKey-CENC):
- shaka-packager is the default.
- mp4decrypt is part of the Bento4 tools.
Both must be discoverable in unshackle's bundled binaries/ directory, the binaries folder of your user data directory, or on your PATH. 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.
You choose the backend with the decryption config key. It can be a single value applied globally, or a per-service mapping:
Global defaultPer service unshackle.yamldecryption: shaka\n
unshackle.yamldecryption:\n default: shaka\n SOMESERVICE: mp4decrypt\n
How the value is interpreted
The default is shaka. Only the exact value mp4decrypt selects mp4decrypt. Anything else (including shaka) selects shaka-packager. Per-service lookups are case-insensitive, with the default/DEFAULT entry used as the fallback.
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 mp4decrypt if you find a track that shaka-packager cannot decrypt.
ClearKey (HLS) does not use these tools
unshackle decrypts an HLS AES-128 ClearKey title in-process with AES-CBC, and ignores the decryption setting entirely. You do not need to configure anything.
"},{"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":"When an HLS playlist references a content key with an EXT-X-KEY tag, unshackle fetches the content key directly (from the given URI or an inline data: 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.
"},{"location":"guide/drm-and-cdm/#clearkey-over-cenc-w3c-eme-orgw3clearkey","title":"ClearKey over CENC (W3C EME org.w3.clearkey)","text":"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:
{\"kids\": [\"<base64url-kid>\", ...], \"type\": \"temporary\"}\n
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 decryption setting applies.
"},{"location":"guide/drm-and-cdm/#widevine-and-playready-on-the-same-title","title":"Widevine and PlayReady on the same title","text":"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 cdm mapping. If it cannot find a matching device, it fails with a clear message such as:
Title needs a Widevine CDM but SOMESERVICE is configured with PlayReady.\n
Use the cdm mapping's DRM-based selection to configure a device for each system. unshackle selects the right one per track automatically.
"},{"location":"guide/drm-and-cdm/#license-both-systems-with-all-drm","title":"License both systems with --all-drm","text":"By default a track licenses with one DRM system. --all-drm gets the content keys for Widevine and for PlayReady on each track that offers both. Use it with --skip-dl and --export 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.
unshackle dl --skip-dl --all-drm --export EXAMPLE 81234567\n
- The
cdm mapping must name a device for each system. A single device name, or --cdm, stops the run with an error that names the missing system. - The order of the
widevine and playready config keys in the cdm 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. - 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.
- With
--cdm-only, unshackle does not read the Key Vaults, and each DRM system sends one challenge for a set of KIDs in a run. - 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.
- If one DRM system does not license, the title fails. With
--best-available 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. - 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.
- With
--cdm-only, the service gets a challenge from each DRM system for each set of KIDs. A licence server that limits the request rate can answer 429, and unshackle then tries again.
Where --all-drm licenses one system only
- A service that gets a different manifest for each DRM system. unshackle shows a warning one time when a track offers one system only.
- 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
--best-available. - An HLS playlist that changes its
EXT-X-KEY entries part-way: only the first set licenses with the second system. - A remote session that the server CDM licenses, and
unshackle import. unshackle shows a warning and ignores the flag. - A remote CDM that stores content keys can answer without a challenge to the service.
"},{"location":"guide/drm-and-cdm/#keys-vaults-and-caching","title":"Keys, vaults, and caching","text":"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:
- Keys already known for the current DRM object.
- An in-process cache of content keys, for the current
dl run. - Your configured key vaults.
- Only if still missing, a live license request.
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 dl command:
Flag Effect --vaults-only Never send a license request; use only cached/vault keys. Fails if a content key is missing. --cdm-only Ignore vaults for sourcing keys and always perform a fresh license request. Over a server_cdm remote session the server still reads its own vaults; the flag only skips the client's decode check on the key it gets back. --cdm <name> Use the named CDM device for this run instead of the one the cdm config maps for the service. Over --remote, that device licenses the remote session, not the server CDM. See key vaults for how to configure vault backends.
"},{"location":"guide/drm-and-cdm/#debugging-drm-issues","title":"Debugging DRM issues","text":"A few configuration toggles help when a title will not decrypt:
Config key Default Effect debug false Global debug output. debug_keys false Log decryption keys. debug_requests false Log HTTP requests. unshackle.yamldebug_keys: true\ndebug_requests: true\n
Keys and paths in logs
When you enable key logging, unshackle writes content keys (KID:key pairs) to the logs. Treat those logs as sensitive. The unrelated redact_paths option (default true) masks local directory paths in log output.
"},{"location":"guide/drm-and-cdm/#see-also","title":"See also","text":" - Downloading: the
dl command and its DRM-related flags. - Key vaults: caching content keys across downloads.
- Configuration: the full
unshackle.yaml reference. - Dependencies: installing shaka-packager and mp4decrypt.
"},{"location":"guide/output-and-naming/","title":"Output & Naming","text":"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 {variable} 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.
If you have not configured unshackle.yaml yet, read Configuration File first. Everything below lives in that file.
"},{"location":"guide/output-and-naming/#how-unshackle-assembles-an-output-path","title":"How unshackle assembles an output path","text":"When a download finishes, unshackle builds the final path from three pieces:
<output directory> / <folder template> / <filename template><extension>\n
- Output directory:
directories.downloads from your config, or whatever you pass to -o/--output on the command line for a single run. - 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
movies folder template, or a single-string folder template that applies to all title kinds (see Folder templates). - Filename template: the
output_template for the title kind (movie, series, or song). - Extension: chosen by the muxer for a movie or an episode:
.mkv for video, .mka for audio-only, .mks for subtitle-only, .mp4 for DTS:X Profile 2 audio. unshackle does not mux a song. It remuxes a song into the container of its codec, such as .flac, .opus, or .m4a. Read Music output files.
A typical episode path
/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
The folder name comes from the series folder template and the file from the series output template. Two command-line flags change this layout for a single run:
Flag Effect -o, --output Use this directory instead of directories.downloads. --no-folder Skip the per-title subfolder; write the file directly into the output directory. --no-source Omit the service source tag from both the filename and folder (the {source} variable resolves to empty)."},{"location":"guide/output-and-naming/#output-templates","title":"Output templates","text":"Filename templates live under the output_template config key, keyed by title kind. Each value is a format string built from {variable} placeholders.
unshackle.yamloutput_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
The recognized kinds are:
Kind Applies to Default when unset movies Movies (required for movie downloads to be named, no built-in default) series TV episodes (required for episode downloads to be named) songs Music tracks \"{track_number}. {title}\" albums Album folders only (see below) - Note
movies and series have no hardcoded filename fallback. If you download those title types, define their templates. songs falls back to \"{track_number}. {title}\" when omitted.
"},{"location":"guide/output-and-naming/#required-vs-optional-variables","title":"Required vs. optional variables","text":" {variable}: 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\". {variable?}: optional. A trailing ? marks the variable conditional. When it is empty, unshackle removes the placeholder and one adjacent separator (., -, or space), so the surrounding text collapses cleanly.
Use ? for anything that is not always there
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:
series: \"{title}.{season_episode}.{episode_name?}.{quality}.{hdr?}.{source}-{tag?}\"\n
For an episode with no on-screen name, {episode_name?} and its adjacent dot disappear."},{"location":"guide/output-and-naming/#separator-style-dots-vs-spaces","title":"Separator style (dots vs. spaces)","text":"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.
Scene style (dots)Readable style (spaces) output_template:\n movies: \"{title}.{year}.{quality}.{source}.WEB-DL.{audio_full}.{video}-{tag}\"\n
The.Movie.2024.1080p.EXAMPLE.WEB-DL.DDP5.1.H.264-TAG.mkv\n
output_template:\n movies: \"{title} ({year}) {quality} {source} WEB-DL {audio_full} {video}\"\n
The Movie (2024) 1080p EXAMPLE WEB-DL DDP5.1 H.264.mkv\n
"},{"location":"guide/output-and-naming/#template-variables","title":"Template variables","text":"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.
"},{"location":"guide/output-and-naming/#common-video","title":"Common / video","text":"Variable Meaning Example title Title name (movie/show/song name; $ is rendered as S) The Show title_type Media kind of the title movie, series, music year Release year 2024 source Service tag / class name (empty with --no-source) EXAMPLE quality Resolution with scan suffix 1080p, 2160p, 576i resolution Resolution number only 1080 video Video codec H.264, H.265 hdr Dynamic-range label HDR, HDR10P, DV, DV.HDR, DV.HDR10P, HLG hfr High frame rate marker (frame rate > 30) HFR edition Edition label from the track, if any Directors Cut tag Release-group tag (from config.tag or --tag) TAG repack REPACK when the --repack flag is used REPACK lang_tag Result of your language_tags rules, if configured MULTi How language_tags rules match
unshackle tries the rules in order, but language comparison is fuzzy: a rule condition of en matches en-US, en-GB, and any other en-* form. Within a single rule, all conditions must match (AND logic) for it to apply. The first rule that fully matches wins. If none match, unshackle removes {lang_tag?} from the filename cleanly.
"},{"location":"guide/output-and-naming/#episode-specific","title":"Episode-specific","text":"Variable Meaning Example season Zero-padded season (S%02d) S01 episode Zero-padded episode (E%02d) E05 season_episode Combined S01E05 episode_name Episode title Pilot part Part index of a split episode, empty otherwise 2 absolute Absolute episode number, zero-padded to 3 digits, empty when unknown 007 date ISO air date, empty when the episode has none 2024-06-01 Daily & sports content
When an episode has an air date, unshackle switches to date-based naming automatically. season and season_episode become the formatted air date, unshackle clears episode and year, and {date} holds the ISO date. The date's internal separator (dots or spaces) follows your series template style.
"},{"location":"guide/output-and-naming/#split-episodes","title":"Split episodes","text":"A few services split one episode into several separately playable videos. Where a service reports that, unshackle folds the part index into {episode} and {season_episode}, so the stock series template names it with no change to your config.
Show.Name.S01E01.Part.2.1080p.EXAMPLE.WEB-DL.DDP5.1.H.264-TAG.mkv\n
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 S01E01 Part 2 instead.
The part is left out of the folder name, so every part of an episode lands in the same season folder:
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
The same holds for a folder template of your own: {season} never picks up the part, and {season_episode} drops it inside a folder template. unshackle names an episode with no part like any other episode.
What media servers do with the part token
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.
For custom templates there is also a standalone {part} variable. You rarely want it, see the caveat on that page.
"},{"location":"guide/output-and-naming/#audio","title":"Audio","text":"Variable Meaning Example audio Audio codec DDP, DD, AAC, DTS-X audio_channels Channel layout; bed.LFE.heights when the track has height channels 5.1, 2.0, 5.1.4 audio_full Codec + channels combined DDP5.1, DTS-X.5.1.4 atmos Atmos when any track carries JOC Atmos dual DUAL for two audio languages (see dual_multi_mode) DUAL multi MULTi for more than two audio languages MULTi dubbed DUBBED for a single audio language that is not the original (strict mode only) DUBBED"},{"location":"guide/output-and-naming/#music-specific","title":"Music-specific","text":"Variable Meaning track_number Zero-padded track number artist / album_artist Artist / album artist (falls back to artist) album Album name disc Disc number (only shown when greater than 1) track_total / disc_total Totals release_type album, single, ep, or another type the service supplies genre Genre explicit Explicit when flagged isrc / upc / label ISRC, UPC and record label Unknown variables are ignored, not errors
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 {quailty} stays in the filename literally, or unshackle drops it. unshackle does not fill it in.
"},{"location":"guide/output-and-naming/#folder-templates","title":"Folder templates","text":"Folder templates sit under a special folder config key inside output_template. 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.
Single folder templatePer-kind folder templates unshackle.yamloutput_template:\n movies: \"{title}.{year}.{quality}.{source}-{tag}\"\n series: \"{title}.{season_episode}.{quality}.{source}-{tag}\"\n folder: \"{title}.{year}\"\n
unshackle.yamloutput_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
The per-kind folder config keys are movies, series, songs, and albums. Any other config key gives a startup warning. Folder templates permit path separators (/ or \\). unshackle formats each segment independently, so you can assemble nested directory structures like Show/Season 01. unshackle reads the separator style from the whole template, so it spaces every segment alike.
Fallback behaviour:
- A per-kind folder template wins if present. If there is none, unshackle uses the single
folder string. If there is no folder string either, unshackle falls back to a built-in default. - Built-in defaults when no folder template is set. Movies get no folder at all unless a
movies folder template (or a single-string folder template) exists. Series fall back to a folder derived from the series output template (stripping {episode}, {episode_name}, and collapsing {season_episode} down to {season}). Music albums fall back to {artist} - {album} ({year}). If the song has no year, the folder name is only {artist} - {album}.
Movies are flat by default
Episodes and songs are always foldered. unshackle writes movies directly into the output directory unless you define a movies folder template (or a single-string folder template, which folders every kind). Set one if you want each movie in its own directory.
"},{"location":"guide/output-and-naming/#music-output-files","title":"Music output files","text":"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.
Codec Extension FLAC .flac Opus .opus Vorbis .ogg AAC, ALAC, and all other codecs .m4a 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.
unshackle writes no .mkv file for music, and the muxing options below do not apply.
The songs output template names the file. The albums folder template names the folder around it.
/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
"},{"location":"guide/output-and-naming/#music-metadata","title":"Music metadata","text":"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 tag and tag_group_name are set, unshackle also writes the group name into a GROUP tag.
unshackle embeds cover art when the service gives an artwork URL. It downloads the image and puts it in the file.
unshackle writes lyrics when the service supplies them: a LYRICS Vorbis comment for FLAC, a USLT frame for MP3, and a \u00a9lyr atom for M4A. Ogg uses the same LYRICS field as FLAC. unshackle does not write synchronized lyrics (SYLT).
A metadata fault does not stop the run. The file is already in place, so unshackle writes a warning and continues.
--no-mux leaves music files untagged
--no-mux 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.
"},{"location":"guide/output-and-naming/#muxing-options","title":"Muxing options","text":"Height channels
A track with height channels is named bed.LFE.heights, such as 5.1.4.
"},{"location":"guide/output-and-naming/#dtsx-profile-2-output","title":"DTS:X Profile 2 output","text":"A title whose audio holds a dtsx or dtsy sample entry (DTS:X Profile 2, DTS-UHD) muxes to MP4 with MP4Box, because Matroska has no CodecID for it. Without MP4Box installed the mux stops.
DTS:X Profile 1 is DTS-HD Master Audio and muxes to MKV as usual.
An MP4 title loses:
- the forced, hearing-impaired and original track flags
- attachments, such as subtitle fonts
- SubStation Alpha (
.ass) subtitles - container tags (
mkvpropedit)
You configure muxing (the combination of video, audio, subtitle, chapter and attachment tracks into a single Matroska file with mkvmerge) under the muxing config key. unshackle muxes only movies and episodes. Read Music output files for what a music download does instead.
unshackle.yamlmuxing:\n set_title: true\n merge_video: false\n merge_audio: true\n default_language:\n audio: en\n subtitle: en\n
Key Type Default Effect set_title bool true Write the title name into the MKV container title with --title. Set to false to omit it. merge_video bool false Group video tracks that share the same resolution, range, and codec into one file so only language varies inside it. merge_audio bool true Merge audio tracks of the same kind so multiple languages sit in one file. default_language map (unset) Preferred language per track type (video / audio / subtitle). A track in the preferred language is flagged as the default track. 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.
default_language only sets the default-track flag
default_language controls which track carries the MKV --default-track flag. Nothing else. It does not change track selection (that stays with -l/--a-lang and friends). It also does not touch which track carries the original flag: --original-flag 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.
merge_video collapses only the language dimension
merge_video groups video tracks by (resolution, range, codec) 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 -r HYBRID,DV,HDR10,SDR --merge-video 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. merge_audio works the same way for audio languages.
A few muxing behaviors are automatic and not configurable:
--no-date is always passed for privacy (no timestamps embedded). - Descriptive audio gets the visually-impaired flag. SDH subtitles get the hearing-impaired flag. Forced subtitles get the forced flag.
- unshackle writes the chapters from the title's chapter list (see Chapters below).
The --no-mux flag skips muxing entirely and writes the individual track files, each with a track-type suffix, into the same output/folder structure.
"},{"location":"guide/output-and-naming/#sample-files","title":"Sample files","text":"--sample and --include-sample write a sample into a Sample folder inside the output folder of the title. The sample keeps the filename of the title, with a SAMPLE tag at the end. The tag uses the separator of the output template.
A movie with --include-sampleSome.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
With --sample, the Sample folder holds the only output file. If the run makes no title folder, the Sample folder is in the downloads directory.
"},{"location":"guide/output-and-naming/#tags-group-naming","title":"Tags & group naming","text":"The release-group tag is the -TAG portion at the end of scene-style names, which the {tag} variable gives. You can swap it per release with tag_rules: ordered rules whose conditions read the release-attribute variables only (quality, resolution, hdr, source, lang_tag, title_type, and so on), and the first rule that matches wins. tag_rules cannot read the title's own fields, such as title and season_episode. See the reference page for the exact list.
unshackle.yamltag: \"MYGROUP\"\ntag_group_name: true\ntag_imdb_tmdb: true\n
Key Type Default Effect tag str \"\" The release-group tag used for {tag}. tag_group_name bool true Write the group name (config.tag) into the MKV Group metadata tag. tag_imdb_tmdb bool true Look up and embed IMDb / TMDB / TVDB external-ID tags in the MKV metadata (uses tmdb_api_key / tvdb_api_key / simkl_client_id when available). unshackle writes the IDs as the Matroska IMDB, TMDB, and TVDB2 tags. TVDB2 values carry the entity prefix the Matroska tagging spec requires: series/73871 for a show, movies/113 for a film.
You can override the tag per run without editing config:
unshackle dl --tag OTHERGROUP EXAMPLE \"...\"\n
The --repack flag adds the REPACK marker (surfaced through the {repack} variable) to the filename for that run:
unshackle dl --repack EXAMPLE \"...\"\n
Empty tags collapse cleanly
If config.tag is empty and your template ends with -{tag?}, the trailing - and the placeholder are both removed. Use the optional form {tag?} if you sometimes download without a tag set.
"},{"location":"guide/output-and-naming/#unicode-filenames","title":"Unicode filenames","text":"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 unicode_filenames to keep the native characters.
unshackle.yamlunicode_filenames: true\n
Value Result false (default) \uae30\uc0dd\ucda9 \u2192 transliterated ASCII; accents stripped. true Native characters preserved in filenames and folders, with the vowel and tone marks of languages such as Thai, Hindi and Bengali. 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.
Regardless of this setting, unshackle always removes or replaces a set of filesystem-unsafe and structural characters during sanitisation. For example, / and ; become &, and unshackle removes characters like \\ * ! ? , ' \" < > | $ # ~. This is why you must never put path-unsafe characters directly in a template.
unshackle warns at startup about a template that contains < > : \" / \\ | ? *. It examines a folder template per path segment, so you can use / there as a directory separator.
"},{"location":"guide/output-and-naming/#directory-filename-configuration","title":"Directory & filename configuration","text":"The directories 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.
unshackle.yamldirectories:\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
Name Purpose downloads Default output directory for finished files. temp Working directory for in-progress downloads, muxing, and intermediate files. cache Title/HTTP cache and update-check state. cookies Per-service cookie files. logs Log files. exports Export JSONs. services, vaults, fonts, commands Search paths for services, key-vault backends, bundled fonts, and CLI commands. wvds, prds, dcsl Widevine devices, PlayReady devices, and DCSL data. Paths can hold a ~ for expansion. unshackle protects the names app_dirs, core_dir, namespace_dir, user_configs, and data, so you cannot change them.
"},{"location":"guide/output-and-naming/#filename-patterns","title":"Filename patterns","text":"The filenames 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.
unshackle.yamlfilenames:\n log: \"unshackle_{name}_{time}.log\"\n chapters: \"Chapters_{title}_{random}.txt\"\n subtitle: \"Subtitle_{id}_{language}.srt\"\n
Name Default Where log unshackle_{name}_{time}.log directories.logs debug_log unshackle_debug_{service}_{time}.jsonl directories.logs config config.yaml per-service directory root_config unshackle.yaml main config filename chapters Chapters_{title}_{random}.txt directories.temp subtitle Subtitle_{id}_{language}.srt directories.temp"},{"location":"guide/output-and-naming/#chapters-naming","title":"Chapters naming","text":"When a title has chapters, unshackle writes them to an OGM chapters file (filenames.chapters) and passes it to the muxer. Unnamed chapters use the chapter_fallback_name template:
unshackle.yamlchapter_fallback_name: \"Chapter {i:02}\"\n
The fallback can hold two placeholders: {i} (chapter number, starting at 1) and {j} (which increments only for unnamed chapters). It permits standard format directives like {i:02}.
"},{"location":"guide/output-and-naming/#removed-migrated-options","title":"Removed & migrated options","text":"scene_naming was removed
The old scene_naming option no longer exists. If it is present in your config, unshackle exits immediately with an error asking you to configure output_template instead. Migrate any scene-naming setup to the templates described on this page.
"},{"location":"guide/output-and-naming/#worked-examples","title":"Worked examples","text":"Each tab shows a template and what it produces for a few different downloads, so you can see how the optional (?) variables appear and disappear.
MoviesTV seriesMulti-languageDaily showsMusic output_template:\n movies: \"{title}.{year}.{edition?}.{quality}.{source}.WEB-DL.{audio_full}.{atmos?}.{video}.{hdr?}-{tag?}\"\n folder:\n movies: \"{title} ({year})\"\n
A 4K Atmos HDR download fills every placeholder:
The Movie (2024)/\n \u2514\u2500 The.Movie.2024.2160p.EXAMPLE.WEB-DL.DDP5.1.Atmos.H.265.HDR-TAG.mkv\n
The same template on a plain 1080p SDR stereo download, where {edition?}, {atmos?} and {hdr?} collapse along with their dots:
The Movie (2024)/\n \u2514\u2500 The.Movie.2024.1080p.EXAMPLE.WEB-DL.AAC2.0.H.264-TAG.mkv\n
A director's cut fills {edition?}:
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
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
The Show (2023)/Season S02/\n \u2514\u2500 The.Show.S02E04.The.Reckoning.2160p.EXAMPLE.WEB-DL.DDP5.1.H.265-TAG.mkv\n
unshackle decides the separator style once for the whole folder template, and every segment then follows it. Spaces outnumber dots in {title} ({year})/Season {season}, so Season {season} keeps its space even though it holds only one variable.
When an episode has no on-screen name, {episode_name?} disappears cleanly:
The Show (2023)/Season S02/\n \u2514\u2500 The.Show.S02E05.2160p.EXAMPLE.WEB-DL.DDP5.1.H.265-TAG.mkv\n
Place {dual?}, {multi?} and {dubbed?} next to each other. At most one of them is ever set (see dual_multi_mode), and the empty ones collapse:
output_template:\n movies: \"{title}.{year}.{quality}.{source}.WEB-DL.{dual?}.{multi?}.{dubbed?}.{audio_full}.{video}-{tag}\"\n
Original English audio plus a French dub (-l en,fr):
The.Movie.2024.1080p.EXAMPLE.WEB-DL.DUAL.DDP5.1.H.264-TAG.mkv\n
Original plus several dubs (-l en,fr,de,es):
The.Movie.2024.1080p.EXAMPLE.WEB-DL.MULTi.DDP5.1.H.264-TAG.mkv\n
Only a dub, original audio left out (-l de on an English-original title):
The.Movie.2024.1080p.EXAMPLE.WEB-DL.DUBBED.DDP5.1.H.264-TAG.mkv\n
Two dialects of one language (en-US + en-GB) count as a single language, so none of the three variables is set:
The.Movie.2024.1080p.EXAMPLE.WEB-DL.DDP5.1.H.264-TAG.mkv\n
For finer control (for example a SUBBED tag driven by subtitle languages), use {lang_tag?} with language_tags rules instead.
Daily content needs no special template. When an episode carries an air date, {season_episode} becomes the date automatically and {episode} and {year} clear:
output_template:\n series: \"{title}.{season_episode}.{episode_name?}.{quality}.{source}.WEB-DL.{audio_full}.{video}-{tag}\"\n
A normal episode and a dated one, same template:
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
The date separator follows your template style: dots here, spaces if your series template uses spaces.
In folder names, {season} becomes the air year (Season 2024 style grouping), and unshackle skips a {year?} in the folder template when it would only repeat that year.
output_template:\n songs: \"{track_number}. {title}\"\n folder:\n albums: \"{album_artist} - {album} ({year})\"\n
The Artist - The Album (2024)/\n \u2514\u2500 01.Opening.Track.mka\n
In \"{track_number}. {title}\" 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.
A multi-disc album with explicit tracks, using more of the music variables. {disc} is empty on disc 1, so {disc?} and its separator only appear from disc 2 onward:
output_template:\n songs: \"{disc?}-{track_number}. {title} {explicit?}\"\n folder:\n albums: \"{album_artist} - {album} ({year}) [{label?}]\"\n
The Artist - The Album (2024) [The Label]/\n \u251c\u2500 01. Opening Track.mka\n \u2514\u2500 02-03. Closing Track Explicit.mka\n
"},{"location":"guide/output-and-naming/#see-also","title":"See also","text":" - Configuration File: the full
unshackle.yaml structure. - Downloading: the
dl command and per-run flags like -o, --no-folder, --tag, and --repack.
"},{"location":"guide/proxies-and-vpn/","title":"Proxies & VPN","text":"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.
The --proxy 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.
Where proxies are configured
All proxy provider configuration lives under the top-level proxy_providers: config key in your unshackle.yaml. 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.
"},{"location":"guide/proxies-and-vpn/#the-proxy-flag","title":"The --proxy flag","text":"Four options on the dl command control proxying at download time:
Option Effect --proxy The proxy to use. Either an explicit URI, or a query that unshackle resolves against your configured providers. --no-proxy Force all proxy use off. No providers are initialised and no proxy query is resolved. --no-proxy-download Use the proxy for the manifest, licence, and authentication, but bypass it for the downloads themselves. --proxy-download Use --proxy for the manifest, licence, and authentication, and a different proxy for the downloads. Takes the same forms as --proxy. Explicit proxy URIunshackle dl --proxy http://user:pass@1.2.3.4:8080 EXAMPLE 81234567\n
Resolve a US server from your configured providersunshackle dl --proxy us EXAMPLE 81234567\n
Target a specific providerunshackle dl --proxy nordvpn:us EXAMPLE 81234567\n
Set a default proxy in config
Like every dl flag, you can give --proxy a default in your configuration, so you do not have to pass it on every command. See Downloading for how dl options and config defaults interact.
"},{"location":"guide/proxies-and-vpn/#-no-proxy-download","title":"--no-proxy-download","text":"Segment downloads are usually the largest share of traffic, and a residential-grade VPN proxy is frequently the slowest part of the chain. --no-proxy-download 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.
Proxy the manifest and licence, download segments directunshackle dl --proxy gb --no-proxy-download EXAMPLE 10a1234\n
When this is unsafe
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 --no-proxy-download, remove it.
"},{"location":"guide/proxies-and-vpn/#-proxy-download","title":"--proxy-download","text":"--proxy-download is the middle ground: the manifest, licence, and authentication go through --proxy, 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 --proxy, so a country code or provider:region resolves against the same providers.
Manifest and licence over NordVPN, downloads over Windscribeunshackle dl --proxy nordvpn:us --proxy-download windscribevpn:us EXAMPLE 10a1234\n
--no-proxy and --no-proxy-download both override --proxy-download. The same region warning applies: if the service ties segment delivery to the manifest region, keep both proxies in that region.
"},{"location":"guide/proxies-and-vpn/#how-proxy-resolution-works","title":"How proxy resolution works","text":"unshackle interprets the value you pass to --proxy in one of three ways. It tries them in this order.
flowchart TD\n A[\"--proxy value\"] --> B{\"Looks like a URI?<br/>http:// https:// socks\"}\n B -- yes --> C[\"Use it verbatim\"]\n B -- no --> D{\"Has a provider prefix?<br/>provider:query\"}\n D -- yes --> E[\"Ask that one provider<br/>for the query\"]\n D -- no --> F[\"Ask every provider in order,<br/>first match wins\"]
- An explicit URI. unshackle uses anything shaped like
http://..., https://..., or a socks... URI exactly as you give it. unshackle logs Using explicit Proxy: ... and does no lookup. A host:port value such as localhost:8080 is also an explicit proxy. - A provider-prefixed query:
provider:query, for example nordvpn:us or gluetun:windscribe:us. 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. - A bare query: a region like
us, gb, or us1234. unshackle asks each loaded proxy provider in order and uses the first proxy any of them returns. A bare city query such as us:seattle does not work: unshackle reads us as a proxy provider name. Use the proxy provider prefix, for example nordvpn:us:seattle. If no proxy provider has a proxy for the query, unshackle stops with No proxy provider had a proxy for <query> and does not continue without a proxy.
unshackle compares the query against a region grammar: a country or location code of two to four letters, with an optional _code part (res_yyz), then an optional server number and/or a :city or -city part. A host:port 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.
A Control D resolver, controld://<resolver>@dns.controld.com, is a fourth form. A --remote client sends it to a server in place of a proxy URI, and the server starts a forwarder for it. See Control D.
"},{"location":"guide/proxies-and-vpn/#provider-load-order","title":"Provider load order","text":"When you do a download without --no-proxy, unshackle instantiates every configured proxy provider once, in this fixed order. It uses that same order for bare-query resolution:
Basic \u2192 ExpressVPN \u2192 NordVPN \u2192 Proton VPN \u2192 Surfshark \u2192 Windscribe \u2192 Gluetun \u2192 Hola \u2192 Control D
So if you have both Basic and NordVPN configured and use --proxy us, a us entry in your Basic config wins, because unshackle tries Basic first. To skip ahead to a specific proxy provider, prefix the query (--proxy nordvpn:us).
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 --proxy nordvpn:us, fails and shows the reason it did not load.
A bare region reaches Control D last
unshackle asks Control D for a bare region such as --proxy us only when no other loaded proxy provider has a proxy for it. Hola loads automatically when the hola-proxy binary is on your PATH, 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 unshackle-us profile and endpoint. The geofence auto-proxy uses the same order. To use Control D directly, prefix the query (--proxy controld:us).
Auto-loading providers
Most providers only load when you configure them under proxy_providers:. 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 hola-proxy binary is found on your PATH.
"},{"location":"guide/proxies-and-vpn/#connection-feedback","title":"Connection feedback","text":"After a proxy provider resolves a query, unshackle prints a line so you can see where you came out:
- Gluetun reports the verified exit IP, country, and city of the container.
- ExpressVPN and Proton VPN print a location summary such as
(USA - New York, #3 of 5): .214. - Other proxy providers log the resolved proxy URL.
"},{"location":"guide/proxies-and-vpn/#exit-check","title":"Exit check","text":"Before the service sends a request, unshackle looks up the proxy exit IP through the proxy. The service stops with Proxy check failed in two cases:
- No IP lookup gets through the proxy. The proxy is down, or it refused the connection.
- The proxy exit IP is the same as your own IP, so traffic does not go through the proxy.
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.
Over the REST API, the server returns this failure to the client as INVALID_PROXY.
"},{"location":"guide/proxies-and-vpn/#basic-static-proxies","title":"Basic (static proxies)","text":"The Basic 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).
Under each two-letter country code you can put either a single proxy string or a list of them:
unshackle.yamlproxy_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
Query forms:
Query Meaning us A proxy for the US. If several are listed, one is chosen at random. us2 The 2nd entry in the US list (1-based). - If a country has a single proxy string, that proxy is always returned.
- If it has a list and you give a plain country code, unshackle picks one at random. Append an index (
de1, de2) to pin a specific entry. - unshackle normalises each URL (a missing scheme defaults to
http) and validates it, so it rejects a malformed URI up front and does not fail mid-download.
unshackle dl --proxy de2 EXAMPLE 81234567\n
"},{"location":"guide/proxies-and-vpn/#control-d","title":"Control D","text":"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, --proxy-download) sees an ordinary HTTP proxy.
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. --proxy controld:yyz --proxy-download controld:yul 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).
Keep both locations in one country. Some CDNs also check the country of the download IP, and refuse a --proxy-download exit in another country with a 403. This applies to every proxy provider.
unshackle search --proxy controld:ca works the same way as dl.
"},{"location":"guide/proxies-and-vpn/#what-you-need","title":"What you need","text":" - 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.
- 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.
unshackle.yamlproxy_providers:\n controld:\n token: api.xxxxxxxxxxxx # a Write API token, from the Control D dashboard\n
unshackle dl --proxy controld:ca EXAMPLE 81234567\n
The token is the only required key. You do not need to create a profile or an endpoint, or to give a profile and resolver: unshackle creates an unshackle-<region> profile and endpoint on your account the first time it needs one, and uses it again on the next run. Give profile and resolver only to use a profile that you made yourself (see How unshackle chooses a profile).
The returned proxy is HTTP on loopback, http://127.0.0.1:{port}. 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:
Query Meaning ca One of Control D's Canadian locations, at random. yul That exact location, by its code. res_yyz A residential location, by its code. A country pick never uses a residential location, so name it this way. The configuration reference lists every controld config key.
"},{"location":"guide/proxies-and-vpn/#how-unshackle-chooses-a-profile","title":"How unshackle chooses a profile","text":"Each region query gets a profile and an endpoint named after it: --proxy controld:ca uses unshackle-ca. For each region, unshackle uses the first match in this list:
- A profile that this process already pointed at that region.
- The endpoint named
unshackle-<region> on your account, made by an earlier run. -
A profile from your config that this process does not use yet. These are optional:
unshackle.yamlproxy_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
The resolver ID is the last part of the endpoint's DoH URL, https://dns.controld.com/<resolver>. You can also give the full URL.
-
A new profile and endpoint named unshackle-<region>, while your config pairs plus the unshackle-* endpoints on the account are fewer than max_profiles. unshackle keeps them for the next run. max_profiles limits only this step: unshackle uses every pair in your config, even more than max_profiles.
- 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
unshackle-* profile that moves, and its endpoint, get the new region's name. unshackle logs Every Control D profile is in use; moving profile \u2026 to \u2026, and connections already open keep the old exit until they close.
Because the names live on the account, every unshackle process agrees on them: two runs, or two jobs on a serve instance, that ask for ca both use unshackle-ca. Two processes can still move a profile under each other when they run out of profiles (step 5).
unshackle changes only the profiles in your config and the profiles of unshackle-* endpoints. It skips an unshackle-* endpoint whose profile an endpoint without that name also uses, so unshackle never redirects a profile that serves your own devices. Leave the unshackle-* profiles empty: no services, no custom rules. unshackle sets their default rule to REDIRECT, 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.
Business accounts pay per endpoint
Personal plans allow an unlimited number of profiles and endpoints. Business plans bill each endpoint every month, so each unshackle-<country> 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 max_profiles to that number. unshackle then never creates a profile.
Everything goes through the proxy, including the segments
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 --no-proxy-download to keep the geo-check on the manifest and the licence while pulling the files over your own connection.
The switch is not instant
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.
Same machine, same IP, over IPv4
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 HTTPS_PROXY for these queries.
The forwarder refuses a connection to an IP address with a 502, 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.
With --remote, the server resolves
unshackle does not send your API token to a server. For --proxy controld:ca with --remote, unshackle points unshackle-ca at Canada with your token, then sends the server only that endpoint's resolver ID, as controld://<resolver>@dns.controld.com. 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.
The server must run a version of unshackle that knows controld://. An older server rejects it with INVALID_PROXY: Proxy provider 'controld' not found when your API key has server_proxy, else a message that asks for a full proxy URI. A bare region, such as --proxy ca, skips Control D with --remote, 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.
"},{"location":"guide/proxies-and-vpn/#troubleshooting-control-d","title":"Troubleshooting Control D","text":"Symptom Cause and fix Proxy check failed, 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. A 502 Bad Gateway for one host. With -d, the log shows Control D returned no A record for \u2026. Control D gave no IPv4 address for that host. A 502 Bad Gateway for one host only. With -d, the log shows Refused \u2026, an address that Control D cannot redirect. The request names the host by IP address. The forwarder refuses it. See the note on IPv4 above. An HTTP 401 or 403 from api.controld.com. The token is a Read token, or its Allowed IPs do not include this machine. Use a Write token. Control D needs both a profile and a resolver or Control D needs max_profiles of 1 or more at startup. The controld config is not valid. Give profile and resolver together, and a max_profiles of 1 or more. Every run fails until you correct it, also a run that does not use Control D. Could not read Control D's locations. unshackle could not get the location list. It tries again at the next Control D query. A 403 for the segments only, with --proxy-download in another country. The CDN checks the country of the download IP. Keep --proxy-download in the same country as --proxy."},{"location":"guide/proxies-and-vpn/#gluetun","title":"Gluetun","text":"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 qmcgaw/gluetun image. That container establishes a WireGuard or OpenVPN tunnel to your chosen VPN provider and exposes a plain HTTP proxy on localhost, which unshackle then routes traffic through. When the download finishes, the container is torn down automatically.
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.
Not available with --remote
Gluetun listens on your machine, so a server on another machine cannot reach it. With --remote, unshackle stops with an error for --proxy gluetun:..., and for any proxy that resolves to localhost or a loopback address, such as a region query that Gluetun answers. Give --remote a proxy the server can reach, or run the service locally. A server on this machine (a remote_services URL on 127.0.0.1) can reach a local proxy, so it is exempt.
Docker is required
Gluetun needs a working Docker installation on your PATH. If Docker is not found, the proxy provider fails to load with an error linking to the install docs. The container also needs the NET_ADMIN capability and access to /dev/net/tun to bring up the tunnel. unshackle requests both automatically.
"},{"location":"guide/proxies-and-vpn/#query-format","title":"Query format","text":"Gluetun uses a nested selector: the proxy provider prefix picks Gluetun, and the rest names the VPN provider and the region.
gluetun:<vpn-provider>:<region>\n
A Windscribe US exit via Gluetununshackle dl --proxy gluetun:windscribe:us EXAMPLE 81234567\n
A NordVPN Germany exit via Gluetununshackle dl --proxy gluetun:nordvpn:de EXAMPLE 81234567\n
After unshackle strips the leading gluetun:, the proxy provider receives exactly provider:region. It must be two colon-separated parts, and anything else is an error. The <vpn-provider> must be one you have configured under gluetun.providers, and unshackle normalises friendly names to Gluetun's identifiers (for example pia and privateinternetaccess both map to private internet access).
"},{"location":"guide/proxies-and-vpn/#configuration","title":"Configuration","text":"Each VPN provider you want to use gets an entry under providers:, carrying its VPN type, credentials, and how your region aliases map onto Gluetun's server selectors.
unshackle.yamlproxy_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
Per-provider keys:
Key Purpose vpn_type wireguard (default) or openvpn. credentials The secrets for the tunnel; see the credential rules below. server_countries Maps your region alias (e.g. us) to Gluetun's country value (e.g. US). server_cities Optional. Maps an alias to a Gluetun city. server_hostnames Optional. Maps an alias directly to a specific server hostname. extra_env Optional. Raw environment variables merged into the container last, for any Gluetun setting not covered above. Credential rules by VPN type:
WireGuardOpenVPN private_key is always required. surfshark, mullvad, and ivpn also require addresses. windscribe additionally requires both addresses and preshared_key (preshared_key may be an empty string, but the config key must be present). - NordVPN and Proton VPN need only
private_key.
- Requires
username and password.
Which vpn_type should I pick?
WireGuard is the default because it can be faster, but it needs the fiddlier credential setup above (private keys, and for some providers addresses and a preshared_key). 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.
Global keys:
Key Default Purpose base_port 8888 The first local port to expose proxies on. Additional containers take the next free ports. auto_cleanup true Remove containers on exit. If false, containers are only stopped, not deleted. container_prefix unshackle-gluetun Prefix for Docker container names. auth_user / auth_password null Optional HTTP-proxy credentials. If set, the local proxy requires auth and the credentials are embedded in the proxy URL. verify_ip true After connecting, verify the container's real exit IP and region."},{"location":"guide/proxies-and-vpn/#region-selection","title":"Region selection","text":"For a given query region, Gluetun resolves the server like this:
- An explicit entry in
server_hostnames, server_cities, or server_countries for that alias always wins. - unshackle changes a
us1239-style query (country code + number) with no explicit mapping into a provider-specific server hostname (for example us1239.nordvpn.com for NordVPN). Surfshark has no numbered servers, so map a Surfshark region to a server name such as us-dal.prod.surfshark.com in server_hostnames. - unshackle expands a bare two-letter code to the full country name Gluetun expects.
A few providers (Windscribe, VyprVPN, VPN Secure) select by region rather than country, and unshackle converts Windscribe region names automatically. For instance us becomes US East and uk/gb become United Kingdom.
"},{"location":"guide/proxies-and-vpn/#container-lifecycle","title":"Container lifecycle","text":"Understanding what Gluetun does behind the scenes helps when something goes wrong:
- Image check. unshackle pulls
qmcgaw/gluetun:latest if it is not already present. - Reuse. If a container for this exact
provider:region 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.
Expect a slow first request, then instant reuse
Bringing up a fresh tunnel takes roughly 10 to 30 seconds for the first request to a given provider:region. 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.
- Port allocation. unshackle chooses a free local port, starting from
base_port. - Start. unshackle launches the container bound to
127.0.0.1:{port}. It passes credentials through a temporary, 0600-permission env-file (never as -e flags), and it overwrites and deletes that file immediately after. - 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
authentication failed or invalid credentials abort early, and unshackle attaches recent logs to the error to help you diagnose it. - IP verification. When
verify_ip 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. - Proxy handed back. You get
http://localhost:{port} (or with auth credentials if configured).
Cleanup and Ctrl+C
unshackle cleans up containers with an atexit handler on normal exit. Gluetun deliberately does not install its own signal handlers, so Ctrl+C continues to work as you expect. If something kills a run hard (for example kill -9), a container can stay behind. With auto_cleanup: true the next run that adopts that name still works, or you can remove it manually with docker rm -f.
"},{"location":"guide/proxies-and-vpn/#troubleshooting","title":"Troubleshooting","text":"Common Gluetun issues
RuntimeError about Docker not found. Install Docker and make sure that docker is on your PATH. invalid credentials / authentication failed in the readiness wait. Your WireGuard/OpenVPN credentials are wrong or in the wrong fields. Double-check private_key, addresses, and (for Windscribe) preshared_key. - Region mismatch error. The VPN connected but exited in a different country than requested. Examine your
server_countries mapping, or set verify_ip: false if you intentionally use a nearby region. - Timeout after 60 seconds. The tunnel never came up. Inspect the container logs (
docker logs <container>) for the underlying VPN error.
"},{"location":"guide/proxies-and-vpn/#expressvpn","title":"ExpressVPN","text":"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.
Enable it and do a download interactively once:
unshackle.yamlproxy_providers:\n expressvpn:\n enable: true\n
With enable: true 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 enable after the first login, but you can keep a YAML block to pin regions or servers:
unshackle.yaml (optional)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
Default file location:
File Default path Token cache {cache}/vpn/expressvpn_tokens.json Where {cache} is your configured cache directory.
Query forms:
Query Meaning us A smart, random US location. us-ny US, New York. us-ny-2 / us-ny2 US, New York, the 2nd server. usny-newyork-2 A full location slug. hostname.expressprovider.com A direct endpoint hostname. The resolved proxy is an HTTPS proxy on port 443. On success, unshackle prints a location summary such as (USA - New York, #3 of 5): .214.
Cache safety
unshackle writes ExpressVPN's token cache with 0600 permissions, so the refresh token is never briefly world-readable.
"},{"location":"guide/proxies-and-vpn/#nordvpn","title":"NordVPN","text":"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.
unshackle.yamlproxy_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
Required keys: username, password. 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 @. If validation fails, you have almost certainly used your login credentials instead of your service credentials.
server_map is optional and maps a region (or code:city) to a pinned NordVPN server ID. Its main use is to tune performance: for a given streaming service one specific server often performs noticeably better than NordVPN's recommended pick. So you can hard-code that server for a day or two as a workaround, until it degrades and you swap in another.
Use gb, not uk, for the United Kingdom
Query the UK as gb. unshackle uses the Alpha-2 country code gb deliberately to stay consistent with its other regional/country-code systems and avoid the language-vs- country-code confusion that uk invites.
Query forms:
Query Meaning us A recommended US server. us1234 The specific server us1234. nordvpn:us:seattle A recommended server in Seattle. 228 A NordVPN numeric country ID. The returned proxy is HTTPS on port 89 (NordVPN disabled its plain-HTTP proxies on port 80 in 2021).
unshackle dl --proxy nordvpn:us:seattle EXAMPLE 81234567\n
"},{"location":"guide/proxies-and-vpn/#proton-vpn","title":"Proton VPN","text":"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.
TV login (recommended)Exported cookies 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:
unshackle.yamlproxy_providers:\n protonvpn:\n enable: true\n
With enable: true 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.
Export your account.proton.me cookies (the AUTH-<UID> cookie) to the Proton cookie file. This method is access-only: it cannot refresh, so you must re-export when it expires.
The AUTH-<UID> cookie is HttpOnly
This is the single most common cause of a failed Proton cookie import: the required AUTH-<UID> 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.
Why this session can't refresh, and lapses after ~24h
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.
Default file locations:
File Default path Cookies {cookies}/vpn/protonvpn.txt Session cache {cache}/vpn/protonvpn.json Proton VPN auto-loads if its cookie file exists. Like ExpressVPN, unshackle writes its cache file with 0600 permissions.
Cache vs cookie precedence
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.
Query forms (after the protonvpn: prefix):
Query Meaning us A random US server (paid tiers preferred over free). us12 Proton US server #12. us:ny A server in New York. 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 (Name - City): server-host.
Proton server numbers aren't sequential
When pinning a server with protonvpn:deNN, do not guess a low number. A country may have non-contiguous IDs like #203, #813, and so on. Copy the number from a previous run's log line (e.g. DE#203) instead.
"},{"location":"guide/proxies-and-vpn/#hola","title":"Hola","text":"Hola requires no configuration at all. It uses the hola-proxy binary, and auto-loads whenever that binary is found on your PATH. If you query Hola but the binary is missing, the proxy provider raises an error that tells you to install it.
The hola-proxy 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. go install puts the binary in $(go env GOPATH)/bin, which must be on your PATH.
Build hola-proxy, then query a countrygo install github.com/Snawoot/hola-proxy@v1.18.2\nunshackle dl --proxy hola:us EXAMPLE 81234567\n
Query forms: a two-letter country code (e.g. us, gb). unshackle asks hola-proxy for available proxies in that country and picks one at random, returning an HTTP proxy.
Temporary bans
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, hola-proxy does not stop, so unshackle waits 30 seconds and then reports the ban. Hola currently uses only datacenter proxies.
"},{"location":"guide/proxies-and-vpn/#surfshark","title":"Surfshark","text":"Surfshark, like NordVPN, uses Service Credentials rather than your login. Make them from the Surfshark manual-setup page.
unshackle.yamlproxy_providers:\n surfsharkvpn:\n username: YOUR_SERVICE_USERNAME\n password: YOUR_SERVICE_PASSWORD\n server_map: # optional: region -> server name\n us: us-dal\n us:seattle: us-sea\n
Required keys: username, password, validated with the same 48-character rule as NordVPN (combined username+password must be 48 alphanumeric characters, case-insensitive, no @). server_map optionally pins a server per region. Give the server name from Surfshark's server list, for example us-dal. A full hostname such as us-dal.prod.surfshark.com also works. Surfshark does not use numeric server IDs. unshackle ignores a numeric or empty value and logs a warning. A us:seattle entry applies only to that city query, and it does not fall back to the us entry.
Query forms:
Query Meaning surfsharkvpn:us A random US server. uk and gb both give a UK server. surfsharkvpn:us-bos A specific server from Surfshark's server list. surfsharkvpn:us:seattle A random server in Seattle. unshackle ignores case, spaces, hyphens and accents in a city name, so us:new-york matches New York. A city also matches the start of a longer name: de:frankfurt matches Frankfurt am Main. A bare us also reaches Surfshark. A bare us-bos can stop at a proxy provider earlier in the order, and a bare us:seattle does not work, so use the surfsharkvpn: prefix for those forms.
The returned proxy is HTTPS on port 443.
"},{"location":"guide/proxies-and-vpn/#windscribe","title":"Windscribe","text":"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).
unshackle.yamlproxy_providers:\n windscribevpn:\n username: YOUR_SERVICE_USERNAME\n password: YOUR_SERVICE_PASSWORD\n server_map: # optional: alias -> hostname\n us: us-east.totallyacdn.com\n us:seattle: us-seattle.totallyacdn.com\n
Required keys: username, password. server_map optionally maps a region (or region:city) directly to a hostname.
Query forms:
Query Meaning us A random US server. us150 / sg007 A specific numbered server. windscribevpn:us:seattle A random server in Seattle. The returned proxy is HTTPS on port 443.
Windscribe is not loaded by the REST API resolver
The dl 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.
"},{"location":"guide/proxies-and-vpn/#developer-notes","title":"Developer notes","text":"Two resolution paths (developers)
unshackle has two proxy-resolution code paths that are intentionally not identical:
unshackle/commands/dl.py inlines its own logic and loads all nine providers, including Windscribe and Gluetun. unshackle/core/proxies/resolve.py::initialize_proxy_providers() is the shared resolver used by the REST API handlers and the remote-service client. It omits Windscribe and Gluetun.
Both paths accept the same query grammar (a direct URI, a provider:query, a bare country query tried against providers in order, or a controld:// resolver), but the set of available providers differs. Keep this in mind when you add a proxy provider: an entry in dl.py does not make it available over the API, and the opposite is also true.
The remote-service client resolves --proxy with its own resolve_remote_proxy_arg(). It changes a controld: query to a controld:// resolver for the server with get_remote_proxy(), and it removes Control D from a bare query, because a loopback forwarder is of no use to a server on another machine.
Implementing a new provider (developers)
Every proxy provider subclasses unshackle.core.proxies.proxy.Proxy and has three methods:
__init__(self, **kwargs) receives its proxy_providers sub-dict splatted as keyword arguments, so YAML keys map 1:1 to constructor parameters. Do authentication and catalogue pre-fetching here. __repr__(self) is a human summary, conventionally \"{n} Countries ({m} Servers)\". get_proxy(self, query) returns a Requests-compatible proxy URI, or None only when the query was valid but no proxy exists. Raise on genuine errors or bad queries.
Optionally add get_connection_info(query) (as Gluetun does) or last_connection_display() (as ExpressVPN and Proton VPN do) to make dl print a friendly connection line instead of the raw proxy URL.
"},{"location":"guide/proxies-and-vpn/#see-also","title":"See also","text":" - Downloading: the full
dl command guide, including where proxy flags sit in the download flow. - Configuration file: the
unshackle.yaml reference, including directories for cookies and cache used by the cookie-based providers. - Configuration reference: the developer-facing configuration API, including the
proxy_providers structure.
"},{"location":"guide/subtitles/","title":"Subtitles","text":"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.
A handful of dl flags and a small subtitle block in your configuration file control most of this. See Downloading for how subtitle flags fit into a full download command.
"},{"location":"guide/subtitles/#supported-formats","title":"Supported formats","text":"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.
Codec (internal name) Format Extension Notes SubRip SRT srt SubRip, the most widely compatible plain-text format SubStationAlpha SSA ssa SubStation Alpha (styled) SubStationAlphav4 ASS ass Advanced SubStation Alpha (styled) TimedTextMarkupLang TTML ttml Timed Text Markup Language (IMSC/DFXP) WebVTT VTT vtt WebVTT SAMI SMI smi Synchronized Accessible Media Interchange MicroDVD SUB sub MicroDVD MPL2 MPL2 mpl2 MPL2 TMP TMP tmp TMP fTTML STPP stpp MPEG-DASH box-encapsulated TTML (IMSC1) fVTT WVTT wvtt MPEG-DASH box-encapsulated WebVTT The two boxed formats convert automatically
fTTML (STPP) and fVTT (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 (fTTML becomes TTML and fVTT 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.
"},{"location":"guide/subtitles/#what-happens-to-a-subtitle-after-download","title":"What happens to a subtitle after download","text":"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:
- Encoding: unshackle forces non-boxed subtitles to UTF-8, and unescapes stray
‎ / ‏ bidirectional entities. - 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.
- WebVTT sanitization: merged WebVTT runs through a repair pipeline that clamps negative timestamps to
00:00:00.000, removes stray cue identifiers (like Q0, Q1) 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 preserve_formatting). - Cue markup normalisation: unshackle removes the WebVTT-only parts of a cue payload, so no player draws them as dialogue. See Cue markup.
- 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
fTTML is likewise unwrapped to TTML first.
You normally do not need to think about any of this. It gives a clean file.
"},{"location":"guide/subtitles/#selecting-and-filtering-subtitles","title":"Selecting and filtering subtitles","text":"Subtitle selection happens through dl flags. The most important is language selection.
Flag Purpose -sl, --s-lang Language(s) wanted for subtitles. Defaults to all. A - prefix excludes, e.g. all,-es. --require-subs Require these languages to exist; if present, download all subtitles. Cannot be combined with --s-lang. -fs, --forced-subs Include forced subtitle tracks (excluded by default). -fso, --forced-subs-only Keep only forced subtitle tracks and drop the other subtitles; implies -fs. -fsl, --forced-s-lang Language(s) wanted for forced subtitles; implies -fs. A - prefix excludes. --exact-lang Exact language matching, with no regional variants. -S, --subs-only Download only subtitle tracks. -ns, --no-subs Do not download subtitle tracks at all. --sub-format Output subtitle format / conversion target (see conversion). --skip-subtitle-errors Skip a subtitle that fails to download instead of aborting the whole title."},{"location":"guide/subtitles/#choosing-languages","title":"Choosing languages","text":"By default (--s-lang all) unshackle keeps every subtitle language the service offers. To narrow it down, pass a comma-separated list of language tags:
English and Spanish subtitles onlyunshackle dl --s-lang en,es EXAMPLE 81234567\n
Language matching is fuzzy by default: en matches en-US, en-GB, and similar variants. If a requested language is missing but others were found, unshackle continues with whatever remains and tells you which languages it dropped.
For strict matching, where es-419 matches only es-419 and never es-ES, add --exact-lang:
Only Latin-American Spanish, no other Spanish variantsunshackle dl --s-lang es-419 --exact-lang EXAMPLE 'https://www.example.com/...'\n
"},{"location":"guide/subtitles/#requiring-languages-before-downloading","title":"Requiring languages before downloading","text":"--require-subs 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.
Fail unless both English and French subs exist, then grab everythingunshackle dl --require-subs en,fr EXAMPLE B0ABCDEFGH\n
--require-subs and --s-lang are mutually exclusive
Because --require-subs forces downloading of all subtitle languages, it cannot be combined with --s-lang. Choose one or the other.
"},{"location":"guide/subtitles/#forced-subtitles","title":"Forced subtitles","text":"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 -fs / --forced-subs to include them:
Include forced tracks alongside full subtitlesunshackle dl --s-lang en --forced-subs EXAMPLE 81234567\n
-fs keeps forced tracks in every selected language. If you only want forced tracks in certain languages, use -fsl / --forced-s-lang instead. It implies -fs, so you do not need both:
All full subtitles, but only the English forced trackunshackle dl --s-lang all --forced-s-lang en EXAMPLE 81234567\n
If you pass both flags, -fsl wins and keeps only forced tracks in its languages. It also understands orig (the title's original language) and all (every forced track, same as plain -fs).
To download the forced tracks and no other subtitle, use -fso / --forced-subs-only. It implies -fs, and --s-lang and -fsl still select the languages:
Only the English forced trackunshackle dl --s-lang en --forced-subs-only EXAMPLE 81234567\n
-fso does not drop video or audio. Add -S 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.
"},{"location":"guide/subtitles/#track-types-forced-sdh-and-cc","title":"Track types: forced, SDH, and CC","text":"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.
- Forced: only signs and foreign dialogue, meant to play when the audio language matches. Off by default. Enable it with
--forced-subs. - SDH (Subtitles for the Deaf and Hard-of-Hearing, also called HOH): a full transcript that includes both dialogue and non-speech sound cues.
- CC (Closed Captions): captions originating from an EIA-608/708 broadcast stream, often uppercase with
>>> speaker markers and sound cues.
SDH and CC are treated together for sorting and stripping
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.
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 subtitle.group_by to language. Use subtitle.type_priority to change the Forced \u2192 Normal \u2192 SDH/CC order itself.
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.
"},{"location":"guide/subtitles/#closed-captions-embedded-in-video","title":"Closed captions embedded in video","text":"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 (SRT) subtitle flagged as CC. This runs automatically unless you disabled subtitles (--no-subs) or video (--no-video / --video-only semantics), and it requires the CCExtractor tool on your PATH.
"},{"location":"guide/subtitles/#automatic-sdh-stripping","title":"Automatic SDH stripping","text":"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 strip_sdh config key.
The check is deliberately loose: if a close-enough plain track already exists (for example an en-GB non-SDH track when the SDH track is en-US), no stripped copy is created. When a stripped copy is created, the original SDH track is kept as well, so you end up with both.
The sdh_method config key selects the stripping engine itself. The default (auto) prefers the subby cleaner for SRT, falls back to SubtitleEdit when you install it, and otherwise uses the built-in filter-subs approach.
Every engine removes the same three things: bracketed sound effects ([MUSIC PLAYING], (door creaks)), speaker labels (MAN:), and font tags. Every engine keeps plain dialogue and inline <i> styling. They differ on music and lyric lines:
sdh_method Engine that runs Lyric lines (\u266a ... \u266a) auto subby for an SRT track. SubtitleEdit for any other format when you install it, otherwise filter-subs. Kept, unless the fallback reaches filter-subs. subby subby, but only for a track that is already SRT. Any other format falls through to filter-subs. Kept for SRT, removed otherwise. subtitleedit SubtitleEdit when you install it, otherwise filter-subs. Kept with SubtitleEdit, removed without it. filter-subs filter-subs always. Removed. Pick filter-subs when you want lyrics gone as well. Pick subby or install SubtitleEdit when you want to read along with the songs.
Why convert_before_strip exists
subby'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 convert_before_strip: non-SubtitleEdit engines need the subtitle converted to SRT first, or the hearing-impaired cues stay in the file.
"},{"location":"guide/subtitles/#converting-subtitle-formats","title":"Converting subtitle formats","text":"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 --sub-format:
Convert every subtitle to SRTunshackle dl --s-lang en,es --sub-format srt EXAMPLE 81234567\n
--sub-format accepts the common format names and aliases, including srt, vtt, ssa, ass, and ttml. Pass original to explicitly keep the source format and skip all conversion:
Keep whatever the service deliveredunshackle dl --sub-format original EXAMPLE 'https://www.example.com/...'\n
Conversion only runs when the source format differs from the target, so --sub-format srt on a track that is already SRT is a no-op.
Down-converting styled subtitles is lossy
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 --sub-format. If you want to preserve styling, convert to a format that supports it (or keep original).
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 sidecar_format: srt will still lossily flatten styled subtitles, dropping positioning, colours, and styling, and a per-download --sub-format srt forces the muxed track to convert as well. To keep raw styled sidecars, set sidecar_format: original.
"},{"location":"guide/subtitles/#how-the-conversion-backend-is-chosen","title":"How the conversion backend is chosen","text":"Under the hood unshackle picks the highest-fidelity converter that supports the source\u2192target pair. Which converter runs depends on the conversion_method config key (default auto) and the formats involved:
Backend Best at Requires subtitleedit Highest fidelity; preserves positioning and italics SubtitleEdit installed subby Native SRT output with clean-up - pysubs2 Best fidelity for styled SSA/ASS - (pure Python, always available) pycaption Last-resort fallback; flattens styling - With conversion_method: auto, 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.
"},{"location":"guide/subtitles/#what-each-backend-preserves","title":"What each backend preserves","text":"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. \u2014 means that the backend cannot convert that pair.
Conversion subtitleedit pysubs2 subby pycaption 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 Reading the table:
- Keep the original: leaving
--sub-format unset (or set to original) never round-trips the file, so every style survives. Only convert when your player cannot read the source format. subtitleedit (SubtitleEdit / seconv): the best choice for anything \u2192 SRT. It is the only backend that carries colour, and it embeds {\\an8} 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. pysubs2: 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. subby: reads only WebVTT/fVTT/SAMI (never ASS), and it is best for \u2192 SRT, where it uniquely converts WebVTT cue settings into {\\an8} positioning. Its CommonIssuesFixer may also drop near-duplicate cues. pycaption: removes all styling. Last-resort fallback only.
What auto picks
auto prefers subtitleedit first when you install it, then falls back to subby for \u2192 SRT and pysubs2 otherwise. The one exception comes from the table above: for ASS/SSA \u2192 TTML or WebVTT it picks pysubs2 even when SubtitleEdit is installed, since SubtitleEdit flattens inline styling on those pairs. Most installs do not ship SubtitleEdit, so in practice auto means subby (\u2192 SRT) or pysubs2. Install SubtitleEdit / seconv if you need colour or the highest \u2192 SRT fidelity.
"},{"location":"guide/subtitles/#cue-markup-and-html-entities","title":"Cue markup and HTML entities","text":"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 conversion_method:
WebVTT markup Result <c.bg_transparent>text</c> Tags removed, text kept. A class only selects a CSS ::cue rule that no player ever receives, so it carries no styling. <i.loud>, <b.x>, <u.y> Class list removed, the styling tag kept. <v Bob>, <lang ja>, <ruby>, <rt> Tags removed, text kept. <00:00:02.000> Removed. These are karaoke timings that no subtitle player renders. &, , ' Decoded to real characters for SRT, SSA, and ASS output. Kept escaped for WebVTT and TTML, which need them. A class list breaks more than you expect
FFmpeg reads SubRip markup as a tag only while the tag name stays inside [0-9a-zA-Z_/]. The dot in <i.loud> 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 i, b, and u exactly, so there the same class silently loses the styling. mpv, VLC, Plex, and Jellyfin all use one of those two readers.
Config wins over a service's preference
A service may set a preferred_conversion_method on its own tracks (for example when it ships subtitles that a particular backend handles best). An explicit conversion_method in unshackle.yaml always overrides that per-track preference, so your config takes precedence. This only matters when a service ships a non-default preference. Leave conversion_method at auto to let the service's hint stand.
"},{"location":"guide/subtitles/#muxed-vs-sidecar-output","title":"Muxed vs. sidecar output","text":"By default unshackle muxes subtitles into the final .mkv. You can instead (or additionally) write them as separate sidecar files next to the video, controlled by the output_mode config key:
mux (default)sidecarboth unshackle.yamlsubtitle:\n output_mode: mux\n
unshackle embeds the subtitles in the Matroska file. It writes nothing separately.
unshackle.yamlsubtitle:\n output_mode: sidecar\n sidecar_format: srt\n
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).
unshackle.yamlsubtitle:\n output_mode: both\n sidecar_format: srt\n
unshackle muxes the subtitles into the video and writes them as sidecar files.
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:
Show.S01E01.1080p.WEB.en.srt\nShow.S01E01.1080p.WEB.en.forced.srt\nShow.S01E01.1080p.WEB.en.sdh.srt\n
The pattern is {base}.{language}[.forced][.sdh].{extension}. The sidecar_format config key sets the sidecar file format. Use a format name like srt or vtt, or original to keep each subtitle in its downloaded format.
"},{"location":"guide/subtitles/#fonts-for-styled-subtitles","title":"Fonts for styled subtitles","text":"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.
"},{"location":"guide/subtitles/#subtitle-configuration","title":"Subtitle configuration","text":"You can set defaults for all of the behaviour above in the subtitle block of your configuration file:
unshackle.yamlsubtitle:\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
Key Default Values Purpose strip_sdh true true / false Auto-generate a stripped non-SDH copy when a language has only an SDH track. preserve_formatting true true / false Keep original WebVTT styling and layout during sanitization. When false, WebVTT is re-encoded more aggressively (merging identical cues, dropping empty ones). conversion_method auto auto, subby, pysubs2, subtitleedit, pycaption Which conversion backend to prefer. auto ranks them per conversion. sdh_method auto auto, subby, subtitleedit, filter-subs Engine used to strip hearing-impaired cues. convert_before_strip true true / false Convert a subtitle to SRT before stripping SDH (for non-SubtitleEdit engines). output_mode mux mux, sidecar, both Whether subtitles are embedded, written as sidecars, or both. sidecar_format srt a format name (e.g. srt, vtt) or original Format used for sidecar files. group_by type type, language Whether all tracks of one type stay together, or each language stays next to its own variants. language_priority (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":"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:
If you want Set Every original style kept, with no re-encode at all --sub-format original, and sidecar_format: original for sidecars The highest conversion fidelity, including colour Install SubtitleEdit. conversion_method stays auto Music and lyric lines stripped along with the sound effects sdh_method: filter-subs Lyric lines kept sdh_method: subby, or install SubtitleEdit No stripped copies made at all strip_sdh: false One backend for every conversion, whatever you install conversion_method: <backend> Two keys read as if they control markup, and do not:
preserve_formatting decides whether unshackle re-encodes a WebVTT file after the repair pipeline. Left true, the cue text passes through as written. Set to false, 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. convert_before_strip 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 subby and filter-subs no-ops on anything that is not already SRT.
SubtitleEdit is optional but recommended
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 PATH. See Installation for how to add it. Without it, unshackle falls back to its built-in Python backends.
"},{"location":"guide/subtitles/#developer-reference","title":"Developer reference","text":"Audience
This section is for people extending unshackle or writing services. Everyday users can stop here.
The subtitle model lives in unshackle.core.tracks.Subtitle. A few internals worth knowing when working with subtitle tracks in code:
- Flags and validation:
Subtitle(codec=..., cc=..., sdh=..., forced=...). A track cannot be both cc and sdh, and you cannot combine forced with either. Both raise ValueError at construction. convert(codec, *, forced=False): converts the downloaded file in place through the backend chain in subtitle_convert.run_conversion. forced=True (what --sub-format sets) is the only way to permit lossy styled down-converts such as ASS\u2192SRT. Raises NotImplementedError if no backend supports the pair and RuntimeError if all attempts fail. strip_hearing_impaired(): removes SDH cues using the engine selected by config.subtitle[\"sdh_method\"]. reverse_rtl(): fixes right-to-left sentence-ending positioning with SubtitleEdit (requires the binary). parse(data, codec): the central parser, returning a pycaption.CaptionSet. It handles the boxed DASH formats, SAMI, and the WebVTT repair helpers. extract_fonts(text): returns the set of font names referenced by an ASS/SSA subtitle, used to decide which fonts to attach at mux time.
The conversion backends (SubtitleEditBackend, SubbyBackend, Pysubs2Backend, PycaptionBackend) each have a small protocol (is_available(), can_convert(), rank(), convert()), and unshackle tries them in rank order, lowest rank first. See the Tracks API reference for the full model.
"},{"location":"guide/troubleshooting/","title":"Troubleshooting & Debugging","text":"When a download fails, a service misbehaves, or unshackle cannot get a content key, unshackle gives you three tools to find out why:
- Debug logging: verbose
DEBUG-level console output plus a structured, machine-readable log file. unshackle env: make sure that unshackle finds the external tools it depends on, and see exactly which directories and config file are in use. - Targeted toggles:
debug_keys and debug_requests for the two areas (DRM keys and raw HTTP traffic) that are deliberately quiet by default.
The sections below cover how to enable each of them, how to read what they give, and which diagnostic fits which failure mode.
"},{"location":"guide/troubleshooting/#turning-on-debug-logging","title":"Turning on debug logging","text":"There are two independent ways to enable debug logging, and they do slightly different things.
The -d / --debug flagThe debug config key The root-level flag turns on verbose logging for a single invocation:
unshackle -d dl SERVICE TITLE_ID\n
It must come before the subcommand, because it is an option on the root unshackle command, not on dl.
-d does three things:
- Sets the console log level to
DEBUG, so every module logs its full detail. - Enables the structured JSON debug log file (see below).
- Adds source-path annotations to console log lines (which file and line each message came from).
To make debug logging the default for every run without typing -d each time, set it in your unshackle.yaml:
debug: true\n
or with the cfg command:
unshackle cfg debug true\n
debug: true is not identical to -d
The debug config key enables the JSON debug log file, but it does not raise the console to DEBUG level and does not add source-path annotations. Those only happen when you pass the -d 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 -d is the most complete option, and you can combine both.
Debug logging can be noisy and revealing
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.
"},{"location":"guide/troubleshooting/#the-structured-json-debug-log","title":"The structured JSON debug log","text":"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 (jq, grep, a text editor). It is safe to attach to a bug report, because unshackle redacts it.
"},{"location":"guide/troubleshooting/#where-it-is-written","title":"Where it is written","text":"unshackle makes the debug log during a dl run, and during import, which wraps dl. The path is:
<logs directory>/unshackle_debug_<service>_<timestamp>.jsonl\n
For example, unshackle_debug_EXAMPLE_20260703-142530.jsonl. The <service> tag and the timestamp mean each download gets its own file, so runs never overwrite each other.
Find your logs directory
The logs directory defaults to a logs folder inside the package data directory, but you can move it with the directories.logs config key. To see the exact resolved path on your machine, use unshackle env info and read the Directories table.
"},{"location":"guide/troubleshooting/#what-a-log-entry-looks-like","title":"What a log entry looks like","text":"Every line is a self-contained JSON object. The first line of each log file records the environment:
{\"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
Quote unshackle_code_hash 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.
Subsequent lines record the operations: service calls, DRM licence requests, vault lookups, downloader progress, and errors. Common fields include:
Field Meaning timestamp UTC ISO-8601 time of the entry. session_id Short random ID shared by every entry in one run, handy for correlating lines. level DEBUG, INFO, WARNING, or ERROR. operation The action being logged, e.g. service_call, download_init, drm_get_widevine_license, vault_get_key, session_end. message Human-readable description (redacted). service Service tag the entry belongs to, when applicable. context Arbitrary structured detail for the operation. request / response HTTP method/URL and response metadata for network operations. duration_ms How long a timed operation took. success Whether the operation succeeded. error On failures: the exception type, message, and a full traceback array (all redacted)."},{"location":"guide/troubleshooting/#reading-and-filtering-the-log","title":"Reading and filtering the log","text":"Because each line is independent JSON, jq is the natural tool:
# 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
unshackle logs the binary-tool versions (shaka-packager, mp4decrypt, mkvmerge, FFmpeg, FFprobe) near the start of a dl run. Often that is the fastest way to make sure that a muxing or decryption failure is really a wrong-version problem.
"},{"location":"guide/troubleshooting/#debugging-drm-keys-with-debug_keys","title":"Debugging DRM keys with debug_keys","text":"By default, unshackle redacts the content keys in the JSON debug log. It writes any field that looks like a content key as [REDACTED]. 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 debug_keys:
debug_keys: true\n
unshackle cfg debug_keys true\n
With debug_keys: true, 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.
Keys are sensitive, turn this back off
debug_keys 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 false when you are done. Note that debug_keys only affects the JSON debug log file. It does not change what the console prints.
Fields that are always redacted regardless of debug_keys (anything whose name contains password, token, secret, auth, or cookie) stay masked, so credentials never leak even in a keys-on log.
"},{"location":"guide/troubleshooting/#debugging-http-traffic-with-debug_requests","title":"Debugging HTTP traffic with debug_requests","text":"When you pass -d, unshackle raises its own modules to DEBUG but deliberately silences the noisy low-level HTTP libraries (urllib3, requests, rnet, httpx, httpcore, hpack, h2) back down to WARNING. Without this, a single download would bury the useful output under thousands of connection-pool and HTTP/2 frame messages.
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 debug_requests:
debug_requests: true\n
unshackle cfg debug_requests true\n
With debug_requests: true, unshackle leaves those libraries at DEBUG level when you operate it with -d, so their request/response chatter appears in the console.
debug_requests needs -d to have any effect
The debug_requests toggle only decides whether unshackle silences the HTTP libraries when the -d flag is active. If you do not operate unshackle with -d (verbose console logging), it changes nothing. Combine them: unshackle -d dl ... with debug_requests: true in config.
"},{"location":"guide/troubleshooting/#what-gets-redacted","title":"What gets redacted","text":"unshackle redacts logged strings so that debug output is safe to share. It applies three passes to every logged message, error, and structured value:
- Secrets: unshackle replaces passwords, tokens, API secrets, auth values, and cookies with
[REDACTED]. - URLs: unshackle collapses every
http(s) URL to redacted. It keeps only the file extension, so a manifest still shows as redacted.mpd and a segment as redacted.m4s. This hides the CDN, manifest, segment, and licence-server locations, but keeps the type of resource. - Local paths: unshackle replaces install-root, virtualenv, and home-directory prefixes with tokens, so your username and machine layout do not appear in logs.
The redact_paths config key controls path redaction, and it is on by default:
redact_paths: true # default - mask local base directories in logged paths\n
Set redact_paths: false 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.
"},{"location":"guide/troubleshooting/#checking-your-environment","title":"Checking your environment","text":"Many \"download failed\" problems are really missing external tools or a config file that is not where you think it is. The unshackle env command group answers both questions before you dig into logs.
"},{"location":"guide/troubleshooting/#env-check","title":"env check","text":"unshackle env check verifies every external binary unshackle can use and prints a table of what's installed:
unshackle env check\n
It reports each tool's status (\u2713 installed / \u2717 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.
The required tools (unshackle will not get far without them) are:
Tool Purpose FFmpeg Media processing FFprobe Media analysis MKVToolNix (mkvmerge) MKV muxing mkvpropedit MKV metadata shaka-packager DRM decryption Optional tools unlock extra capabilities. For example, mp4decrypt (alternative decryptor), dovi_tool / HDR10Plus_tool (Dolby Vision / HDR10+), SubtitleEdit / CCExtractor (subtitle conversion and CC extraction), MPV / FFplay (playback preview), and git (service repositories) or docker (Gluetun VPN, see Proxies & VPN).
First thing to run when something breaks
If a decryption step errors, a mux fails, or a Dolby Vision title will not process, use unshackle env check first. A red \u2717 next to the relevant tool is the answer far more often than a bug in unshackle.
"},{"location":"guide/troubleshooting/#env-info","title":"env info","text":"unshackle env info shows where unshackle reads configuration from and where every working directory lives:
unshackle env info\n
- 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.
- It then prints a Directories table for every configured path:
downloads, temp, cache, cookies, logs, exports, wvds, prds, the services search paths, and more.
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 directories: overrides from your config.
"},{"location":"guide/troubleshooting/#env-clear","title":"env clear","text":"Stale cache or leftover temp files can cause confusing behaviour (an old cached title list, a half-written temp file). env clear wipes those directories safely:
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
Each command reports how many files it removed and how much space it freed, then recreates the empty directory.
Cache-related weirdness
If a service keeps returning stale titles or metadata even after the source changed, clear that service's cache with unshackle env clear cache <SERVICE>. See Vaults for the separate, persistent key-vault store, which env clear does not touch.
"},{"location":"guide/troubleshooting/#common-failure-modes-and-how-to-inspect-them","title":"Common failure modes and how to inspect them","text":"A required tool is missing
Symptom: decryption, muxing, or analysis fails early, sometimes with a \"binary not found\" style error.
Inspect: use unshackle env check and look for a red \u2717 on a required row. Run unshackle setup to install it, or install it by hand, and re-run.
Decryption produces garbage or fails
Symptom: the download completes but the file will not play, or the decrypt step errors.
Inspect: enable debug_keys and operate unshackle with -d. Then examine the JSON debug log's drm_* and vault_* operations to see which content keys unshackle fetched, and from where. Also make sure that shaka-packager (or mp4decrypt) shows a sane version in the download_init binary-versions entry. See DRM & CDM.
A vault served a wrong content key
Symptom: a warning names a content key and the vault it came from, either was bad, trying other vaults (the decode check failed) or is flagged bad, skipping (an earlier run flagged it). The download stops with The content key from the vault did not decrypt the track; run again, was bad and no other source has the key, or No vault or CDM produced a content key that decrypts the track when no source is left to try.
Inspect: while it decrypts a track whose content key came from a vault, unshackle keeps the ciphertext as a .enc 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 bad_keys 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.
A network request fails at the connection or TLS layer
Symptom: timeouts, connection resets, or handshake errors, and unshackle's own logs do not give the full cause.
Inspect: set debug_requests: true and operate unshackle with -d to show the underlying urllib3 / rnet / httpx logs. In the JSON debug log, filter for service_call operations to see which request failed. If you use a proxy, also read Proxies & VPN.
The wrong titles/metadata keep coming back
Symptom: a service returns outdated titles even after the source changed.
Inspect: the title cache is likely serving stale data. Clear it with unshackle env clear cache <SERVICE>, or bypass it for one run using the dl no-cache / reset-cache options (see Downloading and the CLI Reference).
A config value doesn't seem to apply
Symptom: a setting you edited has no effect.
Inspect: use unshackle env info to see which config file unshackle loaded, and unshackle cfg --list to dump the effective values. It is common to edit a config file in a location unshackle does not read from. See below.
"},{"location":"guide/troubleshooting/#why-is-my-config-not-being-picked-up","title":"Why is my config not being picked up?","text":"unshackle loads the first unshackle.yaml it finds, in this order:
unshackle.yaml inside the package's namespace directory. unshackle.yaml in the parent of that directory. unshackle.yaml in your OS user-config directory: on Linux ~/.config/unshackle/unshackle.yaml, on Windows %LOCALAPPDATA%\\unshackle\\unshackle.yaml, on macOS ~/Library/Application Support/unshackle/unshackle.yaml.
If you have config in more than one of these, an earlier one wins and unshackle silently ignores your edits to a later file. unshackle env info 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 cfg command.
Developer note: structured logging in code
Service and command code sends entries through the shared log_event(...) helper (and the timed_operation(...) context manager for timing a block) from unshackle.core.utilities. 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 log_event(\"my_feature_event\", message=\"...\", context={...}). 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 debug_keys enabled.
"},{"location":"guide/troubleshooting/#logging-conventions-when-adding-entries","title":"Logging conventions when adding entries","text":"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 log_event signature does not enforce them, so they are easy to miss and worth stating explicitly.
Log levels are a flow skeleton, not just severity
Treat level as structure, not decoration. Send exactly one INFO milestone per pipeline stage so that jq 'select(.level==\"INFO\")' reads back the whole end-to-end flow of a run. Everything internal goes to DEBUG. Failures go to ERROR. A sparse INFO is the whole point. It is the line a developer skims first to see where a run got to before it broke.
# Read the pipeline's high-level flow, one line per stage\njq 'select(.level == \"INFO\")' unshackle_debug_EXAMPLE_20260703-142530.jsonl\n
No raw dumps
Never log a full Tracks object, an MPD/manifest body, or a response payload. Log only counts, ids, sizes, and safe_display_url(url). 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.
Operation names: <area>_<event>, no registry
Operation names are plain lowercase strings that follow an <area>_<event> convention: manifest_dash_parse, drm_decrypt, vault_get_key, tool_run. 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.
Message reads alone; data lives in fields
Give every entry a single-sentence message that stands on its own. Put all structured data (context, counts, ids, duration_ms) in fields, not in the prose. This separation lets the log be both human-scannable and machine-filterable. A message like \"Parsed DASH manifest\" with context={\"video\": 4, \"audio\": 2} beats \"Parsed manifest with 4 video and 2 audio tracks\".
Let tool runs log themselves
For external-tool calls (FFmpeg, mkvmerge, dovi_tool, and friends), route through run_step / ffprobe, which auto-emit a tool_run entry capturing the binary's version, return code, and duration consistently. Only fall back to calling log_tool_run manually for a direct subprocess.run you genuinely cannot route through run_step. Auto-logging is the preferred path precisely because it captures those fields the same way every time.
"},{"location":"guide/vaults/","title":"Key Vaults","text":"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.
Vaults are entirely optional, but if you download regularly they are one of the biggest quality-of-life improvements you can configure.
Vaults save license calls even on the very first download
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.
"},{"location":"guide/vaults/#what-a-vault-stores","title":"What a vault stores","text":"A vault stores every content key as a KID \u2192 KEY pair, grouped by service:
- KID (Key ID): a 16-byte identifier for a specific encrypted track, stored as 32 lowercase hex characters with no dashes.
- KEY: the 16-byte content key that decrypts that track, also 32 hex characters.
- Service: the canonical service tag (for example
EXAMPLE, not ExampleService) that namespaces the key. Each service gets its own logical table.
Why keys are matched by KID
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.
Null keys are ignored everywhere
A content key made entirely of zeroes (00000000000000000000000000000000) 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.
"},{"location":"guide/vaults/#how-lookups-and-caching-work","title":"How lookups and caching work","text":"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.
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:
- unshackle skips keys that already exist in a vault (it never overwrites or deletes existing data).
- A vault marked
no_push: true receives lookups, but unshackle never writes to it. This is useful for read-only or shared upstream vaults you do not own.
unshackle pushes keys from every source, not only a local CDM. A run against a remote server that licenses with its own CDM (--remote) writes the keys the server returns, and unshackle import writes the keys it reads from an export file.
"},{"location":"guide/vaults/#wrong-keys-from-a-poisoned-vault","title":"Wrong keys from a poisoned vault","text":"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. A KID that is not in this map, 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. Without FFmpeg there is no check at all.
When the decode fails, unshackle:
- Flags the KID:KEY in the
bad_keys 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 no_push, where only the flag is written. A flagged pair cannot go back into a local vault from another vault, a later run, or kv copy. A licence that returns the pair clears the flag and stores it. An API vault that served the pair also gets a report; HTTP and MySQL 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. - 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.
- 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.
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.
Per-segment decryption gives up the retry. With decrypt_segments 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.
unshackle copies a content key from one vault to the others only after this check passes, so a wrong content key 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 bad_keys.
A good two-vault setup
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.
"},{"location":"guide/vaults/#configuring-vaults","title":"Configuring vaults","text":"Declare vaults under the key_vaults list in your unshackle config file. Each entry is a mapping with two required fields, type (which backend to use) and name (a label you choose), plus whatever settings that backend needs.
unshackle.yamlkey_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
The type value is matched to a vault backend by name. The four backends that ship with unshackle are SQLite, MySQL, HTTP, and API, described below.
SQLite vaults are loaded critically
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. MySQL, HTTP, and API vaults are loaded leniently: if one fails to load it is logged and skipped, and the download continues with the remaining vaults.
"},{"location":"guide/vaults/#vault_timeout","title":"vault_timeout","text":"Network-backed vaults (HTTP and API) accept an optional per-vault timeout in seconds. If you omit it, unshackle injects the global default:
unshackle.yamlvault_timeout: 10.0 # default, in seconds\n
A timeout set inline on an individual vault always wins over this global value. The SQLite and MySQL backends do not take a timeout field. MySQL uses vault_timeout as its connect_timeout instead, and falls back to the pymysql default of 10 seconds when vault_timeout is 0. To use a different connect timeout, set connect_timeout on the vault.
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.
"},{"location":"guide/vaults/#sqlite-backend","title":"SQLite backend","text":"A locally-accessed SQLite database file. This is the simplest and fastest option and needs no server.
unshackle.yamlkey_vaults:\n - type: SQLite\n name: local\n path: ~/.local/share/unshackle/vaults/local.db\n
Field Required Description type yes Must be SQLite. name yes A label for this vault. path yes Path to the database file. ~ is expanded. The file (and its tables) are created automatically on first use. no_push no If true, keys are read but never written. Defaults to false. Each service gets its own table (named after the service tag), created on demand with kid and key_ columns. Connections use WAL journaling with a 30-second busy timeout, so multiple threads can safely use the same database file.
One more table, bad_keys, 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.
Moving the .db file silently forks your vault
Because the file is created on demand, if you relocate an existing .db without updating path 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.
Keep a local SQLite vault even when you share a MySQL one
The SQLite vault is best thought of as an offline-only backup should anything ever happen to a shared MySQL 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.
"},{"location":"guide/vaults/#mysql-backend","title":"MySQL backend","text":"A remotely-accessed MySQL/MariaDB database, ideal for sharing keys across several machines. It connects via pymysql. Prefer MariaDB over MySQL where you have the choice.
The vault connects directly to the database server
A MySQL vault (like SQLite) 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.
unshackle.yamlkey_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
Field Required Description type yes Must be MySQL. name yes A label for this vault. host yes Database server hostname or IP. database yes Database (schema) name. username yes Login user. no_push no If true, keys are read but never written. Any additional fields you provide (such as password, port, or ssl) are passed straight through to pymysql.connect, so you can use the full range of its connection options.
Account security is on you, not on unshackle
unshackle enforces none of this. It is operational policy for a database that may be shared with a group. Never connect with the root 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 unshackle database, and grant normal users only SELECT and INSERT. Reserve the CREATE grant for a single trusted user who bootstraps the service tables (see kv prepare); everyone else can insert new keys but should not be creating tables.
Grants determine what the vault can do
On connection the backend reads its own SHOW GRANTS. It requires at least SELECT to load at all (a missing SELECT grant makes the vault fail to load). Writing keys additionally needs INSERT, and creating a new service table needs CREATE. A read-only account still works fine as a lookup source. It cannot push new keys. Because MySQL is loaded leniently during downloads, a permission problem will not abort the run.
"},{"location":"guide/vaults/#http-backend","title":"HTTP backend","text":"A flexible HTTP vault that speaks one of three wire protocols, selected with api_mode. Use this to integrate with a community or self-hosted vault service.
api_mode Transport Authentication Notes query (default) GET with query parameters username + password Full read and write. json POST with a JSON payload password used as a token Read and write per content key; cannot bulk-enumerate keys. decrypt_labs POST in DecryptLabs format api_key sent as a header Read-only. no_push is forced on. query modejson modedecrypt_labs mode unshackle.yamlkey_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
Query mode requires username. Both the username and password are sent as query parameters on each request.
unshackle.yamlkey_vaults:\n - type: HTTP\n name: jsonvault\n host: https://vault.example.com/rpc\n api_mode: json\n password: \"your-api-token\"\n
Requests are POSTed as {\"method\": ..., \"params\": ..., \"token\": ...} using methods like GetKey, InsertKey, and GetServices. Bulk writes (kv copy, kv add) first try InsertKeys with params: {\"keys\": {kid: key, ...}, \"service\": ..., \"title\": ...} (up to 500 content keys per call) and expect {\"inserted\": <count>} back. A server that answers HTTP 404 or Unknown JSON-RPC method to InsertKeys gets one InsertKey call per content key for the rest of the run instead. This mode cannot list all keys in bulk, so a kv copy from a json vault relies on the remote server's own duplicate handling.
unshackle.yamlkey_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
A read-only lookup source. The API key is sent in a decrypt-labs-api-key header and the vault refuses all writes.
Field Required Description type yes Must be HTTP. name yes A label for this vault. host yes Base URL of the vault API. api_mode no query (default), json, or decrypt_labs. username for query Required in query mode; ignored otherwise. password one of these Password (query mode) or token (json mode). api_key one of these Alternative to password; used for decrypt_labs. If you give both, api_key wins. no_push no Read-only when true (always true for decrypt_labs). timeout no Request timeout in seconds; defaults to vault_timeout. You must supply either password or api_key, or the vault will fail to load.
"},{"location":"guide/vaults/#api-backend","title":"API backend","text":"A simple RESTful HTTP vault with a fixed, well-defined protocol. Authentication is a bearer token.
unshackle.yamlkey_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
Field Required Description type yes Must be API. name yes A label for this vault. uri yes Base URI of the vault API (a trailing slash is trimmed). token yes Bearer token, sent as Authorization: Bearer <token>. no_push no If true, keys are read but never written. timeout no Request timeout in seconds; defaults to vault_timeout. headers no Extra HTTP headers sent with every request, for example the Cloudflare Access service-token headers CF-Access-Client-Id and CF-Access-Client-Secret. The backend talks to endpoints under uri (for example GET {uri}/{service}/{kid} to look up a single key). It interprets a numeric code field in each JSON response to detect errors such as an invalid token, rate limiting, or an invalid service tag.
This is unshackle's own protocol, not a generic vault client
The API 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 HTTP 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.
DecryptLabs shortcut
An API vault whose name contains decrypt_labs will have its token filled in automatically from a global decrypt_labs_api_key in your config if you leave token unset. This lets you keep the API key in one place.
"},{"location":"guide/vaults/#managing-vaults-with-unshackle-kv","title":"Managing vaults with unshackle kv","text":"The kv command group manages the contents of your configured vaults. Every subcommand refers to vaults by the name you gave them in key_vaults; an unknown name is an error.
$ unshackle kv --help\n
"},{"location":"guide/vaults/#kv-add-import-keys-from-a-file","title":"kv add: import keys from a file","text":"Add KID:KEY pairs to one or more vaults for a given service. The file must contain one pair per line as HEX:HEX (32 hex characters each); lines that do not match are ignored.
$ unshackle kv add keys.txt EXAMPLE local shared\n
keys.txt9a04f07998404286ab92e65be0885f95:b1c2d3e4f5a6978012345678deadbeef\n0e7cc1a4e2f9411db0f24a3fbb8f8b21:00112233445566778899aabbccddeeff\n
The service argument (EXAMPLE above) is normalized to its canonical tag automatically. Keys that already exist in a vault are reported as skipped.
"},{"location":"guide/vaults/#kv-search-find-a-content-key-by-kid","title":"kv search: find a content key by KID","text":"Search your vaults for a KID and print any matching content key.
$ unshackle kv search 9a04f07998404286ab92e65be0885f95\n
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:
Option Description -s, --service Limit the search to a single service tag. -v, --vault Limit the search to one configured vault by name. Note
Remote vaults that cannot enumerate their service tables (for example an HTTP vault in json or decrypt_labs mode) can only be searched when you also pass --service. Without it, they are skipped.
"},{"location":"guide/vaults/#kv-copy-copy-keys-between-vaults","title":"kv copy: copy keys between vaults","text":"Copy every content key from one or more source vaults into a single destination vault. kv copy never alters existing rows; it adds only genuinely new KIDs and skips null keys.
$ unshackle kv copy shared local\n
The first argument is the destination; the rest are sources. You can supply several sources at once:
$ unshackle kv copy local shared community\n
Option Description -s, --service Only copy the given service. -l, --local-only Only copy services you have installed locally, skipping tables for unknown services. --service and --local-only are mutually exclusive.
A pair the destination vault has flagged in bad_keys is left behind, so a copy does not undo a flag. bad_keys is never treated as a service, so its rows are never copied into a service table.
"},{"location":"guide/vaults/#kv-sync-mirror-vaults-both-ways","title":"kv sync: mirror vaults both ways","text":"Make each of two or more vaults hold every content key the others have. This is effectively a two-way copy between each pair, so afterwards all listed vaults hold the same set of keys.
$ unshackle kv sync local shared\n
It accepts the same --service and --local-only options as copy, and requires at least two vaults. It runs copy between each pair, so it skips flagged pairs and the bad_keys table in the same way.
"},{"location":"guide/vaults/#kv-prepare-pre-create-service-tables","title":"kv prepare: pre-create service tables","text":"Create the per-service tables on table-based vaults (SQLite, MySQL) ahead of time, for every service you have installed. Vaults that do not use tables (the network-backed HTTP and API backends) are skipped.
$ unshackle kv prepare shared\n
This is mainly useful with a MySQL vault where you want the tables created once by an account that has the CREATE grant.
"},{"location":"guide/vaults/#see-also","title":"See also","text":" - Downloading: how keys are recovered and used during a download.
"},{"location":"reference/api/config/","title":"Config API","text":"Auto-generated reference for the Config object that models the unshackle configuration file. For a human-friendly walkthrough of every config key, see the Configuration Reference.
"},{"location":"reference/api/config/#unshackle.core.config.Config","title":"Config","text":"Config(**kwargs)\n
"},{"location":"reference/api/config/#unshackle.core.config.Config.validate_output_templates","title":"validate_output_templates","text":"validate_output_templates()\n
Validate output template configurations and warn about potential issues.
"},{"location":"reference/api/config/#unshackle.core.config.Config.get_folder_template","title":"get_folder_template","text":"get_folder_template(kind)\n
Find the folder template for the given title kind.
kind: one of \"movies\", \"series\", \"songs\", \"albums\". Falls back to the legacy single-string folder template, then \"\".
"},{"location":"reference/api/config/#unshackle.core.config.Config.get_template_separator","title":"get_template_separator","text":"get_template_separator(template_type='movies')\n
Get the filename separator for the given template type.
Analyzes the active template to determine whether it uses dots or spaces between variables. Falls back to dot separator (scene-style) by default.
Parameters:
Name Type Description Default template_type str One of \"movies\", \"series\", or \"songs\".
'movies'"},{"location":"reference/api/config/#unshackle.core.config.restore_bool_languages","title":"restore_bool_languages","text":"restore_bool_languages(data)\n
Put back the language tags no and yes, which YAML reads as booleans.
"},{"location":"reference/api/config/#unshackle.core.config.resolve_decryption","title":"resolve_decryption","text":"resolve_decryption(decryption_map, default, service)\n
Pick the decryption backend for a service (case-insensitive), falling back to default.
"},{"location":"reference/api/config/#unshackle.core.config.resolve_cdm_name","title":"resolve_cdm_name","text":"resolve_cdm_name(cdm, service, override=None)\n
Find a service's top-level CDM entry (case-insensitive), with default fallback.
"},{"location":"reference/api/config/#unshackle.core.config.cdm_entry_names_device","title":"cdm_entry_names_device","text":"cdm_entry_names_device(entry, profile=None)\n
Whether a per-service cdm entry names a device when no quality is known.
An entry that selects only by quality, or by a different profile, names none.
"},{"location":"reference/api/config/#unshackle.core.config.get_config_path","title":"get_config_path","text":"get_config_path()\n
Get Path to Config from any one of the possible locations.
Returns None if no config file could be found.
"},{"location":"reference/api/drm/","title":"DRM API","text":"Auto-generated reference for the DRM systems: Widevine, PlayReady, ClearKey, and related helpers. For configuring DRM as a user, see DRM & CDM Setup.
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKey","title":"ClearKey","text":"ClearKey(key, iv=None)\n
AES-128 ClearKey (HLS) DRM system.
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.
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKey.warn_clear","title":"warn_clear","text":"warn_clear(reason)\n
Warn once per track that unshackle passed a segment through undecrypted.
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKey.decrypt","title":"decrypt","text":"decrypt(path)\n
Decrypt a Track with AES-128 ClearKey (HLS) DRM.
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKey.from_m3u_key","title":"from_m3u_key classmethod","text":"from_m3u_key(m3u_key, session=None)\n
Load a ClearKey from an M3U(8) Playlist's EXT-X-KEY.
Parameters:
Name Type Description Default m3u_key Key A Key object parsed from a m3u(8) playlist using the m3u8 library.
required session Optional[Session] Optional HTTP session used to request external URIs with. Useful to set headers, proxies, cookies, and so forth.
None"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC","title":"ClearKeyCENC","text":"ClearKeyCENC(kids, laurl=None, content_keys=None, **kwargs)\n
W3C EME ClearKey (org.w3.clearkey) DRM System over MPEG-CENC tracks.
Distinct from the HLS AES-128 ClearKey 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).
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.kid","title":"kid property","text":"kid\n
Get first Key ID, if any.
"},{"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":" Bases: Exception
KID (Encryption Key ID) was not found.
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.Exceptions.CEKNotFound","title":"CEKNotFound","text":" Bases: Exception
CEK (Content Encryption Key) for KID was not found in License.
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.Exceptions.EmptyLicense","title":"EmptyLicense","text":" Bases: Exception
License returned no Content Encryption Keys.
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.to_dict","title":"to_dict","text":"to_dict()\n
Serialise this DRM instance for export/import (KIDs + license URL).
unshackle stores the content keys once at the export's track level, and does not duplicate them here.
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.get_license_challenge","title":"get_license_challenge","text":"get_license_challenge()\n
Assemble the W3C EME ClearKey JSON license request for the unkeyed KIDs.
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.get_content_keys","title":"get_content_keys","text":"get_content_keys(*, licence, session=None)\n
Get Content Keys for this DRM Instance from a ClearKey license server.
The licence param is a function. unshackle gives it the W3C JSON license request as challenge. 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.
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.decrypt","title":"decrypt","text":"decrypt(path)\n
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.
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.mp4decrypt_key_args","title":"mp4decrypt_key_args","text":"mp4decrypt_key_args()\n
Build the mp4decrypt --key arguments for every content key.
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.decrypt_with_mp4decrypt","title":"decrypt_with_mp4decrypt","text":"decrypt_with_mp4decrypt(path)\n
Decrypt using mp4decrypt
"},{"location":"reference/api/drm/#unshackle.core.drm.ClearKeyCENC.decrypt_with_shaka_packager","title":"decrypt_with_shaka_packager","text":"decrypt_with_shaka_packager(path)\n
Decrypt with shaka-packager
"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa","title":"MonaLisa","text":"MonaLisa(ticket, device_path, tool_path=None, **kwargs)\n
MonaLisa DRM System.
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.
Initialise MonaLisa DRM.
Parameters:
Name Type Description Default ticket Union[str, bytes] PSSH value from service API (base64 string or raw bytes).
required device_path Path Path to the CDM device file (.mld).
required tool_path Optional[Path] Optional path to an external decryption binary.
None **kwargs Any Additional metadata stored in self.data.
{} Raises:
Type Description TicketNotFound If ticket/PSSH is empty.
KeyExtractionFailed If content key extraction fails.
"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.kid","title":"kid property","text":"kid\n
Get the Key ID.
"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.key","title":"key property","text":"key\n
Get the content key as hex string.
"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.pssh","title":"pssh property","text":"pssh\n
Get the raw PSSH/ticket value as a string.
Returns:
Type Description str The raw PSSH value as a base64 string.
"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.content_id","title":"content_id property","text":"content_id\n
Extract the Content ID from the PSSH for display.
The PSSH contains an embedded Content ID at bytes 21-75 with format: H5DCID-V3-P1-YYYYMMDD-HHMMSS-MEDIAID-TIMESTAMP-SUFFIX
Returns:
Type Description Optional[str] The Content ID string if extractable, None otherwise.
"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.content_keys","title":"content_keys property","text":"content_keys\n
Get content keys in the same format as Widevine/PlayReady.
Returns:
Type Description dict[UUID, str] Dictionary mapping KID to the content key hex string.
"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.key_pair","title":"key_pair property","text":"key_pair\n
The formatted KID:KEY for CLI decryptors (32hex:32hex).
"},{"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":" Bases: Exception
Raised when the caller gives no PSSH/ticket data.
"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.Exceptions.KeyExtractionFailed","title":"KeyExtractionFailed","text":" Bases: Exception
Raised when content key extraction from the ticket fails.
"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.extract_keys","title":"extract_keys","text":"extract_keys()\n
Extract keys from the ticket using the MonaLisa CDM.
"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.from_ticket","title":"from_ticket classmethod","text":"from_ticket(ticket, device_path, tool_path=None)\n
Make a MonaLisa DRM instance from a PSSH/ticket.
Parameters:
Name Type Description Default ticket Union[str, bytes] PSSH value from service API.
required device_path Path Path to the CDM device file (.mld).
required tool_path Optional[Path] Optional path to an external decryption binary.
None Returns:
Type Description MonaLisa MonaLisa DRM instance with extracted keys.
"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.decrypt_segment","title":"decrypt_segment","text":"decrypt_segment(segment_path, output_path=None)\n
Decrypt an individual segment file using the configured CLI tool via subprocess.
Parameters:
Name Type Description Default segment_path Path Path to the segment file to decrypt.
required output_path Optional[Path] Optional path for the decrypted output segment.
None"},{"location":"reference/api/drm/#unshackle.core.drm.MonaLisa.decrypt","title":"decrypt","text":"decrypt(path, output_path=None, *, is_segment=False)\n
Decrypt a media file (segment or track) using the configured CLI tool via subprocess.
Parameters:
Name Type Description Default path Path Path to the target file to decrypt.
required output_path Optional[Path] Optional path for the decrypted output file.
None is_segment bool Set True if this is an individual segment rather than a full track.
False"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady","title":"PlayReady","text":"PlayReady(pssh, kid=None, pssh_b64=None, **kwargs)\n
PlayReady DRM System.
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.extract_kids_from_pssh_b64","title":"extract_kids_from_pssh_b64","text":"extract_kids_from_pssh_b64(pssh_b64)\n
Extract all KIDs from base64-encoded PSSH data.
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.to_dict","title":"to_dict","text":"to_dict()\n
Serialise this DRM instance for export/import (PSSH + KIDs).
unshackle stores the content keys once at the export's track level, and does not duplicate them here.
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.header_kids","title":"header_kids staticmethod","text":"header_kids(header)\n
Return the KIDs one WRM header names, in header order.
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.absorb","title":"absorb","text":"absorb(*others)\n
Fold sibling PlayReady objects into this one so their headers and KIDs get licensed too.
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.
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.distinct_headers","title":"distinct_headers","text":"distinct_headers()\n
Return the WRM headers to license, deduplicated by the KID set each one names.
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.
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.pro_b64_for","title":"pro_b64_for staticmethod","text":"pro_b64_for(header)\n
Build a base64 one-record PlayReady Object holding only this header.
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.
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.extract_keys_from_cdm","title":"extract_keys_from_cdm","text":"extract_keys_from_cdm(cdm, session_id)\n
Extract keys from CDM session with cross-library compatibility.
Parameters:
Name Type Description Default cdm Cdm CDM instance
required session_id bytes Session identifier
required Returns:
Type Description dict Dictionary mapping KID UUIDs to hex keys
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.get_content_keys","title":"get_content_keys","text":"get_content_keys(cdm, certificate, licence)\n
License every distinct WRM header whose KIDs still lack a content key.
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.
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.
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.detect_revocation","title":"detect_revocation staticmethod","text":"detect_revocation(text)\n
Return the decoded error string if a revocation HRESULT is present, else None.
Reads the code from the raw SOAP body (0x8004C065) or from an exception message that carries it, so this method covers any service.
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.decrypt","title":"decrypt","text":"decrypt(path)\n
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.
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.own_kids","title":"own_kids","text":"own_kids()\n
Return the KIDs that identify this track's own content key.
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.
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.mp4decrypt_key_args","title":"mp4decrypt_key_args","text":"mp4decrypt_key_args()\n
Build the mp4decrypt --key arguments for every content key and the zero-KID fallback.
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.decrypt_with_mp4decrypt","title":"decrypt_with_mp4decrypt","text":"decrypt_with_mp4decrypt(path)\n
Decrypt using mp4decrypt
"},{"location":"reference/api/drm/#unshackle.core.drm.PlayReady.decrypt_with_shaka_packager","title":"decrypt_with_shaka_packager","text":"decrypt_with_shaka_packager(path)\n
Decrypt with shaka-packager (original method)
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine","title":"Widevine","text":"Widevine(pssh, kid=None, **kwargs)\n
Widevine DRM System.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.pssh","title":"pssh property","text":"pssh\n
Get Protection System Specific Header Box.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.kid","title":"kid property","text":"kid\n
Get first Key ID, if any.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.kids","title":"kids property","text":"kids\n
Get all Key IDs from PSSH, falling back to the externally provided KID.
"},{"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":" Bases: Exception
PSSH (Protection System Specific Header) was not found.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.Exceptions.KIDNotFound","title":"KIDNotFound","text":" Bases: Exception
KID (Encryption Key ID) was not found.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.Exceptions.CEKNotFound","title":"CEKNotFound","text":" Bases: Exception
CEK (Content Encryption Key) for KID was not found in License.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.Exceptions.EmptyLicense","title":"EmptyLicense","text":" Bases: Exception
License returned no Content Encryption Keys.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.from_track","title":"from_track classmethod","text":"from_track(track, session=None)\n
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.
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.
You can give your own requests.Session to use custom headers and more.
Raises:
Type Description PSSHNotFound If the PSSH was not found within the data.
KIDNotFound If the KID was not found within the data or PSSH.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.from_init_data","title":"from_init_data classmethod","text":"from_init_data(init_data)\n
Get PSSH and KID from within Initialization Segment Data.
Use this method only when a PSSH cannot be given directly. It is rare to need to use this.
Raises:
Type Description PSSHNotFound If the PSSH was not found within the data.
KIDNotFound If the KID was not found within the data or PSSH.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.to_dict","title":"to_dict","text":"to_dict()\n
Serialise this DRM instance for export/import (PSSH + KIDs).
unshackle stores the content keys once at the export's track level, and does not duplicate them here.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.get_content_keys","title":"get_content_keys","text":"get_content_keys(cdm, certificate, licence)\n
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.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.decrypt","title":"decrypt","text":"decrypt(path)\n
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.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.own_kids","title":"own_kids","text":"own_kids()\n
Return the KIDs that identify this track's own content key.
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.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.mp4decrypt_key_args","title":"mp4decrypt_key_args","text":"mp4decrypt_key_args()\n
Build the mp4decrypt --key arguments for every content key and the zero-KID fallback.
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.decrypt_with_mp4decrypt","title":"decrypt_with_mp4decrypt","text":"decrypt_with_mp4decrypt(path)\n
Decrypt using mp4decrypt
"},{"location":"reference/api/drm/#unshackle.core.drm.Widevine.decrypt_with_shaka_packager","title":"decrypt_with_shaka_packager","text":"decrypt_with_shaka_packager(path)\n
Decrypt with shaka-packager (original method)
"},{"location":"reference/api/drm/#unshackle.core.drm.drm_from_dict","title":"drm_from_dict","text":"drm_from_dict(data)\n
Reconstruct a Widevine/PlayReady/ClearKeyCENC DRM instance from its to_dict() form.
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.
"},{"location":"reference/api/drm/#unshackle.core.drm.real_kids","title":"real_kids","text":"real_kids(drm)\n
Return the KIDs a DRM object names, without the all-zero and test-pattern placeholders.
"},{"location":"reference/api/drm/#unshackle.core.drm.own_kids","title":"own_kids","text":"own_kids(drm)\n
Return the real KIDs that identify the track's own content key, as the DRM object knows them.
"},{"location":"reference/api/service/","title":"Service API","text":"Auto-generated reference for the Service base class that every service plugin subclasses. See Creating a Service for a guided walkthrough and Service Architecture for the wider object model.
"},{"location":"reference/api/service/#unshackle.core.service.TimeoutSession","title":"TimeoutSession","text":" Bases: Session
requests.Session applying DEFAULT_TIMEOUT when the caller passes none.
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 timeout= wins. :class:TimeoutHTTPAdapter on the mounted adapters still replaces an explicit timeout=None with the default, so there is no unbounded read, as with RnetSession where the client-level timeouts always apply. Pass a large timeout instead.
"},{"location":"reference/api/service/#unshackle.core.service.TimeoutHTTPAdapter","title":"TimeoutHTTPAdapter","text":"TimeoutHTTPAdapter(\n *args, timeout=DEFAULT_TIMEOUT, **kwargs\n)\n
Bases: HTTPAdapter
HTTPAdapter applying DEFAULT_TIMEOUT when the caller passes none.
Backstops :class:TimeoutSession for the session.send(prepared) path, which bypasses Session.request. RnetSession bounds those too through its client, so this keeps parity. A per-request non-None timeout= wins. None (unset, or explicitly passed) gets the default, because the adapter cannot distinguish the two, and rnet has no unbounded mode either.
Source code in unshackle/core/service.py def __init__(self, *args: Any, timeout: Any = DEFAULT_TIMEOUT, **kwargs: Any) -> None:\n self.default_timeout = timeout\n super().__init__(*args, **kwargs)\n
"},{"location":"reference/api/service/#unshackle.core.service.TrackRequest","title":"TrackRequest dataclass","text":"TrackRequest(\n codecs=list(),\n ranges=(lambda: [SDR])(),\n best_available=False,\n)\n
Holds what the user requested for video codec and range selection.
Services read from this instead of ctx.parent.params for vcodec/range.
Attributes:
Name Type Description codecs list[Codec] Requested codecs from CLI. Empty list means no filter (accept any).
ranges list[Range] Requested ranges from CLI. Defaults to [SDR].
"},{"location":"reference/api/service/#unshackle.core.service.Service","title":"Service","text":"Service(ctx)\n
The Service Base Class.
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.
Source code in unshackle/core/service.py def __init__(self, ctx: click.Context):\n console.print(Padding(Rule(f\"[rule.text]Service: {self.__class__.__name__}\"), (1, 2)))\n\n self.config = ctx.obj.config\n\n self.log = logging.getLogger(self.__class__.__name__)\n\n self.session = self.get_session()\n self.cache = Cacher(self.__class__.__name__)\n self.title_cache = TitleCacher(self.__class__.__name__)\n self.cache_dir = config.directories.cache / self.__class__.__name__\n\n self.ctx = ctx\n self.credential = None # Will be set in authenticate()\n self.current_region = None # Will be set based on proxy/geolocation\n self._input_bridge: Optional[InputBridge] = None\n\n # Set track request from CLI params - services can read/override in their __init__\n vcodec = ctx.parent.params.get(\"vcodec\") if ctx.parent else None\n range_ = ctx.parent.params.get(\"range_\") if ctx.parent else None\n best_available = ctx.parent.params.get(\"best_available\", False) if ctx.parent else False\n self.track_request = TrackRequest(\n codecs=list(vcodec) if vcodec else [],\n ranges=list(range_) if range_ else [Video.Range.SDR],\n best_available=bool(best_available),\n )\n\n 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} -> {sanitize_proxy_for_log(mapped_value)}\"\n )\n if proxy_provider_name:\n # Specific provider requested\n try:\n proxy_provider = find_provider(ctx.obj.proxy_providers, proxy_provider_name)\n except ValueError:\n proxy_provider = None\n if proxy_provider:\n mapped_proxy_uri = proxy_provider.get_proxy(mapped_value)\n if mapped_proxy_uri:\n proxy = mapped_proxy_uri\n self.log.info(\n f\"Using mapped proxy from {proxy_provider.__class__.__name__}: \"\n f\"{sanitize_proxy_for_log(proxy, mask_host=isinstance(proxy_provider, Basic))}\"\n )\n else:\n self.log.warning(\n f\"Failed to get proxy for mapped value '{sanitize_proxy_for_log(mapped_value)}', using default\"\n )\n else:\n self.log.warning(f\"Proxy provider '{proxy_provider_name}' not found, using default proxy\")\n else:\n for proxy_provider in ctx.obj.proxy_providers:\n mapped_proxy_uri = proxy_provider.get_proxy(mapped_value)\n if mapped_proxy_uri:\n proxy = mapped_proxy_uri\n self.log.info(\n f\"Using mapped proxy from {proxy_provider.__class__.__name__}: \"\n f\"{sanitize_proxy_for_log(proxy, mask_host=isinstance(proxy_provider, Basic))}\"\n )\n break\n else:\n self.log.warning(\n f\"No provider could resolve mapped value '{sanitize_proxy_for_log(mapped_value)}', using default\"\n )\n\n if not proxy:\n # don't override the explicit proxy set by the user, even if they may be geoblocked\n with console.status(\"Checking if current region is Geoblocked...\", spinner=\"dots\"):\n if self.GEOFENCE 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 \"Pass --proxy with a proxy outside the blocked regions.\"\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 for proxy_provider in ctx.obj.proxy_providers:\n proxy = proxy_provider.get_proxy(requested_proxy)\n if proxy:\n self.log.info(f\"Got Proxy from {proxy_provider.__class__.__name__}\")\n break\n if not proxy:\n self.log.warning(\n f\"No proxy available for {requested_proxy}. \"\n f\"Pass --proxy with a proxy in {requested_proxy}, or the request can fail.\"\n )\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 # 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 \"Pass --proxy with a proxy outside the blocked regions.\"\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
"},{"location":"reference/api/service/#unshackle.core.service.Service.is_region_allowed","title":"is_region_allowed classmethod","text":"is_region_allowed(region)\n
True when an exit IP in region (two-letter region code, any case) can use the service.
An unknown region (None or empty) is allowed, because there is nothing to compare.
Source code in unshackle/core/service.py @classmethod\ndef is_region_allowed(cls, region: Optional[str]) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.get_tracks_for_variants","title":"get_tracks_for_variants","text":"get_tracks_for_variants(title, fetch_fn)\n
Call fetch_fn for each codec/range combo in track_request, merge results.
Services that need separate API calls per codec/range combo can use this helper from their get_tracks() implementation.
The fetch_fn signature should be: (title, codec, range_) -> Tracks
For HYBRID range, this helper calls fetch_fn with HDR10 and DV separately, then merges the DV video tracks into the HDR10 result.
Parameters:
Name Type Description Default title Title_T The title to process.
required fetch_fn Callable[..., Tracks] A callable that fetches tracks for a specific codec/range.
required Source code in unshackle/core/service.py def get_tracks_for_variants(\n self,\n title: Title_T,\n fetch_fn: Callable[..., Tracks],\n) -> Tracks:\n \"\"\"Call fetch_fn for each codec/range combo in track_request, merge results.\n\n Services that need separate API calls per codec/range combo can use this\n helper from their get_tracks() implementation.\n\n The fetch_fn signature should be: (title, codec, range_) -> Tracks\n\n For HYBRID range, this helper calls fetch_fn with HDR10 and DV separately,\n then merges the DV video tracks into the HDR10 result.\n\n Args:\n title: The title to process.\n fetch_fn: A callable that fetches tracks for a specific codec/range.\n \"\"\"\n all_tracks = Tracks()\n first = True\n\n codecs = self.track_request.codecs or [None]\n ranges = self.track_request.ranges or [Video.Range.SDR]\n\n for range_val in ranges:\n if range_val == Video.Range.HYBRID:\n # HYBRID: fetch HDR10 first (full tracks), then DV (video only)\n for codec_val in codecs:\n try:\n hdr_tracks = fetch_fn(title, codec=codec_val, range_=Video.Range.HDR10)\n except (ValueError, SystemExit) as e:\n if self.track_request.best_available:\n self.log.warning(f\" - HDR10 not available for HYBRID, skipping ({e})\")\n continue\n raise\n if first:\n all_tracks.add(hdr_tracks, warn_only=True)\n if hdr_tracks.manifest_url and not all_tracks.manifest_url:\n all_tracks.manifest_url = hdr_tracks.manifest_url\n first = False\n else:\n for video in hdr_tracks.videos:\n all_tracks.add(video, warn_only=True)\n\n try:\n dv_tracks = fetch_fn(title, codec=codec_val, range_=Video.Range.DV)\n for video in dv_tracks.videos:\n all_tracks.add(video, warn_only=True)\n except (ValueError, SystemExit):\n self.log.info(\" - No DolbyVision manifest available for HYBRID\")\n else:\n for codec_val in codecs:\n try:\n tracks = fetch_fn(title, codec=codec_val, range_=range_val)\n except (ValueError, SystemExit) as e:\n if self.track_request.best_available:\n codec_name = codec_val.name if codec_val else \"default\"\n self.log.warning(f\" - {range_val.name}/{codec_name} not available, skipping ({e})\")\n continue\n raise\n if first:\n all_tracks.add(tracks, warn_only=True)\n if tracks.manifest_url and not all_tracks.manifest_url:\n all_tracks.manifest_url = tracks.manifest_url\n first = False\n else:\n for video in tracks.videos:\n all_tracks.add(video, warn_only=True)\n\n return all_tracks\n
"},{"location":"reference/api/service/#unshackle.core.service.Service.get_session","title":"get_session staticmethod","text":"get_session()\n
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
Source code in unshackle/core/service.py @staticmethod\ndef get_session() -> requests.Session:\n \"\"\"\n Creates a Python-requests HTTP session, adds common headers\n from config, cookies, retry handler, and a proxy if available.\n :returns: Prepared Python-requests HTTP session\n \"\"\"\n session = TimeoutSession()\n session.headers.update(config.headers)\n # Retry / pool policy mirrors RnetSession via the shared constants in session.py:\n # same total, forcelist, backoff cap, allowed_methods (incl. POST, so license\n # requests retry on both paths), and pool size. Accepted divergence: urllib3's\n # backoff_jitter adds an absolute 0..N seconds whereas rnet jitters \u00b110% of the\n # backoff, the only intentional difference, not worth hand-rolling a retry loop.\n session.mount(\n \"https://\",\n TimeoutHTTPAdapter(\n max_retries=Retry(\n total=MAX_RETRIES,\n backoff_factor=BACKOFF_FACTOR,\n backoff_max=MAX_BACKOFF,\n backoff_jitter=0.2,\n status_forcelist=STATUS_FORCELIST,\n allowed_methods=RETRY_METHODS,\n respect_retry_after_header=True,\n ),\n pool_connections=POOL_MAX_SIZE,\n pool_maxsize=POOL_MAX_SIZE,\n pool_block=True,\n ),\n )\n session.mount(\"http://\", session.adapters[\"https://\"])\n return session\n
"},{"location":"reference/api/service/#unshackle.core.service.Service.get_binaries","title":"get_binaries staticmethod","text":"get_binaries()\n
Declare custom binary dependencies required by this service. :returns: List of dicts, each with a name and optional candidates and desc.
Source code in unshackle/core/service.py @staticmethod\ndef get_binaries() -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.authenticate","title":"authenticate","text":"authenticate(cookies=None, credential=None)\n
Authenticate the Service with Cookies and/or Credentials (Email/Username and Password).
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 ANONYMOUS_SEARCH, which does not operate this method.
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.
Do not store the cookies outside this function either. However, you can load the cookies into the service HTTP session.
Source code in unshackle/core/service.py def authenticate(self, cookies: Optional[CookieJar] = None, credential: Optional[Credential] = None) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.request_input","title":"request_input","text":"request_input(prompt)\n
Request interactive input from the user.
Locally, prompts through the shared rich console so the prompt renders alongside Live progress. A remote-dl session relays it through its :class:InputBridge, and a REST download job relays it through prompt_user to the job's input_prompt.
Source code in unshackle/core/service.py def request_input(self, prompt: str) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.wait_for_approval","title":"wait_for_approval","text":"wait_for_approval(message, check, timeout, interval=3.0)\n
Show message, then call check until it returns a value.
Use it for a login that the user approves on another device, such as a pair code. check returns None while the approval is pending, and must return within a few seconds. Raises TimeoutError after timeout seconds, and RuntimeError when the remote session no longer exists. A REST download job shows message as its notice.
Source code in unshackle/core/service.py def wait_for_approval(\n self, message: str, check: Callable[[], Optional[T]], timeout: float, interval: float = 3.0\n) -> 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 >= deadline:\n raise TimeoutError(f\"No approval within {timeout:.0f}s\")\n time.sleep(interval)\n finally:\n show_notice(None)\n
"},{"location":"reference/api/service/#unshackle.core.service.Service.search","title":"search","text":"search()\n
Find titles from the Service by query.
The Service class must take the query as a CLI argument. Ideally re-use the title ID argument (that is, self.title).
unshackle displays the search results in the order yielded.
Source code in unshackle/core/service.py def search(self) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.get_widevine_service_certificate","title":"get_widevine_service_certificate","text":"get_widevine_service_certificate(\n *, challenge, title, track\n)\n
Get the Widevine Service Certificate used for Privacy Mode.
:param challenge: The service challenge, providing this to a License endpoint should return the privacy certificate that the service uses. :param title: The current Title 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 Track needing decryption. Provided for same reason as title. :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.
Source code in unshackle/core/service.py def get_widevine_service_certificate(\n self, *, challenge: bytes, title: Title_T, track: AnyTrack\n) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.get_widevine_license","title":"get_widevine_license","text":"get_widevine_license(*, challenge, title, track)\n
Get a Widevine License message by sending a License Request (challenge).
This License message contains the encrypted content keys and will be read by the Cdm and decrypted.
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.
:param challenge: The license challenge from the Widevine CDM. :param title: The current Title 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 Track needing decryption. Provided for same reason as title. :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.
Source code in unshackle/core/service.py def get_widevine_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.get_playready_license","title":"get_playready_license","text":"get_playready_license(*, challenge, title, track)\n
Get a PlayReady License message by sending a License Request (challenge).
This License message contains the encrypted content keys and will be read by the CDM and decrypted.
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.
:param challenge: The license challenge from the PlayReady CDM. :param title: The current Title 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 Track needing decryption. Provided for same reason as title. :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.
Source code in unshackle/core/service.py def get_playready_license(\n self, *, challenge: bytes, title: Title_T, track: AnyTrack\n) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.get_clearkey_license","title":"get_clearkey_license","text":"get_clearkey_license(*, challenge, title, track)\n
Get a W3C ClearKey License (JWK Set) by sending a License Request (challenge).
Used for DASH org.w3.clearkey tracks. unshackle uses no CDM here: the challenge is the W3C EME JSON license request, e.g. {\"kids\": [\"<base64url>\"], \"type\": \"temporary\"}, and the license is a JWK Set, e.g. {\"keys\": [{\"kty\": \"oct\", \"k\": \"...\", \"kid\": \"...\"}]}.
:param challenge: The JSON license request bytes to POST to the license server. :param title: The current Title 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 Track needing decryption. Provided for same reason as title. :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 content_keys in get_tracks.
Source code in unshackle/core/service.py def get_clearkey_license(\n self, *, challenge: bytes, title: Title_T, track: AnyTrack\n) -> 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\": [\"<base64url>\"], \"type\": \"temporary\"}``,\n and the license is a JWK Set, e.g. ``{\"keys\": [{\"kty\": \"oct\", \"k\": \"...\", \"kid\": \"...\"}]}``.\n\n :param challenge: The JSON license request bytes to POST to the license server.\n :param title: The current `Title` from get_titles that unshackle processes now. unshackle\n gives this in case it holds data you need, for example for an HTTP request.\n :param track: The current `Track` needing decryption. Provided for same reason as `title`.\n :return: The JWK Set license as a dict, JSON str, or raw bytes. Return None (the default)\n to let the framework POST the challenge to the manifest-provided Laurl, if any.\n Services with no license server can instead pre-populate the DRM object's\n `content_keys` in get_tracks.\n \"\"\"\n return None\n
"},{"location":"reference/api/service/#unshackle.core.service.Service.get_titles","title":"get_titles abstractmethod","text":"get_titles()\n
Get Titles for the provided title ID.
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.
You must return at least one object. If you do not, unshackle presumes an invalid Title ID.
You can use the data 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.
Source code in unshackle/core/service.py @abstractmethod\ndef get_titles(self) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.get_titles_cached","title":"get_titles_cached","text":"get_titles_cached(title_id=None)\n
Cached wrapper around get_titles() to reduce redundant API calls.
This method checks the cache before calling get_titles() and handles fallback to cached data when API calls fail.
Parameters:
Name Type Description Default title_id str Optional title ID for cache key generation. If not provided, will try to extract from service instance.
None Returns:
Type Description Titles_T Titles object (Movies, Series, or Album)
Source code in unshackle/core/service.py def get_titles_cached(self, title_id: str = None) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.apply_title_map","title":"apply_title_map","text":"apply_title_map(titles)\n
Rewrite service-provided titles using the per-service title_map config.
title_map lives under services.<TAG> in unshackle.yaml. Applied after the title cache so config edits take effect without a cache reset, and before any --enrich override so enrich wins. See remap_titles for the match rules.
Source code in unshackle/core/service.py def apply_title_map(self, titles: Titles_T) -> Titles_T:\n \"\"\"\n Rewrite service-provided titles using the per-service ``title_map`` config.\n\n ``title_map`` lives under ``services.<TAG>`` 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.get_tracks","title":"get_tracks abstractmethod","text":"get_tracks(title)\n
Get Track objects of the Title.
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.
Each Track in the Tracks should represent a Video/Audio track, Representation, or Adaptation, or a Subtitle file.
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.
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.
Make sure you correctly mark which Tracks have encryption, and which DRM System they use, with the drm property.
If you can get the Track's KID (Key ID) as a 32 char (16 bit) HEX string, give it to the Track's kid 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.
:param title: The current Title from get_titles that unshackle processes now. :return: Tracks object containing Video, Audio, Subtitles, and Chapters, if available.
Source code in unshackle/core/service.py @abstractmethod\ndef get_tracks(self, title: Title_T) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.get_chapters","title":"get_chapters abstractmethod","text":"get_chapters(title)\n
Get Chapters for the Title.
Parameters:
Name Type Description Default title Title_T The current Title from get_titles that unshackle processes now.
required You must return a Chapters object containing 0 or more Chapter objects.
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.
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 chapter_fallback_name. For example, \"Chapter {i:02}\" for \"Chapter 01\".
Source code in unshackle/core/service.py @abstractmethod\ndef get_chapters(self, title: Title_T) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.on_segment_downloaded","title":"on_segment_downloaded","text":"on_segment_downloaded(track, segment)\n
Called when one of a Track's Segments has finished downloading.
Parameters:
Name Type Description Default track AnyTrack The Track object that had a Segment downloaded.
required segment Path The Path to the downloaded Segment.
required Source code in unshackle/core/service.py def on_segment_downloaded(self, track: AnyTrack, segment: Path) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.on_track_downloaded","title":"on_track_downloaded","text":"on_track_downloaded(track)\n
Called when a Track has finished downloading.
Parameters:
Name Type Description Default track AnyTrack The downloaded Track object.
required Source code in unshackle/core/service.py def on_track_downloaded(self, track: AnyTrack) -> None:\n \"\"\"\n Called when a Track has finished downloading.\n\n Parameters:\n track: The downloaded Track object.\n \"\"\"\n
"},{"location":"reference/api/service/#unshackle.core.service.Service.on_track_decrypted","title":"on_track_decrypted","text":"on_track_decrypted(track, drm, segment=None)\n
Called when a Track has finished decrypting.
Parameters:
Name Type Description Default track AnyTrack The decrypted Track object.
required drm DRM_T The DRM object it decrypted with.
required segment Optional[Segment] The decrypted HLS segment information. None for DASH and ISM tracks and for an HLS track that merged during the download (merge_segments).
None Source code in unshackle/core/service.py def on_track_decrypted(self, track: AnyTrack, drm: DRM_T, segment: Optional[m3u8.Segment] = None) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.Service.on_track_repacked","title":"on_track_repacked","text":"on_track_repacked(track)\n
Called when a Track has finished repacking.
Parameters:
Name Type Description Default track AnyTrack The repacked Track object.
required Source code in unshackle/core/service.py def on_track_repacked(self, track: AnyTrack) -> None:\n \"\"\"\n Called when a Track has finished repacking.\n\n Parameters:\n track: The repacked Track object.\n \"\"\"\n
"},{"location":"reference/api/service/#unshackle.core.service.Service.on_track_multiplex","title":"on_track_multiplex","text":"on_track_multiplex(track)\n
Called immediately before unshackle multiplexes a Track into a Container.
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.
Parameters:
Name Type Description Default track AnyTrack The repacked Track object.
required Source code in unshackle/core/service.py def on_track_multiplex(self, track: AnyTrack) -> 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
"},{"location":"reference/api/service/#unshackle.core.service.grow_session_pool","title":"grow_session_pool","text":"grow_session_pool(session, size)\n
Grow a shared requests session's connection pool to size before track downloads start.
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 downloads * workers 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 get_adapter. RnetSession does not block on its idle-pool cap, so this function skips it.
Every mounted adapter grows in place, through its own init_poolmanager. A service can mount an :class:HTTPAdapter subclass, such as SSLCiphers, on any prefix. Mounting a new adapter over it would drop that subclass state, and its TLS context with it.
Source code in unshackle/core/service.py def grow_session_pool(session: Any, size: int) -> 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) >= size:\n continue\n adapter.init_poolmanager(size, size, block=True)\n adapter.proxy_manager.clear()\n
"},{"location":"reference/api/service/#unshackle.core.service.sanitize_proxy_for_log","title":"sanitize_proxy_for_log","text":"sanitize_proxy_for_log(uri, mask_host=False)\n
Sanitise a proxy URI for logs by masking any embedded userinfo (username/password).
serve sends these log lines to the client of a remote session, so the mask is unconditional and debug mode never lifts it. mask_host hides the hostname as well, for a proxy that came from the user-supplied Basic proxy provider.
Source code in unshackle/core/service.py def sanitize_proxy_for_log(uri: Optional[str], mask_host: bool = False) -> 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
"},{"location":"reference/api/titles/","title":"Titles API","text":"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.
"},{"location":"reference/api/titles/#unshackle.core.titles.Episode","title":"Episode","text":"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
Bases: Title
"},{"location":"reference/api/titles/#unshackle.core.titles.Episode.matches_wanted","title":"matches_wanted","text":"matches_wanted(wanted)\n
Whether a parsed -w key set selects this episode.
A part-ful episode answers to both its base key and its part key, so -w s1e1 takes every part. A dated episode also answers to its ISO air date. ! keys are part-qualified exclusions resolved here.
"},{"location":"reference/api/titles/#unshackle.core.titles.Episode.part_suffix","title":"part_suffix","text":"part_suffix()\n
.Part.2 / Part 2 in the series template's own separator style.
"},{"location":"reference/api/titles/#unshackle.core.titles.Episode.build_template_context","title":"build_template_context","text":"build_template_context(\n media_info, show_service=True, include_part=True\n)\n
Build template context dictionary from MediaInfo.
"},{"location":"reference/api/titles/#unshackle.core.titles.Episode.air_date_display","title":"air_date_display","text":"air_date_display()\n
Render air_date using the series template's own separator (dots or spaces).
"},{"location":"reference/api/titles/#unshackle.core.titles.Episode.folder_season","title":"folder_season","text":"folder_season()\n
Season folder label: air year when the air date parsed to a date, else SxxExx-style season.
"},{"location":"reference/api/titles/#unshackle.core.titles.Episode.part_label","title":"part_label","text":"part_label()\n
.2 selection-syntax suffix for console output, empty when part-less.
"},{"location":"reference/api/titles/#unshackle.core.titles.Movie","title":"Movie","text":"Movie(\n id_,\n service,\n name,\n year=None,\n language=None,\n data=None,\n description=None,\n)\n
Bases: Title
"},{"location":"reference/api/titles/#unshackle.core.titles.Movie.build_template_context","title":"build_template_context","text":"build_template_context(media_info, show_service=True)\n
Build template context dictionary from MediaInfo.
"},{"location":"reference/api/titles/#unshackle.core.titles.Album","title":"Album","text":"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
Bases: Music
Backward-compatible collection name for album-style music releases.
"},{"location":"reference/api/titles/#unshackle.core.titles.Music","title":"Music","text":"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
Bases: SortedKeyList, ABC
A grouped music release, such as an album, EP, single, compilation, or playlist.
"},{"location":"reference/api/titles/#unshackle.core.titles.Song","title":"Song","text":"Song(\n id_,\n service,\n name,\n artist,\n album,\n track,\n disc=1,\n year=None,\n language=None,\n data=None,\n album_artist=None,\n release_type=\"album\",\n total_tracks=None,\n total_discs=None,\n genre=None,\n explicit=None,\n isrc=None,\n upc=None,\n copyright=None,\n label=None,\n lyrics=None,\n artwork_url=None,\n)\n
Bases: Title
"},{"location":"reference/api/titles/#unshackle.core.titles.Song.matches_wanted","title":"matches_wanted","text":"matches_wanted(wanted)\n
Whether a parsed -w key set selects this song.
A song shares the episode key space, its disc reading as the season and its track as the episode, so -w 1-5 takes tracks 1 to 5 and -w 2x3 takes disc 2 track 3. A song has no parts and no air date, so it answers to its disc-and-track key only.
"},{"location":"reference/api/titles/#unshackle.core.titles.Song.build_template_context","title":"build_template_context","text":"build_template_context(media_info, show_service=True)\n
Build template context dictionary from MediaInfo.
"},{"location":"reference/api/titles/#unshackle.core.titles.remap_titles","title":"remap_titles","text":"remap_titles(titles, title_map)\n
Rewrite titles in-place using an exact-match title_map.
Some services name a title differently from how the user wants it stored, which can break library matching. title_map maps a source title string to the desired output title. Episodes are matched on their title (the show name), Movies and Songs on their name. Returns the same collection for convenient chaining.
"},{"location":"reference/api/tracks/","title":"Tracks API","text":"Auto-generated reference for the track model: Tracks, Track, and the media-specific subclasses. See Service Architecture for how these fit together.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Attachment","title":"Attachment","text":"Attachment(\n path=None,\n url=None,\n name=None,\n mime_type=None,\n description=None,\n session=None,\n)\n
Make a new Attachment.
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.
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.
Parameters:
Name Type Description Default path Union[Path, str, None] Path to an existing file.
None url Optional[str] URL to download the attachment from.
None name Optional[str] Name of the attachment.
None mime_type Optional[str] MIME type of the attachment.
None description Optional[str] Description of the attachment.
None session Optional[AnySession] Optional requests HTTP session to download the file with.
None"},{"location":"reference/api/tracks/#unshackle.core.tracks.Attachment.id","title":"id property","text":"id\n
Compute an ID from the attachment data.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Attachment.download","title":"download","text":"download(\n session=None,\n *,\n no_proxy_download=False,\n proxy_download=None,\n)\n
Download a URL-backed attachment to the temp directory.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Attachment.to_dict","title":"to_dict","text":"to_dict()\n
Serialise a URL-backed attachment for export/import.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Attachment.delete","title":"delete","text":"delete()\n
Delete the file only if it is in the temp directory. Files in other locations belong to the user.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Attachment.from_url","title":"from_url classmethod","text":"from_url(\n url,\n name=None,\n mime_type=None,\n description=None,\n session=None,\n)\n
Make an attachment from a URL.
Parameters:
Name Type Description Default url str URL to download the attachment from.
required name Optional[str] Name of the attachment.
None mime_type Optional[str] MIME type of the attachment.
None description Optional[str] Description of the attachment.
None session Optional[AnySession] Optional requests HTTP session to download the file with.
None Returns:
Name Type Description Attachment 'Attachment' A new attachment instance.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Audio","title":"Audio","text":"Audio(\n *args,\n codec=None,\n bitrate=None,\n channels=None,\n joc=None,\n descriptive=False,\n **kwargs,\n)\n
Bases: Track
Make a new Audio track object.
Parameters:
Name Type Description Default codec Optional[Codec] An Audio.Codec enum representing the audio codec. If not specified, unshackle uses MediaInfo to get the codec after it downloads the track.
None bitrate Optional[Union[str, int, float]] A number or float representing the average bandwidth in bits/s. unshackle rounds float values up to the nearest integer.
None channels Optional[Union[str, int, float]] 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.
None joc Optional[int] The number of Joint-Object-Coding Channels/Objects in the audio track.
None descriptive Union[bool, int] Mark this audio as being descriptive audio for the blind.
False 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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Audio.atmos","title":"atmos property","text":"atmos\n
Return True if the audio track contains Atmos.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Audio.parse_channels","title":"parse_channels staticmethod","text":"parse_channels(channels)\n
Converts a Channel string to a float representing the audio channel layout. E.g. \"3\" -> \"3.0\", \"2.1\" -> \"2.1\", \".1\" -> \"0.1\".
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.
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->6.0.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Audio.channel_total","title":"channel_total staticmethod","text":"channel_total(channels)\n
Total number of channels in either channel form, so a caller can compare both.
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\" -> 10.0.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Audio.to_music_container","title":"to_music_container","text":"to_music_container()\n
Remux the track into the container of its codec, as a standalone audio file.
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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Audio.get_track_name","title":"get_track_name","text":"get_track_name()\n
Return the base Track Name.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapter","title":"Chapter","text":"Chapter(timestamp, name=None)\n
Make a new Chapter with a Timestamp and optional name.
The timestamp may be in the following formats: - \"HH:MM:SS\" string, e.g., 25:05:23. - \"HH:MM:SS.mss\" string, e.g., 25:05:23.120. - a timecode integer in milliseconds, e.g., 90323120 is 25:05:23.120. - a timecode float in seconds, e.g., 90323.12 is 25:05:23.120.
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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapter.id","title":"id property","text":"id\n
Compute an ID from the Chapter data.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapter.named","title":"named property","text":"named\n
True if the Chapter has a name.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapters","title":"Chapters","text":"Chapters(iterable=None)\n
Bases: SortedKeyList, ABC
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapters.id","title":"id property","text":"id\n
Compute an ID from the Chapter data.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapters.loads","title":"loads classmethod","text":"loads(data)\n
Load chapter data from a string.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapters.load","title":"load classmethod","text":"load(path)\n
Load chapter data from a file.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapters.dumps","title":"dumps","text":"dumps(fallback_name='')\n
Return chapter data in OGM-based Simple Chapter format. https://mkvtoolnix.download/doc/mkvmerge.html#mkvmerge.chapters.simple
Parameters:
Name Type Description Default fallback_name str Name used for Chapters without a Name set.
'' The fallback name can use the following variables in f-string style:
- {i}: The Chapter number starting at 1. E.g.,
\"Chapter {i}\": \"Chapter 1\", \"Intro\", \"Chapter 3\". - {j}: A number starting at 1 that increments any time a Chapter has no name. E.g.,
\"Chapter {j}\": \"Chapter 1\", \"Intro\", \"Chapter 2\".
unshackle formats these with f-strings, so format directives work. For example, \"Chapter {i:02}\" will result in \"Chapter 01\".
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Chapters.dump","title":"dump","text":"dump(path, *args, **kwargs)\n
Write chapter data in OGM-based Simple Chapter format to a file.
Parameters:
Name Type Description Default path Union[Path, str] The file path to write the Chapter data to, overwriting any existing data.
required See Chapters.dumps for more parameter documentation.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Hybrid","title":"Hybrid","text":"Hybrid(videos, source, output_name=None)\n
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Hybrid.log","title":"log instance-attribute","text":"log = logging.getLogger('hybrid')\n
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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Hybrid.level_5","title":"level_5","text":"level_5(input_video)\n
Make Level 5 active area metadata through crop detection on the HDR10 track.
This resolves mismatches where DV has no black bars but HDR10 does (or vice versa) by telling the display the correct active area.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Hybrid.sanitize_l6","title":"sanitize_l6 staticmethod","text":"sanitize_l6(max_mdl, min_mdl, max_cll, max_fall)\n
Clamp static L6 values to a valid relationship.
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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Hybrid.level_6","title":"level_6","text":"level_6()\n
Edit RPU Level 6 values using the static L6 luminance data from the RPU.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Hybrid.extract_hdr10plus","title":"extract_hdr10plus","text":"extract_hdr10plus(video)\n
Extract HDR10+ metadata from the video track
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Hybrid.probe_hdr_metadata","title":"probe_hdr_metadata","text":"probe_hdr_metadata()\n
Extract mastering display and Content Light Level metadata from the HDR10 track with FFprobe.
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)
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Hybrid.convert_hdr10plus_to_dv","title":"convert_hdr10plus_to_dv","text":"convert_hdr10plus_to_dv()\n
Convert HDR10+ metadata to Dolby Vision RPU
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle","title":"Subtitle","text":"Subtitle(\n *args,\n codec=None,\n cc=False,\n sdh=False,\n forced=False,\n **kwargs,\n)\n
Bases: Track
Make a new Subtitle track object.
Parameters:
Name Type Description Default codec Optional[Codec] A Subtitle.Codec enum representing the subtitle format. If not specified, unshackle uses MediaInfo to get the format after it downloads the track.
None cc bool 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 - >>> (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.
False sdh bool 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.
False forced bool 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.
False Note: If codec is not specified, unshackle can skip some checks or assume a value. Give as much information as possible.
Information on Subtitle Types 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.
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)
More in-depth information, examples, and stuff to look for can be found in the Parameter explanation list above.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.get_track_name","title":"get_track_name","text":"get_track_name()\n
Return the base Track Name.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.strip_webvtt_cue_classes","title":"strip_webvtt_cue_classes staticmethod","text":"strip_webvtt_cue_classes(text)\n
Reduce a cue payload to the markup every target format shares: <i>, <b> and <u> without their class list. It removes class spans (<c.foo>), <v>, <lang>, <ruby>/<rt> and karaoke timestamps (<00:00:01.000>).
A class only selects a CSS ::cue 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 [0-9a-zA-Z_/]. The dot fails that test, so FFmpeg prints <i.loud> as cue text and then emits the closing italic-off with nothing opened. FFmpeg's WebVTT reader matches i/b/u 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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.strip_webvtt_timestamp_map","title":"strip_webvtt_timestamp_map staticmethod","text":"strip_webvtt_timestamp_map(text)\n
Remove X-TIMESTAMP-MAP header lines (RFC 8216 \u00a73.5, HLS only).
Cue times are already absolute, but SubtitleEdit reads the header and offsets every cue by it during conversion.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.sanitize_webvtt_timestamps","title":"sanitize_webvtt_timestamps staticmethod","text":"sanitize_webvtt_timestamps(text)\n
Fix invalid timestamps in WebVTT files, particularly negative timestamps.
Parameters:
Name Type Description Default text str The WebVTT text as string
required Returns:
Type Description str Sanitized WebVTT text
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.has_webvtt_cue_identifiers","title":"has_webvtt_cue_identifiers staticmethod","text":"has_webvtt_cue_identifiers(text)\n
Examine WebVTT text for cue identifiers that need removal.
Parameters:
Name Type Description Default text str The WebVTT text as string
required Returns:
Type Description bool True if the text has cue identifiers, False otherwise
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.sanitize_webvtt_cue_identifiers","title":"sanitize_webvtt_cue_identifiers staticmethod","text":"sanitize_webvtt_cue_identifiers(text)\n
Remove WebVTT cue identifiers that can confuse subtitle parsers.
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).
Parameters:
Name Type Description Default text str The WebVTT text as string
required Returns:
Type Description str Sanitized WebVTT text with cue identifiers removed
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.parse_vtt_time","title":"parse_vtt_time staticmethod","text":"parse_vtt_time(t)\n
Parse WebVTT timestamp to milliseconds. Returns 0 for malformed input.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.has_overlapping_webvtt_cues","title":"has_overlapping_webvtt_cues staticmethod","text":"has_overlapping_webvtt_cues(text)\n
Examine WebVTT text for overlapping cues that need merging.
Detects cues with start times within 50ms of each other and the same end time, which indicates multi-line subtitles split into separate cues.
Parameters:
Name Type Description Default text str The WebVTT text as string
required Returns:
Type Description bool True if the text has overlapping cues, False otherwise
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.merge_overlapping_webvtt_cues","title":"merge_overlapping_webvtt_cues staticmethod","text":"merge_overlapping_webvtt_cues(text)\n
Merge WebVTT cues that have overlapping/near-identical times but different line positions.
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).
Parameters:
Name Type Description Default text str The WebVTT text as string
required Returns:
Type Description str WebVTT text with overlapping cues merged
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.sanitize_webvtt","title":"sanitize_webvtt staticmethod","text":"sanitize_webvtt(text)\n
More thorough sanitization of WebVTT files that corrects multiple potential issues.
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.
Parameters:
Name Type Description Default text str The WebVTT text as string
required Returns:
Type Description str Sanitized WebVTT text
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.convert","title":"convert","text":"convert(codec, *, forced=False)\n
Convert this Subtitle to another format.
Backend selection is data-driven (see tracks/subtitle_convert.py): unshackle uses the best available backend that can convert source->target, and falls back through the capability chain on failure. The conversion_method config key (auto | subby | pysubs2 | subtitleedit | pycaption) pins the backend, and preferred_conversion_method nudges it per-service. An explicit config value always wins.
forced marks an explicit user request (--sub-format). unshackle skips lossy downconverts of styled formats (SSA/ASS -> SRT) unless forced is True.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.extract_fonts","title":"extract_fonts staticmethod","text":"extract_fonts(text)\n
Font names referenced by an ASS/SSA subtitle.
Covers both sources that need attaching for correct rendering: - the Fontname column of every Style: line in [V4+ Styles]/[V4 Styles] (column located from the section's Format: line, not assumed by index), and - inline \\fn font overrides inside Dialogue override blocks.
This method removes a leading @ (vertical-writing prefix), de-duplicates the names case-insensitively, and prefers a mixed-case spelling over an all-lowercase one.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.sanitize_broken_webvtt","title":"sanitize_broken_webvtt staticmethod","text":"sanitize_broken_webvtt(text)\n
Remove or fix corrupted WebVTT lines, particularly those with invalid timestamps.
Parameters:
Name Type Description Default text str The WebVTT text as string
required Returns:
Type Description str Sanitized WebVTT text with corrupted lines removed
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.space_webvtt_headers","title":"space_webvtt_headers staticmethod","text":"space_webvtt_headers(data)\n
Space out the WEBVTT Headers from Captions.
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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.merge_same_cues","title":"merge_same_cues staticmethod","text":"merge_same_cues(caption_set)\n
Merge captions with the same timecodes and text as one in-place.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.filter_unwanted_cues","title":"filter_unwanted_cues staticmethod","text":"filter_unwanted_cues(caption_set)\n
Filter out subtitle cues containing only \u00a0 or whitespace.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.merge_segmented_wvtt","title":"merge_segmented_wvtt staticmethod","text":"merge_segmented_wvtt(data, period_start=0.0)\n
Convert Segmented DASH WebVTT cues into a pycaption Caption List. Also returns an ISO 639-2 alpha-3 language tag if available.
Code ported originally by xhlove to Python from shaka-player. rlaphoenix has since improved it with pymp4 and pycaption functions.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.sample_slice","title":"sample_slice","text":"sample_slice(starts, timescale=1, window=None)\n
Return the segments of window plus one segment on each side.
Cue times in a segment are absolute, so sample_start stays zero and trim makes the cut. A track that ends before the window keeps only its last segment.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.trim","title":"trim","text":"trim(start, end)\n
Keep the cues between start and end seconds and move them to start at zero.
Returns False and leaves the file whole when pysubs2 cannot read or write its format.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.strip_hearing_impaired","title":"strip_hearing_impaired","text":"strip_hearing_impaired()\n
Remove the SDH captions.
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
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Subtitle.reverse_rtl","title":"reverse_rtl","text":"reverse_rtl()\n
Reverse RTL (Right to Left) Start/End on Captions. Use this to fix the positioning of sentence-ending characters.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.DownloadContext","title":"DownloadContext dataclass","text":"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
Shared arguments passed to each manifest's download_track.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.DownloadContext.ensure_session","title":"ensure_session","text":"ensure_session()\n
Return the HTTP session, or a new Session if none was set.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track","title":"Track","text":"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
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.data","title":"data property writable","text":"data\n
Arbitrary track data dictionary.
This uses a defaultdict with a dict as the factory for easier nested saving and safer exists-checks.
Reserved keys:
- \"hls\" used by the HLS class.
- playlist: m3u8.model.Playlist - The primary track information.
- media: m3u8.model.Media - The audio/subtitle track information.
- segment_durations: list[int] - A list of each segment's duration.
- \"dash\" used by the DASH class.
- manifest: lxml.ElementTree - DASH MPD manifest.
- period: lxml.Element - The period of this track.
- adaptation_set: lxml.Element - The adaptation set of this track.
- representation: lxml.Element - The representation of this track.
- timescale: int - The timescale of the track's segments.
- segment_durations: list[int] - A list of each segment's duration.
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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.drm_preference","title":"drm_preference property writable","text":"drm_preference\n
DRM system this track must license with, one of the names in DRM_PREFERENCE_TYPES.
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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.sample_slice","title":"sample_slice","text":"sample_slice(starts, timescale=1, window=None)\n
Return the slice of segments that hold window, from the start time of each segment.
Sets sample_start to the start time of the first kept segment, in seconds. A video keeps sample_tail 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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.sample_byte_range","title":"sample_byte_range","text":"sample_byte_range(session)\n
Find the bytes of a one-file track that hold the sample window.
Reads the start of the file for a sidx 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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.can_sample","title":"can_sample","text":"can_sample(session)\n
Return False when a sample cannot cut this track, because it is one file with no segment index.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.add_init_drm","title":"add_init_drm","text":"add_init_drm(init_data, cdm)\n
Add the Widevine and PlayReady DRM that the init segment carries and the track does not have.
A track with a different DRM type stays as it is. The DRM system that agrees with the CDM comes first.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.prefers_playready","title":"prefers_playready","text":"prefers_playready(cdm)\n
Whether to try PlayReady before Widevine. The track's preference wins over the loaded CDM.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.download","title":"download","text":"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
Download and optionally Decrypt this Track.
For a URL-descriptor Video or Audio track with no drm set, unshackle probes the DRM from the track's init data and stores it on the track, so a service need not declare drm itself.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.move","title":"move","text":"move(target)\n
Move the Track's file from current location, to target location. This will overwrite anything at the target path.
Raises:
Type Description TypeError If the target argument is not the expected type.
ValueError If track has no file to move, or the target does not exist.
OSError If the file somehow failed to move.
Returns the new location of the track.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.to_dict","title":"to_dict","text":"to_dict()\n
Serialise the track for export/import (identity/URL/descriptor/language).
DRM is not serialised here. The export writer attaches the licensed DRM + keys. Subclasses add their own codec/quality fields.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.base_kwargs_from_dict","title":"base_kwargs_from_dict staticmethod","text":"base_kwargs_from_dict(data)\n
Assemble the shared Track constructor kwargs from a to_dict() payload.
DRM is not reconstructed here: to_dict does not serialise it, and the import flow attaches the licensed DRM + content keys separately.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.from_dict","title":"from_dict classmethod","text":"from_dict(data)\n
Reconstruct the correct Track subclass from a to_dict() payload.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.get_track_name","title":"get_track_name","text":"get_track_name()\n
Get the Track Name.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.get_drm_for_cdm","title":"get_drm_for_cdm","text":"get_drm_for_cdm(cdm)\n
Return the DRM matching the provided CDM, if available.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.get_key_id","title":"get_key_id","text":"get_key_id(init_data=None, *args, **kwargs)\n
Probe the DRM encryption Key ID (KID) for this specific track.
It can find the Key ID by probing the track with FFprobe for enc_key_id data, as well as for mp4 tenc (Track Encryption) boxes.
It explicitly ignores PSSH information like the PSSH box, as the box is likely to contain multiple Key IDs that may or may not be for this specific track.
To retrieve the initialization segment, this method calls :meth:get_init_segment with the positional and keyword arguments. This method then uses the return value of get_init_segment to find the Key ID.
Returns:
Type Description Optional[UUID] The Key ID as a UUID object, or None if unshackle cannot find the Key ID.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.load_drm_if_needed","title":"load_drm_if_needed","text":"load_drm_if_needed(service=None)\n
Load DRM information for this track if the parser deferred it.
Parameters:
Name Type Description Default service Service | None Service instance that can fetch track-specific DRM info
None Returns:
Type Description bool True if the DRM loaded or is already present, False if the load failed
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.load_drm_from_playlist","title":"load_drm_from_playlist","text":"load_drm_from_playlist()\n
Fallback method to load DRM by fetching this track's individual playlist.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.get_init_segment","title":"get_init_segment","text":"get_init_segment(\n maximum_size=20000,\n url=None,\n byte_range=None,\n session=None,\n)\n
Get the Track's initial segment data.
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.
If byte_range 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 maximum_size.
The default maximum_size of 20000 (20KB) is a tried-and-tested value that seems to work well across the board.
Parameters:
Name Type Description Default maximum_size int 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.
20000 url Optional[str] Explicit init map or file URL to probe from.
None byte_range Optional[str] Range of bytes to download from the explicit or implicit URL.
None session Optional[Session] HTTP session context, for example authorization and headers.
None"},{"location":"reference/api/tracks/#unshackle.core.tracks.Track.repackage","title":"repackage","text":"repackage(bsf_v=None)\n
Remux the track with FFmpeg -c copy.
A given bsf_v goes into the same pass as -bsf:v, 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 bsf_v so the remux still succeeds. Returns True if unshackle applied the requested bsf_v (always False when bsf_v is None, because the caller requested nothing).
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks","title":"Tracks","text":"Tracks(*args, manifest_url=None)\n
Video, Audio, Subtitle, Chapter, and Attachment Track Store. It provides convenience functions for listing, sorting, and selecting tracks.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.sample_base","title":"sample_base property","text":"sample_base\n
The earliest sample_start of the video and audio tracks, which a sample mux uses as time zero.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.exists","title":"exists","text":"exists(by_id=None, by_url=None)\n
Examine whether a track already exists, by various methods.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.add","title":"add","text":"add(tracks, warn_only=False)\n
Add a provided track to its appropriate array.
A track whose ID is already in the collection raises ValueError. With warn_only set, this method skips such a track and logs how many it skipped.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.sort_videos","title":"sort_videos","text":"sort_videos(by_language=None, exact_match=False)\n
Sort video tracks by resolution then bitrate, and optionally language.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.sort_audio","title":"sort_audio","text":"sort_audio(\n by_language=None, codec_priority=None, exact_match=False\n)\n
Sort audio tracks by bitrate, codec priority, Atmos, descriptive, and optionally language.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.sort_subtitles","title":"sort_subtitles","text":"sort_subtitles(\n by_language=None,\n type_priority=None,\n group_by=None,\n exact_match=False,\n)\n
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.
Section Order - by_language groups prioritized to top, and ascending alphabetically
- then rest ascending alphabetically after the prioritized groups (Each section ascending alphabetically, but separated)
Type Order - Forced
- Normal
- Hard of Hearing (SDH/CC) (Least to most captions expected in the subtitle)
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.
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.
exact_match makes a by_language entry sort only its own tag. By default \"en\" also sorts \"en-US\" and \"en-GB\".
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.filter","title":"filter","text":"filter(predicate)\n
Return a new Tracks with tracks filtered by predicate, preserving metadata.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.merge_video_selections","title":"merge_video_selections staticmethod","text":"merge_video_selections(*groups)\n
Concatenate video selections, dropping duplicates (by track id, order-preserving).
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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.partition_hybrid_videos","title":"partition_hybrid_videos staticmethod","text":"partition_hybrid_videos(videos, non_hybrid_ranges)\n
Split videos into hybrid-ingredient candidates and the standalone-deliverable pool.
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 -r HYBRID muxes only the hybrid while -r HYBRID,HDR10P also delivers HDR10+.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.flag_hybrid_ingredients","title":"flag_hybrid_ingredients staticmethod","text":"flag_hybrid_ingredients(\n hybrid_selected, non_hybrid_selected\n)\n
Mark tracks selected only as hybrid ingredients so the standalone mux loop skips them.
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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Tracks.mux","title":"mux","text":"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
Multiplex all the Tracks into a Matroska Container file.
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.
Parameters:
Name Type Description Default title str Set the Matroska Container file title. Usually displayed in players instead of the filename if set.
required delete bool Delete all track files after multiplexing.
True progress Optional[partial] Update a rich progress bar with completed=.... This must be the progress object's update() func, pre-set with task id by functools.partial.
None audio_expected bool Whether the output must have audio. unshackle uses this to decide if it adds embedded audio metadata.
True title_language Optional[Language] The title's intended language. Used to select the best video track for audio metadata when multiple video tracks exist.
None skip_subtitles bool Skip muxing subtitle tracks into the container.
False output_path Optional[Path] 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.
None"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video","title":"Video","text":"Video(\n *args,\n codec=None,\n range_=None,\n bitrate=None,\n width=None,\n height=None,\n fps=None,\n scan_type=None,\n closed_captions=None,\n dv_compatible_bitstream=False,\n **kwargs,\n)\n
Bases: Track
Make a new Video track object.
Parameters:
Name Type Description Default codec Optional[Codec] A Video.Codec enum representing the video codec. If not specified, unshackle uses MediaInfo to get the codec after it downloads the track.
None range_ Optional[Range] A Video.Range enum representing the video colour range. Defaults to SDR if not specified.
None bitrate Optional[Union[str, int, float]] A number or float representing the average bandwidth in bytes/s. unshackle rounds float values up to the nearest integer.
None width Optional[int] The horizontal resolution of the video.
None height Optional[int] The vertical resolution of the video.
None fps Optional[Union[str, int, float]] 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.
None 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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.Range","title":"Range","text":" Bases: str, Enum
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.Range.from_cicp","title":"from_cicp staticmethod","text":"from_cicp(primaries, transfer, matrix)\n
Convert CICP (Coding-Independent Code Points) values to Video Range.
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.
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)
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.
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
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.change_color_range","title":"change_color_range","text":"change_color_range(range_)\n
Change the Video's Colour Range to Limited (0) or Full (1).
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.vui_bsf","title":"vui_bsf","text":"vui_bsf()\n
Return the -bsf:v value that rewrites SPS VUI colour metadata to match self.range.
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 {h264,hevc}_metadata=... string suitable for FFmpeg -bsf:v.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.normalize_vui","title":"normalize_vui","text":"normalize_vui()\n
Rewrite SPS VUI colour metadata to match self.range.
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.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.ccextractor","title":"ccextractor","text":"ccextractor(track_id, out_path, language, original=False)\n
Return a TextTrack object representing CC track extracted by CCExtractor.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.extract_c608","title":"extract_c608","text":"extract_c608()\n
Extract Apple-Style c608 box (CEA-608) subtitle using CCExtractor.
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.
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.
Need a test file with more than one c608 box, before unshackle can extract more than one CEA-608 track.
"},{"location":"reference/api/tracks/#unshackle.core.tracks.Video.remove_eia_cc","title":"remove_eia_cc","text":"remove_eia_cc()\n
Remove EIA-CC data from Bitstream while keeping SEI data.
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.
"},{"location":"reference/configuration/","title":"Configuration Reference","text":"Every config key you can set in unshackle.yaml, with its name, type, default value, and behaviour, split into one page per area. A worked config is on the annotated example page.
Where the file lives, how unshackle discovers it, and how to edit it: The Configuration File.
How defaults work
Every config key is optional except output_template, which dl requires. Without it, dl 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 yaml.safe_load. An empty or missing file means every other config key falls back to its default.
Two keys behave specially on load
curl_impersonate is a deprecated alias of network and emits a DeprecationWarning. scene_naming has been removed. If it is set to any value, unshackle exits immediately with an error telling you to use output_template instead.
See Deprecated & removed keys.
"},{"location":"reference/configuration/#quick-index","title":"Quick index","text":"Area Keys Directories directories, filenames, services_repo_force Services & authentication services, credentials, firefox_cookies, remote_services, serve Download & processing dl, continue_downloads, merge_segments, subtitle, audio, muxing, language_tags, dual_multi_mode Output & naming output_template, tag, tag_rules, tag_group_name, tag_imdb_tmdb, chapter_fallback_name, unicode_filenames DRM & CDM cdm, remote_cdm, decryption Network & proxy network, headers, proxy_providers Key vaults key_vaults, vault_timeout Post-scripts post_scripts External API keys omdb_api_key, tmdb_api_key, tvdb_api_key, tvdb_pin, tvdb_order, simkl_client_id, metadata_providers, anilist_title_language, disable_metadata, decrypt_labs_api_key, ipinfo_api_key Caching & updates title_cache_enabled, title_cache_time, title_cache_max_retention, update_checks, update_check_interval Appearance theme Logging, privacy & debug redact_paths, debug, debug_keys, debug_requests, set_terminal_bg Deprecated & removed curl_impersonate, downloader, scene_naming"},{"location":"reference/configuration/directories/","title":"Directories","text":"The directories 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 Path(...).expanduser(), so ~ works.
unshackle.yamldirectories:\n downloads: ~/Media/unshackle\n temp: /mnt/fast-scratch/unshackle-temp\n wvds: ~/.unshackle/WVDs\n prds: ~/.unshackle/PRDs\n
Key Type Default Overridable Purpose downloads path <repo>/downloads Yes Default output directory for finished files. temp path <repo>/temp Yes Temporary working files during download/decrypt/mux. cache path <data>/cache Yes Generic cache, title cache, and the update-check store. cookies path <data>/cookies Yes Per-service cookie files (and VPN cookie files). logs path <data>/logs Yes Log files. exports path <data>/exports Yes Export JSON files. wvds path <data>/WVDs Yes Widevine device files (.wvd). prds path <data>/PRDs Yes PlayReady device files (.prd). dcsl path <data>/DCSL Yes DCSL data. commands path unshackle/commands Yes CLI command modules. services list | path [unshackle/services] Yes Service search paths and/or remote repo specs (see below). vaults path unshackle/vaults Yes Vault backend modules. fonts path unshackle/fonts Yes Bundled fonts. user_configs path unshackle/ No protected Where unshackle.yaml lives. data path unshackle/ No protected Base for the data subdirectories above. core_dir path unshackle/core No protected Package core. namespace_dir path unshackle/ No protected Package root. app_dirs - AppDirs(\"unshackle\", False) No protected Internal AppDirs instance. The services directory is special
services may be a list, and each entry can be either a local directory or a repository spec: a git URL (https://..., ssh://..., git@..., or anything ending in .git) or owner/repo 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.
directories:\n services:\n - you/your-services # cloned from GitHub\n - https://example.com/private.git@stable\n - ~/my-services # local, lowest priority\n
How git-backed service repos are handled
unshackle's use of git is read-only on the remote: it only ever does a shallow clone, fetch, pull, and a local reset. unshackle never pushes anything. Your existing git credential helper authenticates private repos, and unshackle stores no tokens of its own. Clones live under <first-local-services-dir>/_repos/<host>__<owner>__<repo>/ (or the bundled unshackle/services), 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.
Automatic and manual refresh behave differently
The automatic 24 h-TTL refresh that happens during a normal dl/search 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, __pycache__) never block it. The manual unshackle util refresh-services command instead hard-resets the clone to upstream, discarding any local edits.
Set services_repo_force: true to make the automatic 24 h refresh behave like refresh-services. When a refresh is due, the run fetches and hard-resets every clone, and discards any local edits in _repos/. Runs between refreshes do not touch the network. Use it on unattended hosts where nobody edits the clones by hand.
services_repo_force: true\n
Refresh inside serve
A running server does not restart to pick up a refresh. Both the periodic refresh (serve.services_refresh_interval, see serve) and the manual POST /api/maintenance/refresh-services 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; GET /api/services marks it with pending_update in the meantime.
Read-only installs and reinstalls
If the services directory lives inside the installed package, a reinstall can delete the _repos clones. They are re-cloned on next use. On read-only installs you must point services at a writable path, or cloning will fail.
"},{"location":"reference/configuration/directories/#filenames","title":"Filenames","text":"The filenames config key is a dict of templated file/name patterns. unshackle uses each value verbatim (no path processing). It fills in braced fields like {time} and {service} at runtime.
Key Type Default Notes log str \"unshackle_{name}_{time}.log\" Written under directories.logs. debug_log str \"unshackle_debug_{service}_{time}.jsonl\" Structured debug log, under directories.logs. config str \"config.yaml\" Per-service config file, under that service's directory. root_config str \"unshackle.yaml\" The main config filename itself. chapters str \"Chapters_{title}_{random}.txt\" Under directories.temp. subtitle str \"Subtitle_{id}_{language}.srt\" Under directories.temp."},{"location":"reference/configuration/download/","title":"Download & processing","text":""},{"location":"reference/configuration/download/#dl","title":"dl","text":" - Type:
dict \u00a0\u00b7\u00a0 Default: {}
Persistent defaults for the dl command. unshackle uses the block as Click's default_map, so you can give any dl flag a default here. See Downloading and the CLI Reference for what each flag does.
Config key naming. A config key is the flag's long name with dashes replaced by underscores (--best-available \u2192 best_available, --sub-format \u2192 sub_format). A few config keys use the flag's internal destination and not its visible name. Set these exact config keys:
Flag Config key -r / --range range --list list --tmdb tmdb_id --imdb imdb_id --anilist anilist_id -naa / --noatmos no_atmos -o / --output output_dir --cdm-only / --vaults-only cdm_only Precedence (highest first): an explicit CLI flag \u2192 a per-service services.<TAG>.dl override \u2192 this global dl: block \u2192 the built-in default. In other words, config only fills in options you did not set on the command line.
Common config keys. This is a useful subset, and every dl flag works:
Key Type Default Sets lang list [\"orig\"] Video/audio language(s); orig = original language. A - prefix excludes, e.g. [all, -es]. a_lang / v_lang list [] Audio- / video-only language override. A - prefix excludes. s_lang list [\"all\"] Subtitle language(s). A - prefix excludes, e.g. [all, -es]. quality list [] (best) Resolution(s), e.g. [1080]. vcodec list [] (any) Video codec(s), e.g. [H265]. acodec list [] (any) Audio codec(s), e.g. [EC3]. range list [\"SDR\"] Colour range(s): SDR, HLG, HDR10, HDR10P, DV, HYBRID. channels float (unset) Audio channels, e.g. 6 for 5.1. sub_format str (unset) Convert subtitles to this format (srt, vtt, original, ...). forced_subs bool false Include forced subtitle tracks. forced_s_lang list [] Forced subtitle language(s); implies forced_subs. A - prefix excludes. forced_subs_only bool false Keep only forced subtitle tracks; implies forced_subs. audio_description bool false Include descriptive (audio-description) tracks. audio_description_only bool false Keep only descriptive (audio-description) tracks. no_subs / no_audio / no_chapters / no_attachments bool false Skip that track type. no_attachments also skips attaching subtitle fonts. downloads int 1 Tracks downloaded concurrently. workers int (downloader default) Threads per track. speed_limit str (unlimited) Total download speed cap across all downloads combined, e.g. 500k, 5M, 1.5G or plain bytes/sec. Values are bytes, not bits (5M = 5.0 MB/s). slow str (unset) Inter-title delay, e.g. \"20-40\". best_available bool false Warn instead of failing when a requested resolution, range, or language is missing, or when one DRM system does not license under --all-drm. The CLI flag is --best-available, also spelled --warn-only. proxy str (unset) Default proxy URI or 2-letter country. no_folder bool false Do not create a per-title folder. no and yes are language tags
YAML reads a bare no as false and a bare yes as true. unshackle puts both back to the tags no (Norwegian) and yes (Nyankpa) in every config key that takes a language: lang, v_lang, a_lang, s_lang, forced_s_lang, require_audio, require_video, require_subs, language_priority, muxing.default_language and the language_tags rules. Quotes (lang: \"no\") work as well.
Global download defaultsdl:\n lang: [en]\n quality: [1080]\n range: [HDR10]\n vcodec: [H265]\n sub_format: srt\n downloads: 2\n
Language exclusions in YAML
The language keys accept the same - exclusion tokens as the command line. Give them as a list or as one comma-separated string.
dl:\n s_lang: [all, -es]\n a_lang: \"orig,-es\"\n
See Excluding languages for the rules.
Per-service overrides
A dl block nested under a service in services takes the same keys and applies to that service only.
dl:\n lang: [en]\nservices:\n EXAMPLE1:\n dl:\n lang: [en, ja]\n range: [DV]\n
serve uses these same keys
The serve block accepts most of the same dl 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, speed_limit for example. serve has its own global_speed_limit.
"},{"location":"reference/configuration/download/#continue_downloads","title":"continue_downloads","text":" - Type:
bool \u00a0\u00b7\u00a0 Default: false
Keep a failed download's completed segment files so the next download resumes from where it stopped instead of restarting from byte zero.
unshackle reuses only whole, fully downloaded segments. It always discards partially written segments, and no partial-byte (Range) 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.
What can and cannot resume
- Segmented DASH, ISM, and HLS tracks resume.
- 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).
- 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.
- A track downloaded with
merge_segments or decrypt_segments never resumes. Both options consume or rewrite the segment files during the download.
For a one-off resume without changing config, pass dl --continue-downloads on the command line (the flag can only enable resume, never disable it).
Resume failed downloadscontinue_downloads: true\n
"},{"location":"reference/configuration/download/#merge_segments","title":"merge_segments","text":" - Type:
bool \u00a0\u00b7\u00a0 Default: false
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.
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 decrypt_segments also on, each segment is appended after its decryption completes, never before.
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.
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 EXT-X-KEY, with no EXT-X-DISCONTINUITY, 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.
No resume
A track that merges segment by segment always downloads from the start. continue_downloads cannot reuse its segments, because unshackle deletes each segment after it appends it.
merge_segments: true\n
"},{"location":"reference/configuration/download/#subtitle","title":"subtitle","text":" - Type:
dict \u00a0\u00b7\u00a0 Default: {}
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.
Sub-key Type Default Description strip_sdh bool true Strip SDH/CC cues (hearing-impaired annotations) into a clean track. sdh_method str \"auto\" SDH-stripping backend to use. preserve_formatting bool true Pass WebVTT cue text through as written. false re-encodes it through pycaption, which merges identical cues but flattens styling. unshackle removes WebVTT-only cue markup either way. convert_before_strip bool true Convert to the working format before stripping SDH. conversion_method str \"auto\" Subtitle conversion backend. output_mode str \"mux\" mux embeds subtitles in the MKV; sidecar writes separate files; both writes sidecars and still muxes. sidecar_format str \"srt\" Format for sidecar files when output_mode is sidecar or both. type_priority list (unset) Ordered ranking of subtitle types (forced, normal, sdh; CC counts as SDH). Types you leave out fall to the end. group_by str \"type\" Which key groups the subtitle tracks. type puts all forced tracks together, then all normal, then all SDH. language keeps each language next to its own variants. language_priority 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. subtitle:\n strip_sdh: true\n output_mode: sidecar\n sidecar_format: srt\n
group_by track order
group_by Result type Danish, Finnish, French, \u2026 Danish SDH, Finnish SDH, French SDH language Danish, Danish SDH, Finnish, Finnish SDH, French, French SDH type_priority still sets the order of the variants, so with group_by: language it controls the order inside each language.
language_priority sorts languages, it does not select them
subtitle:\n group_by: language\n language_priority: [en, es, fr]\n
Result for an English title Default English, Arabic, Bulgarian, Spanish, French, Japanese With the list above English, Spanish, French, Arabic, Bulgarian, Japanese unshackle removes nothing, unlike -sl, which drops every subtitle language it does not name.
Use orig in the list for the title's original language. A base tag also covers its regional forms, so en sorts en-US and en-GB, but zh does not cover zh-Hant, which you must name. The sort ignores entries that match no track, and it ignores entries that are not valid language tags.
--exact-lang applies here too: with it, en sorts only en, and en-US falls to the alphabetical tail with the rest. Name each tag you want when you use that flag.
type_priority picks the default subtitle only with muxing.default_language
At mux time the default flag goes to every forced subtitle whose language matches the first audio track, so a full dialogue track never becomes default on its own. type_priority alone does not change that. Name a subtitle language in muxing.default_language and the first track in that language gets the flag instead, which is where type_priority decides which track that is:
muxing:\n default_language:\n subtitle: en\nsubtitle:\n type_priority: [normal, sdh, forced]\n
"},{"location":"reference/configuration/download/#audio","title":"audio","text":" - Type:
dict \u00a0\u00b7\u00a0 Default: {}
Audio handling options. The most notable sub-key is codec_priority, an ordered list of audio codecs used to break ties in track selection. language_priority is an ordered list of languages that sort to the top of the audio tracks.
audio:\n codec_priority:\n - EAC3\n - AC3\n language_priority:\n - orig\n - en\n
codec_priority is a soft priority: nothing is dropped
codec_priority 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 codec_priority, and audio-description tracks are always forced to the end regardless of it. When codec_priority is unset, tracks sort by bitrate alone, with those same Atmos/descriptive rules still applied.
"},{"location":"reference/configuration/download/#muxing","title":"muxing","text":" - Type:
dict \u00a0\u00b7\u00a0 Default: {}
Matroska (MKV) muxing options.
Sub-key Type Default Description set_title bool true Write a human-readable title into the MKV container. default_language dict {} Force which language is flagged default per track type, e.g. {audio: en, subtitle: en}. merge_audio bool true Merge all audio into one file. --split-audio on the CLI flips this off. merge_video bool false Merge video tracks that share height, range, and codec into one file, so only language varies inside a file. --merge-video on the CLI flips this on. concurrency int 4 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 1 on a hard disk, where parallel writes are slower. muxing:\n set_title: true\n concurrency: 4\n default_language:\n audio: en\n subtitle: en\n
"},{"location":"reference/configuration/download/#language_tags","title":"language_tags","text":" - Type:
dict \u00a0\u00b7\u00a0 Default: {}
Language-tag remapping and the rule engine behind the {lang_tag} filename variable. When a rules list is present, unshackle evaluates each rule in order and uses the first match's tag. A rule can examine:
Condition Meaning audio At least one audio language matches. subs_contain At least one subtitle language matches. subs_contain_all Every listed language must be present. dual / multi / dubbed true matches when that filename variable is set, false when it is not. Each language condition takes one language tag or a list of them. A list matches when any entry matches, except subs_contain_all, which needs them all. An entry that is not a valid language tag (for example japanese) never matches. dual, multi and dubbed take a bare true or false, 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.
dual, multi and dubbed 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 DUAL, MULTi and DUBBED text. A rule that names dubbed: true and a language tags a localized dub without tagging a native release the same way.
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
Put {lang_tag} where you want the name
These rules fill {lang_tag}. To use your own name in place of the fixed text, keep {lang_tag?} in the template and leave out {dual?}, {multi?} and {dubbed?}.
"},{"location":"reference/configuration/download/#dual_multi_mode","title":"dual_multi_mode","text":" - Type:
str \u00a0\u00b7\u00a0 Default: strict
Rule set for the {dual}, {multi}, and {dubbed} filename variables.
strict (default)count (legacy) Variable Set when {dual} Exactly two audio languages and one is the title's original language. {multi} Three or more audio languages, even without the original. {dubbed} A single audio language that is not the title's original language (requires a known original). Variable Set when {dual} Exactly two audio languages (original language ignored). {multi} Three or more audio languages. {dubbed} Never set. dual_multi_mode: strict\n
Dialects count as one language
Regional variants of the same base language (e.g. en-US and en-GB) collapse to a single language in both modes, so they never trigger {dual} on their own.
"},{"location":"reference/configuration/drm/","title":"DRM & CDM","text":"These are the config keys. For concepts, device provisioning, and the wvd/prd commands see the DRM & CDM guide. Device files themselves live in directories.wvds (.wvd) and directories.prds (.prd).
"},{"location":"reference/configuration/drm/#cdm","title":"cdm","text":" - Type:
dict \u00a0\u00b7\u00a0 Default: {}
Maps a service tag to the CDM (Widevine/PlayReady device) to use, with a default fallback. Resolution is case-insensitive: an override (dl --cdm <name>, or the cdm field of an API job) wins, then the per-service entry, then default. An override pins one device for the whole run and skips any quality or Widevine/PlayReady sub-entries.
Over --remote, 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 widevine or playready sub-entry, or a profile or default 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 default entry, the server CDM licenses when the API key has it. See remote_services.
cdm:\n default: chromecdm_l3\n EXAMPLE2: android_l1\n
A value may also be a nested dict for advanced selection by quality, DRM system, or profile:
cdm:\n EXAMPLE1:\n \">=1080\": android_l1 # by track height\n \"<1080\": chromecdm_l3\n widevine: android_l1 # by DRM system\n playready: sl3000\n default: chromecdm_l3\n
Quality keys can hold 1080, >=1080, >720, <=576, <480 style comparisons. DRM keys are widevine / playready. 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 widevine/playready when present, or else the credential profile name, then default.
When an entry holds widevine and playready, 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 widevine / playready dict in a quality key does not set the order. The server CDM of a remote session follows the same order.
A quality key can also hold a dict of widevine / playready devices, and so can the top-level default entry:
cdm:\n default:\n widevine: chromecdm_l3\n playready: sl2000\n EXAMPLE1:\n \">=1080\": { widevine: android_l1, playready: sl3000 }\n \"<1080\": { widevine: chromecdm_l3, playready: sl2000 }\n
A quality key that holds one device name applies to both DRM systems. When a track needs the other system, unshackle uses the widevine / playready config key of the entry. dl --all-drm needs a device for each system from one of these shapes.
unshackle finds the resolved name in remote_cdm by name first. If no entry matches, unshackle loads it as a local device file, in this order: <name>.prd in directories.prds, <name>.prd in directories.wvds, then <name>.wvd in directories.wvds.
"},{"location":"reference/configuration/drm/#remote_cdm","title":"remote_cdm","text":" - Type:
list[dict] \u00a0\u00b7\u00a0 Default: []
A list of remote CDM definitions. unshackle matches each entry by its name (referenced from cdm), and its type selects the backend:
type Backend Key fields decrypt_labs Decrypt Labs KeyXtractor host, device_name, secret (fields) custom_api Fully YAML-configurable remote API host (required), device, auth, endpoints, request_mapping, response_mapping, caching, timeout (fields) (none), Device Type: PLAYREADY pyplayready RemoteCdm host, secret, device_name, security_level (default 3000) (none), otherwise pywidevine RemoteCdm host, secret, device_name, device_type, system_id, security_level (default 3000) 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
For the two pywidevine/pyplayready backends, field names are read case-insensitively in both styles: Device Type/device_type, System ID/system_id, Security Level/security_level, Host/host, Secret/secret, Device Name/device_name.
Serve APIs behind a proxy
unshackle does not send upstream's HEAD request or examine the Server response header, so the server can operate behind a reverse proxy or a CDN that removes or changes that header. Thus a host 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 secret from the request.
PlayReady host needs a /playready suffix
pyplayready's RemoteCdm treats host as a base URL and appends its own endpoint paths, so a PlayReady entry's host must include the trailing /playready segment (for example https://cdm.example.com/playready). Without it the server returns 404 rather than a configuration error.
"},{"location":"reference/configuration/drm/#remote-cdm-decrypt-labs","title":"decrypt_labs fields","text":"Field Default Notes host https://keyxtractor.decryptlabs.com device_name ChromeCDM ChromeCDM, L1, L2, L3 (Widevine) or SL2, SL3 (PlayReady). The host decides which of these names it serves. secret from decrypt_labs_api_key Sent as the decrypt-labs-api-key header. An error is raised if neither is set. system_id 26830 (Widevine), 0 (PlayReady) security_level Widevine 3; PlayReady 2000 for SL2, else 3000 unshackle uses PlayReady mode when device_type is PLAYREADY or device_name starts with SL.
"},{"location":"reference/configuration/drm/#remote-cdm-custom-api","title":"custom_api fields","text":"Field Type Notes host str Required. Base URL of the API. device dict name, type (CHROME, ANDROID, PLAYREADY), system_id, security_level auth dict type (default header): header uses header_name (default Authorization) and key; bearer uses bearer_token or key; basic uses username and password. custom_headers is merged in for any type. endpoints dict get_request and decrypt_response, each {path, method, timeout} request_mapping dict Per endpoint: param_names, static_params, conditional_params, transforms, nested_params, exclude_params response_mapping dict Per endpoint: fields, transforms, response_types, success_conditions, error_fields, key_fields caching dict enabled, use_vaults, check_cached_first legacy dict Legacy mode options. timeout int Default 30. Request timeout in seconds. Transforms cover base64/hex/JSON encoding and kid:key parsing. unshackle uses PlayReady mode when device.type is PLAYREADY or the device name is SL2/SL3.
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
"},{"location":"reference/configuration/drm/#decryption","title":"decryption","text":" - Type:
str or dict \u00a0\u00b7\u00a0 Default: \"shaka\"
Selects the tool that physically decrypts CENC-encrypted tracks. unshackle compares the value case-insensitively. \"mp4decrypt\" selects Bento4's mp4decrypt, and anything else (including \"shaka\") selects shaka-packager. When the value is a dict, unshackle compares the service tag case-insensitively and uses the default entry as the fallback.
unshackle decrypts HLS AES-128 ClearKey in-process and ignores this setting.
GlobalPer-service decryption: shaka\n
decryption:\n default: shaka\n EXAMPLE1: mp4decrypt\n
"},{"location":"reference/configuration/drm/#decrypt_segments","title":"decrypt_segments","text":" - Type:
bool \u00a0\u00b7\u00a0 Default: false
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.
This works with mp4decrypt only. Set decryption to mp4decrypt for the service (or as the default); with shaka 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 EXT-X-KEY and no EXT-X-DISCONTINUITY. Every other track keeps the whole-file decryption.
No resume
A track that decrypts segment by segment always downloads from the start. continue_downloads cannot reuse its segments, because a reused segment is already decrypted.
decrypt_segments: true\n
"},{"location":"reference/configuration/example/","title":"A complete annotated example","text":"The following config sets a handful of common config keys. Every config key not shown keeps its default.
unshackle.yamldirectories:\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
For how these interact at runtime, continue to Downloading, DRM & CDM, and Output & naming.
"},{"location":"reference/configuration/misc/","title":"Other Settings","text":"Smaller configuration areas: external metadata API keys, caching and update checks, logging and debug flags, and deprecated keys.
"},{"location":"reference/configuration/misc/#external-api-keys","title":"External API keys","text":"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.
Key Type Default Description omdb_api_key str \"\" OMDb API key for IMDb metadata lookups; a fallback for when the keyless imdb provider has no answer. Free keys are available on the OMDb site. tmdb_api_key str \"\" TMDB API key for metadata enrichment and external-ID tags. simkl_client_id str \"\" SIMKL client ID for metadata lookups; an alternative/fallback source to TMDB. tvdb_api_key str \"\" TheTVDB v4 API key; a fallback source to TMDB, strongest on TV series. Also the source --enrich --tvdb reads. Free keys are available on the TVDB site. tvdb_pin str \"\" Subscriber PIN, only needed for a user-supported TVDB key. Leave empty for a normal project key. tvdb_order str \"\" Default for --tvdb-order: renumber episodes to a TVDB season order (official, dvd, absolute, alternate, regional). Empty keeps the numbering the service gives. metadata_providers list or map (see below) Metadata providers to use, in the order they are tried. anilist_title_language str english Which AniList title variant to use: english, romaji, or native. disable_metadata bool false Set to true to stop all automatic metadata lookups. An ID you give yourself is still looked up. decrypt_labs_api_key str \"\" Global Decrypt Labs API key (used by remote CDM / vault). ipinfo_api_key str \"\" ipinfo.io API key for IP/region lookups. How metadata_providers is applied
A lookup goes to each metadata provider in turn and stops at the first good match, so the order decides which source wins. metadata_providers sets that order:
metadata_providers: [tvdb, tmdb, simkl]\n
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:
metadata_providers: [imdb, omdb, simkl, tmdb, tvdb, anilist]\n
Whatever the order, unshackle skips a metadata provider that has no API key. imdb and anilist need no API key, so they are always available. Available names are imdb, omdb, simkl, tmdb, tvdb, and anilist. The old name imdbapi still works and is read as imdb.
anilist 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.
The order applies to a title search and to a direct lookup of an ID you give with --tmdb, --imdb, --tvdb, or --anilist. A supplied ID always goes to the providers that read that kind of ID, and it never falls back to a title search.
Which AniList title anilist_title_language picks
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:
anilist_title_language: romaji\n
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.
What disable_metadata turns off
With disable_metadata: true, unshackle never contacts a metadata provider on its own. The title search is dead, and that includes the keyless imdb metadata provider. Titles, years and languages then come only from the service.
disable_metadata: true\n
An ID you give with --tmdb, --imdb, --tvdb, or --anilist 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 --enrich still reads that source. unshackle stops only the lookups you did not ask for.
The imdb provider needs no key
It replaces the earlier imdbapi metadata provider, which read a third-party mirror (api.tiffara.com) and needed the imdb_api_enabled switch. That option is gone: delete it from your config, where it is now ignored.
A different order per title kind
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, tv and movie, and this example sets both of them and names every metadata provider, so nothing is left to the default:
metadata_providers:\n tv: [tvdb, tmdb, simkl, imdb, omdb]\n movie: [tmdb, imdb, omdb, simkl, tvdb]\n
Each list is independent: it both orders and filters that kind on its own, so unshackle still uses for movie a metadata provider you leave out of tv. Here unshackle tries TVDB first for a series and last for a film.
You do not need to give both keys, or a full list in each. A kind you leave out uses the default order:
metadata_providers:\n tv: [tvdb, tmdb] # movies keep the default order\n
tv covers every episode and movie covers every film. unshackle only looks up metadata for those two kinds, so unshackle ignores any other config key, such as anime or music.
ipinfo_api_key never touches your service sessions
unshackle sends the token only to api.ipinfo.io, as a per-request Authorization 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 ip-api.in as a last resort.
"},{"location":"reference/configuration/misc/#caching-updates","title":"Caching & updates","text":""},{"location":"reference/configuration/misc/#title-cache","title":"Title cache","text":"unshackle caches fetched title metadata (region- and account-aware) to avoid repeat API calls.
Key Type Default Description title_cache_enabled bool true Master switch for the title cache. title_cache_time int (seconds) 1800 (30 min) Lifetime of fresh cached titles. title_cache_max_retention int (seconds) 86400 (24 h) Total retention window for a cached title, counted from when it was cached. Past title_cache_time 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 update_checks bool true Whether to check for new unshackle releases. update_check_interval int (hours) 24 Minimum hours between update checks. Note
Update checks query the GitHub releases API with a fixed 5-second timeout and cache the result in directories.cache/update_check.json.
"},{"location":"reference/configuration/misc/#appearance","title":"Appearance","text":"Key Type Default Description theme str catppuccin-mocha Named colour theme for all CLI output: banner, logs, progress bars, and help screens. One of catppuccin-mocha (aliases default, catppuccin, mocha), dracula, nord, gruvbox, one-dark (alias onedark), tokyo-night (alias tokyonight), monokai, flexoki, solarized-dark (alias solarized). Case-insensitive; underscores work in place of hyphens. Unknown names fall back to the default with a warning. Preview them all with unshackle env theme."},{"location":"reference/configuration/misc/#logging-privacy-debug","title":"Logging, privacy & debug","text":"Key Type Default Description redact_paths bool true Mask install-root / venv / home prefixes in logged paths (<unshackle>, <venv>, ~). Set false to show full paths. debug bool false Global debug mode. debug_keys bool false Log decryption keys. debug_requests bool false Log HTTP requests. set_terminal_bg bool false Append the theme's background colour to output styling. Effect of set_terminal_bg
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.
Key exposure
With debug_keys on, unshackle writes the content keys to the structured debug log at INFO level during the DRM handshake. Treat debug, debug_keys, and the unshackle_debug_*.jsonl files as sensitive, and keep redact_paths enabled when sharing logs.
debug_keys affects only content-encryption keys (the content_key/key 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.
"},{"location":"reference/configuration/misc/#deprecated-removed-keys","title":"Deprecated & removed keys","text":"Key Status Behaviour curl_impersonate Deprecated \u2192 use network Emits a DeprecationWarning; still honoured only if network is absent. downloader Deprecated Any value other than \"requests\" emits a DeprecationWarning; the value is otherwise ignored (the unified requests downloader is always used). scene_naming Removed If set to any non-null value, unshackle exits with an error directing you to configure output_template instead. imdb_api_enabled Removed Ignored. It gated the old imdbapi provider, which the keyless imdb provider replaces. Safe to delete from your config."},{"location":"reference/configuration/network/","title":"Network & proxy","text":""},{"location":"reference/configuration/network/#network","title":"network","text":" - Type:
dict \u00a0\u00b7\u00a0 Default: {}
TLS-fingerprinting and HTTP client settings for the rnet-based HTTP session.
Sub-key Type Default Description browser str \"Chrome131\" Impersonation preset. Must be an exact preset name (e.g. Chrome131, Firefox135, Edge101, Safari18, OkHttp4_12, OkHttp5, Opera118); unknown names raise an error. http1_only bool (unset) Force HTTP/1.1. http2_only bool (unset) Force HTTP/2. connect_timeout int 10 Connect timeout in seconds. read_timeout int 30 Read timeout in seconds (max gap between response chunks). timeout int (unset) Total request timeout in seconds. allow_redirects bool (unset) Follow redirects automatically (rnet client default when unset). pool_idle_timeout int 55 Seconds an idle pooled connection is kept (default stays under typical ~60s CDN idle kills). pool_max_idle_per_host int 64 Max idle connections kept per host. pool_max_size int (unset) Max total connections in the pool. tcp_keepalive int 30 TCP keepalive time in seconds. tcp_keepalive_interval int (unset) TCP keepalive probe interval in seconds. tcp_keepalive_retries int (unset) TCP keepalive probe retry count. tcp_nodelay bool (unset) Disable Nagle's algorithm. network:\n browser: Firefox135\n http2_only: true\n
Measured effect of http1_only
Both http1_only and http2_only 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.
Renamed from curl_impersonate
The old curl_impersonate section is a deprecated alias. If you still use it, unshackle honours it (only when network is absent) but emits a DeprecationWarning. Rename it to network.
"},{"location":"reference/configuration/network/#headers","title":"headers","text":" - Type:
dict \u00a0\u00b7\u00a0 Default: {}
Default HTTP headers merged into every HTTP session unshackle makes.
headers:\n Accept-Language: en-US,en;q=0.9\n
Don't set Accept-Encoding (and similar) here
Compatibility headers such as Accept-Encoding 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 Accept-Language, User-Agent). Per-service headers belong in that service's own config.
"},{"location":"reference/configuration/network/#proxy_providers","title":"proxy_providers","text":" - Type:
dict \u00a0\u00b7\u00a0 Default: {}
Proxy/VPN provider configuration. Each sub-key names a proxy provider, and unshackle passes its block straight to that provider's constructor. See Proxies & VPN for the full proxy provider guide. Recognised proxy providers and their exit ports:
Provider Config key Credentials Proxy scheme/port Basic (static) basic country \u2192 URI(s) as specified Control D controld Write API token (profile/resolver pairs optional) http://127.0.0.1:{port} (local forwarder) NordVPN nordvpn service credentials (48 chars combined) https://...:89 Surfshark surfsharkvpn service credentials (48 chars combined) https://...:443 Windscribe windscribevpn service credentials https://...:443 ExpressVPN expressvpn device login (enable: true) / token cache https://cat:...@...:443 ProtonVPN protonvpn TV login or exported cookies https://...:4443 (or :443 Secure Core) Gluetun gluetun per-VPN keys/creds http://localhost:{port} (local Docker) Hola (none, auto) none http://...:{peer} 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: <service username>\n password: <service password>\n
"},{"location":"reference/configuration/network/#controld","title":"controld","text":"Config keys of the Control D proxy provider. See Control D for how unshackle uses them.
Key Type Default Meaning token str required A Control D API token of type Write. profile str none Optional. The ID of a profile you made for unshackle. Give it together with resolver. Without it, unshackle creates unshackle-<region> profiles itself. resolver str none Optional. The resolver ID of an endpoint that uses profile, or its DoH URL https://dns.controld.com/<resolver>. profiles list [] Optional. More pairs, each a mapping with profile and resolver. max_profiles int 4 The most profiles unshackle uses: your pairs plus the unshackle-* endpoints on the account. It must be 1 or more. unshackle creates an unshackle-<region> profile and endpoint only while the total is lower. Provider loading differs between CLI and REST server
The dl CLI loads all providers, including gluetun. The REST API / remote-client path does not load gluetun, because it starts a local Docker container. ExpressVPN and ProtonVPN also auto-load when their cached session exists, and Hola auto-loads whenever the hola-proxy binary is present.
"},{"location":"reference/configuration/output/","title":"Output & naming","text":"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 & naming guide.
"},{"location":"reference/configuration/output/#output_template","title":"output_template","text":" - Type:
dict \u00a0\u00b7\u00a0 Required (no usable default; dl exits with an error if this is missing)
Filename templates keyed by media kind, using {variable} placeholders. Recognised kinds are movies, series, and songs (and albums for folder templates). A trailing ? on a variable (e.g. {quality?}) marks it optional: if empty, it and one adjacent separator are dropped.
unshackle.yamloutput_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
The nested folder sub-key controls output subfolders, and unshackle pops it out of output_template:
- A dict sets per-kind folder templates (kinds:
movies, series, songs, albums). - A str sets a single folder template for everything.
unshackle validates templates on load and emits warnings for unknown variables, non-string values, filesystem-unsafe characters (< > : \" / \\ | ? *), empty templates, and unknown folder-kind keys.
All valid template variables title, year, season, episode, season_episode, episode_name, part, absolute, date, quality, resolution, source, tag, track_number, artist, album_artist, album, disc, track_total, disc_total, release_type, genre, explicit, isrc, upc, label, audio, audio_channels, audio_full, atmos, dual, multi, dubbed, video, hdr, hfr, edition, repack, lang_tag, title_type.
{part?} is already inside {season_episode}
part holds the bare part index of a split episode (2) and is empty on every other title. unshackle folds it into {episode} and {season_episode}, so the shipped series template names split episodes correctly with no edit. Putting {part?} next to either of them renders the part twice (S01E01.Part.2.2). Use the standalone variable only in a template that names neither {episode} nor {season_episode}, and note that it is always empty in a folder template, since folders do not carry the part.
{absolute} counts episodes across seasons
absolute holds the absolute episode number, zero-padded to 3 digits (007), and is empty on titles that have none. You add it to the name yourself, and it never replaces {season} or {episode}. Any series with a TVDB absolute order can use it, anime most often. Services can supply it, and --enrich fills it in from TVDB. Use {absolute?} so the name stays clean when it is unknown.
"},{"location":"reference/configuration/output/#tagging-naming-keys","title":"Tagging & naming keys","text":"Key Type Default Description tag str \"\" Release-group tag. Fills the {tag} template variable and is written into MKV/audio tags. tag_group_name bool true Include the group name (tag) in the MKV Group tag. tag_imdb_tmdb bool true Write IMDb/TMDB/TVDB external-ID tags into the MKV (needs metadata providers). chapter_fallback_name str \"\" Fallback template for chapter names, e.g. \"Chapter {i:02}\". unicode_filenames bool false Allow Unicode in filenames; when false, names are ASCII-sanitised."},{"location":"reference/configuration/output/#tag_rules","title":"tag_rules","text":" - Type:
list \u00a0\u00b7\u00a0 Default: []
Conditionally replaces tag for a given download. Each rule pairs a when dict of conditions with the tag to use when they hold. unshackle evaluates the rules in order and the first match wins. If no rule matches, the global tag stays.
unshackle.yamltag_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
Rule semantics:
- Every condition in
when must hold (they are AND-ed). - A value can be a scalar or a list. A list matches if any entry matches.
- Comparison is case-insensitive string equality.
- The keys of
when are the filename template variables for the release itself: title_type, quality, resolution, source, video, hdr, hfr, audio, audio_channels, audio_full, atmos, dual, multi, dubbed, edition, repack, and lang_tag. Only these are available. unshackle adds the title's own fields (title, year, season, episode, and so on) after it evaluates the rules, so a condition cannot use them. - An unknown key in
when 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 tag, and skips it.
Put the more specific rules first, because unshackle stops at the first match.
Match hdr on the exact value
Matching is exact, and hdr is a composite label for Dolby Vision titles: a DV title with an HDR10 base layer gives DV.HDR, and with an HDR10+ base layer DV.HDR10P. Plain DV does not match those. Name every variant you want, as the example above does. Note also that HDR10 gives HDR, not HDR10. The full set of values is HDR, HDR10P, DV, DV.HDR, DV.HDR10P, and HLG, as listed in the variable table.
"},{"location":"reference/configuration/output/#operators","title":"Operators","text":"A condition value can start with a comparison operator, which unshackle applies to the rest of the value:
unshackle.yamltag_rules:\n - when: { resolution: \"<1080\" }\n tag: SDGROUP\n - when: { quality: \">=2160\" }\n tag: UHDGROUP\n - when: { video: \"!=H.265\" }\n tag: AVCGROUP\n
>, <, >=, <= compare numbers. unshackle reads the first number out of the actual value, so \">=2160\" matches a quality of 2160p. If the actual value has no number, the condition fails. =, ==, and != 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 \"!=2160\" holds for it and \"==2160\" does not. - An ordering operator with a text operand (for example
\">DV\") is a mistake: unshackle logs a warning and the condition fails. So does an operator with nothing after it (\">=\"). - A value with no operator keeps the plain equality behaviour described above.
Quote operator values in YAML
Two of these operators break an unquoted YAML value, and both stop the config from loading:
> opens a folded block scalar, so quality: >=2160 fails with a \"while scanning a block scalar\" error. ! starts a tag, so hdr: !=DV fails with a \"could not determine a constructor\" error.
Quote every operator value: quality: \">=2160\", resolution: \"<1080\", video: \"!=H.265\".
Keep a negation out of lists
A list matches if any entry matches, so two or more != entries in one list are always true. Give a negation as a single value, not as a list entry.
title_type is the media kind of the title: movie, series, or music. It is useful to give each kind its own group:
tag_rules:\n - when: { title_type: movie }\n tag: MOVIEGRP\n - when: { title_type: series }\n tag: TVGRP\n
The resolved tag applies to the {tag} filename variable only. The Group metadata tag written into MKV and music files always uses tag.
--tag wins
An explicit dl --tag on the command line disables the rules completely and uses the given tag.
"},{"location":"reference/configuration/post-scripts/","title":"Post-scripts","text":"Operate your own script when a download finishes, with unshackle's metadata passed in as {variable} placeholders. Use it to hand a finished file to an uploader, send a notification, or start a library scan.
"},{"location":"reference/configuration/post-scripts/#post_scripts","title":"post_scripts","text":" - Type:
list[dict] \u00a0\u00b7\u00a0 Default: [] (unshackle operates no scripts)
unshackle.yamlpost_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
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 {command: \"...\", event: success, mode: file}.
Key Default Meaning command required The command to run, with {variable} placeholders event success success when a file was written, failure when the download failed mode file file, season, or run. See Modes wait false true makes unshackle wait for the script to exit before carrying on. See Waiting for a script unshackle skips an entry whose event or mode 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 command it cannot split into arguments, such as one with an unbalanced quote, and logs a warning. Neither stops the download or the other entries.
"},{"location":"reference/configuration/post-scripts/#how-the-command-runs","title":"How the command runs","text":"unshackle splits the command into arguments first, and then substitutes the variables into those arguments. The process runs without a shell.
This is what keeps a title like Bob\"; rm -rf ~ 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.
Prefix your variables
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 {title} whose value is --upload-file=/etc/passwd would arrive as an option to your script, not as text. Write --title={title}, not a bare {title}, 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 -), and logs a warning instead.
No shell features, and name your interpreter
Pipes, &&, > redirection, ~ and globs do not work, because unshackle uses no shell. If you want them, make the shell explicit: bash -c \"...\".
For the same reason there is no interpreter lookup. Write python /opt/upload.py rather than /opt/upload.py. unshackle will not guess whether you meant the system Python or the one in its own virtual environment.
On Windows, when a fixed part of an argument contains a space, quote the whole argument (\"--out=C:\\My Dir\\{filename}\"), not only the value. Substituted values never need quoting on any OS.
On Windows, do not target a .bat or .cmd file directly. Windows runs batch files through cmd.exe, 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 (python upload.py, pwsh -File upload.ps1) instead.
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.
One process per file
In file mode a large season pack starts one process per episode with nothing throttling them. If your script is heavy, set wait: true, queue the work inside the script, or use mode: season.
"},{"location":"reference/configuration/post-scripts/#wait","title":"Waiting for a script","text":"unshackle.yamlpost_scripts:\n - command: \"python /opt/upload.py --file={filepath}\"\n wait: true\n
With wait: true, unshackle waits until the script exits, then writes the exit code to the debug log and carries on. Because the file 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. --postscript entries never wait.
"},{"location":"reference/configuration/post-scripts/#variables","title":"Variables","text":"Metadata comes from the same naming context that produced the file's name, built per output file. So {quality} and {hdr} always give the values for the file unshackle passes in. Downloading -q 1080,2160 -r HDR10,SDR produces four files, each with its own invocation and its own values.
Variable Value {filepath} Absolute path of the output file {filename} Its filename, with extension {folder} Absolute path of its parent folder {ext} Its extension, including the dot {sidecars} Sidecar subtitle files written for this output, newline separated {title} Show, movie or track name, sanitized {title_raw} Exactly what the service returned, untouched {title_id} The service's ID for the title {service} Service tag {year} {season} {episode} {episode_name} Season and episode are plain numbers (1, 5) {part} Part number of a split episode as a plain number (1 for Part.1). Empty when the episode has no part {season_episode} {absolute} {date} As in the filename template: {season_episode} keeps the part suffix (S01E05.Part.1) while {episode} drops it {quality} {resolution} {hdr} {hfr} {vcodec} {acodec} {edition} {tag} {lang_tag} As in the filename template, for this file {tmdb} {imdb} {tvdb} The tagging IDs in use, otherwise empty. See Tagging IDs {error} Failure message. Empty on success Every variable from your output_template is available here as well, including {video} and {audio}, of which {vcodec} and {acodec} are aliases.
Empty variables become an empty string
--tmdb={tmdb} with no ID resolved hands your script --tmdb=, so treat an empty string as absent. Write your script to accept an empty value for every variable.
Empty is common, and not only when data is missing:
- No metadata provider found an ID.
{tmdb} 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. - The title has no such field. Movies have no
{season}, {episode} or {part}, and music has none of them. - The naming context renders it empty on purpose.
{hdr} is empty for an SDR file, because SDR is the absence of an HDR tag in a filename rather than a tag that reads SDR. {edition}, {atmos}, {multi}, {dual} and {hfr} behave the same way. If your script needs the word SDR, derive it from an empty {hdr} yourself. - The post-script is a
failure one. A failed download has no output file to read metadata from, so everything that comes from the output file is empty. See Events.
There is no {variable?} conditional here, unlike output_template. 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.
Season and episode are the plain numbers, not the S01E05 form used in filenames. The padding and the separator belong to the filename template rather than to the data.
"},{"location":"reference/configuration/post-scripts/#music-variables","title":"Music variables","text":"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. {season}, {episode}, {part} and {episode_name} are always empty for music.
Variable Value {artist} Track artist {album_artist} Album artist, falling back to the track artist {album} Album name {track_number} {disc} Zero padded. {disc} is empty on a single-disc release {track_total} {disc_total} Zero padded totals, empty when the service did not give them {isrc} {upc} {label} {genre} As the service reported them, empty when absent {release_type} album, single, ep, and so on. A service that reports nothing gives album {explicit} The word Explicit when the track is flagged, otherwise empty In a file post-script {title} is the track name. See Modes for what an album post-script puts in {title}.
{year} is empty when the service gives the release no year. {ext} is the container the track arrived in, such as .flac, because a music download is not muxed.
"},{"location":"reference/configuration/post-scripts/#tagging-ids","title":"Tagging IDs","text":"{tmdb}, {imdb} and {tvdb} 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.
They hold an ID you passed with --tmdb, --imdb or --tvdb, 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.
"},{"location":"reference/configuration/post-scripts/#sidecar-files","title":"Sidecar files","text":"{sidecars} 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 {sidecars} to be empty unless subtitle.output_mode is sidecar or both, which is not the default. A music download writes no sidecars at all.
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.
When one download writes several outputs (-q 1080,720), each output's folder gets its own copy of the sidecar files, and each invocation lists the copies sitting beside its own {filepath}.
Reading {sidecars} in Pythonsubs = [p for p in sys.argv[i].removeprefix(\"--subs=\").split(\"\\n\") if p]\n
"},{"location":"reference/configuration/post-scripts/#modes","title":"Modes","text":"mode Runs {filepath} {sidecars} file Once per output file That file That output's sidecars season Once per season folder, after that season's last queued title Empty Empty run Once per folder written, at the end of the run Empty Empty season means everything this run asked for
A season post-script fires when the last title this run queued for that season finishes. With -w S01-S02 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.
A title that fails stops the whole run. unshackle dispatches the failure post-script for that title and then returns. It downloads no further title, and no season or run 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.
unshackle attaches the post-script to the folder, not to the season, so one season landing in several folders (-q 1080,720 with a quality-dependent folder template) fires it once per folder, each with its own {folder}. A movie is a group of its own: a season post-script fires for a movie's folder as soon as the movie finishes.
In run mode every variable except {folder} is empty, because one run can cover several shows. Only {folder} is meaningful, which makes it useful for starting a library scan once.
"},{"location":"reference/configuration/post-scripts/#music","title":"Music","text":"Music uses the same three modes, with the album standing in for the season.
mode Runs file Once per track, after its metadata has been written season Once per album folder, after every queued track of that album has landed run Once per folder written, at the end of the run In a file post-script {title} and {title_raw} are the track name. In an album post-script they are the album name, and the per-track variables {track_number}, {disc} and {isrc} are empty, in the same way that {episode} is empty in a season post-script.
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.
"},{"location":"reference/configuration/post-scripts/#events","title":"Events","text":"success runs after the file has moved to its final path. failure runs when the download fails, with {filepath} empty and {error} set. Each track of an album is its own title. A music failure post-script therefore describes the track that failed, not the release.
failure only fires in file mode
A failure entry with mode: season or mode: run never runs. Leave mode at its default on a failure entry.
A failure post-script has no output file to read metadata from, so it carries only what the title object already knew: {title}, {title_raw}, {title_id}, {year}, {season}, {episode}, {part}, {season_episode}, {absolute}, {date}, {episode_name}, the music release fields such as {artist} and {album}, {service}, the tagging IDs and {error}. Everything that comes from the output file, such as {quality}, {hdr}, {vcodec} and {acodec}, is empty.
A resumed --continue-downloads download that finishes runs success as usual. unshackle sees your script's exit code only when that entry sets wait: true, 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.
A success post-script always names a file this run wrote. There is no skip-if-exists path in dl today, so nothing fires for a title that was not downloaded.
"},{"location":"reference/configuration/post-scripts/#-postscript","title":"--postscript","text":"dl accepts --postscript \"<command>\", repeatable. Every command given this way runs with event: success and mode: file.
$ unshackle dl --postscript \"python /opt/upload.py {filepath}\" SERVICE TITLE_ID\n
It replaces the post_scripts config for that run rather than adding to it, so no configured entry runs while it is in use. That includes your season, run and failure entries, which have no --postscript equivalent.
"},{"location":"reference/configuration/post-scripts/#-no-postscript","title":"--no-postscript","text":"dl --no-postscript operates the run with no post-script. It silences every configured entry and every --postscript command, for each event and mode. Use it to skip an uploader or a notifier for one run without an edit to unshackle.yaml.
$ unshackle dl --no-postscript SERVICE TITLE_ID\n
"},{"location":"reference/configuration/post-scripts/#the-rest-api","title":"The REST API","text":"The API never accepts a post-script command. postscript, post_script and post_scripts in a POST /api/download body get 400 INVALID_PARAMETERS. A command that arrives from an HTTP caller would be remote code execution.
unshackle does operate the scripts defined in unshackle.yaml for API jobs, music jobs included. Only the command itself may not cross the network.
"},{"location":"reference/configuration/post-scripts/#logging","title":"Logging","text":"unshackle logs the command it operated twice: at DEBUG level on the console, and as a post_script_dispatch entry in the structured JSON debug log when that log is on.
unshackle masks both the same way, and honours redact_paths, which is on by default. Debug logs get shared in issue reports, and a post-script command line is mostly paths. URL credentials and token= / api_key= query parameters are also masked.
Do not hardcode secrets in the command
unshackle cannot recognise an arbitrary secret in the command line, such as -H \"Authorization: Bearer <key>\", and logs it verbatim. Read the secret from a file or an environment variable inside your script rather than putting it in the command.
"},{"location":"reference/configuration/post-scripts/#limitations","title":"Limitations","text":" - No
success post-script operates under --no-mux or --skip-dl, because neither writes a muxed output. A failure post-script still runs under --no-mux if the download itself fails. failure post-scripts only operate in file mode. - There is no webhook sender. Call
curl from a script instead. - Script output is not captured. Redirect it inside your own script if you want a log.
"},{"location":"reference/configuration/services/","title":"Services & authentication","text":""},{"location":"reference/configuration/services/#services","title":"services","text":" - Type:
dict keyed by service tag \u00a0\u00b7\u00a0 Default: {}
Per-service configuration, keyed by the canonical service tag (for example EXAMPLE1, EXAMPLE2, EXAMPLE3). unshackle reads several well-known sub-keys out of each service's block:
proxy_map: remaps the region query you passed to -p/--proxy for this service. A config key is that query, or \"provider:query\" 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 -p a full proxy URL. title_map: 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. dl: per-service download defaults, using the same keys as the global dl block.
Individual services may read any additional keys they define. unshackle hands the merged result (the service's own config.yaml with this block layered on top) to the service as self.config.
User- or device-specific values (API keys, account IDs, device attributes) belong in this block rather than in the service's own config.yaml, which holds shared defaults. See creating a service.
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
"},{"location":"reference/configuration/services/#credentials","title":"credentials","text":" - Type:
dict keyed by service tag \u00a0\u00b7\u00a0 Default: {}
Per-service login credentials. Each value is a username:password[:extra] string, the same data as a [username, password] (or [username, password, extra]) list, or a dict of profile name to either of those. With the dict form, -p/--profile selects the entry, and unshackle uses the default config key when you give no profile, or when the named profile is missing. unshackle parses these into Credential objects. It also uses the credential's SHA-1 as an account hash for cache keys.
credentials:\n EXAMPLE2: user@example.com:hunter2\n EXAMPLE1:\n default: primary@example.com:pw1\n second: secondary@example.com:pw2\n
Cookies vs credentials
unshackle stores cookies as files under directories.cookies, not in this config key. A service's authenticate() accepts cookies, credentials, or both.
"},{"location":"reference/configuration/services/#firefox_cookies","title":"firefox_cookies","text":" - Type:
dict keyed by service tag \u00a0\u00b7\u00a0 Default: {}
Settings for extracting cookies directly from a local Firefox profile. A service block must give hosts, 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 local_storage boolean, unshackle also pulls matching entries from webappsstore.sqlite, which only services that keep auth tokens in localStorage rather than in HTTP cookies need. Extraction is read-only.
Firefox does not need to be closed
The extractor copies both cookies.sqlite and its WAL file into a 0700 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.
Extraction falls back silently to file cookies
If extraction yields no cookies or fails for any reason, unshackle silently falls back to the normal file-based cookie path (cookies/<SERVICE>.txt or cookies/<SERVICE>/<profile>.txt), with no error reported.
"},{"location":"reference/configuration/services/#remote_services","title":"remote_services","text":" - Type:
dict \u00a0\u00b7\u00a0 Default: {}
Definitions of remote unshackle service servers, used by the --remote mode. Each entry is named by you (pick it with --server, or do not write that flag when you configure only one) and gives the server's url (required), an optional api_key, an optional auth_headers list, an optional server_cdm boolean, an optional timeout in seconds, and an optional services sub-dict of per-service local overrides such as title_map.
Leave server_cdm 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. true asks for the server CDM and falls back to the local CDM when the server refuses; false always uses the local CDM. dl --cdm <name> on a remote run has the same effect as false for that run: the device you name licenses the remote session. A cdm entry for the service has the same effect for that service when it names the device that unshackle loaded. Both take priority over server_cdm: true. Remove the entry to use the server CDM for that service. The default entry does not count.
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.
auth_headers lists extra header names to send the API key in, tried before the defaults X-Secret-Key and X-Api-Key, which unshackle always appends as fallbacks. It sends the first name. If the server answers 401, 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 auth_headers: [\"Authorization\", \"x-secret-key\"] as Authorization, x-secret-key, X-Api-Key.
timeout is the time in seconds that the client waits for data from the server. The default is 120. 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 timeout 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. 0 means the default.
In --remote mode unshackle turns the server's service list into synthetic CLI commands that operate against it, falling back to the tags in that services sub-dict when unshackle cannot fetch the list. Each synthetic command carries the server-side service's options and documentation, so unshackle dl --remote <TAG> -h 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.
"},{"location":"reference/configuration/services/#serve","title":"serve","text":" - Type:
dict \u00a0\u00b7\u00a0 Default: {}
Configuration for the serve command (the built-in REST API server). The full server guide is the REST API section. These are the config keys.
Sub-key Type Default Description api_secret str (unset) Master secret the server accepts in the X-Secret-Key header. Required unless you start the server with --no-key. users dict {} Per-user API keys and their allowlists (see below). tiers dict {} Named settings that users entries reference by name (see below). services list (unset) Global service allowlist. Omit to allow all. remote_only bool false Expose only the remote service session endpoints (health, services, search, session) and disable the rest of the REST API. dashboard dict (unset) Developer dashboard: key is the API key for the read-only /api/dashboard/ endpoints (status, remote sessions, remote session logs, jobs, keys, services, health, logs, SSE events). Unset leaves those routes unregistered. See dashboard endpoints. session_ttl int (s) 300 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. max_sessions int or null 100 Maximum concurrent remote sessions; at the cap the server evicts the oldest. Set it to null or 0 for no limit, which is also what /api/dashboard/status then reports, so a dashboard can tell \"no cap\" from a cap that happens to sit at the default. history_limit int 100 How many finished jobs to retain in history. compression_level int 1 gzip level for responses. services_refresh_interval int (s) 0 How often the server pulls the git-backed service repositories in directories.services and hot-reloads the services that changed. 0 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. services_staged_max_age int (s) 0 How long a staged service waits for its jobs and sessions before the server swaps it in anyway. 0 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. global_speed_limit str (unlimited) Server-wide download speed cap, e.g. 10M, 1.5G or plain bytes/sec (same format as speed_limit). One shared budget across all concurrent jobs; the server ignores per-job speed limits while it is set. cdm_overrides list or bool (unset) Allowed per-request CDM overrides: a list of permitted device names, or true for any. Unset rejects every override. allow_job_credentials bool false Permit clients to supply credentials per job. server_accounts dict {} Services whose remote sessions use the server's own credentials and cookie files instead of the client's (see below). devices list (auto) Widevine devices offered; auto-filled from directories.wvds. playready_devices list (auto) PlayReady devices; auto-filled from directories.prds. Each entry under users uses that user's API key as its name, and can set its own services, devices, and playready_devices allowlists, narrowing the global ones, plus an optional username used as the log label for that API key (defaults to a truncated form of the API key). A user with no playready_devices config key gets no PlayReady access at all, not the global list.
Reload serve settings without a restart
Send SIGHUP to a running server (systemctl reload with ExecReload=kill -HUP $MAINPID 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 users, tiers, services and device lists in one step. Open CDM sessions and remote sessions continue; an API key you removed gets 401 on its next request. A file that does not parse or validate keeps the running settings and logs the reason. A change to remote_only, services_refresh_interval, the first PlayReady device, or any command-line flag needs a restart, and the log says so. Windows has no SIGHUP: restart the server there.
server_cdm decides whether the server runs the CDM licensing for that API key. Set it to true to enable every service, or to a list of service tags to enable only those. It is false unless the entry sets it. For a service the API key does not cover, the server tells a remote client configured with server_cdm: true to license with its own local CDM instead, and a client that asks anyway gets a FORBIDDEN error. Because a download job always licenses with the server's CDM, an API key without server_cdm for that service also cannot submit or retry /api/download jobs. Keys that have no users entry, such as api_secret, keep server CDM access.
A remote client that picks its own device licenses the remote session with that device. It picks with dl --cdm, with a cdm entry for the service, or with server_cdm: false in its remote_services 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.
server_cdm_max_height 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 default entry. A service the map does not name or sets to null gets the default, and with no default it has no limit. The server compares the limit with the lowest -q 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 -q when the remote session starts:
- With no
-q, or a -q 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. - With a
-q 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 SERVER_CDM_CAPPED error. - A download job must pass a
quality at or below the limit, and must not set best_available or a HYBRID range. HYBRID always keeps the lowest Dolby Vision track, at any quality. A job with no quality, with a higher one, with best_available, or with HYBRID gets a SERVER_CDM_CAPPED error. The server checks the values the job runs with, after it applies the service defaults and the serve: download defaults.
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.
server_vault lets a remote session that the client's own device licenses take content keys from the server vault. Set it to true for every service, or to a list of service tags. It is false unless the entry sets it, and server_cdm 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.
admin is a boolean that lets the API key run the maintenance endpoints (clear-cache, clear-temp, refresh-services). It is false unless the entry sets it. Keys that have no users entry, such as api_secret, keep that access.
A tier names an entry under serve.tiers, which holds the settings that several API keys share. Today a tier carries rate_limit, the requests per hour that API key may make; an API key can also set its own rate_limit, which wins over its tier's. An API key with neither has no limit. Going over the limit answers 429 with a Retry-After header. The server keeps a fixed window rather than a sliding one: it opens on the first request and resets an hour later. A tier that names no entry under serve.tiers, or a rate_limit 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 /api/health.
server_accounts 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 credentials. For a service that is not listed the server never uses its own accounts: a client that sends nothing authenticates with nothing.
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
Each entry under a service names a profile from credentials, or a cookie file cookies/<TAG>/<profile>.txt 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 global. Quote no (Norway), because YAML reads the bare word as false.
The region of a remote session is the country the client asked for with --proxy (ca, ca1, provider:ca), the server's own region with --no-proxy, or the client's own region otherwise. A full proxy URI carries no country, so with one only a global account matches. The server picks the profiles that cover that region (or are global) 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 -p/--profile.
Cookies come only from the profile's own file (cookies/EXAMPLE1/ca_main.txt; the server does not read a bare cookies/EXAMPLE1.txt), and each account keeps its own persistent cache under cache/_accounts/EXAMPLE1/<profile>/, so refreshed tokens survive the remote session but never cross accounts. serve refuses to start when a listed profile has neither an entry under credentials nor a cookie file. /api/search, /api/list-titles and /api/list-tracks use the same pool, matched on the client's reported region, and return FORBIDDEN 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.
A users entry opts in to those accounts with server_accounts: true (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 /api/services does not advertise the server's accounts to it. API keys with no users entry, such as api_secret, keep access.
server_proxy decides whether that API key may use the proxy providers the server has configured. There is no implicit access: only the boolean true on the API key's users entry grants it, and an API key without a users 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 proxy, not to match the client's region, and not for a service geofence. This applies to remote sessions, search, title lists, and /api/download jobs alike. Such a client must send a full proxy URI, or no_proxy to accept the server's own connection. Set server_proxy: true to let that API key send a country code or a provider:country 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.
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
dl keys inside serve
Most dl flag keys (downloads, workers, best_available, and so on) can be set directly inside serve, 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.
"},{"location":"reference/configuration/vaults/","title":"Key vaults","text":"The full guide is at Vaults. Two keys configure them.
"},{"location":"reference/configuration/vaults/#key_vaults","title":"key_vaults","text":" - Type:
list[dict] \u00a0\u00b7\u00a0 Default: []
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 type (the backend module name) and a name, plus backend-specific keys.
type Purpose Required keys Notes SQLite Local SQLite database name, path Loaded critically; a failure aborts the run. MySQL Remote MySQL database name, host, database, username Extra keys (e.g. password, port) forwarded to pymysql. connect_timeout defaults to vault_timeout. API RESTful JSON API name, uri, token Optional headers map is sent with every request. Honours vault_timeout. HTTP HTTP API with modes name, host, one of password/api_key, and username in query mode api_mode: query (default), json, decrypt_labs. Honours vault_timeout. 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
Per-entry options
no_push: true makes a vault read-only (unshackle fetches content keys from it but never writes to it). - A vault of
type: API whose name contains decrypt_labs auto-fills its token from decrypt_labs_api_key when not set inline. Vault type values are case-sensitive module names. - unshackle treats an all-zero content key (32 zeros) as \"no key\" everywhere and never stores it.
Bad content keys
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 bad_keys table of every SQLite vault with the name of the vault that supplied it, and every vault lookup skips a flagged pair from then on. A SQLite vault also refuses to store a flagged pair again. Only the SQLite backend stores flags; an API vault that supplied the pair gets a report. A serve instance with server_cdm flags a pair the same way when a remote client reports it, so a server whose key_vaults hold no SQLite entry cannot remember a bad content key.
"},{"location":"reference/configuration/vaults/#vault_timeout","title":"vault_timeout","text":" - Type:
float \u00a0\u00b7\u00a0 Default: 10.0
Timeout in seconds for vault operations. Injected automatically into any backend whose constructor accepts a timeout parameter (a per-vault timeout still wins). The MySQL backend uses it as the default connect_timeout.
"}]}
\ No newline at end of file