Files
unshackle/docs/dev/service-architecture.md
T

36 KiB

Service Architecture

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.

!!! info "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.

The shape of a download

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        →  which movies / episodes / songs exist
      │
Service.get_tracks        →  fetch a manifest for one title ...
      │
manifest.to_tracks        →  ... parsed into Video / Audio / Subtitle tracks
      │
Track.download            →  fetch + merge segments (core-driven)
      │
DRM license + decrypt     →  service license hooks → CDM → decrypt tool
      │
Tracks.mux                →  mkvmerge → tagged .mkv (movie / episode)
      │                      a Song skips the muxer and keeps its own container
  1. get_titles() returns a Titles collection: the movies, episodes, or songs the platform exposes for the requested ID.
  2. 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.
  3. 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.

The Service base class

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.

Class variables

Declared at the top of your service class, class variables such as ALIASES, GEOFENCE and NO_SUBTITLES describe the service to the framework. The attributes table of [Service][unshackle.core.service.Service] in the Service API gives each one, with its type and purpose.

Required methods

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).

Optional methods and hooks

  • 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.
  • Licence callbacks: see DRM hooks below.
  • request_input(prompt, qr=None): 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, qr=None): 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. Both methods take qr, the text of a QR code to scan, and the terminal or UI that shows the user the message draws it. When the login API gives only a PNG, read_qr_image(data) in unshackle.core.console gives the text.
  • Event callbacks: on_segment_downloaded, on_track_downloaded, on_track_decrypted, on_track_repacked, on_track_multiplex let a service react to pipeline events.

What __init__ wires up for you

You rarely override __init__. The base constructor takes the Click context and sets up the objects your methods rely on, such as self.session, self.cache and self.track_request. The attributes table of [Service][unshackle.core.service.Service] lists each one. Request and HTTP session objects explains the main ones.

The constructor also resolves proxies: it reads --proxy, which dl and search have already resolved through 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. A proxy whose exit is outside GEOFENCE logs a warning and the run continues. See Proxies and VPN.

!!! note "TrackRequest" self.track_request is a [TrackRequest][unshackle.core.service.TrackRequest] built from the CLI. Use it in get_tracks to decide which variants to fetch. A service that fetches the HYBRID variants itself must also fetch HDR10P when generate_dv is set and the title has no DV track, because unshackle prefers an HEVC HDR10+ base. get_tracks_for_variants does this for you.

Titles and the Title hierarchy

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.

!!! warning "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.

Constructors at a glance

Each subclass adds its own required fields on top of id_ and service:

=== "Movie"

```python
Movie(id_, service, name, year=None, language=None, data=None, description=None)
```

You must give `name`. `year` is optional, but it must be a positive integer if you
give it.

=== "Episode"

```python
Episode(id_, service, title, season, number,
        name=None, year=None, language=None, data=None,
        description=None, air_date=None)
```

`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"

```python
Song(id_, service, name, artist, album, track, disc=1, year=None,
     language=None, data=None, ...)
```

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`, `synced_lyrics`,
`lyrics_suffix`, and `artwork_url`. Read the class for the current list. Give `lyrics` as
plain text: the tagger embeds it as is. With `synced_lyrics` (timed LRC, SRT or TTML) and
`lyrics_suffix` (`".lrc"`, `".srt"`, `".ttml"`), unshackle also saves the timed lyrics beside the
final audio file under that suffix. To make LRC or SRT text from millisecond times, use
`lrc_stamp`, `cues_to_lrc`, `lrc_to_cues` and `cues_to_srt` from `unshackle.core.music`.
You can set these fields in `get_tracks()` too, and a remote client gets them back.

For a playlist whose songs keep the tags of their own album, give `position` (a positive integer,
from 1) to every song. The track list, the download order and `-w` then use that number. The
tags, the file name and the folder keep `track`, `disc` and `album`. Set it in `get_titles()`,
because a remote client does not read it again after the listing. Such a song also needs an `id` that
stays the same in each listing: `position` does not identify it.

`Album` and `Music` take the facts of the collection itself: `kind`, `title`, `artist`, `year`,
`total_tracks`, `total_discs`, `artwork_url`, `total_duration`, `owner` and `description`. A
remote client gets all of them. When every song has the same `album` and `album_artist`, the listing
takes a `title`, `artist` or `year` that you do not give, and the release date, quality, genre and
label, from the first song. The listing of any other collection, such as a playlist of single songs,
has no line for them. `build_music_from_songs` uses the same test before it takes the title, artist, year, artwork or
totals from the songs.

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. The keys
that a remote client gets back are `MUSIC_DATA_KEYS` in `unshackle/core/titles/music.py`,
for example `artists` (a list) and `replaygain_track_gain`.

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. The audio sort ranks a hi-res FLAC above a CD FLAC by `bitrate`. Set
`bit_depth` and `sample_rate` (Hz) on each `Audio` track, and `--list` shows them as
"24-bit / 96 kHz", so do not write that text into `name`. The same two keys in
`Song.data` give the Hi-Res badge in the release listing.

When the first song's `Song.data` has no bit depth or sample rate, or a lower one, `dl`
copies them from the best selected lossless track (FLAC, ALAC or PCM) of the first song.
If that changes the Quality row, `dl` shows the release header again. A lossy track
changes nothing.

A `Song` is an ordinary `Title` on the one generic download path. unshackle has no
music-specific service API and no separate path for music.

Core picks the container of a `Song` from the codec in the downloaded file, so a music
service does not rename the track path. Read
[Music output files](../guide/output-and-naming.md#music-output-files).

The **MUSIC_EXAMPLE** reference service, at `unshackle/services/MUSIC_EXAMPLE/`, shows
the full music surface.

Title remapping

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.

Tracks and the Track model

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 → Audio → Subtitle → Chapter → Attachment.

!!! warning "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.

The base Track

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.

When each URL of a URL track costs a request, give the track an empty url and set track.resolve_url to a callable that returns the URL. unshackle calls it only for a track that it downloads. Over --remote, the client asks the server for the URL of each track it downloads, and the server calls the callable then. A track whose callable fails gets no URL, and its download fails.

When the service has the media playlist of an HLS track as text and no playlist URL, set track.data["hls"]["playlist_text"] to the text, and set url to a URL that its segment URIs resolve against. unshackle downloads from the text and does not fetch a playlist. A from_file playlist works the same way. Over --remote and in an export, the text goes with the track, but a file: URL does not. The client accepts the text only as a media playlist whose segment URIs are absolute http or https URLs, and drops the track otherwise.

Video

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, LCEVC.
  • Video.Range: SDR, HLG, HDR10, HDR10P (HDR10+), VIVID (HDR Vivid), DV (Dolby Vision), and HYBRID. HYBRID is special: it tells the pipeline to select both an HDR10(+) or PQ HDR Vivid base and a DV track and merge the DV RPU onto the base track with dovi_tool (see Dolby Vision hybrid).

!!! note "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.

When the file of a track also holds a track of another kind, set track.data["own_stream_only"] = True on the track. The mux then takes from that file only the track of the same kind: the video of a video track, or the audio of an audio track. Use it for a video file with in-band audio that the service also gives as audio tracks, or for an audio version that comes as a whole video file. The value also goes to a --remote client. A track without it muxes everything in its file.

Audio

Audio adds bitrate, channels, joc (Joint Object Coding, the Atmos indicator), descriptive, bit_depth and sample_rate (Hz). DASH sets sample_rate from audioSamplingRate, ISM from SamplingRate, and HLS sets both from the BIT-DEPTH and SAMPLE-RATE attributes when the playlist has them. A service sets bit_depth itself. Audio.Codec covers AAC, AC3 (DD), EC3 (DD+), AC4, OPUS, OGG (Vorbis), DTS, DTSX, DTSHD, MPEGH, AV3A (Audio Vivid), ALAC, FLAC, and MP3. The atmos property is True when joc is set (or when extra flags it).

Subtitle

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, SCC, 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.

Chapters and attachments

  • 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. A url attachment downloads through the same downloader as a track, with the same retries. If it still fails, dl stops the run with a one-line error.

Selection, sorting, and muxing

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.

Manifest parsers

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.

The parser contract

  1. 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.
  2. to_tracks(...): parses the manifest into a Tracks container of Video, Audio, and Subtitle objects, each carrying descriptor-specific state.
  3. 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).

!!! tip "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.

DASH and HLS to_tracks skip a Representation or variant whose codec unshackle does not know, and log one warning with its codec string. They raise ValueError only when they skip at least one and no track is left.

Segment-filtering hooks

  • HLS: set track.OnSegmentFilter(segment) to drop unwanted segments (ads/bumpers). An EXT-X-KEY applies to each later segment until the next EXT-X-KEY with the same KEYFORMAT, or with another METHOD, also when the filter or --sample drops the segment that carries it. METHOD=NONE ends every EXT-X-KEY. unshackle ignores an EXT-X-KEY that applies to dropped segments only: no licence, no request and no new decryption. It also ignores the EXT-X-DISCONTINUITY of a dropped segment. A dropped ad break thus does not disturb decryption when the playlist repeats the EXT-X-KEY of the title after the break. Without the repeat, the segments after the break take the EXT-X-KEY of the ads, and METHOD=NONE there makes them clear.
  • 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.

Format gotchas worth knowing

  • 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. When a period's fragment timeline starts again near 0, as in a stitched ad stream that packages each part of the title on its own, the merge moves that period to follow the periods it keeps before it. A timeline that continues is not changed, so the gaps of filtered ad periods stay in it. Audio that runs past a period join is cut where the next period starts. Plain WebVTT periods and HLS subtitles across EXT-X-DISCONTINUITY blocks get the same treatment: fVTT through its tfdt, and WebVTT through its cue times, which move to the block's playlist start when that puts more cues inside the block.
  • 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.
  • Segments of each format: unshackle inflates a segment body that is one whole gzip member before the merge, up to a size limit. A CDN can send such a body with no Content-Encoding header. Any other body stays as it is, such as AES-128 ciphertext that starts with the gzip magic.
  • 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 does not read the tracks of the second manifest as duplicates of the first.

DRM hooks

If a track carries DRM, the framework licenses and decrypts it, but it needs your service to talk to the platform's license server. unshackle recognizes six DRM classes:

DRM class System License flow
Widevine Widevine CDM challenge → license server → content keys (.wvd device)
PlayReady PlayReady CDM challenge (WRM header) → license server → content keys (.prd device)
ClearKeyCENC W3C org.w3.clearkey or W3C common PSSH over CENC JSON KID request → JWK set; no CDM
ClearKey HLS AES-128 content key fetched directly from a URI; no CDM, no challenge
CustomDRM a system that a DRM plugin adds CustomDRM("<plugin id>", kids=..., data=...). For a plugin that holds its key, put the key in data. For a plugin that licenses locally, put only the data the plugin reads: unshackle licenses it at the licence step. The plugin decrypts. Its README names the data it reads
ClearKeyCTR AES-128-CTR over a whole file the service gives the IV and licenses the content key at the licence step; no CDM, no license server

!!! warning "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.

The service-side hooks

The framework supplies the CDM and the decryption backend. Your service gives the network calls that must carry the CDM's challenge. Override the licence callbacks that your platform needs: get_widevine_service_certificate, get_widevine_license, get_playready_license and get_clearkey_license. Each one gets challenge, title and track as keyword arguments, and returns the licence as the server gives it, without decoding it. The base get_playready_license calls get_widevine_license, and the base get_clearkey_license returns None, so that the framework POSTs the challenge to the manifest Laurl. The Service API gives the signature and the return type of each callback.

A licence callback can also declare optional keyword arguments. get_widevine_license can ask for pssh and session_id. get_playready_license can ask for pssh_b64 and session_id. session_id is the open CDM session. A callback gets only the arguments that its signature declares. When a --remote client licenses with its own CDM, the callback on the server gets pssh or pssh_b64 for the header that the client licenses, but no session_id.

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 callback is only the "send this challenge, give me back the license" step.

The FairPlay bridge hook

unshackle has no FairPlay CDM and never sends a FairPlay challenge. For a FairPlay-only HLS track it can send a PlayReady or Widevine challenge for the KIDs of the init segments to the licence server of the platform. This works only when that server issues the same content key to PlayReady or Widevine. The bridge runs only for a service that defines get_fairplay_bridge_license. The base class does not define it.

def get_fairplay_bridge_license(
    self, *, challenge: bytes, title: Title_T, track: AnyTrack, drm_system: str
) -> bytes | str:
    """The licence server of this platform issues the content keys of its FairPlay-only tracks to PlayReady."""
    licence = self.get_playready_license if drm_system == "playready" else self.get_widevine_license
    return licence(challenge=challenge, title=title, track=track)
  • drm_system is "playready" or "widevine". The hook must accept it.
  • The hook can also declare the optional arguments of the licence callback of that system (see The service-side hooks). It gets only the arguments that it declares.
  • The key IDs are on the DRM object of the track (track.drm[0].kids) when the hook runs. A service that needs its own request shape builds the request in the hook.
  • The hook gets only the challenges of FairPlay-only tracks. The challenge of every other track goes to get_playready_license or get_widevine_license.

The DRM system of the challenge is the drm_preference of the track, else the system of the configured CDM. For a licence server that issues the content key to one system only, set drm_preference on the FairPlay-only tracks in get_tracks():

for track in tracks.videos + tracks.audio:
    if not track.drm:
        track.drm_preference = "playready"

The init segment (EXT-X-MAP) of the track must name a real key ID in its tenc box. When the tenc key ID is all zeros and the playlist has one key URI, the pssh boxes of the init segment can name it. unshackle never reads a key ID from the skd:// URI.

Without the hook, dl leaves each FairPlay-only track out of the selection and takes the next best track that licenses. It logs one line for each title: Left out 2 FairPlay-only tracks: EXAMPLE has no FairPlay bridge hook. With the hook, dl still leaves out FairPlay-only DASH tracks, because the bridge works for HLS only.

A licence server that does not issue the content key refuses the challenge, and can flag the device. Test the route with a licence-only run (--cdm-only --skip-dl) before a service relies on it.

Decrypting a cbcs file yourself

Some tracks cannot use the framework's decryption: a single cbcs file whose sample entries share a zero default KID, or a sample entry whose content key no CDM can license and only a separate process can use. For these, set no drm on the track and override two methods:

  • decrypts_samples(track) returns True for such a track.
  • get_sample_decrypter(track, entry) returns, for the 1-based stsd entry, the 16-byte content key or a cbcs.SampleDecrypter. A SampleDecrypter gets the protected bytes of each sample of one fragment, cut to whole AES blocks, and returns plaintexts of the same lengths. It handles full-sample cbcs only, not pattern encryption.

When the download of the track ends, unshackle calls unshackle.core.drm.cbcs.decrypt_file, and the progress row shows "Decrypting". decrypt_file writes the plaintext back in place and removes the protection boxes, so the muxer reads a clear file. Then your on_track_decrypted runs with drm set to None, and after it your on_track_downloaded runs and gets the clear file. In a remote session get_sample_decrypter runs on the server: the client sends the samples through the samples route, so a decrypter that needs a process on the server also works for a remote client.

A playlist whose key tag unshackle cannot license

A service that must choose the DRM system itself, or one that knows the key ID, puts the DRM object on the track and needs no FairPlay bridge hook:

  1. Read the key ID from the init segment of the encrypted segments. HLS.get_track_kid_from_init returns it for the track, a reader of init segments (HLS.init_reader(playlist, session)) and that init segment.
  2. Put a DRM object that names the key ID on the track: drm_stub from unshackle.core.drm.cenc with "playready" or "widevine" and the key ID. When only one of the two systems issues the content key, also set track.drm_preference to it.
  3. Let your licence callback send the challenge to the server that issues that key.

drm_stub builds the header from the key ID alone, so this works with a licence server that goes by the key ID, not with one that checks a header a packager signed. When every EXT-X-KEY of the playlist names a key system that unshackle cannot license, unshackle ignores those tags and licenses and decrypts the track with its DRM object, for one content key per track. Any other track that has only such tags stops with None of the key systems are supported before it downloads a segment.

How unshackle chooses a CDM and finds keys

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.

Dolby Vision and hybrid

Two DV mechanisms sit on top of the track model. DV fixup re-exposes DV signalling on HLS and DASH streams that carry a valid DV RPU but advertise plain HEVC, with DV only in the supplemental codecs (dv_compatible_bitstream). --list shows such a track as HDR10+DV or HDR10P+DV. A service sets hdr10_base on a DV track that has an HDR10 base layer (DV profile 8.1), and --list shows it as DV+HDR10. The HLS and DASH parsers set stereo on a stereoscopic 3D (MV-HEVC) track: an HLS REQ-VIDEO-LAYOUT that names CH-STEREO, or a DV profile 20 codec. --list shows it as 3D. Hybrid processing (Video.Range.HYBRID) selects an HDR10(+) or PQ HDR Vivid 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 the base 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.

Request and HTTP session objects

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: a plain dict. unshackle loads the service's own config.yaml, then merges the user's services.<TAG> block from unshackle.yaml over it. Nested keys merge one by one, the user's value wins, and a list in the user's block replaces the whole list. Use it for per-service settings like base URLs, an API key, or a title_map. See Services & authentication for the override keys.
  • 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. To impersonate a browser TLS fingerprint, override get_session() to return an rnet HTTP session from session() in unshackle.core.session, which 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. A login with cookies only uses a hash of the path of its cookie file.
  • 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. If you put the cookies of a different account into the same cookie file, use --reset-cache once.

Creating a Service gives a complete minimal service.

Where to go next