Compare commits

..
19 Commits
Author SHA1 Message Date
imSp4rky f26f9bcbe2 feat(video): normalize SPS VUI to match manifest-derived range
Some services ship HDR10/HLG bitstreams whose SPS VUI still carries BT.709 colour primaries/transfer/matrix, causing mediainfo and downstream players to mis-classify the file. The manifest-derived `Video.range` is the source of truth; rewrite the VUI with ffmpeg h264_metadata/hevc_metadata BSF after repackage and before mux. Skips SDR, DV, and HYBRID; no-op when the VUI is already correct.
2026-05-16 13:55:05 -06:00
imSp4rky ead88fe066 feat(hls): detect DV-composite tracks and restore signaling post-mux
Parse HLS SUPPLEMENTAL-CODECS to identify tracks that ship Dolby Vision RPU NALs in a stream whose primary codec is plain hvc1 (e.g. fMP4 ladders signalled as dvh1.08.x only via SUPPLEMENTAL-CODECS). Tag such tracks with the new `dv_compatible_bitstream` flag on Video.

Add DVFixup helper that runs `dovi_tool extract-rpu | inject-rpu` on flagged tracks before mux so the muxed MKV is recognised as Dolby Vision. Soft-fails to the source bitstream if dovi_tool is missing or any step errors.

Range stays whatever VIDEO-RANGE signalled. HDR10+ presence is a bitstream feature, not a codec-string feature, so services that know their encoder embeds HDR10+ SEI must override Video.range themselves.
2026-05-16 13:52:57 -06:00
imSp4rky b4d422459c refactor(hybrid): extract dovi_tool and run_step helpers
Centralise dovi_tool subcommand invocations behind a thin wrapper module so Hybrid no longer re-implements argv construction, status spinners, and stderr handling per call site. Adds a generic `run_step` helper for subprocess steps that must produce a non-empty output file.
2026-05-16 13:50:55 -06:00
imSp4rky cda8120b6d fix(title): use original-language audio for filename metadata
When a non-original audio language is the default (via muxing.default_language or sort order), the filename audio codec/channel fields still reflect the title's original-language track instead of whichever track appears first in the muxed MKV.
2026-05-16 11:56:04 -06:00
imSp4rky c0dc1eb91f docs(output): document muxing.default_language override 2026-05-15 08:22:45 -06:00
imSp4rky ccf8bafaf7 feat(mux): add muxing.default_language to override default track per type
Allows users to force a preferred audio/video/subtitle language as the MKV default track regardless of the title's original_language. Each track type falls back to its previous default rule when no match is found.
2026-05-14 14:24:23 -06:00
imSp4rky 0aca0e8888 feat(dl): cache content keys in-memory to skip duplicate license requests
A title with many tracks sharing the same KID issued one license request per track even when keys were identical. Add an in-memory KID -> key cache shared across all tracks of a single invocation, populated on vault hit and on license success. Subsequent tracks with cached KIDs short-circuit before the vault and license calls, reducing traffic to one request per unique KID.
2026-05-14 11:58:31 -06:00
imSp4rky 60441f05c4 fix(title): detect Atmos across all audio tracks for filename template
The {atmos?} placeholder checked only the first MediaInfo audio track, so a mux with a non-Atmos dub listed first dropped the Atmos tag from the filename even when another track carried JOC. Scan all audio tracks instead.
2026-05-14 10:22:55 -06:00
imSp4rky 82ab996777 fix(dl): prefer Atmos in -l best/all language selection
The per-language picker used max() keyed on bitrate only, so a higher-bitrate non-Atmos track was selected over a lower-bitrate Atmos track. Switch the key to (bool(x.atmos), x.bitrate) so Atmos wins with bitrate as tiebreaker, matching Tracks.sort_audio.
2026-05-14 10:00:25 -06:00
imSp4rky c0929bf217 fix(template_formatter): preserve dash separator around empty conditional
When an empty conditional sits between a dot and a dash (e.g. `.{atmos?}-{tag}`),
the left-side dot was kept and the dash before the tag was dropped, producing
`...DDP5.1.TAG` instead of `...DDP5.1-TAG`. Prefer the dash when it is the
right-side separator.

Closes #107
2026-05-12 08:24:31 -06:00
imSp4rky 20c15f761b fix(proxies/nordvpn): use *.proxy.nordvpn.com for HTTPS proxy
NordVPN's HTTPS proxy endpoints now serve a certificate valid only for *.proxy.nordvpn.com. Connecting to the legacy <server>.nordvpn.com:89 hostname fails with SSLCertVerificationError (hostname mismatch).

Rewrite direct queries, server_map entries, and API-returned hostnames to the proxy subdomain so cert validation succeeds.
2026-05-11 09:55:48 -06:00
imSp4rky 9e4fdcdcd8 fix(dl): re-pick DV/HDR10 when HYBRID falls back under best_available
When HYBRID is requested alongside other ranges with best_available and no HDR10 base layer exists, the pre-validation hybrid selection had already locked in the lowest-resolution DV track. Snapshot the pre-hybrid pool and redo Cartesian range/quality/codec/lang selection over surviving ranges so DV (or HDR10-only) honors --worst and default best-pick semantics.
2026-05-10 11:04:29 -06:00
imSp4rky 7fb88e9a97 docs: update docs to match current codebase 2026-05-08 17:54:45 -06:00
imSp4rky 4c981e2ffd fix(tracks): honor --worst in hybrid range selection
select_hybrid always picked max-bitrate HDR10 base layer, ignoring the --worst flag. Thread worst through to use min bitrate when requested.
2026-05-08 15:37:09 -06:00
imSp4rky 5984eefcbe fix(sanitize): preserve parentheses, strip unidecode bracket artifacts (#105)
Commit 10cca7d re-added () to the stripped character set, which broke output_template patterns like ({year?}). The original reason for stripping parens was that unidecode maps 【】 to "[(" and ")]", leaving artifacts like [(SERIES NAME)] in filenames.

Allow parens in filenames so templates render correctly, and collapse the unidecode "[(" / ")]" sequences immediately after transliteration so unicode brackets still come out as [SERIES NAME].
2026-05-05 08:39:38 -06:00
imSp4rky 08c0862691 fix(manifests): clean stale .!dev resume markers before merge
HLS/DASH/ISM iterdir included leftover .!dev control files from aborted runs, crashing HLS merge_discontinuity and silently corrupting DASH/ISM merged output.
2026-05-04 22:51:45 -06:00
imSp4rky db313a8ee2 refactor(routes, subtitle, track): improve code readability by formatting list structures 2026-05-04 22:21:03 -06:00
imSp4rky a7af898617 feat(ip-info): consolidate IP lookup, add ipinfo.io token support
Replace get_ip_info + get_cached_ip_info pair with a single unshackle.core.utils.ip_info module providing a normalized return shape across providers. Adds optional ipinfo_api_key config for the ipinfo.io Lite endpoint (higher rate limits, ASN/org/continent data), swaps the ipapi.co fallback for ip-api.in, and migrates all callers (service, gluetun, remote_service, api/handlers, DSNP, YT) to the new import path. Auth token is sent per-request and never attached to the shared session headers.
2026-05-04 22:20:43 -06:00
imSp4rky 8f4cac6c7b chore(pre-commit): update hook versions in .pre-commit-config.yaml 2026-05-04 22:20:02 -06:00
33 changed files with 1744 additions and 623 deletions
+5 -5
View File
@@ -3,21 +3,21 @@
repos: repos:
- repo: https://github.com/compilerla/conventional-pre-commit - repo: https://github.com/compilerla/conventional-pre-commit
rev: v4.2.0 rev: v4.4.0
hooks: hooks:
- id: conventional-pre-commit - id: conventional-pre-commit
stages: [commit-msg] stages: [commit-msg]
- repo: https://github.com/astral-sh/ruff-pre-commit - repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.11.3 rev: v0.15.12
hooks: hooks:
- id: ruff - id: ruff
args: [--fix] args: [--fix]
- repo: https://github.com/pycqa/isort - repo: https://github.com/pycqa/isort
rev: 6.0.1 rev: 9.0.0a3
hooks: hooks:
- id: isort - id: isort
- repo: https://github.com/PyCQA/bandit - repo: https://github.com/PyCQA/bandit
rev: 1.8.3 rev: 1.9.4
hooks: hooks:
- id: bandit - id: bandit
args: args:
@@ -26,7 +26,7 @@ repos:
- --confidence-level=medium - --confidence-level=medium
additional_dependencies: ['bandit[toml]'] additional_dependencies: ['bandit[toml]']
- repo: https://github.com/pre-commit/pre-commit-hooks - repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0 rev: v6.0.0
hooks: hooks:
- id: end-of-file-fixer - id: end-of-file-fixer
- id: trailing-whitespace - id: trailing-whitespace
+66 -5
View File
@@ -13,6 +13,7 @@ unshackle serve # Default: localhost:8786
unshackle serve -h 0.0.0.0 -p 8888 # Listen on all interfaces unshackle serve -h 0.0.0.0 -p 8888 # Listen on all interfaces
unshackle serve --no-key # Disable authentication unshackle serve --no-key # Disable authentication
unshackle serve --api-only # REST API only, no CDM endpoints unshackle serve --api-only # REST API only, no CDM endpoints
unshackle serve --remote-only # Only expose remote service session endpoints
``` ```
### CLI Options ### CLI Options
@@ -28,22 +29,34 @@ unshackle serve --api-only # REST API only, no CDM endpoints
| `--no-key` | `false` | Disable API key authentication (allows all requests) | | `--no-key` | `false` | Disable API key authentication (allows all requests) |
| `--debug-api` | `false` | Include tracebacks and stderr in API error responses | | `--debug-api` | `false` | Include tracebacks and stderr in API error responses |
| `--debug` | `false` | Enable debug logging for API operations | | `--debug` | `false` | Enable debug logging for API operations |
| `--remote-only` | `false` | Only expose remote service session endpoints (health, services, search, session) |
### Configuration ### Configuration
- `api_secret` - Secret key for REST API authentication. Required unless `--no-key` is used. All API requests must include this key via the `X-API-Key` header or `api_key` query parameter. - `api_secret` - Secret key for REST API authentication. Required unless `--no-key` is used. All API requests must include this key via the `X-Secret-Key` header.
- `compression_level` - Compression level for API payloads (manifests, cache, cookies). `0`=off, `1`=fast, `6`=balanced, `9`=max. Default: `1`.
- `session_ttl` - Session inactivity timeout in seconds. Each request resets the timer. Default: `300`.
- `max_sessions` - Maximum concurrent sessions before the oldest is evicted. Default: `100`.
- `services` - Optional global service allowlist. Only these service tags are exposed. If omitted, all services are available.
- `devices` - List of Widevine device files (.wvd). If not specified, auto-populated from the WVDs directory. - `devices` - List of Widevine device files (.wvd). If not specified, auto-populated from the WVDs directory.
- `playready_devices` - List of PlayReady device files (.prd). If not specified, auto-populated from the PRDs directory. - `playready_devices` - List of PlayReady device files (.prd). If not specified, auto-populated from the PRDs directory.
- `users` - Dictionary mapping user secret keys to their access configuration: - `users` - Dictionary mapping user secret keys to their access configuration:
- `devices` - List of Widevine devices this user can access - `devices` - List of Widevine devices this user can access
- `playready_devices` - List of PlayReady devices this user can access - `playready_devices` - List of PlayReady devices this user can access
- `username` - Internal logging name for the user (not visible to users) - `username` - Internal logging name for the user (not visible to users)
- `services` - Optional per-user service allowlist. Effective access is the intersection of global and per-user allowlists.
For example, For example,
```yaml ```yaml
serve: serve:
api_secret: "your-secret-key-here" api_secret: "your-secret-key-here"
compression_level: 1
session_ttl: 300
max_sessions: 100
# services: # global allowlist (optional)
# - EXAMPLE1
# - EXAMPLE2
users: users:
secret_key_for_jane: # 32bit hex recommended, case-sensitive secret_key_for_jane: # 32bit hex recommended, case-sensitive
devices: # list of allowed Widevine devices for this user devices: # list of allowed Widevine devices for this user
@@ -51,18 +64,18 @@ serve:
playready_devices: # list of allowed PlayReady devices for this user playready_devices: # list of allowed PlayReady devices for this user
- my_playready_device - my_playready_device
username: jane # only for internal logging, users will not see this name username: jane # only for internal logging, users will not see this name
# services: # per-user allowlist (optional)
# - EXAMPLE1
secret_key_for_james: secret_key_for_james:
devices: devices:
- generic_nexus_4464_l3 - generic_nexus_4464_l3
username: james username: james
secret_key_for_john:
devices:
- generic_nexus_4464_l3
username: john
# devices can be manually specified by path if you don't want to add it to # devices can be manually specified by path if you don't want to add it to
# unshackle's WVDs directory for whatever reason # unshackle's WVDs directory for whatever reason
# devices: # devices:
# - 'C:\Users\john\Devices\test_devices_001.wvd' # - 'C:\Users\john\Devices\test_devices_001.wvd'
# playready_devices:
# - '/path/to/device.prd'
``` ```
### REST API ### REST API
@@ -133,3 +146,51 @@ Check for updates from the GitHub repository on startup. Default: `true`.
How often to check for updates, in hours. Default: `24`. How often to check for updates, in hours. Default: `24`.
--- ---
## title_cache_enabled (bool)
Enable or disable title metadata caching globally. Default: `true`.
---
## title_cache_time (int)
Title cache duration in seconds. Default: `1800` (30 minutes).
---
## title_cache_max_retention (int)
Maximum cache retention in seconds, used as fallback when the upstream API fails. Default: `86400` (24 hours).
---
## unicode_filenames (bool)
When `false`, replaces non-ASCII characters in output filenames with ASCII equivalents. Default: `false`.
---
## ipinfo_api_key (str)
Optional ipinfo.io token. When set, unshackle uses the ipinfo.io Lite endpoint for IP/geolocation lookups instead of the unauthenticated fallback.
---
## tmdb_api_key (str)
Optional TMDB API key, used for metadata enrichment and IMDb/TMDb tagging.
---
## simkl_client_id (str)
Optional Simkl client ID for metadata lookups.
---
## decrypt_labs_api_key (str)
Optional Decrypt Labs API key, used by services that integrate with the service.
---
+454 -78
View File
@@ -1,6 +1,8 @@
# REST API Documentation # REST API Documentation
The unshackle REST API allows you to control downloads, search services, and manage jobs remotely. Start the server with `unshackle serve` and access the interactive Swagger UI at `http://localhost:8786/api/docs/`. The unshackle REST API allows you to control downloads, search services, drive remote downloads from a thin client, and (optionally) co-host the pywidevine/pyplayready CDM. Start the server with `unshackle serve` and access the interactive Swagger UI at `http://localhost:8786/api/docs/`.
The server is built on **aiohttp** (not FastAPI). Implementation lives in `unshackle/commands/serve.py` and `unshackle/core/api/` (`routes.py`, `handlers.py`, `session_store.py`, `input_bridge.py`, `download_manager.py`, `download_worker.py`).
## Quick Start ## Quick Start
@@ -8,32 +10,109 @@ The unshackle REST API allows you to control downloads, search services, and man
# Start the server (no authentication) # Start the server (no authentication)
unshackle serve --no-key unshackle serve --no-key
# Start with authentication # Start with authentication (api_secret in unshackle.yaml)
unshackle serve # Requires api_secret in unshackle.yaml unshackle serve
# Serve only the REST API (no pywidevine/pyplayready CDM)
unshackle serve --api-only
# Serve only the remote-dl session endpoints (CORS/Cloudflare friendly)
unshackle serve --remote-only
# Disable just one CDM
unshackle serve --no-widevine
unshackle serve --no-playready
# Verbose error responses (tracebacks/stderr in JSON)
unshackle serve --debug-api
``` ```
`serve` flags:
| Flag | Description |
| --- | --- |
| `-h, --host` | Bind host (default `127.0.0.1`) |
| `-p, --port` | Bind port (default `8786`) |
| `--caddy` | Also launch Caddy using `Caddyfile` next to the unshackle config |
| `--api-only` | REST API only; skip the bundled pywidevine/pyplayready CDM endpoints |
| `--no-widevine` | Disable Widevine CDM endpoints |
| `--no-playready` | Disable PlayReady CDM endpoints |
| `--no-key` | Disable API key authentication entirely |
| `--debug-api` | Include tracebacks/stderr in error responses |
| `--debug` | Enable DEBUG-level logging for API operations |
| `--remote-only` | Expose only `/api/health`, `/api/services`, `/api/search`, and `/api/session/*` (implies `--api-only`) |
## Authentication ## Authentication
When `api_secret` is set in `unshackle.yaml`, all API requests require authentication via: When `api_secret` is set in `unshackle.yaml`, all API requests require the **`X-Secret-Key`** header. There is no query-parameter fallback. `/api/health` is always reachable without authentication. `--no-key` disables auth entirely (not recommended for public-facing servers).
- **Header**: `X-API-Key: your-secret-key-here`
- **Query parameter**: `?api_key=your-secret-key-here`
Use `--no-key` to disable authentication entirely (not recommended for public-facing servers).
```yaml ```yaml
# unshackle.yaml # unshackle.yaml
serve: serve:
api_secret: "your-secret-key-here" api_secret: "your-master-secret" # falls back to global users map below
remote_only: false # also toggleable via --remote-only
services: ["EXAMPLE1", "EXAMPLE2"] # optional global service allowlist
users:
user-secret-1:
username: alice
devices: ["my_widevine_l3"] # Widevine WVD names this user may use
playready_devices: ["my_pr_sl2000"] # PlayReady PRD names; defaults to [] (no access)
services: ["EXAMPLE1"] # optional per-user allowlist (intersected with global)
user-secret-2:
username: bob
devices: []
playready_devices: []
``` ```
### Service allowlists
`config.serve.services` is the global allowlist; `users.<key>.services` further narrows it per key. The effective set is the intersection. Endpoints affected: `/api/services`, `/api/search`, `/api/list-titles`, `/api/list-tracks`, `/api/download`, and all `/api/session/*` routes.
### CDM access (server-side decryption)
There is no separate "tier" flag. Whether the server can return KID:KEY for a session-mode download depends solely on the device lists configured for the calling user key:
- Empty `devices` and `playready_devices` -> server can only proxy CDM challenges; the client must run its own CDM and parse the license.
- Populated lists -> the client may set `mode: "server_cdm"` on `/api/session/{id}/license` and receive `{ "keys": { "<track_id>": { "<KID>": "<KEY>" } } }` instead of raw license bytes.
Per-service CDM type can be pinned via `config.cdm` (`widevine`/`playready`) or per-service `cdm_type`; otherwise the server picks the type the user has devices for.
---
## Endpoint Map
Standard endpoints (suppressed in `--remote-only` mode are marked R):
| Method | Path | R |
| --- | --- | :-: |
| GET | `/api/health` | ok |
| GET | `/api/services` | ok |
| POST | `/api/search` | ok |
| POST | `/api/list-titles` | hidden |
| POST | `/api/list-tracks` | hidden |
| POST | `/api/download` | hidden |
| GET | `/api/download/jobs` | hidden |
| GET | `/api/download/jobs/{job_id}` | hidden |
| DELETE | `/api/download/jobs/{job_id}` | hidden |
| POST | `/api/session/create` | ok |
| GET | `/api/session/{session_id}` | ok |
| DELETE | `/api/session/{session_id}` | ok |
| GET | `/api/session/{session_id}/titles` | ok |
| POST | `/api/session/{session_id}/tracks` | ok |
| POST | `/api/session/{session_id}/segments` | ok |
| POST | `/api/session/{session_id}/license` | ok |
| GET | `/api/session/{session_id}/prompt` | ok |
| POST | `/api/session/{session_id}/prompt` | ok |
CDM endpoints (`/{wvd}/...`, `/playready/{prd}/...`) are exposed unless `--api-only` / `--remote-only` / `--no-widevine` / `--no-playready` is set, and use pywidevine / pyplayready's own auth scheme.
--- ---
## Endpoints ## Endpoints
### GET /api/health ### GET /api/health
Health check with version and update information. Health check with version and update information. Always reachable without auth.
```bash ```bash
curl http://localhost:8786/api/health curl http://localhost:8786/api/health
@@ -55,13 +134,13 @@ curl http://localhost:8786/api/health
### GET /api/services ### GET /api/services
List all available streaming services. List all available streaming services (filtered by the effective allowlist for the caller).
```bash ```bash
curl http://localhost:8786/api/services curl -H "X-Secret-Key: $KEY" http://localhost:8786/api/services
``` ```
Returns an array of services with `tag`, `aliases`, `geofence`, `title_regex`, `url`, and `help` text. Returns `{"services": [...]}`. Each entry has `tag`, `aliases`, `geofence`, `title_regex`, `url` (from `cli.short_help`), `help` (full docstring), and `cli_params` describing the service-level Click parameters.
--- ---
@@ -84,8 +163,9 @@ Search for titles from a streaming service.
```bash ```bash
curl -X POST http://localhost:8786/api/search \ curl -X POST http://localhost:8786/api/search \
-H "X-Secret-Key: $KEY" \
-H "Content-Type: application/json" \ -H "Content-Type: application/json" \
-d '{"service": "EXAMPLE", "query": "example show"}' -d '{"service": "EXAMPLE1", "query": "example show"}'
``` ```
```json ```json
@@ -107,7 +187,7 @@ curl -X POST http://localhost:8786/api/search \
### POST /api/list-titles ### POST /api/list-titles
Get available titles (seasons/episodes/movies) for a service and title ID. Get available titles (seasons/episodes/movies) for a service and title ID. Disabled in `--remote-only` mode.
**Required parameters:** **Required parameters:**
| Parameter | Type | Description | | Parameter | Type | Description |
@@ -117,31 +197,16 @@ Get available titles (seasons/episodes/movies) for a service and title ID.
```bash ```bash
curl -X POST http://localhost:8786/api/list-titles \ curl -X POST http://localhost:8786/api/list-titles \
-H "X-Secret-Key: $KEY" \
-H "Content-Type: application/json" \ -H "Content-Type: application/json" \
-d '{"service": "EXAMPLE", "title_id": "abc123def456"}' -d '{"service": "EXAMPLE1", "title_id": "abc123def456"}'
```
```json
{
"titles": [
{
"type": "episode",
"name": "Pilot",
"series_title": "Example Show",
"season": 1,
"number": 1,
"year": 2024,
"id": "abc123def789"
}
]
}
``` ```
--- ---
### POST /api/list-tracks ### POST /api/list-tracks
Get video, audio, and subtitle tracks for a title. Get video, audio, and subtitle tracks for a title. Disabled in `--remote-only` mode.
**Required parameters:** **Required parameters:**
| Parameter | Type | Description | | Parameter | Type | Description |
@@ -157,23 +222,13 @@ Get video, audio, and subtitle tracks for a title.
| `proxy` | string | `null` | Proxy URI or country code | | `proxy` | string | `null` | Proxy URI or country code |
| `no_proxy` | boolean | `false` | Disable all proxy use | | `no_proxy` | boolean | `false` | Disable all proxy use |
```bash
curl -X POST http://localhost:8786/api/list-tracks \
-H "Content-Type: application/json" \
-d '{
"service": "EXAMPLE",
"title_id": "abc123def456",
"wanted": ["S01E01"]
}'
```
Returns video, audio, and subtitle tracks with codec, bitrate, resolution, language, and DRM information. Returns video, audio, and subtitle tracks with codec, bitrate, resolution, language, and DRM information.
--- ---
### POST /api/download ### POST /api/download
Start a download job. Returns immediately with a job ID (HTTP 202). Start a download job. Returns immediately with a job ID (HTTP 202). Disabled in `--remote-only` mode.
**Required parameters:** **Required parameters:**
| Parameter | Type | Description | | Parameter | Type | Description |
@@ -185,8 +240,8 @@ Start a download job. Returns immediately with a job ID (HTTP 202).
| Parameter | Type | Default | Description | | Parameter | Type | Default | Description |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| `quality` | array[int] | best | Resolution(s) (e.g., `[1080, 2160]`) | | `quality` | array[int] | best | Resolution(s) (e.g., `[1080, 2160]`) |
| `vcodec` | string or array | any | Video codec(s): `H264`, `H265`/`HEVC`, `VP9`, `AV1`, `VC1` | | `vcodec` | string or array | any | Video codec(s): `H264`, `H265`/`HEVC`, `VP9`, `AV1`, `VC1`, `VP8` |
| `acodec` | string or array | any | Audio codec(s): `AAC`, `AC3`, `EC3`, `AC4`, `OPUS`, `FLAC`, `ALAC`, `DTS` | | `acodec` | string or array | any | Audio codec(s): `AAC`, `AC3`, `EC3`, `AC4`, `OPUS`, `FLAC`, `ALAC`, `DTS`, `OGG` |
| `vbitrate` | int | highest | Video bitrate in kbps | | `vbitrate` | int | highest | Video bitrate in kbps |
| `abitrate` | int | highest | Audio bitrate in kbps | | `abitrate` | int | highest | Audio bitrate in kbps |
| `range` | array[string] | `["SDR"]` | Color range(s): `SDR`, `HDR10`, `HDR10+`, `HLG`, `DV`, `HYBRID` | | `range` | array[string] | `["SDR"]` | Color range(s): `SDR`, `HDR10`, `HDR10+`, `HLG`, `DV`, `HYBRID` |
@@ -247,7 +302,7 @@ Start a download job. Returns immediately with a job ID (HTTP 202).
| `no_proxy` | boolean | `false` | Disable all proxy use | | `no_proxy` | boolean | `false` | Disable all proxy use |
| `workers` | int | `null` | Max threads per track download | | `workers` | int | `null` | Max threads per track download |
| `downloads` | int | `1` | Concurrent track downloads | | `downloads` | int | `1` | Concurrent track downloads |
| `slow` | string | `null` | Add delay between titles. `true` for 60-120s, or `MIN-MAX` (e.g. `20-40`) | | `slow` | boolean | `false` | Add 60-120s delay between titles |
| `best_available` | boolean | `false` | Continue if requested quality unavailable | | `best_available` | boolean | `false` | Continue if requested quality unavailable |
| `skip_dl` | boolean | `false` | Skip download, only get decryption keys | | `skip_dl` | boolean | `false` | Skip download, only get decryption keys |
| `export` | boolean | `false` | Export manifest, track URLs, keys, and subtitles to JSON in the exports directory | | `export` | boolean | `false` | Export manifest, track URLs, keys, and subtitles to JSON in the exports directory |
@@ -259,9 +314,10 @@ Start a download job. Returns immediately with a job ID (HTTP 202).
```bash ```bash
curl -X POST http://localhost:8786/api/download \ curl -X POST http://localhost:8786/api/download \
-H "X-Secret-Key: $KEY" \
-H "Content-Type: application/json" \ -H "Content-Type: application/json" \
-d '{ -d '{
"service": "EXAMPLE", "service": "EXAMPLE1",
"title_id": "abc123def456", "title_id": "abc123def456",
"wanted": ["S01E01"], "wanted": ["S01E01"],
"quality": [1080, 2160], "quality": [1080, 2160],
@@ -285,25 +341,18 @@ curl -X POST http://localhost:8786/api/download \
### GET /api/download/jobs ### GET /api/download/jobs
List all download jobs with optional filtering and sorting. List all download jobs with optional filtering and sorting. Disabled in `--remote-only` mode.
**Query parameters:** **Query parameters:**
| Parameter | Type | Default | Description | | Parameter | Type | Default | Description |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| `status` | string | all | Filter by status: `queued`, `downloading`, `completed`, `failed`, `cancelled` | | `status` | string | all | Filter by status: `queued`, `downloading`, `completed`, `failed`, `cancelled` |
| `service` | string | all | Filter by service tag | | `service` | string | all | Filter by service tag |
| `sort_by` | string | `created_time` | Sort field: `created_time`, `status`, `service` | | `sort_by` | string | `created_time` | Sort field: `created_time`, `started_time`, `completed_time`, `progress`, `status`, `service` |
| `sort_order` | string | `desc` | Sort order: `asc`, `desc` | | `sort_order` | string | `desc` | Sort order: `asc`, `desc` |
```bash ```bash
# List all jobs curl -H "X-Secret-Key: $KEY" "http://localhost:8786/api/download/jobs?status=completed"
curl http://localhost:8786/api/download/jobs
# Filter by status
curl "http://localhost:8786/api/download/jobs?status=completed"
# Filter by service
curl "http://localhost:8786/api/download/jobs?service=EXAMPLE"
``` ```
--- ---
@@ -312,19 +361,15 @@ curl "http://localhost:8786/api/download/jobs?service=EXAMPLE"
Get detailed information about a specific download job including progress, parameters, and error details. Get detailed information about a specific download job including progress, parameters, and error details.
```bash
curl http://localhost:8786/api/download/jobs/504db959-80b0-446c-a764-7924b761d613
```
```json ```json
{ {
"job_id": "504db959-80b0-446c-a764-7924b761d613", "job_id": "504db959-80b0-446c-a764-7924b761d613",
"status": "completed", "status": "completed",
"created_time": "2026-02-27T18:00:00.000000", "created_time": "2026-02-27T18:00:00.000000",
"service": "EXAMPLE", "service": "EXAMPLE1",
"title_id": "abc123def456", "title_id": "abc123def456",
"progress": 100.0, "progress": 100.0,
"parameters": { ... }, "parameters": { },
"started_time": "2026-02-27T18:00:01.000000", "started_time": "2026-02-27T18:00:01.000000",
"completed_time": "2026-02-27T18:00:15.000000", "completed_time": "2026-02-27T18:00:15.000000",
"output_files": [], "output_files": [],
@@ -337,13 +382,339 @@ curl http://localhost:8786/api/download/jobs/504db959-80b0-446c-a764-7924b761d61
### DELETE /api/download/jobs/{job_id} ### DELETE /api/download/jobs/{job_id}
Cancel a queued or running download job. Cancel a queued or running download job. Returns 400 if the job has already terminated.
```bash ---
curl -X DELETE http://localhost:8786/api/download/jobs/504db959-80b0-446c-a764-7924b761d613
## Remote Service Sessions
These endpoints back the `RemoteService` adapter in `unshackle/core/remote_service.py`. They let a thin `dl` client (or any consumer) authenticate against a service on the server, fetch titles/tracks/manifests, and either proxy CDM challenges or have the server resolve KID:KEY directly. The `dl` command's `RemoteService` adapter replaces the old `remote_dl` command. These endpoints are the only `/api/*` routes available in `--remote-only` mode (in addition to `health`, `services`, and `search`).
### POST /api/session/create
Authenticate against a service and open a session. Body fields:
| Field | Type | Description |
| --- | --- | --- |
| `service` | string | Service tag (required) |
| `title_id` | string | Title ID/URL (required) |
| `credentials` | object | Auth credentials forwarded to `Service.authenticate` |
| `cookies` | string | Cookie blob (Netscape or JSON) |
| `proxy` | string | Proxy URI or country code |
| `no_proxy` | bool | Force-disable proxies |
| `profile` | string | Profile name |
| `cache` | object | Optional pre-warmed title cache payload |
If the service requires interactive input during authentication, poll `GET /api/session/{id}/prompt` and submit responses via `POST /api/session/{id}/prompt` until status is `authenticated`.
**Request:**
```json
{
"service": "EXAMPLE1",
"title_id": "abc123def456",
"credentials": {"username": "alice", "password": "hunter2"},
"cookies": "# Netscape HTTP Cookie File\n...",
"proxy": "us",
"no_proxy": false,
"profile": "default",
"cache": {}
}
``` ```
Returns confirmation on success, or an error if the job has already completed or been cancelled. **Response (202-style; auth runs asynchronously):**
```json
{
"session_id": "f1c4a8b2-9c7e-4d2a-bf91-2d3e4f5a6b7c",
"service": "EXAMPLE1",
"status": "authenticating"
}
```
### GET /api/session/{session_id}
Returns session metadata. 404 if expired or unknown.
```json
{
"session_id": "f1c4a8b2-9c7e-4d2a-bf91-2d3e4f5a6b7c",
"service": "EXAMPLE1",
"valid": true,
"expires_in": 3600,
"track_count": 0,
"title_count": 0
}
```
### DELETE /api/session/{session_id}
Tears down the session, cancels any pending prompts, and returns any updated per-session cache files (base64-encoded, zlib-compressed) so the client can re-warm next time.
```json
{
"status": "ok",
"cache": {
"tokens": "eJzLSM3JyVcozy/KSVGo5AIAGgQEvQ=="
}
}
```
### GET /api/session/{session_id}/titles
Returns the resolved titles list.
```json
{
"session_id": "f1c4a8b2-9c7e-4d2a-bf91-2d3e4f5a6b7c",
"titles": [
{
"type": "episode",
"name": "Pilot",
"series_title": "Example Show",
"season": 1,
"number": 1,
"year": 2024,
"id": "ep-0001",
"language": "en"
},
{
"type": "movie",
"name": "Example Movie",
"year": 2024,
"id": "mov-0001",
"language": "en"
}
]
}
```
### POST /api/session/{session_id}/tracks
**Request:**
```json
{"title_id": "ep-0001"}
```
**Response:**
```json
{
"title": {
"type": "episode",
"name": "Pilot",
"series_title": "Example Show",
"season": 1,
"number": 1,
"year": 2024,
"id": "ep-0001",
"language": "en"
},
"video": [
{
"id": "v-1080p-h264",
"codec": "H264",
"codec_display": "H.264",
"bitrate": 6000,
"width": 1920,
"height": 1080,
"resolution": "1920x1080",
"fps": "23.976",
"range": "SDR",
"range_display": "SDR",
"language": "en",
"drm": [
{
"type": "widevine",
"pssh": "AAAAW3Bzc2gAAAAA7e+...",
"kids": ["abcdef0123456789abcdef0123456789"],
"license_url": "https://license.example.com/widevine"
}
],
"descriptor": "DASH",
"url": "https://cdn.example.com/manifest.mpd"
}
],
"audio": [
{
"id": "a-en-eac3",
"codec": "EC3",
"codec_display": "Dolby Digital Plus",
"bitrate": 640,
"channels": "5.1",
"language": "en",
"atmos": false,
"descriptive": false,
"drm": null,
"descriptor": "DASH",
"url": "https://cdn.example.com/manifest.mpd"
}
],
"subtitles": [
{
"id": "s-en-vtt",
"codec": "WebVTT",
"language": "en",
"forced": false,
"sdh": false,
"cc": false,
"descriptor": "DASH",
"url": "https://cdn.example.com/subs/en.vtt"
}
],
"chapters": [
{"timestamp": "00:00:00.000", "name": "Chapter 1"}
],
"attachments": [],
"manifests": [
{
"type": "dash",
"url": "https://cdn.example.com/manifest.mpd",
"data": "eJzNVk1v2zAM/Ss..."
}
],
"session_headers": {
"User-Agent": "Mozilla/5.0 ..."
},
"session_cookies": {
"session": "abc123"
},
"server_cdm_type": "widevine"
}
```
### POST /api/session/{session_id}/segments
**Request:**
```json
{"track_ids": ["v-1080p-h264", "a-en-eac3"]}
```
**Response:**
```json
{
"tracks": {
"v-1080p-h264": {
"descriptor": "DASH",
"url": "https://cdn.example.com/manifest.mpd",
"drm": [
{
"type": "widevine",
"pssh": "AAAAW3Bzc2gAAAAA7e+...",
"kids": ["abcdef0123456789abcdef0123456789"],
"license_url": "https://license.example.com/widevine"
}
],
"headers": {"User-Agent": "Mozilla/5.0 ..."},
"cookies": {"session": "abc123"},
"data": {}
},
"a-en-eac3": {
"descriptor": "DASH",
"url": "https://cdn.example.com/manifest.mpd",
"drm": null,
"headers": {"User-Agent": "Mozilla/5.0 ..."},
"cookies": {"session": "abc123"},
"data": {}
}
}
}
```
### POST /api/session/{session_id}/license
Two modes, selected by the `mode` field.
**`mode: "proxy"` (default)** -- forward a client-built CDM challenge to the service's license endpoint.
Request:
```json
{
"mode": "proxy",
"track_id": "v-1080p-h264",
"challenge": "CAESxQEK...",
"drm_type": "widevine",
"pssh": "AAAAW3Bzc2gAAAAA7e+..."
}
```
Response:
```json
{"license": "CAIS3wIK..."}
```
**`mode: "server_cdm"`** -- the server uses its own CDM to license the track and extract keys. Single-track form takes `track_id`; batch form takes `track_ids`. Requires the calling user key to have a matching device (`devices` for Widevine, `playready_devices` for PlayReady) in `unshackle.yaml`.
Request (batch):
```json
{
"mode": "server_cdm",
"track_ids": ["v-1080p-h264", "a-en-eac3"],
"drm_type": "widevine"
}
```
Response:
```json
{
"keys": {
"v-1080p-h264": {
"abcdef0123456789abcdef0123456789": "00112233445566778899aabbccddeeff"
},
"a-en-eac3": {
"abcdef0123456789abcdef0123456789": "00112233445566778899aabbccddeeff"
}
},
"drm_type": "widevine"
}
```
### GET /api/session/{session_id}/prompt
Polled by the client during interactive authentication (OTP, PIN, device codes). Backed by the `InputBridge` in `unshackle/core/api/input_bridge.py`; `Service.request_input()` blocks server-side until the client posts a response.
Pending input:
```json
{"status": "pending_input", "prompt": "Enter OTP code: "}
```
Other states:
```json
{"status": "authenticating"}
```
```json
{"status": "authenticated"}
```
```json
{"status": "failed", "error": "Invalid credentials"}
```
### POST /api/session/{session_id}/prompt
Unblocks the server-side `request_input()` call.
Request:
```json
{"response": "123456"}
```
Response:
```json
{"status": "accepted"}
```
--- ---
@@ -357,22 +728,25 @@ All endpoints return consistent error responses:
"error_code": "INVALID_PARAMETERS", "error_code": "INVALID_PARAMETERS",
"message": "Invalid vcodec: XYZ. Must be one of: H264, H265, VP9, AV1, VC1, VP8", "message": "Invalid vcodec: XYZ. Must be one of: H264, H265, VP9, AV1, VC1, VP8",
"timestamp": "2026-02-27T18:00:00.000000+00:00", "timestamp": "2026-02-27T18:00:00.000000+00:00",
"details": { ... } "details": { }
} }
``` ```
Common error codes: Common error codes:
- `INVALID_INPUT` - Malformed request body
- `INVALID_PARAMETERS` - Invalid parameter values - `INVALID_INPUT` -- malformed request body
- `MISSING_SERVICE` - Service tag not provided - `INVALID_PARAMETERS` -- invalid parameter values
- `INVALID_SERVICE` - Service not found - `MISSING_SERVICE` -- service tag not provided
- `SERVICE_ERROR` - Service initialization or runtime error - `INVALID_SERVICE` -- service not found or not in the caller's allowlist
- `AUTH_FAILED` - Authentication failure - `SERVICE_ERROR` -- service initialization or runtime error
- `NOT_FOUND` - Job or resource not found - `AUTH_FAILED` -- authentication failure
- `INTERNAL_ERROR` - Unexpected server error - `NOT_FOUND` / `TRACK_NOT_FOUND` / session not found -- job/session/track/title missing
- `INTERNAL_ERROR` -- unexpected server error
When `--debug-api` is enabled, error responses include additional `debug_info` with tracebacks and stderr output. When `--debug-api` is enabled, error responses include additional `debug_info` with tracebacks and stderr output.
Authentication errors from the auth middleware are returned as `{"status": 401, "message": "..."}` (not the standard error envelope).
--- ---
## Download Job Lifecycle ## Download Job Lifecycle
@@ -385,3 +759,5 @@ downloading -> cancelled
``` ```
Jobs are retained for 24 hours after completion. The server supports up to 2 concurrent downloads by default. Jobs are retained for 24 hours after completion. The server supports up to 2 concurrent downloads by default.
Remote sessions are managed by `SessionStore` (`unshackle/core/api/session_store.py`); idle sessions and their `InputBridge` instances are cleaned up by a background loop started/stopped with the app lifecycle.
+23 -95
View File
@@ -2,103 +2,28 @@
This document covers configuration options related to downloading and processing media content. This document covers configuration options related to downloading and processing media content.
## aria2c (dict) ## downloader
- `max_concurrent_downloads` unshackle ships a single unified downloader at `unshackle/core/downloaders/requests.py`. The legacy
Maximum number of parallel downloads. Default: `min(32,(cpu_count+4))` `aria2c`, `curl_impersonate`, and `n_m3u8dl_re` backends have been removed; their config blocks no
Note: Overrides the `max_workers` parameter of the aria2(c) downloader function. longer have any effect.
- `max_connection_per_server`
Maximum number of connections to one server for each download. Default: `1`
- `split`
Split a file into N chunks and download each chunk on its own connection. Default: `5`
- `file_allocation`
Specify file allocation method. Default: `"prealloc"`
- `"none"` doesn't pre-allocate file space. The unified downloader:
- `"prealloc"` pre-allocates file space before download begins. This may take some time depending on the size of the
file.
- `"falloc"` is your best choice if you are using newer file systems such as ext4 (with extents support), btrfs, xfs
or NTFS (MinGW build only). It allocates large(few GiB) files almost instantly. Don't use falloc with legacy file
systems such as ext3 and FAT32 because it takes almost same time as prealloc, and it blocks aria2 entirely until
allocation finishes. falloc may not be available if your system doesn't have posix_fallocate(3) function.
- `"trunc"` uses ftruncate(2) system call or platform-specific counterpart to truncate a file to a specified length.
--- - Works with both a standard `requests.Session` and `RnetSession` (rnet/BoringSSL TLS impersonation,
which replaces the previous `curl_cffi` backend). When a service exposes its own session via
`self.session`, TLS fingerprinting is preserved on every segment.
- Uses adaptive chunk sizing between **512 KB and 4 MB**, picked from the response `Content-Length`.
- Spawns **up to `min(16, cpu_count + 4)` worker threads** by default for segmented downloads
(override via `--workers` / `dl.workers`).
- Resumes interrupted downloads via HTTP `Range` requests (a sibling `<file>.!dev` control file
marks an in-progress download).
- Has a single-URL fast path: if the server supports byte ranges and the file is at least 64 MB,
the file is split into 16 MB parts and downloaded in parallel into a pre-allocated file.
- Is selected per-track via `track.downloader`, which defaults to this unified `requests` downloader.
## curl_impersonate (dict) There is no `downloader:` config key to set anymore. Setting one to a legacy value will emit a
`DeprecationWarning` and otherwise be ignored.
- `browser` - The Browser to impersonate as. A list of available Browsers and Versions are listed here:
<https://github.com/yifeikong/curl_cffi#sessions>
Default: `"chrome124"`
For example,
```yaml
curl_impersonate:
browser: "chrome120"
```
---
## downloader (str | dict)
Choose what software to use to download data throughout unshackle where needed.
You may provide a single downloader globally or a mapping of service tags to
downloaders.
Options:
- `requests` (default) - <https://github.com/psf/requests>
- `aria2c` - <https://github.com/aria2/aria2>
- `curl_impersonate` - <https://github.com/yifeikong/curl-impersonate> (via <https://github.com/yifeikong/curl_cffi>)
- `n_m3u8dl_re` - <https://github.com/nilaoda/N_m3u8DL-RE>
Note that aria2c can reach the highest speeds as it utilizes threading and more connections than the other downloaders. However, aria2c can also be one of the more unstable downloaders. It will work one day, then not another day. It also does not support HTTP(S) proxies natively (non-HTTP proxies are bridged via pproxy).
Note that `n_m3u8dl_re` will automatically fall back to `requests` for track types it does not support, specifically: direct URL downloads, Subtitle tracks, and Attachment tracks.
Example mapping:
```yaml
downloader:
EXAMPLE: requests
EXAMPLE2: n_m3u8dl_re
EXAMPLE3: n_m3u8dl_re
default: requests
```
The `default` entry is optional. If omitted, `requests` will be used for services not listed.
---
## n_m3u8dl_re (dict)
Configuration for N_m3u8DL-RE downloader. This downloader supports HLS, DASH, and ISM (Smooth Streaming) manifests.
It will automatically fall back to the `requests` downloader for unsupported track types (direct URLs, subtitles, attachments).
- `thread_count`
Number of threads to use for downloading. Default: Uses the same value as max_workers from the command
(which defaults to `min(32,(cpu_count+4))`).
- `ad_keyword`
Keyword to identify and potentially skip advertisement segments. Default: `None`
- `use_proxy`
Whether to use proxy when downloading. Default: `true`
- `retry_count`
Number of times to retry failed downloads. Default: `10`
N_m3u8DL-RE also respects the `decryption` config setting. When content keys are provided, it will use
the configured decryption engine (`shaka` or `mp4decrypt`) and automatically locate the corresponding binary.
For example,
```yaml
n_m3u8dl_re:
thread_count: 16
ad_keyword: "advertisement"
use_proxy: true
retry_count: 10
```
--- ---
@@ -159,6 +84,8 @@ to a CLI option on the `dl` command. CLI arguments always take priority over con
| `acodec` | str or list | any | Audio codec(s): `AAC`, `AC3`, `EC3`, `AC4`, `OPUS`, `FLAC`, `ALAC`, `DTS` | | `acodec` | str or list | any | Audio codec(s): `AAC`, `AC3`, `EC3`, `AC4`, `OPUS`, `FLAC`, `ALAC`, `DTS` |
| `vbitrate` | int | highest | Video bitrate in kbps | | `vbitrate` | int | highest | Video bitrate in kbps |
| `abitrate` | int | highest | Audio bitrate in kbps | | `abitrate` | int | highest | Audio bitrate in kbps |
| `vbitrate_range` | str | none | Video bitrate window in kbps, format `MIN-MAX` (e.g., `6000-7000`) |
| `abitrate_range` | str | none | Audio bitrate window in kbps, format `MIN-MAX` |
| `range_` | str or list | `SDR` | Color range(s): `SDR`, `HDR10`, `HDR10+`, `HLG`, `DV`, `HYBRID` | | `range_` | str or list | `SDR` | Color range(s): `SDR`, `HDR10`, `HDR10+`, `HLG`, `DV`, `HYBRID` |
| `channels` | float | any | Audio channels (e.g., `5.1`, `7.1`) | | `channels` | float | any | Audio channels (e.g., `5.1`, `7.1`) |
| `worst` | bool | `false` | Select the lowest bitrate track within the specified quality. Requires `quality` | | `worst` | bool | `false` | Select the lowest bitrate track within the specified quality. Requires `quality` |
@@ -202,6 +129,7 @@ to a CLI option on the `dl` command. CLI arguments always take priority over con
| `no_source` | bool | `false` | Remove source tag from filename | | `no_source` | bool | `false` | Remove source tag from filename |
| `no_mux` | bool | `false` | Do not mux tracks into a container file | | `no_mux` | bool | `false` | Do not mux tracks into a container file |
| `split_audio` | bool | `false` | Create separate output files per audio codec | | `split_audio` | bool | `false` | Create separate output files per audio codec |
| `export` | bool | `false` | Write a JSON sidecar with manifest URLs, subtitles, per-track KID:KEY, codec/track info |
**Metadata enrichment:** **Metadata enrichment:**
@@ -217,8 +145,8 @@ to a CLI option on the `dl` command. CLI arguments always take priority over con
| Key | Type | Default | Description | | Key | Type | Default | Description |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| `downloads` | int | `1` | Concurrent track downloads | | `downloads` | int | `1` | Concurrent track downloads |
| `workers` | int | auto | Max threads per track download | | `workers` | int | `min(16, cpu_count + 4)` | Max threads per track download (segments / ranged parts) |
| `slow` | bool | `false` | Add 60-120s delay between titles | | `slow` | bool or `MIN-MAX` | `false` | Randomized delay between titles. `true` uses 60-120s; pass `MIN-MAX` (e.g., `20-40`) for a custom range |
| `skip_dl` | bool | `false` | Skip download, only get decryption keys | | `skip_dl` | bool | `false` | Skip download, only get decryption keys |
| `cdm_only` | bool | `null` | Only use CDM (`true`) or only vaults (`false`) | | `cdm_only` | bool | `null` | Only use CDM (`true`) or only vaults (`false`) |
+18 -8
View File
@@ -153,8 +153,16 @@ providers:
### Specific Server Selection ### Specific Server Selection
Use `--proxy gluetun:nordvpn:us1239` for specific server selection. Unshackle builds the hostname Use a `<country><number>` region (e.g. `us1239`) to target a specific server. Unshackle builds the
automatically based on the provider (e.g., `us1239.nordvpn.com` for NordVPN). hostname automatically per provider:
| Provider | Hostname format |
|----------|-----------------|
| NordVPN | `us1239.nordvpn.com` |
| Surfshark | `us-1239.prod.surfshark.com` |
| ExpressVPN | `us-1239.expressvpn.com` |
| CyberGhost | `us-s1239.cg-dialup.net` |
| Other | `us1239` (passed as-is to `SERVER_HOSTNAMES`) |
### Extra Environment Variables ### Extra Environment Variables
@@ -187,12 +195,14 @@ proxy_providers:
## Features ## Features
- **Container Reuse**: First request takes 10-30s; subsequent requests are instant. Containers from other sessions are also detected and reused. - **Container Reuse**: First request takes 10-30s; subsequent requests are instant. Containers created by other unshackle processes are auto-detected via `docker inspect` and reused.
- **IP Verification**: Automatically verifies VPN exit IP matches requested region (configurable via `verify_ip`) - **Ready Detection**: Waits up to 60s for both the HTTP proxy to listen (`[http proxy] listening`) and the VPN tunnel to come up (`initialization sequence completed` or `public ip address is`) before returning the proxy URI. Bails early on `fatal` or `invalid credentials` log lines.
- **Concurrent Sessions**: Multiple downloads share the same container - **IP Verification**: When `verify_ip: true` (default), looks up the exit IP via `ipinfo.io` through the proxy and compares country code to the requested region. Retries 3 times with exponential backoff (1s, 2s, 4s).
- **Specific Servers**: Use `--proxy gluetun:nordvpn:us1239` for specific server selection - **Concurrent Sessions**: Multiple downloads share the same container; ports are allocated thread-safely starting at `base_port`.
- **Automatic Image Pull**: The Gluetun Docker image (`qmcgaw/gluetun:latest`) is pulled automatically on first use - **Specific Servers**: Use `--proxy gluetun:nordvpn:us1239` for specific server selection (see table above).
- **Secure Credentials**: Credentials are passed via temporary env files (mode 0600) rather than command-line arguments - **Automatic Image Pull**: The Gluetun Docker image (`qmcgaw/gluetun:latest`) is pulled automatically on first use (5 min timeout).
- **Secure Credentials**: Credentials are passed via temporary env files (mode 0600), then zero-overwritten and unlinked after `docker run`. They never appear in process listings.
- **Auto Cleanup**: Containers are removed via `atexit` (Ctrl+C still works normally). Disable with `auto_cleanup: false` to leave them stopped instead.
## Container Management ## Container Management
+29 -2
View File
@@ -138,8 +138,8 @@ All requests will use these unless changed explicitly or implicitly via a Server
These should be sane defaults and anything that would only be useful for some Services should not These should be sane defaults and anything that would only be useful for some Services should not
be put here. be put here.
Avoid headers like 'Accept-Encoding' as that would be a compatibility header that curl_cffi will Avoid headers like 'Accept-Encoding' as that would be a compatibility header that the underlying
set for you. HTTP backend (rnet) will set for you as part of its browser impersonation profile.
I recommend using, I recommend using,
@@ -149,3 +149,30 @@ User-Agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML
``` ```
--- ---
## HTTP Session Backend
unshackle uses [`rnet`](https://github.com/0x676e67/rnet) (Rust + BoringSSL) for HTTP with TLS
fingerprinting. `RnetSession` is a drop-in `requests.Session` replacement and is what
`self.session` exposes to services. It supports:
- Browser/app impersonation via named `rnet.Impersonate` presets (Chrome, Edge, Firefox, Safari,
OkHttp, etc.) — picks JA3, ALPN, HTTP/2 SETTINGS and header order to match the chosen client.
- Native rnet proxy support (HTTP, HTTPS, SOCKS5) — used by all proxy providers below.
- Cookie-jar and `requests`-style `data=` / `json=` / `headers=` kwargs for compatibility.
The legacy `curl_cffi` backend has been removed. The config key is still spelled
`curl_impersonate` for backward compatibility, but its value now selects an rnet preset.
### curl_impersonate (dict)
```yaml
curl_impersonate:
browser: Chrome131 # exact rnet.Impersonate preset name
```
`browser` must be an exact `rnet.Impersonate` preset name (e.g. `Chrome131`, `Chrome124`,
`Edge101`, `Firefox133`, `Safari18`, `OkHttp4_12`). See the rnet README for the full list.
Default when unset: `Chrome131`.
---
+38 -2
View File
@@ -38,7 +38,7 @@ This is **required** in your `unshackle.yaml` — a warning is shown if not conf
Available variables: `{title}`, `{year}`, `{season}`, `{episode}`, `{season_episode}`, `{episode_name}`, Available variables: `{title}`, `{year}`, `{season}`, `{episode}`, `{season_episode}`, `{episode_name}`,
`{quality}`, `{resolution}`, `{source}`, `{audio}`, `{audio_channels}`, `{audio_full}`, `{quality}`, `{resolution}`, `{source}`, `{audio}`, `{audio_channels}`, `{audio_full}`,
`{video}`, `{hdr}`, `{hfr}`, `{atmos}`, `{dual}`, `{multi}`, `{tag}`, `{edition}`, `{repack}`, `{video}`, `{hdr}`, `{hfr}`, `{atmos}`, `{dual}`, `{multi}`, `{tag}`, `{edition}`, `{repack}`,
`{lang_tag}` `{lang_tag}`, `{track_number}`, `{artist}`, `{album}`, `{disc}`
Add `?` suffix to make a variable conditional (omitted when empty): `{year?}`, `{hdr?}`, `{repack?}` Add `?` suffix to make a variable conditional (omitted when empty): `{year?}`, `{hdr?}`, `{repack?}`
@@ -70,17 +70,26 @@ If not configured, the default folder naming is used:
- Series: Derived from the `series` template with episode-specific variables removed - Series: Derived from the `series` template with episode-specific variables removed
- Songs: `Artist - Album (Year)` - Songs: `Artist - Album (Year)`
`folder` accepts either a single string (applies to all title kinds) or a mapping with per-kind
templates keyed by `movies`, `series`, and/or `songs`. Unknown keys are warned about and ignored.
```yaml ```yaml
output_template: output_template:
movies: '{title}.{year}.{repack?}.{edition?}.{quality}.{source}.WEB-DL.{dual?}.{multi?}.{audio_full}.{atmos?}.{hdr?}.{hfr?}.{video}-{tag}' movies: '{title}.{year}.{repack?}.{edition?}.{quality}.{source}.WEB-DL.{dual?}.{multi?}.{audio_full}.{atmos?}.{hdr?}.{hfr?}.{video}-{tag}'
series: '{title}.{year?}.{season_episode}.{episode_name?}.{repack?}.{edition?}.{quality}.{source}.WEB-DL.{dual?}.{multi?}.{audio_full}.{atmos?}.{hdr?}.{hfr?}.{video}-{tag}' series: '{title}.{year?}.{season_episode}.{episode_name?}.{repack?}.{edition?}.{quality}.{source}.WEB-DL.{dual?}.{multi?}.{audio_full}.{atmos?}.{hdr?}.{hfr?}.{video}-{tag}'
songs: '{track_number}.{title}.{repack?}.{edition?}.{source?}.WEB-DL.{audio_full}.{atmos?}-{tag}' songs: '{track_number}.{title}.{repack?}.{edition?}.{source?}.WEB-DL.{audio_full}.{atmos?}-{tag}'
# Scene-style folder # Scene-style folder (single template, applies to all kinds)
folder: '{title}.{year?}.{repack?}.{edition?}.{lang_tag?}.{quality}.{source}.WEB-DL.{dual?}.{multi?}.{audio_full}.{atmos?}.{hdr?}.{hfr?}.{video}-{tag}' folder: '{title}.{year?}.{repack?}.{edition?}.{lang_tag?}.{quality}.{source}.WEB-DL.{dual?}.{multi?}.{audio_full}.{atmos?}.{hdr?}.{hfr?}.{video}-{tag}'
# Plex-friendly folder # Plex-friendly folder
# folder: '{title} ({year?})' # folder: '{title} ({year?})'
# Per-kind folder templates
# folder:
# movies: '{title} ({year})'
# series: '{title} ({year?})'
# songs: '{artist} - {album} ({year?})'
``` ```
Example outputs: Example outputs:
@@ -195,6 +204,32 @@ Enable/disable tagging downloaded files with IMDB/TMDB/TVDB identifiers (when av
Note: The `--split-audio` CLI flag overrides this setting. When `--split-audio` is passed, Note: The `--split-audio` CLI flag overrides this setting. When `--split-audio` is passed,
`merge_audio` is effectively set to `false` for that run. `merge_audio` is effectively set to `false` for that run.
- `default_language` (dict)
Override which track is flagged as the default in the muxed MKV, regardless
of the title's original language. Useful when you always want your player to
open on a specific language (e.g. always default to Polish audio even on
English originals). Only affects the MKV `--default-track` flag — track
selection (`-l`, `--alang`, etc.) is unchanged. All keys are optional; each
track type falls back to its previous default rule when the configured
language isn't present in the manifest.
- `audio`: BCP-47 tag (e.g. `pl`, `en`, `pt-BR`). Wins over `is_original_lang`.
The `--original-flag` continues to mark the true original-audio track.
- `video`: BCP-47 tag. Wins over the title-language / first-track rule.
- `subtitle`: BCP-47 tag. Wins over the "forced sub matching audio" rule.
Languages are matched with the same close-match logic used elsewhere
(`pt` matches `pt-BR`, etc.). Supports per-service overrides like the rest
of `muxing`.
```yaml
muxing:
default_language:
audio: pl
video: pl
subtitle: pl
```
--- ---
## chapter_fallback_name (str) ## chapter_fallback_name (str)
@@ -230,6 +265,7 @@ The following directories are available and may be overridden,
- `cache` - Expiring data like Authorization tokens, or other misc data. - `cache` - Expiring data like Authorization tokens, or other misc data.
- `cookies` - Expiring Cookie data. - `cookies` - Expiring Cookie data.
- `logs` - Logs. - `logs` - Logs.
- `exports` - JSON sidecar exports written when `--export` is used on `dl`.
- `wvds` - Widevine Devices. - `wvds` - Widevine Devices.
- `prds` - PlayReady Devices. - `prds` - PlayReady Devices.
- `dcsl` - Device Certificate Status List. - `dcsl` - Device Certificate Status List.
+66 -7
View File
@@ -26,8 +26,8 @@ EXAMPLE:
### Per-Service Configuration Overrides ### Per-Service Configuration Overrides
You can override many global configuration options on a per-service basis by nesting them under the You can override many global configuration options on a per-service basis by nesting them under the
service tag in the `services` section. Supported override keys include: `dl`, `aria2c`, `n_m3u8dl_re`, service tag in the `services` section. Supported override keys include: `dl`, `subtitle`, `muxing`,
`curl_impersonate`, `subtitle`, `muxing`, `headers`, and more. `headers`, `proxy_map`, and more.
Overrides are merged with global config (not replaced) -- only specified keys are overridden, others Overrides are merged with global config (not replaced) -- only specified keys are overridden, others
use global defaults. CLI arguments always take priority over service-specific config. use global defaults. CLI arguments always take priority over service-specific config.
@@ -39,13 +39,53 @@ services:
RATE_LIMITED_SERVICE: RATE_LIMITED_SERVICE:
dl: dl:
downloads: 2 # Limit concurrent track downloads downloads: 2 # Limit concurrent track downloads
workers: 4 # Reduce workers to avoid rate limits workers: 4 # Reduce workers to avoid rate limits
n_m3u8dl_re: headers:
thread_count: 4 # Very low thread count User-Agent: "..." # Service-specific UA override
aria2c:
max_concurrent_downloads: 1
``` ```
Note: unshackle uses a single unified `requests`-based downloader. The legacy `aria2c`,
`n_m3u8dl_re`, and `curl_impersonate` override sections have been removed.
### Service Class Conventions
Each service directory under `unshackle/services/` exports a class extending
`unshackle.core.service.Service`. The class name must match the directory name (the service tag).
Key class variables (defined on `Service` or by service-level idiom):
- `ALIASES: tuple[str, ...]` — alternative tags accepted on the CLI. Empty by default.
- `GEOFENCE: tuple[str, ...]` — ISO country codes the service is available in. Empty == no geofence.
- `TITLE_RE: str` — regex (with named groups, e.g. `(?P<id>...)`, `(?P<type>...)`) used by the
service to parse the CLI title argument. Service-level idiom, not declared on the base class.
- `NO_SUBTITLES: bool` — service-level idiom indicating the service has no subtitle tracks.
`self.*` helpers available after `super().__init__(ctx)`:
- `self.session` — pre-configured HTTP session (`requests.Session`, or `RnetSession` when TLS
impersonation is active). Cookies, headers, proxies pre-applied.
- `self.config` — merged service config (per-service `config.yaml` plus the `services.<TAG>` block
from `unshackle.yaml`).
- `self.log` — `logging.Logger` named for the service class.
- `self.cache` — generic `Cacher` for arbitrary key/value persistence.
- `self.title_cache` — specialized `TitleCacher` for title metadata.
- `self.track_request` — `TrackRequest` built from CLI flags. Fields: `codecs: list[Video.Codec]`,
`ranges: list[Video.Range]` (defaults to `[SDR]`), `best_available: bool`. Services may
read or rewrite these (e.g. force HEVC for HDR ranges).
- `self.credential` — set during `authenticate()`; `None` if cookies-only.
- `self.current_region` — lowercase ISO country code from proxy/geolocation, or `None`.
- `self.request_input(prompt: str) -> str` — interactive prompt. Falls through to `input()`
locally; under `serve`, the attached `InputBridge` relays the prompt to the remote client.
Driving CLI flags (parsed into `self.track_request`):
- `-v` / `--vcodec` — comma-separated `Video.Codec` list (e.g. `H264,H265`).
- `-a` / `--acodec` — comma-separated audio codec list.
- `-r` / `--range` — comma-separated `Video.Range` list (`SDR`, `HDR10`, `HDR10+`, `DV`,
`HYBRID`). Defaults to `[SDR]`.
- `-q` / `--quality` — resolution list.
- `--vbitrate-range` / `--abitrate-range` — `MIN-MAX` kbps windows.
--- ---
## credentials (dict[str, str|list|dict]) ## credentials (dict[str, str|list|dict])
@@ -119,6 +159,25 @@ simkl_client_id: "your_client_id_here"
--- ---
## ipinfo_api_key (str)
Optional API token for [ipinfo.io](https://ipinfo.io). When set, unshackle uses the free authenticated **Lite** endpoint (`https://api.ipinfo.io/lite/me`), which has substantially higher rate limits than the anonymous endpoint and returns richer fields (ASN, organization name, continent). Leave empty to use the anonymous ipinfo.io endpoint, with [ip-api.in](https://ip-api.in) as a final fallback.
To obtain an ipinfo.io token:
1. Sign up for a free account at <https://ipinfo.io/signup>
2. Copy the token from your dashboard
For example,
```yaml
ipinfo_api_key: "12a3b45cd678ef" # Not a real key
```
**Note**: The token is only ever sent to `api.ipinfo.io` as a per-request `Authorization` header — it is never attached to your session for service requests. Used by `core/utils/ip_info.py` for region detection and proxy verification.
---
## title_cache_enabled (bool) ## title_cache_enabled (bool)
Enable/disable caching of title metadata to reduce redundant API calls. Default: `true`. Enable/disable caching of title metadata to reduce redundant API calls. Default: `true`.
+40 -19
View File
@@ -1,39 +1,41 @@
# Subtitle Processing Configuration # Subtitle Processing Configuration
This document covers subtitle processing and formatting options. This document covers subtitle processing and formatting options under the top-level `subtitle:` key in `unshackle.yaml`.
For the canonical example, see `unshackle/unshackle-example.yaml`.
## subtitle (dict) ## subtitle (dict)
Control subtitle conversion and SDH (hearing-impaired) stripping behavior. Control subtitle conversion, SDH (hearing-impaired) stripping, formatting preservation, and output behavior.
- `conversion_method`: How to convert subtitles between formats. Default: `auto`. - `conversion_method`: How to convert subtitles between formats. Default: `auto`.
- `auto`: Smart routing - use subby for WebVTT/SAMI, pycaption for others. - `auto`: Smart routing - subby for WebVTT/fVTT/SAMI; for SSA/ASS/MicroDVD/MPL2/TMP use SubtitleEdit when available, otherwise pysubs2; standard pycaption/SubtitleEdit pipeline for everything else.
- `subby`: Always use subby with CommonIssuesFixer. - `subby`: Always use subby with `CommonIssuesFixer` (falls back to standard if the source codec isn't supported by subby).
- `subtitleedit`: Prefer SubtitleEdit when available; otherwise fallback to standard conversion. - `subtitleedit`: Prefer SubtitleEdit when available; otherwise fall back to the standard pycaption pipeline.
- `pycaption`: Use only the pycaption library (no SubtitleEdit, no subby). - `pycaption`: Use only the pycaption library (no SubtitleEdit, no subby). Limited to SRT, TTML, and WebVTT outputs.
- `pysubs2`: Use pysubs2 library (supports SRT, SSA, ASS, WebVTT, TTML, SAMI, MicroDVD, MPL2, TMP formats). - `pysubs2`: Use pysubs2 (supports SRT, SSA, ASS, WebVTT, TTML, SAMI, MicroDVD, MPL2, TMP).
- `sdh_method`: How to strip SDH cues. Default: `auto`. - `sdh_method`: How to strip SDH cues. Default: `auto`.
- `auto`: Try subby for SRT first, then SubtitleEdit, then filter-subs. - `auto`: Try subby for SRT first, then SubtitleEdit (when `conversion_method` is `auto`/`subtitleedit` and the binary is available), then subtitle-filter as the final fallback.
- `subby`: Use subby's SDHStripper. **Note:** Only works with SRT files; other formats will fall back to alternative methods. - `subby`: Use subby's `SDHStripper`. **Only operates on SRT**; for other codecs the call returns without stripping.
- `subtitleedit`: Use SubtitleEdit's RemoveTextForHI when available. - `subtitleedit`: Use SubtitleEdit's `/RemoveTextForHI` when the binary is available; otherwise falls through to subtitle-filter.
- `filter-subs`: Use the subtitle-filter library. - `filter-subs`: Use the `subtitle-filter` library directly (`rm_fonts`, `rm_ast`, `rm_music`, `rm_effects`, `rm_names`, `rm_author`).
- `strip_sdh`: Enable/disable automatic SDH (hearing-impaired) cue stripping. Default: `true`. - `strip_sdh`: Enable/disable automatic SDH stripping for tracks flagged as SDH. Default: `true`.
- `convert_before_strip`: When using `filter-subs` SDH method, automatically convert subtitles to SRT format first for better compatibility. Default: `true`. - `convert_before_strip`: When falling through to the subtitle-filter path, auto-convert non-SRT subtitles to SRT first for better compatibility. Default: `true`. Has no effect when SubtitleEdit handles stripping directly.
- `preserve_formatting`: Keep original subtitle tags and positioning during conversion. When true, skips pycaption processing for WebVTT files to keep tags like `<i>`, `<b>`, and positioning intact. Default: `true`. - `preserve_formatting`: Keep original subtitle tags and positioning during WebVTT processing. When `true`, sanitized WebVTT is written back without round-tripping through pycaption, preserving tags like `<i>`, `<b>`, and `line:` positioning. Default: `true`.
- `output_mode`: Controls how subtitles are included in the output. Default: `mux`. - `output_mode`: Controls how subtitles are included in the output. Default: `mux`.
- `mux`: Embed subtitles in the MKV container only. - `mux`: Embed subtitles in the MKV container only.
- `sidecar`: Save subtitles as separate files only (not muxed into the container). - `sidecar`: Save subtitles as separate files only (not muxed).
- `both`: Embed subtitles in the MKV container and save as sidecar files. - `both`: Embed in the MKV container and save as sidecar files.
- `sidecar_format`: Format for sidecar subtitle files (used when `output_mode` is `sidecar` or `both`). Default: `srt`. - `sidecar_format`: Format for sidecar subtitle files (used when `output_mode` is `sidecar` or `both`). Default: `srt`.
- `srt`: SubRip format. - `srt`: SubRip.
- `vtt`: WebVTT format. - `vtt`: WebVTT.
- `ass`: Advanced SubStation Alpha format. - `ass`: Advanced SubStation Alpha.
- `original`: Keep the subtitle in its current format without conversion. - `original`: Keep the subtitle in its current format without conversion.
Example: Example:
@@ -49,4 +51,23 @@ subtitle:
sidecar_format: srt sidecar_format: srt
``` ```
## WebVTT Sanitization (automatic, not configurable)
After download, WebVTT and segmented WebVTT (`fVTT`/`WVTT`) tracks pass through a fixed sanitization pipeline before any conversion or muxing:
1. **Segment merge** — segmented DASH/HLS WebVTT is stitched via `merge_segmented_webvtt` (uses pysubs2 for lenient parsing when `conversion_method` is `auto` or `pysubs2`, otherwise pycaption directly).
2. **Negative timestamps** — `sanitize_webvtt_timestamps` rewrites `-HH:MM:SS.mmm` cues to `00:00:00.000`.
3. **Cue identifiers** — `sanitize_webvtt_cue_identifiers` strips letter+digit IDs (e.g. `Q0`, `S12`) on their own line before a timing line, which otherwise confuse parsers like pysubs2.
4. **Overlapping cues** — `merge_overlapping_webvtt_cues` collapses cues with start times within 50 ms and matching end times into a single multi-line cue, ordered by `line:` percentage (lower % = higher on screen = first line).
5. **Fallback hardening** — when `preserve_formatting` is `false` and the first pycaption parse fails, `sanitize_webvtt` retries with a `WEBVTT` header guard, hour-padded timings, and another negative-timestamp pass; if that still fails, the sanitized text is written as-is.
`sanitize_broken_webvtt` and `space_webvtt_headers` additionally run inside `Subtitle.parse()` to drop malformed `-->` lines and reflow merged-segment headers. `merge_same_cues` and `filter_unwanted_cues` (drops `&nbsp;`/whitespace-only cues) run only on the pycaption path.
These behaviors are intentional and have no config knobs — they apply to every WebVTT track regardless of `conversion_method`.
## Related
- Filename sanitization (e.g. parenthesis handling, unidecode bracket artifacts from PR #105) lives in `unshackle/core/utilities.py::sanitize_filename` and is governed by `output_template`, not the `subtitle:` config block.
- Subtitle codec support and the conversion matrix are defined in `unshackle/core/tracks/subtitle.py`.
--- ---
+97 -9
View File
@@ -53,6 +53,7 @@ from unshackle.core.titles import Movie, Movies, Series, Song, Title_T
from unshackle.core.titles.episode import Episode from unshackle.core.titles.episode import Episode
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
from unshackle.core.tracks.attachment import Attachment from unshackle.core.tracks.attachment import Attachment
from unshackle.core.tracks.dv_fixup import apply_dv_fixup
from unshackle.core.tracks.hybrid import Hybrid from unshackle.core.tracks.hybrid import Hybrid
from unshackle.core.utilities import (find_font_with_fallbacks, get_debug_logger, get_system_fonts, init_debug_logger, from unshackle.core.utilities import (find_font_with_fallbacks, get_debug_logger, get_system_fonts, init_debug_logger,
is_close_match, suggest_font_packages, time_elapsed_since) is_close_match, suggest_font_packages, time_elapsed_since)
@@ -558,6 +559,7 @@ class dl:
DRM_TABLE_LOCK = Lock() DRM_TABLE_LOCK = Lock()
EXPORT_LOCK = Lock() EXPORT_LOCK = Lock()
LICENSE_KEY_CACHE: dict[UUID, str] = {}
def __init__( def __init__(
self, self,
@@ -1663,7 +1665,7 @@ class dl:
] ]
# Apply hybrid selection to HDR10+DV tracks # Apply hybrid selection to HDR10+DV tracks
hybrid_filter = title.tracks.select_hybrid(hybrid_candidate_tracks, quality) hybrid_filter = title.tracks.select_hybrid(hybrid_candidate_tracks, quality, worst=worst)
hybrid_selected = list(filter(hybrid_filter, hybrid_candidate_tracks)) hybrid_selected = list(filter(hybrid_filter, hybrid_candidate_tracks))
if non_hybrid_ranges and non_hybrid_tracks: if non_hybrid_ranges and non_hybrid_tracks:
@@ -1702,6 +1704,7 @@ class dl:
sys.exit(1) sys.exit(1)
# choose best track by range and quality # choose best track by range and quality
pre_hybrid_videos: list[Video] = list(title.tracks.videos) if has_hybrid else []
if has_hybrid: if has_hybrid:
# Apply hybrid selection for HYBRID tracks # Apply hybrid selection for HYBRID tracks
hybrid_candidate_tracks = [ hybrid_candidate_tracks = [
@@ -1718,12 +1721,14 @@ class dl:
if not quality: if not quality:
best_resolution = max((v.height for v in hybrid_candidate_tracks), default=None) best_resolution = max((v.height for v in hybrid_candidate_tracks), default=None)
if best_resolution: if best_resolution:
hybrid_filter = title.tracks.select_hybrid(hybrid_candidate_tracks, [best_resolution]) hybrid_filter = title.tracks.select_hybrid(
hybrid_candidate_tracks, [best_resolution], worst=worst
)
hybrid_selected = list(filter(hybrid_filter, hybrid_candidate_tracks)) hybrid_selected = list(filter(hybrid_filter, hybrid_candidate_tracks))
else: else:
hybrid_selected = [] hybrid_selected = []
else: else:
hybrid_filter = title.tracks.select_hybrid(hybrid_candidate_tracks, quality) hybrid_filter = title.tracks.select_hybrid(hybrid_candidate_tracks, quality, worst=worst)
hybrid_selected = list(filter(hybrid_filter, hybrid_candidate_tracks)) hybrid_selected = list(filter(hybrid_filter, hybrid_candidate_tracks))
# For non-hybrid ranges, apply Cartesian product selection # For non-hybrid ranges, apply Cartesian product selection
@@ -1810,6 +1815,31 @@ class dl:
f"Continuing with remaining range(s): {', '.join(r.name for r in other_ranges)}" f"Continuing with remaining range(s): {', '.join(r.name for r in other_ranges)}"
) )
range_ = other_ranges range_ = other_ranges
fallback_pool = pre_hybrid_videos
if video_multi_lang:
fallback_langs = list(dict.fromkeys(str(v.language) for v in fallback_pool))
else:
fallback_langs = [None]
fallback_selected: list[Video] = []
for resolution, color_range, codec, vlang in product(
quality or [None], other_ranges, vcodec or [None], fallback_langs
):
candidates = [
t
for t in fallback_pool
if (
not resolution
or t.height == resolution
or int(t.width * (9 / 16)) == resolution
)
and (not color_range or t.range == color_range)
and (not codec or t.codec == codec)
and (vlang is None or str(t.language) == vlang)
]
match = candidates[-1] if worst and candidates else next(iter(candidates), None)
if match and match not in fallback_selected:
fallback_selected.append(match)
title.tracks.videos = fallback_selected
else: else:
self.log.error(msg) self.log.error(msg)
self.log.error(msg_detail) self.log.error(msg_detail)
@@ -1907,6 +1937,7 @@ class dl:
if "best" in processed_lang or "all" in processed_lang: if "best" in processed_lang or "all" in processed_lang:
unique_languages = {track.language for track in title.tracks.audio} unique_languages = {track.language for track in title.tracks.audio}
selected_audio = [] selected_audio = []
best_key = lambda x: (bool(x.atmos), x.bitrate or 0) # noqa: E731
for language in unique_languages: for language in unique_languages:
codecs_to_check = acodec if (acodec and len(acodec) > 1) else [None] codecs_to_check = acodec if (acodec and len(acodec) > 1) else [None]
for codec in codecs_to_check: for codec in codecs_to_check:
@@ -1920,18 +1951,19 @@ class dl:
if audio_description: if audio_description:
standards = [t for t in base_candidates if not t.descriptive] standards = [t for t in base_candidates if not t.descriptive]
if standards: if standards:
selected_audio.append(max(standards, key=lambda x: x.bitrate or 0)) selected_audio.append(max(standards, key=best_key))
descs = [t for t in base_candidates if t.descriptive] descs = [t for t in base_candidates if t.descriptive]
if descs: if descs:
selected_audio.append(max(descs, key=lambda x: x.bitrate or 0)) selected_audio.append(max(descs, key=best_key))
else: else:
selected_audio.append(max(base_candidates, key=lambda x: x.bitrate or 0)) selected_audio.append(max(base_candidates, key=best_key))
title.tracks.audio = selected_audio title.tracks.audio = selected_audio
else: else:
# If multiple codecs were explicitly requested, pick the best track per codec per # If multiple codecs were explicitly requested, pick the best track per codec per
# requested language instead of selecting *all* bitrate variants of a codec. # requested language instead of selecting *all* bitrate variants of a codec.
if acodec and len(acodec) > 1: if acodec and len(acodec) > 1:
selected_audio: list[Audio] = [] selected_audio: list[Audio] = []
best_key = lambda x: (bool(x.atmos), x.bitrate or 0) # noqa: E731
for language in processed_lang: for language in processed_lang:
for codec in acodec: for codec in acodec:
@@ -1948,12 +1980,12 @@ class dl:
if audio_description: if audio_description:
standards = [t for t in candidates if not t.descriptive] standards = [t for t in candidates if not t.descriptive]
if standards: if standards:
selected_audio.append(max(standards, key=lambda x: x.bitrate or 0)) selected_audio.append(max(standards, key=best_key))
descs = [t for t in candidates if t.descriptive] descs = [t for t in candidates if t.descriptive]
if descs: if descs:
selected_audio.append(max(descs, key=lambda x: x.bitrate or 0)) selected_audio.append(max(descs, key=best_key))
else: else:
selected_audio.append(max(candidates, key=lambda x: x.bitrate or 0)) selected_audio.append(max(candidates, key=best_key))
title.tracks.audio = selected_audio title.tracks.audio = selected_audio
else: else:
@@ -2278,6 +2310,13 @@ class dl:
# we don't want to fill up the log with "Repacked x track" # we don't want to fill up the log with "Repacked x track"
self.log.info("Repacked one or more tracks with FFMPEG") self.log.info("Repacked one or more tracks with FFMPEG")
with console.status("Normalizing video VUI..."):
for track in title.tracks.videos:
try:
track.normalize_vui()
except Exception as e: # noqa: BLE001
self.log.warning(f"VUI normalization skipped for {track.id}: {e}")
muxed_paths = [] muxed_paths = []
muxed_audio_codecs: dict[Path, Optional[Audio.Codec]] = {} muxed_audio_codecs: dict[Path, Optional[Audio.Codec]] = {}
append_audio_codec_suffix = True append_audio_codec_suffix = True
@@ -2402,6 +2441,9 @@ class dl:
else: else:
# Normal mode: process each video track separately # Normal mode: process each video track separately
for video_track in title.tracks.videos or [None]: for video_track in title.tracks.videos or [None]:
if video_track and getattr(video_track, "dv_compatible_bitstream", False):
apply_dv_fixup(video_track)
task_description = "Multiplexing" task_description = "Multiplexing"
if video_track: if video_track:
if len(quality) > 1: if len(quality) > 1:
@@ -2794,6 +2836,26 @@ class dl:
is_track_kid = ["", "*"][kid == track_kid] is_track_kid = ["", "*"][kid == track_kid]
cached_key = self.LICENSE_KEY_CACHE.get(kid)
if cached_key:
drm.content_keys[kid] = cached_key
label = f"[text2]{kid.hex}:{cached_key}{is_track_kid} from cache"
if not any(f"{kid.hex}:{cached_key}" in x.label for x in cek_tree.children):
cek_tree.add(label)
if self.debug_logger:
self.debug_logger.log(
level="INFO",
operation="license_cache_hit",
service=self.service,
context={
"kid": kid.hex,
"content_key": cached_key,
"track": str(track),
"drm_type": "Widevine",
},
)
continue
if not cdm_only: if not cdm_only:
content_key, vault_used = self.vaults.get_key(kid) content_key, vault_used = self.vaults.get_key(kid)
if content_key: if content_key:
@@ -2802,6 +2864,7 @@ class dl:
if not any(f"{kid.hex}:{content_key}" in x.label for x in cek_tree.children): if not any(f"{kid.hex}:{content_key}" in x.label for x in cek_tree.children):
cek_tree.add(label) cek_tree.add(label)
self.vaults.add_key(kid, content_key, excluding=vault_used) self.vaults.add_key(kid, content_key, excluding=vault_used)
self.LICENSE_KEY_CACHE[kid] = content_key
if self.debug_logger: if self.debug_logger:
self.debug_logger.log_vault_query( self.debug_logger.log_vault_query(
@@ -2906,6 +2969,8 @@ class dl:
# So we re-add the keys from vaults earlier overwriting blanks or removed KIDs data. # So we re-add the keys from vaults earlier overwriting blanks or removed KIDs data.
drm.content_keys.update(from_vaults) drm.content_keys.update(from_vaults)
self.LICENSE_KEY_CACHE.update(drm.content_keys)
successful_caches = self.vaults.add_keys(drm.content_keys) successful_caches = self.vaults.add_keys(drm.content_keys)
self.log.info( self.log.info(
f"Cached {len(drm.content_keys)} Key{'' if len(drm.content_keys) == 1 else 's'} to " f"Cached {len(drm.content_keys)} Key{'' if len(drm.content_keys) == 1 else 's'} to "
@@ -2972,6 +3037,26 @@ class dl:
is_track_kid = ["", "*"][kid == track_kid] is_track_kid = ["", "*"][kid == track_kid]
cached_key = self.LICENSE_KEY_CACHE.get(kid)
if cached_key:
drm.content_keys[kid] = cached_key
label = f"[text2]{kid.hex}:{cached_key}{is_track_kid} from cache"
if not any(f"{kid.hex}:{cached_key}" in x.label for x in cek_tree.children):
cek_tree.add(label)
if self.debug_logger:
self.debug_logger.log(
level="INFO",
operation="license_cache_hit",
service=self.service,
context={
"kid": kid.hex,
"content_key": cached_key,
"track": str(track),
"drm_type": "PlayReady",
},
)
continue
if not cdm_only: if not cdm_only:
content_key, vault_used = self.vaults.get_key(kid) content_key, vault_used = self.vaults.get_key(kid)
if content_key: if content_key:
@@ -2980,6 +3065,7 @@ class dl:
if not any(f"{kid.hex}:{content_key}" in x.label for x in cek_tree.children): if not any(f"{kid.hex}:{content_key}" in x.label for x in cek_tree.children):
cek_tree.add(label) cek_tree.add(label)
self.vaults.add_key(kid, content_key, excluding=vault_used) self.vaults.add_key(kid, content_key, excluding=vault_used)
self.LICENSE_KEY_CACHE[kid] = content_key
if self.debug_logger: if self.debug_logger:
self.debug_logger.log_vault_query( self.debug_logger.log_vault_query(
@@ -3054,6 +3140,8 @@ class dl:
drm.content_keys.update(from_vaults) drm.content_keys.update(from_vaults)
self.LICENSE_KEY_CACHE.update(drm.content_keys)
successful_caches = self.vaults.add_keys(drm.content_keys) successful_caches = self.vaults.add_keys(drm.content_keys)
self.log.info( self.log.info(
f"Cached {len(drm.content_keys)} Key{'' if len(drm.content_keys) == 1 else 's'} to " f"Cached {len(drm.content_keys)} Key{'' if len(drm.content_keys) == 1 else 's'} to "
+2 -2
View File
@@ -1986,9 +1986,9 @@ def _resolve_handler_proxy(data: Dict[str, Any], normalized_service: str) -> tup
client_region = data.get("client_region") client_region = data.get("client_region")
if not proxy_param and not no_proxy and client_region and proxy_providers: if not proxy_param and not no_proxy and client_region and proxy_providers:
try: try:
from unshackle.core.utilities import get_cached_ip_info from unshackle.core.utils.ip_info import get_ip_info
server_ip_info = get_cached_ip_info(None) server_ip_info = get_ip_info(None, cached=True)
server_region = server_ip_info.get("country", "").lower() if server_ip_info else None server_region = server_ip_info.get("country", "").lower() if server_ip_info else None
except Exception: except Exception:
server_region = None server_region = None
+23 -21
View File
@@ -1327,24 +1327,26 @@ def setup_swagger(app: web.Application) -> None:
) )
# Add routes with OpenAPI documentation # Add routes with OpenAPI documentation
swagger.add_routes([ swagger.add_routes(
web.get("/api/health", health), [
web.get("/api/services", services), web.get("/api/health", health),
web.post("/api/search", search), web.get("/api/services", services),
web.post("/api/list-titles", list_titles), web.post("/api/search", search),
web.post("/api/list-tracks", list_tracks), web.post("/api/list-titles", list_titles),
web.post("/api/download", download), web.post("/api/list-tracks", list_tracks),
web.get("/api/download/jobs", download_jobs), web.post("/api/download", download),
web.get("/api/download/jobs/{job_id}", download_job_detail), web.get("/api/download/jobs", download_jobs),
web.delete("/api/download/jobs/{job_id}", cancel_download_job), web.get("/api/download/jobs/{job_id}", download_job_detail),
# Remote-DL session endpoints web.delete("/api/download/jobs/{job_id}", cancel_download_job),
web.post("/api/session/create", session_create), # Remote-DL session endpoints
web.get("/api/session/{session_id}/titles", session_titles), web.post("/api/session/create", session_create),
web.post("/api/session/{session_id}/tracks", session_tracks), web.get("/api/session/{session_id}/titles", session_titles),
web.post("/api/session/{session_id}/segments", session_segments), web.post("/api/session/{session_id}/tracks", session_tracks),
web.post("/api/session/{session_id}/license", session_license), web.post("/api/session/{session_id}/segments", session_segments),
web.get("/api/session/{session_id}/prompt", session_prompt_get), web.post("/api/session/{session_id}/license", session_license),
web.post("/api/session/{session_id}/prompt", session_prompt_submit), web.get("/api/session/{session_id}/prompt", session_prompt_get),
web.get("/api/session/{session_id}", session_info), web.post("/api/session/{session_id}/prompt", session_prompt_submit),
web.delete("/api/session/{session_id}", session_delete), web.get("/api/session/{session_id}", session_info),
]) web.delete("/api/session/{session_id}", session_delete),
]
)
+1
View File
@@ -93,6 +93,7 @@ class Config:
self.tmdb_api_key: str = kwargs.get("tmdb_api_key") or "" self.tmdb_api_key: str = kwargs.get("tmdb_api_key") or ""
self.simkl_client_id: str = kwargs.get("simkl_client_id") or "" self.simkl_client_id: str = kwargs.get("simkl_client_id") or ""
self.decrypt_labs_api_key: str = kwargs.get("decrypt_labs_api_key") or "" self.decrypt_labs_api_key: str = kwargs.get("decrypt_labs_api_key") or ""
self.ipinfo_api_key: str = kwargs.get("ipinfo_api_key") or ""
self.update_checks: bool = kwargs.get("update_checks", True) self.update_checks: bool = kwargs.get("update_checks", True)
self.update_check_interval: int = kwargs.get("update_check_interval", 24) self.update_check_interval: int = kwargs.get("update_check_interval", 24)
+7
View File
@@ -489,6 +489,9 @@ class DASH:
) )
raise FileNotFoundError(error_msg) raise FileNotFoundError(error_msg)
for control_file in save_dir.glob("*.!dev"):
control_file.unlink(missing_ok=True)
segments_to_merge = [x for x in sorted(save_dir.iterdir()) if x.is_file()] segments_to_merge = [x for x in sorted(save_dir.iterdir()) if x.is_file()]
if debug_logger: if debug_logger:
@@ -850,6 +853,10 @@ class DASH:
def get_video_range( def get_video_range(
codecs: str, all_supplemental_props: list[Element], all_essential_props: list[Element] codecs: str, all_supplemental_props: list[Element], all_essential_props: list[Element]
) -> Video.Range: ) -> Video.Range:
# TODO: Detect Dolby Vision composite streams in DASH manifests (DV RPU embedded but
# primary codec is plain hvc1, signaled via a separate AdaptationSet/Representation
# with DV codec strings or DolbyVisionConfigurationBox). When found, mark the track
# with dv_compatible_bitstream=True so DVFixup runs pre-mux. No DASH samples seen yet.
if codecs.startswith(("dva1", "dvav", "dvhe", "dvh1")): if codecs.startswith(("dva1", "dvav", "dvhe", "dvh1")):
return Video.Range.DV return Video.Range.DV
+62 -12
View File
@@ -5,6 +5,7 @@ import html
import json import json
import logging import logging
import os import os
import re
import shutil import shutil
import subprocess import subprocess
import sys import sys
@@ -36,8 +37,14 @@ from unshackle.core.utilities import get_debug_logger, get_extension, is_close_m
class HLS: class HLS:
SUPP_CODECS_RE = re.compile(r'SUPPLEMENTAL-CODECS="([^"]+)"', re.IGNORECASE)
def __init__( def __init__(
self, manifest: M3U8, session: Optional[Union[Session, RnetSession]] = None, url: Optional[str] = None self,
manifest: M3U8,
session: Optional[Union[Session, RnetSession]] = None,
url: Optional[str] = None,
raw_text: Optional[str] = None,
): ):
if not manifest: if not manifest:
raise ValueError("HLS manifest must be provided.") raise ValueError("HLS manifest must be provided.")
@@ -49,6 +56,7 @@ class HLS:
self.manifest = manifest self.manifest = manifest
self.session = session or Session() self.session = session or Session()
self.url = url self.url = url
self.raw_text = raw_text
@classmethod @classmethod
def from_url(cls, url: str, session: Optional[Union[Session, RnetSession]] = None, **args: Any) -> HLS: def from_url(cls, url: str, session: Optional[Union[Session, RnetSession]] = None, **args: Any) -> HLS:
@@ -78,7 +86,7 @@ class HLS:
master = m3u8.loads(content, uri=url) master = m3u8.loads(content, uri=url)
return cls(master, session, url=url) return cls(master, session, url=url, raw_text=content)
@classmethod @classmethod
def from_text(cls, text: str, url: str) -> HLS: def from_text(cls, text: str, url: str) -> HLS:
@@ -94,7 +102,31 @@ class HLS:
master = m3u8.loads(text, uri=url) master = m3u8.loads(text, uri=url)
return cls(master) return cls(master, raw_text=text)
def supplemental_codecs_by_uri(self) -> dict[str, str]:
"""Map each variant URI to its SUPPLEMENTAL-CODECS value.
python-m3u8 drops this attribute, so we re-parse the raw text to recover it for
Dolby Vision composite detection (dvh1.08.x advertised only in SUPPLEMENTAL-CODECS
while primary CODECS stays plain hvc1).
"""
if not self.raw_text:
return {}
out: dict[str, str] = {}
lines = self.raw_text.splitlines()
for i, line in enumerate(lines):
if not line.startswith("#EXT-X-STREAM-INF"):
continue
supp_match = self.SUPP_CODECS_RE.search(line)
if not supp_match:
continue
for j in range(i + 1, len(lines)):
uri = lines[j].strip()
if uri and not uri.startswith("#"):
out[uri] = supp_match.group(1)
break
return out
def to_tracks(self, language: Union[str, Language]) -> Tracks: def to_tracks(self, language: Union[str, Language]) -> Tracks:
""" """
@@ -126,6 +158,9 @@ class HLS:
) )
tracks = Tracks() tracks = Tracks()
supplemental_codecs = self.supplemental_codecs_by_uri()
dv_supp_prefixes = ("dva1", "dvav", "dvhe", "dvh1")
for playlist in self.manifest.playlists: for playlist in self.manifest.playlists:
audio_group = playlist.stream_info.audio audio_group = playlist.stream_info.audio
audio_codec: Optional[Audio.Codec] = None audio_codec: Optional[Audio.Codec] = None
@@ -146,6 +181,26 @@ class HLS:
else: else:
primary_track_type = Video primary_track_type = Video
primary_codecs = (playlist.stream_info.codecs or "").lower()
primary_has_dv = any(codec.split(".")[0] in dv_supp_prefixes for codec in primary_codecs.split(","))
supp_codecs_str = supplemental_codecs.get(playlist.uri, "")
supp_dv_codec: Optional[str] = None
for codec in supp_codecs_str.lower().split(","):
token = codec.strip().split("/")[0]
if token.split(".")[0] in dv_supp_prefixes:
supp_dv_codec = token
break
video_range = (
Video.Range.DV if primary_has_dv else Video.Range.from_m3u_range_tag(playlist.stream_info.video_range)
)
# DV-composite track: primary codec is plain HEVC but SUPPLEMENTAL-CODECS advertises
# a DV codec. Range stays whatever VIDEO-RANGE signaled (HDR10/HLG/SDR); DVFixup will
# restore DV signaling post-download. Services that know their encoder embeds HDR10+
# SEI must override `range` themselves (see services/ATV).
dv_compatible_bitstream = primary_track_type is Video and not primary_has_dv and supp_dv_codec is not None
tracks.add( tracks.add(
primary_track_type( primary_track_type(
id_=hex(crc32(str(playlist).encode()))[2:], id_=hex(crc32(str(playlist).encode()))[2:],
@@ -164,18 +219,14 @@ class HLS:
# video track args # video track args
**( **(
dict( dict(
range_=Video.Range.DV range_=video_range,
if any(
codec.split(".")[0] in ("dva1", "dvav", "dvhe", "dvh1")
for codec in (playlist.stream_info.codecs or "").lower().split(",")
)
else Video.Range.from_m3u_range_tag(playlist.stream_info.video_range),
width=playlist.stream_info.resolution[0] if playlist.stream_info.resolution else None, width=playlist.stream_info.resolution[0] if playlist.stream_info.resolution else None,
height=playlist.stream_info.resolution[1] if playlist.stream_info.resolution else None, height=playlist.stream_info.resolution[1] if playlist.stream_info.resolution else None,
fps=playlist.stream_info.frame_rate, fps=playlist.stream_info.frame_rate,
closed_captions=cc_by_group_id.get( closed_captions=cc_by_group_id.get(
(playlist.stream_info.closed_captions or "").strip('"'), [] (playlist.stream_info.closed_captions or "").strip('"'), []
), ),
dv_compatible_bitstream=dv_compatible_bitstream,
) )
if primary_track_type is Video if primary_track_type is Video
else {} else {}
@@ -655,9 +706,8 @@ class HLS:
status_update["downloaded"] = f"HLS {downloaded}" status_update["downloaded"] = f"HLS {downloaded}"
progress(**status_update) progress(**status_update)
# see https://github.com/devine-dl/devine/issues/71 for control_file in segment_save_dir.glob("*.!dev"):
for control_file in segment_save_dir.glob("*.aria2__temp"): control_file.unlink(missing_ok=True)
control_file.unlink()
progress(total=total_segments, completed=0, downloaded="Merging") progress(total=total_segments, completed=0, downloaded="Merging")
+3
View File
@@ -325,6 +325,9 @@ class ISM:
) )
raise FileNotFoundError(error_msg) raise FileNotFoundError(error_msg)
for control_file in save_dir.glob("*.!dev"):
control_file.unlink(missing_ok=True)
segments_to_merge = [x for x in sorted(save_dir.iterdir()) if x.is_file()] segments_to_merge = [x for x in sorted(save_dir.iterdir()) if x.is_file()]
if debug_logger: if debug_logger:
+2 -1
View File
@@ -13,7 +13,8 @@ import requests
from unshackle.core import binaries from unshackle.core import binaries
from unshackle.core.proxies.proxy import Proxy from unshackle.core.proxies.proxy import Proxy
from unshackle.core.utilities import get_country_code, get_country_name, get_debug_logger, get_ip_info from unshackle.core.utilities import get_country_code, get_country_name, get_debug_logger
from unshackle.core.utils.ip_info import get_ip_info
# Global registry for cleanup on exit # Global registry for cleanup on exit
_gluetun_instances: list["Gluetun"] = [] _gluetun_instances: list["Gluetun"] = []
+5 -2
View File
@@ -64,7 +64,7 @@ class NordVPN(Proxy):
if re.match(r"^[a-z]{2}\d+$", query): if re.match(r"^[a-z]{2}\d+$", query):
# country and nordvpn server id, e.g., us1, fr1234 # country and nordvpn server id, e.g., us1, fr1234
hostname = f"{query}.nordvpn.com" hostname = f"{query}.proxy.nordvpn.com"
else: else:
if query.isdigit(): if query.isdigit():
# country id # country id
@@ -86,7 +86,7 @@ class NordVPN(Proxy):
if server_mapping: if server_mapping:
# country was set to a specific server ID in config # country was set to a specific server ID in config
hostname = f"{country['code'].lower()}{server_mapping}.nordvpn.com" hostname = f"{country['code'].lower()}{server_mapping}.proxy.nordvpn.com"
else: else:
# get the recommended server ID # get the recommended server ID
recommended_servers = self.get_recommended_servers(country["id"]) recommended_servers = self.get_recommended_servers(country["id"])
@@ -113,6 +113,9 @@ class NordVPN(Proxy):
# NordVPN uses the alpha2 of 'GB' in API responses, but 'UK' in the hostname # NordVPN uses the alpha2 of 'GB' in API responses, but 'UK' in the hostname
hostname = f"gb{hostname[2:]}" hostname = f"gb{hostname[2:]}"
if hostname.endswith(".nordvpn.com") and not hostname.endswith(".proxy.nordvpn.com"):
hostname = hostname[: -len(".nordvpn.com")] + ".proxy.nordvpn.com"
return f"https://{self.username}:{self.password}@{hostname}:89" return f"https://{self.username}:{self.password}@{hostname}:89"
def get_country(self, by_id: Optional[int] = None, by_code: Optional[str] = None) -> Optional[dict]: def get_country(self, by_id: Optional[int] = None, by_code: Optional[str] = None) -> Optional[dict]:
+2 -2
View File
@@ -481,9 +481,9 @@ class RemoteService:
if not no_proxy and not proxy: if not no_proxy and not proxy:
try: try:
from unshackle.core.utilities import get_cached_ip_info from unshackle.core.utils.ip_info import get_ip_info
ip_info = get_cached_ip_info(self._session) ip_info = get_ip_info(self._session, cached=True)
if ip_info and ip_info.get("country"): if ip_info and ip_info.get("country"):
create_data["client_region"] = ip_info["country"].lower() create_data["client_region"] = ip_info["country"].lower()
except Exception: except Exception:
+2 -2
View File
@@ -29,7 +29,7 @@ from unshackle.core.title_cacher import TitleCacher, get_account_hash, get_regio
from unshackle.core.titles import Title_T, Titles_T from unshackle.core.titles import Title_T, Titles_T
from unshackle.core.tracks import Chapters, Tracks from unshackle.core.tracks import Chapters, Tracks
from unshackle.core.tracks.video import Video from unshackle.core.tracks.video import Video
from unshackle.core.utilities import get_cached_ip_info, get_ip_info from unshackle.core.utils.ip_info import get_ip_info
@dataclass @dataclass
@@ -232,7 +232,7 @@ class Service(metaclass=ABCMeta):
else: else:
# No proxy, use cached IP info for title caching (non-critical) # No proxy, use cached IP info for title caching (non-critical)
try: try:
ip_info = get_cached_ip_info(self.session) ip_info = get_ip_info(self.session, cached=True)
self.current_region = ip_info.get("country", "").lower() if ip_info else None self.current_region = ip_info.get("country", "").lower() if ip_info else None
except Exception as e: except Exception as e:
self.log.debug(f"Failed to get cached IP info: {e}") self.log.debug(f"Failed to get cached IP info: {e}")
+19 -3
View File
@@ -61,7 +61,21 @@ class Title:
returned dict with their specific fields (e.g., season/episode). returned dict with their specific fields (e.g., season/episode).
""" """
primary_video_track = next(iter(media_info.video_tracks), None) primary_video_track = next(iter(media_info.video_tracks), None)
primary_audio_track = next(iter(media_info.audio_tracks), None) original_lang_tag = (
str(self.language).split("-")[0].lower() if self.language else ""
)
primary_audio_track = None
if original_lang_tag:
primary_audio_track = next(
(
t
for t in media_info.audio_tracks
if t.language and t.language.split("-")[0].lower() == original_lang_tag
),
None,
)
if primary_audio_track is None:
primary_audio_track = next(iter(media_info.audio_tracks), None)
unique_audio_languages = len({x.language.split("-")[0] for x in media_info.audio_tracks if x.language}) unique_audio_languages = len({x.language.split("-")[0] for x in media_info.audio_tracks if x.language})
context: dict[str, Any] = { context: dict[str, Any] = {
@@ -143,14 +157,16 @@ class Title:
channel_count = primary_audio_track.channel_s or primary_audio_track.channels or 0 channel_count = primary_audio_track.channel_s or primary_audio_track.channels or 0
channels = float(channel_count) channels = float(channel_count)
features = primary_audio_track.format_additionalfeatures or "" has_atmos = any(
"JOC" in (t.format_additionalfeatures or "") or t.joc for t in media_info.audio_tracks
)
context.update( context.update(
{ {
"audio": AUDIO_CODEC_MAP.get(codec, codec), "audio": AUDIO_CODEC_MAP.get(codec, codec),
"audio_channels": f"{channels:.1f}", "audio_channels": f"{channels:.1f}",
"audio_full": f"{AUDIO_CODEC_MAP.get(codec, codec)}{channels:.1f}", "audio_full": f"{AUDIO_CODEC_MAP.get(codec, codec)}{channels:.1f}",
"atmos": "Atmos" if ("JOC" in features or primary_audio_track.joc) else "", "atmos": "Atmos" if has_atmos else "",
} }
) )
+117
View File
@@ -0,0 +1,117 @@
"""
DV fixup for HLS composite HEVC streams.
Some services deliver DV Profile 8.1 in a stream whose primary CODECS is plain
hvc1, with DV advertised only via SUPPLEMENTAL-CODECS. The fMP4 carries DV RPU NALs but
the container does not signal DV, so muxing produces an MKV that mediainfo and DV-capable
TVs see as plain HDR10/HDR10+.
A dovi_tool extract-rpu / inject-rpu round-trip rewrites the bitstream so it is recognised
as DV after muxing. HDR10+ SEI NALs and HDR10 base layer signaling survive untouched.
"""
from __future__ import annotations
import logging
from pathlib import Path
from typing import TYPE_CHECKING
from rich.padding import Padding
from rich.rule import Rule
from unshackle.core.binaries import FFMPEG, DoviTool
from unshackle.core.config import config
from unshackle.core.console import console
from unshackle.core.utilities import get_debug_logger
from unshackle.core.utils import dovi
from unshackle.core.utils.subprocess import run_step
if TYPE_CHECKING:
from unshackle.core.tracks import Video
class DVFixup:
"""Round-trip a DV-composite HEVC track through dovi_tool to restore DV signaling."""
def __init__(self, video: "Video") -> None:
self.log = logging.getLogger("dv-fixup")
self.debug_logger = get_debug_logger()
self.video = video
if not DoviTool:
raise EnvironmentError("dovi_tool is required for DV-composite fixup but was not found.")
if not FFMPEG:
raise EnvironmentError("ffmpeg is required for DV-composite fixup but was not found.")
if not video.path or not Path(video.path).exists():
raise ValueError(f"Video track {video.id} was not downloaded before DV fixup.")
def run(self) -> Path:
"""Execute the fixup. Returns the DV-signaled HEVC path, or the original
source path on any failure so muxing can proceed with the as-downloaded file."""
source = Path(self.video.path)
height = self.video.height or 0
console.print(Padding(Rule(f"[rule.text]DV Composite Fixup ({height}p)"), (1, 2)))
fixed_hevc = source.with_name(f"{self.video.id}.dv.hevc")
if fixed_hevc.exists() and fixed_hevc.stat().st_size > 0:
self.log.info("✓ DV signaling already restored (reusing existing fixup)")
return fixed_hevc
tmp = config.directories.temp
tmp.mkdir(parents=True, exist_ok=True)
suffix = f"{self.video.id}_{height or 'na'}"
raw_hevc = tmp / f"dvfix_{suffix}.hevc"
rpu = tmp / f"dvfix_{suffix}_rpu.bin"
try:
run_step(
[FFMPEG, "-nostdin", "-y", "-i", source, "-c:v", "copy", "-f", "hevc", raw_hevc],
status="Demuxing HEVC bitstream...",
output=raw_hevc,
label="ffmpeg demux",
)
dovi.extract_rpu_with_fallback(raw_hevc, rpu)
dovi.inject_rpu(raw_hevc, rpu, fixed_hevc, status="Re-injecting DV RPU with proper signaling...")
except Exception as e:
self.log.warning(f"DV fixup failed ({e}); muxing source as-is.")
if self.debug_logger:
self.debug_logger.log(
level="WARNING",
operation="dv_fixup",
message="DV fixup failed; falling back to source",
context={"error": str(e), "source": str(source)},
)
for leftover in (raw_hevc, rpu, fixed_hevc):
leftover.unlink(missing_ok=True)
return source
for leftover in (raw_hevc, rpu):
leftover.unlink(missing_ok=True)
self.log.info("✓ DV signaling restored")
if self.debug_logger:
self.debug_logger.log(
level="INFO",
operation="dv_fixup",
message="DV fixup complete",
context={"source": str(source), "output": str(fixed_hevc)},
success=True,
)
return fixed_hevc
def apply_dv_fixup(video: "Video") -> None:
"""Run DV fixup on `video` if flagged as DV-composite. Updates `video.path` in place
and deletes the original source file so the standard mux cleanup handles the new path."""
if not getattr(video, "dv_compatible_bitstream", False):
return
if not video.path or not Path(video.path).exists():
return
original = Path(video.path)
fixed = DVFixup(video).run()
if fixed != original:
video.path = fixed
original.unlink(missing_ok=True)
__all__ = ("DVFixup", "apply_dv_fixup")
+78 -181
View File
@@ -10,10 +10,12 @@ from pathlib import Path
from rich.padding import Padding from rich.padding import Padding
from rich.rule import Rule from rich.rule import Rule
from unshackle.core.binaries import FFMPEG, DoviTool, FFProbe, HDR10PlusTool from unshackle.core.binaries import FFMPEG, FFProbe, HDR10PlusTool
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.console import console from unshackle.core.console import console
from unshackle.core.utilities import get_debug_logger from unshackle.core.utilities import get_debug_logger
from unshackle.core.utils import dovi
from unshackle.core.utils.subprocess import run_step
class Hybrid: class Hybrid:
@@ -138,51 +140,27 @@ class Hybrid:
Path.unlink(config.directories.temp / "dv.mkv") Path.unlink(config.directories.temp / "dv.mkv")
Path.unlink(config.directories.temp / "HDR10.hevc", missing_ok=True) Path.unlink(config.directories.temp / "HDR10.hevc", missing_ok=True)
Path.unlink(config.directories.temp / "DV.hevc", missing_ok=True) Path.unlink(config.directories.temp / "DV.hevc", missing_ok=True)
Path.unlink(config.directories.temp / f"{self.rpu_file}", missing_ok=True) for rpu_name in ("RPU.bin", "RPU_UNT.bin", "RPU_L5.bin", "RPU_L6.bin"):
Path.unlink(config.directories.temp / "RPU_L6.bin", missing_ok=True) Path.unlink(config.directories.temp / rpu_name, missing_ok=True)
Path.unlink(config.directories.temp / "RPU_L5.bin", missing_ok=True)
Path.unlink(config.directories.temp / "L5.json", missing_ok=True) Path.unlink(config.directories.temp / "L5.json", missing_ok=True)
Path.unlink(config.directories.temp / "L6.json", missing_ok=True) Path.unlink(config.directories.temp / "L6.json", missing_ok=True)
def ffmpeg_simple(self, save_path, output):
"""Simple ffmpeg execution without progress tracking"""
p = subprocess.run(
[
str(FFMPEG) if FFMPEG else "ffmpeg",
"-nostdin",
"-i",
str(save_path),
"-c:v",
"copy",
str(output),
"-y", # overwrite output
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
return p
def extract_stream(self, save_path, type_): def extract_stream(self, save_path, type_):
output = Path(config.directories.temp / f"{type_}.hevc") output = Path(config.directories.temp / f"{type_}.hevc")
try:
with console.status(f"Extracting {type_} stream...", spinner="dots"): run_step(
result = self.ffmpeg_simple(save_path, output) [FFMPEG or "ffmpeg", "-nostdin", "-y", "-i", save_path, "-c:v", "copy", output],
status=f"Extracting {type_} stream...",
if result.returncode: output=output,
output.unlink(missing_ok=True) label=f"ffmpeg extract {type_}",
)
except RuntimeError as e:
if self.debug_logger: if self.debug_logger:
self.debug_logger.log( self.debug_logger.log(
level="ERROR", level="ERROR",
operation="hybrid_extract_stream", operation="hybrid_extract_stream",
message=f"Failed extracting {type_} stream", message=f"Failed extracting {type_} stream",
context={ context={"type": type_, "input": str(save_path), "output": str(output), "error": str(e)},
"type": type_,
"input": str(save_path),
"output": str(output),
"returncode": result.returncode,
"stderr": (result.stderr or b"").decode(errors="replace"),
"stdout": (result.stdout or b"").decode(errors="replace"),
},
) )
self.log.error(f"x Failed extracting {type_} stream") self.log.error(f"x Failed extracting {type_} stream")
sys.exit(1) sys.exit(1)
@@ -202,48 +180,30 @@ class Hybrid:
): ):
return return
with console.status( rpu_name = "RPU_UNT" if untouched else "RPU"
f"Extracting{' untouched ' if untouched else ' '}RPU from Dolby Vision stream...", spinner="dots" rpu_path = config.directories.temp / f"{rpu_name}.bin"
): dv_stream = config.directories.temp / "DV.hevc"
extraction_args = [str(DoviTool)] spinner = f"Extracting{' untouched ' if untouched else ' '}RPU from Dolby Vision stream..."
if not untouched:
extraction_args += ["-m", "3"]
extraction_args += [
"extract-rpu",
config.directories.temp / "DV.hevc",
"-o",
config.directories.temp / f"{'RPU' if not untouched else 'RPU_UNT'}.bin",
]
rpu_extraction = subprocess.run( try:
extraction_args, dovi.extract_rpu(dv_stream, rpu_path, mode=None if untouched else 3, status=spinner)
stdout=subprocess.PIPE, except RuntimeError as e:
stderr=subprocess.PIPE, stderr_text = str(e)
)
rpu_name = "RPU" if not untouched else "RPU_UNT"
if rpu_extraction.returncode:
Path.unlink(config.directories.temp / f"{rpu_name}.bin")
stderr_text = rpu_extraction.stderr.decode(errors="replace") if rpu_extraction.stderr else ""
if self.debug_logger: if self.debug_logger:
self.debug_logger.log( self.debug_logger.log(
level="ERROR", level="ERROR",
operation="hybrid_extract_rpu", operation="hybrid_extract_rpu",
message=f"Failed extracting{' untouched ' if untouched else ' '}RPU", message=f"Failed extracting{' untouched ' if untouched else ' '}RPU",
context={ context={"untouched": untouched, "error": stderr_text},
"untouched": untouched,
"returncode": rpu_extraction.returncode,
"stderr": stderr_text,
"args": [str(a) for a in extraction_args],
},
) )
if b"MAX_PQ_LUMINANCE" in rpu_extraction.stderr: if "MAX_PQ_LUMINANCE" in stderr_text:
self.extract_rpu(video, untouched=True) self.extract_rpu(video, untouched=True)
elif b"Invalid PPS index" in rpu_extraction.stderr: return
if "Invalid PPS index" in stderr_text:
raise ValueError("Dolby Vision VideoTrack seems to be corrupt") raise ValueError("Dolby Vision VideoTrack seems to be corrupt")
else: raise ValueError(f"Failed extracting{' untouched ' if untouched else ' '}RPU from Dolby Vision stream")
raise ValueError(f"Failed extracting{' untouched ' if untouched else ' '}RPU from Dolby Vision stream")
elif self.debug_logger: if self.debug_logger:
self.debug_logger.log( self.debug_logger.log(
level="DEBUG", level="DEBUG",
operation="hybrid_extract_rpu", operation="hybrid_extract_rpu",
@@ -399,34 +359,22 @@ class Hybrid:
with open(l5_path, "w") as f: with open(l5_path, "w") as f:
json.dump(l5_json, f, indent=4) json.dump(l5_json, f, indent=4)
with console.status("Editing RPU Level 5 active area...", spinner="dots"): try:
result = subprocess.run( dovi.editor(
[ config.directories.temp / self.rpu_file,
str(DoviTool), l5_path,
"editor", config.directories.temp / "RPU_L5.bin",
"-i", status="Editing RPU Level 5 active area...",
str(config.directories.temp / self.rpu_file), label="dovi_tool editor (L5)",
"-j",
str(l5_path),
"-o",
str(config.directories.temp / "RPU_L5.bin"),
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
) )
except RuntimeError as e:
if result.returncode:
if self.debug_logger: if self.debug_logger:
self.debug_logger.log( self.debug_logger.log(
level="ERROR", level="ERROR",
operation="hybrid_level5", operation="hybrid_level5",
message="Failed editing RPU Level 5 values", message="Failed editing RPU Level 5 values",
context={ context={"error": str(e)},
"returncode": result.returncode,
"stderr": (result.stderr or b"").decode(errors="replace"),
},
) )
Path.unlink(config.directories.temp / "RPU_L5.bin", missing_ok=True)
raise ValueError("Failed editing RPU Level 5 values") raise ValueError("Failed editing RPU Level 5 values")
if self.debug_logger: if self.debug_logger:
@@ -447,20 +395,16 @@ class Hybrid:
if os.path.isfile(config.directories.temp / "RPU_L6.bin"): if os.path.isfile(config.directories.temp / "RPU_L6.bin"):
return return
with console.status("Reading RPU luminance metadata...", spinner="dots"): try:
result = subprocess.run( with console.status("Reading RPU luminance metadata...", spinner="dots"):
[str(DoviTool), "info", "-i", str(config.directories.temp / self.rpu_file), "-s"], info_text = dovi.info_summary(config.directories.temp / self.rpu_file)
capture_output=True, except RuntimeError as e:
text=True,
)
if result.returncode != 0:
if self.debug_logger: if self.debug_logger:
self.debug_logger.log( self.debug_logger.log(
level="ERROR", level="ERROR",
operation="hybrid_level6", operation="hybrid_level6",
message="Failed reading RPU metadata for Level 6 values", message="Failed reading RPU metadata for Level 6 values",
context={"returncode": result.returncode, "stderr": (result.stderr or "")}, context={"error": str(e)},
) )
raise ValueError("Failed reading RPU metadata for Level 6 values") raise ValueError("Failed reading RPU metadata for Level 6 values")
@@ -469,7 +413,7 @@ class Hybrid:
max_mdl = None max_mdl = None
min_mdl = None min_mdl = None
for line in result.stdout.splitlines(): for line in info_text.splitlines():
if "RPU content light level (L1):" in line: if "RPU content light level (L1):" in line:
parts = line.split("MaxCLL:")[1].split(",") parts = line.split("MaxCLL:")[1].split(",")
max_cll = int(float(parts[0].strip().split()[0])) max_cll = int(float(parts[0].strip().split()[0]))
@@ -506,34 +450,22 @@ class Hybrid:
with open(l6_path, "w") as f: with open(l6_path, "w") as f:
json.dump(level6_data, f, indent=4) json.dump(level6_data, f, indent=4)
with console.status("Editing RPU Level 6 values...", spinner="dots"): try:
result = subprocess.run( dovi.editor(
[ config.directories.temp / self.rpu_file,
str(DoviTool), l6_path,
"editor", config.directories.temp / "RPU_L6.bin",
"-i", status="Editing RPU Level 6 values...",
str(config.directories.temp / self.rpu_file), label="dovi_tool editor (L6)",
"-j",
str(l6_path),
"-o",
str(config.directories.temp / "RPU_L6.bin"),
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
) )
except RuntimeError as e:
if result.returncode:
if self.debug_logger: if self.debug_logger:
self.debug_logger.log( self.debug_logger.log(
level="ERROR", level="ERROR",
operation="hybrid_level6", operation="hybrid_level6",
message="Failed editing RPU Level 6 values", message="Failed editing RPU Level 6 values",
context={ context={"error": str(e)},
"returncode": result.returncode,
"stderr": (result.stderr or b"").decode(errors="replace"),
},
) )
Path.unlink(config.directories.temp / "RPU_L6.bin", missing_ok=True)
raise ValueError("Failed editing RPU Level 6 values") raise ValueError("Failed editing RPU Level 6 values")
if self.debug_logger: if self.debug_logger:
@@ -555,38 +487,22 @@ class Hybrid:
if os.path.isfile(config.directories.temp / self.hevc_file): if os.path.isfile(config.directories.temp / self.hevc_file):
return return
with console.status(f"Injecting Dolby Vision metadata into {self.hdr_type} stream...", spinner="dots"): try:
inject_cmd = [ dovi.inject_rpu(
str(DoviTool),
"inject-rpu",
"-i",
config.directories.temp / "HDR10.hevc", config.directories.temp / "HDR10.hevc",
"--rpu-in",
config.directories.temp / self.rpu_file, config.directories.temp / self.rpu_file,
] config.directories.temp / self.hevc_file,
status=f"Injecting Dolby Vision metadata into {self.hdr_type} stream...",
inject_cmd.extend(["-o", config.directories.temp / self.hevc_file]) label="dovi_tool inject-rpu",
inject = subprocess.run(
inject_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
) )
except RuntimeError as e:
if inject.returncode:
if self.debug_logger: if self.debug_logger:
self.debug_logger.log( self.debug_logger.log(
level="ERROR", level="ERROR",
operation="hybrid_inject_rpu", operation="hybrid_inject_rpu",
message="Failed injecting Dolby Vision metadata into HDR10 stream", message="Failed injecting Dolby Vision metadata into HDR10 stream",
context={ context={"error": str(e)},
"returncode": inject.returncode,
"stderr": (inject.stderr or b"").decode(errors="replace"),
"stdout": (inject.stdout or b"").decode(errors="replace"),
"cmd": [str(a) for a in inject_cmd],
},
) )
Path.unlink(config.directories.temp / self.hevc_file)
raise ValueError("Failed injecting Dolby Vision metadata into HDR10 stream") raise ValueError("Failed injecting Dolby Vision metadata into HDR10 stream")
if self.debug_logger: if self.debug_logger:
@@ -611,35 +527,29 @@ class Hybrid:
if not HDR10PlusTool: if not HDR10PlusTool:
raise ValueError("HDR10Plus_tool not found. Please install it to use HDR10+ to DV conversion.") raise ValueError("HDR10Plus_tool not found. Please install it to use HDR10+ to DV conversion.")
with console.status("Extracting HDR10+ metadata...", spinner="dots"): try:
# HDR10Plus_tool needs raw HEVC stream run_step(
extraction = subprocess.run(
[ [
str(HDR10PlusTool), HDR10PlusTool,
"extract", "extract",
str(config.directories.temp / "HDR10.hevc"), config.directories.temp / "HDR10.hevc",
"-o", "-o",
str(config.directories.temp / self.hdr10plus_file), config.directories.temp / self.hdr10plus_file,
], ],
stdout=subprocess.PIPE, status="Extracting HDR10+ metadata...",
stderr=subprocess.PIPE, output=config.directories.temp / self.hdr10plus_file,
label="hdr10plus_tool extract",
) )
except RuntimeError as e:
if extraction.returncode:
if self.debug_logger: if self.debug_logger:
self.debug_logger.log( self.debug_logger.log(
level="ERROR", level="ERROR",
operation="hybrid_extract_hdr10plus", operation="hybrid_extract_hdr10plus",
message="Failed extracting HDR10+ metadata", message="Failed extracting HDR10+ metadata",
context={ context={"error": str(e)},
"returncode": extraction.returncode,
"stderr": (extraction.stderr or b"").decode(errors="replace"),
"stdout": (extraction.stdout or b"").decode(errors="replace"),
},
) )
raise ValueError("Failed extracting HDR10+ metadata") raise ValueError("Failed extracting HDR10+ metadata")
# Check if the extracted file has content
file_size = os.path.getsize(config.directories.temp / self.hdr10plus_file) file_size = os.path.getsize(config.directories.temp / self.hdr10plus_file)
if file_size == 0: if file_size == 0:
if self.debug_logger: if self.debug_logger:
@@ -744,33 +654,20 @@ class Hybrid:
with open(config.directories.temp / "extra.json", "w") as f: with open(config.directories.temp / "extra.json", "w") as f:
json.dump(extra_metadata, f, indent=2) json.dump(extra_metadata, f, indent=2)
# Generate DV RPU from HDR10+ metadata try:
conversion = subprocess.run( dovi.generate_from_hdr10plus(
[ config.directories.temp / "extra.json",
str(DoviTool), config.directories.temp / self.hdr10plus_file,
"generate", config.directories.temp / "RPU.bin",
"-j", label="dovi_tool generate",
str(config.directories.temp / "extra.json"),
"--hdr10plus-json",
str(config.directories.temp / self.hdr10plus_file),
"-o",
str(config.directories.temp / "RPU.bin"),
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
) )
except RuntimeError as e:
if conversion.returncode:
if self.debug_logger: if self.debug_logger:
self.debug_logger.log( self.debug_logger.log(
level="ERROR", level="ERROR",
operation="hybrid_convert_hdr10plus", operation="hybrid_convert_hdr10plus",
message="Failed converting HDR10+ to Dolby Vision", message="Failed converting HDR10+ to Dolby Vision",
context={ context={"error": str(e)},
"returncode": conversion.returncode,
"stderr": (conversion.stderr or b"").decode(errors="replace"),
"stdout": (conversion.stdout or b"").decode(errors="replace"),
},
) )
raise ValueError("Failed converting HDR10+ to Dolby Vision") raise ValueError("Failed converting HDR10+ to Dolby Vision")
+36 -28
View File
@@ -461,15 +461,17 @@ class Subtitle(Track):
content_lines.append(lines[i]) content_lines.append(lines[i])
i += 1 i += 1
cues.append({ cues.append(
"start_ms": Subtitle._parse_vtt_time(start_str), {
"end_ms": Subtitle._parse_vtt_time(end_str), "start_ms": Subtitle._parse_vtt_time(start_str),
"start_str": start_str, "end_ms": Subtitle._parse_vtt_time(end_str),
"end_str": end_str, "start_str": start_str,
"line_pos": line_pos, "end_str": end_str,
"content": "\n".join(content_lines), "line_pos": line_pos,
"settings": settings, "content": "\n".join(content_lines),
}) "settings": settings,
}
)
else: else:
i += 1 i += 1
@@ -494,19 +496,23 @@ class Subtitle(Track):
group.sort(key=lambda x: x["line_pos"]) group.sort(key=lambda x: x["line_pos"])
# Use the earliest start time from the group # Use the earliest start time from the group
earliest = min(group, key=lambda x: x["start_ms"]) earliest = min(group, key=lambda x: x["start_ms"])
merged_cues.append({ merged_cues.append(
"start_str": earliest["start_str"], {
"end_str": group[0]["end_str"], "start_str": earliest["start_str"],
"content": "\n".join(c["content"] for c in group), "end_str": group[0]["end_str"],
"settings": "", "content": "\n".join(c["content"] for c in group),
}) "settings": "",
}
)
else: else:
merged_cues.append({ merged_cues.append(
"start_str": current["start_str"], {
"end_str": current["end_str"], "start_str": current["start_str"],
"content": current["content"], "end_str": current["end_str"],
"settings": current["settings"], "content": current["content"],
}) "settings": current["settings"],
}
)
i = j if len(group) > 1 else i + 1 i = j if len(group) > 1 else i + 1
@@ -1145,14 +1151,16 @@ class Subtitle(Track):
if cue_box.type == b"sttg": if cue_box.type == b"sttg":
layout = Layout(webvtt_positioning=cue_box.settings) layout = Layout(webvtt_positioning=cue_box.settings)
elif cue_box.type == b"payl": elif cue_box.type == b"payl":
nodes.extend([ nodes.extend(
node [
for line in cue_box.cue_text.split("\n") node
for node in [ for line in cue_box.cue_text.split("\n")
CaptionNode.create_text(WebVTTReader()._decode(line)), for node in [
CaptionNode.create_break(), CaptionNode.create_text(WebVTTReader()._decode(line)),
CaptionNode.create_break(),
]
] ]
]) )
nodes.pop() nodes.pop()
if nodes: if nodes:
+22 -21
View File
@@ -358,9 +358,6 @@ class Track:
status_update["downloaded"] = f"URL {downloaded}" status_update["downloaded"] = f"URL {downloaded}"
progress(**status_update) progress(**status_update)
# see https://github.com/devine-dl/devine/issues/71
save_path.with_suffix(f"{save_path.suffix}.aria2__temp").unlink(missing_ok=True)
self.path = save_path self.path = save_path
events.emit(events.Types.TRACK_DOWNLOADED, track=self) events.emit(events.Types.TRACK_DOWNLOADED, track=self)
@@ -687,25 +684,29 @@ class Track:
if hasattr(self, "data") and self.data.get("audio_language"): if hasattr(self, "data") and self.data.get("audio_language"):
audio_lang = self.data["audio_language"] audio_lang = self.data["audio_language"]
audio_name = self.data.get("audio_language_name", audio_lang) audio_name = self.data.get("audio_language_name", audio_lang)
args.extend([ args.extend(
"-metadata:s:a:0", [
f"language={audio_lang}", "-metadata:s:a:0",
"-metadata:s:a:0", f"language={audio_lang}",
f"title={audio_name}", "-metadata:s:a:0",
"-metadata:s:a:0", f"title={audio_name}",
f"handler_name={audio_name}", "-metadata:s:a:0",
]) f"handler_name={audio_name}",
]
)
args.extend([ args.extend(
# Following are very important! [
"-map_metadata", # Following are very important!
"-1", # don't transfer metadata to output file "-map_metadata",
"-fflags", "-1", # don't transfer metadata to output file
"bitexact", # only have minimal tag data, reproducible mux "-fflags",
"-codec", "bitexact", # only have minimal tag data, reproducible mux
"copy", "-codec",
str(output_path), "copy",
]) str(output_path),
]
)
subprocess.run( subprocess.run(
args, args,
+43 -8
View File
@@ -316,7 +316,7 @@ class Tracks:
new_tracks.attachments = list(self.attachments) new_tracks.attachments = list(self.attachments)
return new_tracks return new_tracks
def select_hybrid(self, tracks, quality): def select_hybrid(self, tracks, quality, worst: bool = False):
# Prefer HDR10+ over HDR10 as the base layer (preserves dynamic metadata) # Prefer HDR10+ over HDR10 as the base layer (preserves dynamic metadata)
base_ranges = (Video.Range.HDR10P, Video.Range.HDR10) base_ranges = (Video.Range.HDR10P, Video.Range.HDR10)
base_tracks = [] base_tracks = []
@@ -327,12 +327,13 @@ class Tracks:
if base_tracks: if base_tracks:
break break
pick = min if worst else max
base_selected = [] base_selected = []
for res in quality: for res in quality:
candidates = [v for v in base_tracks if v.height == res or int(v.width * 9 / 16) == res] candidates = [v for v in base_tracks if v.height == res or int(v.width * 9 / 16) == res]
if candidates: if candidates:
best = max(candidates, key=lambda v: v.bitrate) chosen = pick(candidates, key=lambda v: v.bitrate)
base_selected.append(best) base_selected.append(chosen)
dv_tracks = [v for v in tracks if v.range == Video.Range.DV] dv_tracks = [v for v in tracks if v.range == Video.Range.DV]
lowest_dv = min(dv_tracks, key=lambda v: v.height) if dv_tracks else None lowest_dv = min(dv_tracks, key=lambda v: v.height) if dv_tracks else None
@@ -427,13 +428,40 @@ class Tracks:
if config.muxing.get("set_title", True): if config.muxing.get("set_title", True):
cl.extend(["--title", title]) cl.extend(["--title", title])
default_language = config.muxing.get("default_language") or {}
preferred_video_lang = default_language.get("video")
preferred_audio_lang = default_language.get("audio")
preferred_subtitle_lang = default_language.get("subtitle")
preferred_video_idx: Optional[int] = None
if preferred_video_lang:
preferred_video_idx = next(
(idx for idx, v in enumerate(self.videos) if is_close_match(v.language, [preferred_video_lang])),
None,
)
preferred_audio_idx: Optional[int] = None
if preferred_audio_lang:
preferred_audio_idx = next(
(idx for idx, a in enumerate(self.audio) if is_close_match(a.language, [preferred_audio_lang])),
None,
)
preferred_subtitle_idx: Optional[int] = None
if preferred_subtitle_lang and not skip_subtitles:
preferred_subtitle_idx = next(
(idx for idx, s in enumerate(self.subtitles) if is_close_match(s.language, [preferred_subtitle_lang])),
None,
)
for i, vt in enumerate(self.videos): for i, vt in enumerate(self.videos):
if not vt.path or not vt.path.exists(): if not vt.path or not vt.path.exists():
raise ValueError("Video Track must be downloaded before muxing...") raise ValueError("Video Track must be downloaded before muxing...")
events.emit(events.Types.TRACK_MULTIPLEX, track=vt) events.emit(events.Types.TRACK_MULTIPLEX, track=vt)
is_default = False if preferred_video_idx is not None:
if title_language: is_default = i == preferred_video_idx
elif title_language:
is_default = vt.language == title_language is_default = vt.language == title_language
if not any(v.language == title_language for v in self.videos): if not any(v.language == title_language for v in self.videos):
is_default = vt.is_original_lang or i == 0 is_default = vt.is_original_lang or i == 0
@@ -489,6 +517,10 @@ class Tracks:
if not at.path or not at.path.exists(): if not at.path or not at.path.exists():
raise ValueError("Audio Track must be downloaded before muxing...") raise ValueError("Audio Track must be downloaded before muxing...")
events.emit(events.Types.TRACK_MULTIPLEX, track=at) events.emit(events.Types.TRACK_MULTIPLEX, track=at)
if preferred_audio_idx is not None:
audio_default = i == preferred_audio_idx
else:
audio_default = at.is_original_lang
cl.extend( cl.extend(
[ [
"--track-name", "--track-name",
@@ -496,7 +528,7 @@ class Tracks:
"--language", "--language",
f"0:{at.language}", f"0:{at.language}",
"--default-track", "--default-track",
f"0:{at.is_original_lang}", f"0:{audio_default}",
"--visual-impaired-flag", "--visual-impaired-flag",
f"0:{at.descriptive}", f"0:{at.descriptive}",
"--original-flag", "--original-flag",
@@ -510,11 +542,14 @@ class Tracks:
) )
if not skip_subtitles: if not skip_subtitles:
for st in self.subtitles: for i, st in enumerate(self.subtitles):
if not st.path or not st.path.exists(): if not st.path or not st.path.exists():
raise ValueError("Text Track must be downloaded before muxing...") raise ValueError("Text Track must be downloaded before muxing...")
events.emit(events.Types.TRACK_MULTIPLEX, track=st) events.emit(events.Types.TRACK_MULTIPLEX, track=st)
default = bool(self.audio and is_close_match(st.language, [self.audio[0].language]) and st.forced) if preferred_subtitle_idx is not None:
default = i == preferred_subtitle_idx
else:
default = bool(self.audio and is_close_match(st.language, [self.audio[0].language]) and st.forced)
cl.extend( cl.extend(
[ [
"--track-name", "--track-name",
+63
View File
@@ -228,6 +228,7 @@ class Video(Track):
fps: Optional[Union[str, int, float]] = None, fps: Optional[Union[str, int, float]] = None,
scan_type: Optional[Video.ScanType] = None, scan_type: Optional[Video.ScanType] = None,
closed_captions: Optional[list[dict[str, Any]]] = None, closed_captions: Optional[list[dict[str, Any]]] = None,
dv_compatible_bitstream: bool = False,
**kwargs: Any, **kwargs: Any,
) -> None: ) -> None:
""" """
@@ -294,6 +295,7 @@ class Video(Track):
self.scan_type = scan_type self.scan_type = scan_type
self.closed_captions: list[dict[str, Any]] = closed_captions or [] self.closed_captions: list[dict[str, Any]] = closed_captions or []
self.needs_duration_fix = False self.needs_duration_fix = False
self.dv_compatible_bitstream = dv_compatible_bitstream
def __str__(self) -> str: def __str__(self) -> str:
return " | ".join( return " | ".join(
@@ -365,6 +367,67 @@ class Video(Track):
self.path = output_path self.path = output_path
original_path.unlink() original_path.unlink()
def normalize_vui(self) -> bool:
"""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 the bitstream
was rewritten.
"""
if not self.path or not self.path.exists():
return False
if self.codec not in (Video.Codec.AVC, Video.Codec.HEVC):
return False
if self.range in (Video.Range.SDR, Video.Range.DV, Video.Range.HYBRID):
return False
vui = {
Video.Range.HDR10: (9, 16, 9),
Video.Range.HDR10P: (9, 16, 9),
Video.Range.HLG: (9, 18, 9),
}.get(self.range)
if not vui:
return False
if not binaries.FFMPEG:
raise EnvironmentError('FFmpeg executable "ffmpeg" was not found but is required for this call.')
primaries, transfer, matrix = vui
filter_key = {Video.Codec.AVC: "h264_metadata", Video.Codec.HEVC: "hevc_metadata"}[self.codec]
bsf = (
f"{filter_key}=colour_primaries={primaries}"
f":transfer_characteristics={transfer}"
f":matrix_coefficients={matrix}"
)
original_path = self.path
output_path = original_path.with_stem(f"{original_path.stem}_vui")
try:
subprocess.run(
[
binaries.FFMPEG,
"-hide_banner",
"-loglevel",
"error",
"-i",
str(original_path),
"-codec",
"copy",
"-bsf:v",
bsf,
str(output_path),
],
check=True,
)
except subprocess.CalledProcessError:
output_path.unlink(missing_ok=True)
return False
self.path = output_path
original_path.unlink()
return True
def ccextractor( def ccextractor(
self, track_id: Any, out_path: Union[Path, str], language: Language, original: bool = False self, track_id: Any, out_path: Union[Path, str], language: Language, original: bool = False
) -> Optional[Subtitle]: ) -> Optional[Subtitle]:
+3 -108
View File
@@ -22,14 +22,12 @@ from uuid import uuid4
import chardet import chardet
import pycountry import pycountry
import requests
from construct import ValidationError from construct import ValidationError
from fontTools import ttLib from fontTools import ttLib
from langcodes import Language, closest_match from langcodes import Language, closest_match
from pymp4.parser import Box from pymp4.parser import Box
from unidecode import unidecode from unidecode import unidecode
from unshackle.core.cacher import Cacher
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.constants import LANGUAGE_EXACT_DISTANCE, LANGUAGE_MAX_DISTANCE from unshackle.core.constants import LANGUAGE_EXACT_DISTANCE, LANGUAGE_MAX_DISTANCE
@@ -131,6 +129,8 @@ def sanitize_filename(filename: str, spacer: str = ".") -> str:
# optionally replace non-ASCII characters with ASCII equivalents # optionally replace non-ASCII characters with ASCII equivalents
if not config.unicode_filenames: if not config.unicode_filenames:
filename = unidecode(filename) filename = unidecode(filename)
filename = re.sub(r"\[\(+", "[", filename)
filename = re.sub(r"\)+\]", "]", filename)
# remove or replace further characters as needed # remove or replace further characters as needed
filename = "".join(c for c in filename if unicodedata.category(c) != "Mn") # hidden characters filename = "".join(c for c in filename if unicodedata.category(c) != "Mn") # hidden characters
@@ -138,7 +138,7 @@ def sanitize_filename(filename: str, spacer: str = ".") -> str:
if spacer == ".": if spacer == ".":
filename = re.sub(r" - ", spacer, filename) # title separators to spacer (avoids .-. pattern) filename = re.sub(r" - ", spacer, filename) # title separators to spacer (avoids .-. pattern)
filename = re.sub(r"[:; ]", spacer, filename) # structural chars to (spacer) filename = re.sub(r"[:; ]", spacer, filename) # structural chars to (spacer)
filename = re.sub(r"[\\*!?¿,'\"" "()<>|$#~]", "", filename) # not filename safe chars filename = re.sub(r"[\\*!?¿,'\"" "<>|$#~]", "", filename) # not filename safe chars
filename = re.sub(rf"[{spacer}]{{2,}}", spacer, filename) # remove extra neighbouring (spacer)s filename = re.sub(rf"[{spacer}]{{2,}}", spacer, filename) # remove extra neighbouring (spacer)s
return filename return filename
@@ -354,111 +354,6 @@ def get_country_code(name: str) -> Optional[str]:
return None return None
def get_ip_info(session: Optional[requests.Session] = None) -> dict:
"""
Use ipinfo.io to get IP location information.
If you provide a Requests Session with a Proxy, that proxies IP information
is what will be returned.
"""
return (session or requests.Session()).get("https://ipinfo.io/json").json()
def get_cached_ip_info(session: Optional[requests.Session] = None) -> Optional[dict]:
"""
Get IP location information with 24-hour caching and fallback providers.
This function uses a global cache to avoid repeated API calls when the IP
hasn't changed. Should only be used for local IP checks, not for proxy verification.
Implements smart provider rotation to handle rate limiting (429 errors).
Args:
session: Optional requests session (usually without proxy for local IP)
Returns:
Dict with IP info including 'country' key, or None if all providers fail
"""
log = logging.getLogger("get_cached_ip_info")
cache = Cacher("global").get("ip_info")
if cache and not cache.expired:
return cache.data
provider_state_cache = Cacher("global").get("ip_provider_state")
provider_state = provider_state_cache.data if provider_state_cache and not provider_state_cache.expired else {}
providers = {
"ipinfo": "https://ipinfo.io/json",
"ipapi": "https://ipapi.co/json",
}
session = session or requests.Session()
provider_order = ["ipinfo", "ipapi"]
current_time = time.time()
for provider_name in list(provider_order):
if provider_name in provider_state:
rate_limit_info = provider_state[provider_name]
if (current_time - rate_limit_info.get("rate_limited_at", 0)) < 300:
log.debug(f"Provider {provider_name} was rate limited recently, trying other provider first")
provider_order.remove(provider_name)
provider_order.append(provider_name)
break
for provider_name in provider_order:
provider_url = providers[provider_name]
try:
log.debug(f"Trying IP provider: {provider_name}")
response = session.get(provider_url, timeout=10)
if response.status_code == 429:
log.warning(f"Provider {provider_name} returned 429 (rate limited), trying next provider")
if provider_name not in provider_state:
provider_state[provider_name] = {}
provider_state[provider_name]["rate_limited_at"] = current_time
provider_state[provider_name]["rate_limit_count"] = (
provider_state[provider_name].get("rate_limit_count", 0) + 1
)
provider_state_cache.set(provider_state, expiration=300)
continue
elif response.status_code == 200:
data = response.json()
normalized_data = {}
if "country" in data:
normalized_data = data
elif "country_code" in data:
normalized_data = {
"country": data.get("country_code", "").lower(),
"region": data.get("region", ""),
"city": data.get("city", ""),
"ip": data.get("ip", ""),
}
if normalized_data and "country" in normalized_data:
log.debug(f"Successfully got IP info from provider: {provider_name}")
if provider_name in provider_state:
provider_state[provider_name].pop("rate_limited_at", None)
provider_state_cache.set(provider_state, expiration=300)
normalized_data["_provider"] = provider_name
cache.set(normalized_data, expiration=86400)
return normalized_data
else:
log.debug(f"Provider {provider_name} returned status {response.status_code}")
except Exception as e:
log.debug(f"Provider {provider_name} failed with exception: {e}")
continue
log.warning("All IP geolocation providers failed")
return None
def time_elapsed_since(start: float) -> str: def time_elapsed_since(start: float) -> str:
""" """
Get time elapsed since a timestamp as a string. Get time elapsed since a timestamp as a string.
+130
View File
@@ -0,0 +1,130 @@
"""Thin wrappers around dovi_tool subcommands used by DVFixup and Hybrid.
Centralises argv construction, status spinners, and error handling so callers do not
re-implement subprocess plumbing per call site. Each wrapper:
- Resolves `binaries.DoviTool` and raises EnvironmentError if missing.
- Delegates to `core.utils.subprocess.run_step` for execution, output validation, and
stderr-tail RuntimeError on failure.
- Returns captured stderr so callers can inspect specific failure modes (e.g. the
MAX_PQ_LUMINANCE retry path in extract_rpu).
"""
from __future__ import annotations
import subprocess
from pathlib import Path
from typing import Optional
from unshackle.core import binaries
from unshackle.core.utils.subprocess import run_step
def _require_dovi_tool() -> str:
if not binaries.DoviTool:
raise EnvironmentError("dovi_tool executable was not found but is required.")
return str(binaries.DoviTool)
def extract_rpu(
source: Path,
output: Path,
*,
mode: Optional[int] = 3,
status: Optional[str] = "Extracting DV RPU...",
label: str = "dovi_tool extract-rpu",
) -> bytes:
"""Extract DV RPU NALs from a raw HEVC stream. `mode=None` skips the -m flag (untouched)."""
tool = _require_dovi_tool()
args: list = [tool]
if mode is not None:
args += ["-m", str(mode)]
args += ["extract-rpu", source, "-o", output]
return run_step(args, status=status, output=output, label=label)
def inject_rpu(
source: Path,
rpu: Path,
output: Path,
*,
status: Optional[str] = "Re-injecting DV RPU...",
label: str = "dovi_tool inject-rpu",
) -> bytes:
"""Inject a DV RPU back into a raw HEVC stream, producing DV-signaled output."""
tool = _require_dovi_tool()
return run_step(
[tool, "inject-rpu", "-i", source, "--rpu-in", rpu, "-o", output],
status=status,
output=output,
label=label,
)
def editor(
source: Path,
json_spec: Path,
output: Path,
*,
status: Optional[str] = "Editing DV RPU...",
label: str = "dovi_tool editor",
) -> bytes:
"""Apply a JSON edit spec to an RPU file."""
tool = _require_dovi_tool()
return run_step(
[tool, "editor", "-i", source, "-j", json_spec, "-o", output],
status=status,
output=output,
label=label,
)
def info_summary(rpu: Path) -> str:
"""Return the textual summary (`dovi_tool info -i ... -s`) for an RPU file."""
tool = _require_dovi_tool()
p = subprocess.run([tool, "info", "-i", str(rpu), "-s"], capture_output=True, text=True)
if p.returncode != 0:
raise RuntimeError(f"dovi_tool info failed: {(p.stderr or '')[-400:]}")
return p.stdout
def generate_from_hdr10plus(
extra_json: Path,
hdr10plus_json: Path,
output: Path,
*,
status: Optional[str] = "Generating DV RPU from HDR10+ metadata...",
label: str = "dovi_tool generate",
) -> bytes:
"""Build a DV RPU from extracted HDR10+ metadata + an extra JSON descriptor."""
tool = _require_dovi_tool()
return run_step(
[tool, "generate", "-j", extra_json, "--hdr10plus-json", hdr10plus_json, "-o", output],
status=status,
output=output,
label=label,
)
def extract_rpu_with_fallback(source: Path, output: Path, *, label: str = "dovi_tool extract-rpu") -> bytes:
"""Try `-m 3` first; on MAX_PQ_LUMINANCE error, retry untouched (no -m). Returns stderr.
Used when the caller wants automatic normalization but cannot abort if the source
rejects mode-3 conversion.
"""
try:
return extract_rpu(source, output, mode=3, label=label)
except RuntimeError as e:
if "MAX_PQ_LUMINANCE" not in str(e):
raise
return extract_rpu(source, output, mode=None, status="Extracting DV RPU (untouched)...", label=label)
__all__ = (
"extract_rpu",
"extract_rpu_with_fallback",
"inject_rpu",
"editor",
"info_summary",
"generate_from_hdr10plus",
)
+234
View File
@@ -0,0 +1,234 @@
from __future__ import annotations
import logging
import time
from typing import Any, Callable, Optional
import requests
from unshackle.core.cacher import Cacher
CACHE_KEY = "ip_info_v2"
CACHE_TTL = 86400 # 24 hours
PROVIDER_STATE_KEY = "ip_provider_state"
RATE_LIMIT_COOLDOWN = 300 # 5 minutes
REQUEST_TIMEOUT = 10
Fetcher = Callable[[requests.Session], Optional[dict]]
class _RateLimited(Exception):
"""Raised by a provider fetcher when the upstream returns 429."""
def _empty() -> dict:
return {
"ip": "",
"country": "",
"country_code": "",
"region": "",
"city": "",
"org": "",
"asn": "",
"as_name": "",
"continent_code": "",
}
def _parse_ipinfo_lite(data: dict) -> Optional[dict]:
code = (data.get("country_code") or "").strip()
if not code:
return None
asn = (data.get("asn") or "").strip()
as_name = (data.get("as_name") or "").strip()
org = f"{asn} {as_name}".strip() if (asn or as_name) else ""
out = _empty()
out.update(
{
"ip": data.get("ip") or "",
"country": code.lower(),
"country_code": code.upper(),
"org": org,
"asn": asn,
"as_name": as_name,
"continent_code": (data.get("continent_code") or "").upper(),
}
)
return out
def _parse_ipinfo(data: dict) -> Optional[dict]:
code = (data.get("country") or "").strip()
if not code:
return None
out = _empty()
out.update(
{
"ip": data.get("ip") or "",
"country": code.lower(),
"country_code": code.upper(),
"region": data.get("region") or "",
"city": data.get("city") or "",
"org": data.get("org") or "",
}
)
return out
def _parse_ip_api_in(data: dict) -> Optional[dict]:
code = (data.get("country_code") or "").strip()
if not code:
return None
asn = (data.get("asn") or "").strip()
org_name = (data.get("organization") or "").strip()
org = f"{asn} {org_name}".strip() if (asn or org_name) else ""
out = _empty()
out.update(
{
"ip": data.get("ip") or "",
"country": code.lower(),
"country_code": code.upper(),
"region": data.get("region") or "",
"city": data.get("city") or "",
"org": org,
"asn": asn,
"as_name": org_name,
"continent_code": (data.get("continent_code") or "").upper(),
}
)
return out
def _check(response: requests.Response) -> Optional[dict]:
"""Raise _RateLimited on 429, return parsed JSON on 200, else None."""
if response.status_code == 429:
raise _RateLimited()
if response.status_code != 200:
return None
try:
return response.json()
except ValueError:
return None
def _fetch_ipinfo_lite(token: str) -> Fetcher:
headers = {"Authorization": f"Bearer {token}"}
def fetch(session: requests.Session) -> Optional[dict]:
payload = _check(session.get("https://api.ipinfo.io/lite/me", headers=headers, timeout=REQUEST_TIMEOUT))
return _parse_ipinfo_lite(payload) if payload else None
return fetch
def _fetch_ipinfo(session: requests.Session) -> Optional[dict]:
payload = _check(session.get("https://ipinfo.io/json", timeout=REQUEST_TIMEOUT))
return _parse_ipinfo(payload) if payload else None
def _fetch_ip_api_in(session: requests.Session) -> Optional[dict]:
"""ip-api.in has no /me endpoint — resolve IP via ipify first, then look it up."""
ip_resp = session.get("https://api.ipify.org", timeout=REQUEST_TIMEOUT)
if ip_resp.status_code == 429:
raise _RateLimited()
if ip_resp.status_code != 200:
return None
ip = (ip_resp.text or "").strip()
if not ip:
return None
payload = _check(session.get(f"https://ip-api.in/api/v1/ip/{ip}", timeout=REQUEST_TIMEOUT))
if not payload or not payload.get("success"):
return None
return _parse_ip_api_in(payload.get("data") or {})
def _build_providers() -> list[tuple[str, Fetcher]]:
"""Return ordered (name, fetcher) pairs. Token read at call time."""
from unshackle.core.config import config
providers: list[tuple[str, Fetcher]] = []
token = (getattr(config, "ipinfo_api_key", "") or "").strip()
if token:
providers.append(("ipinfo_lite", _fetch_ipinfo_lite(token)))
providers.append(("ipinfo", _fetch_ipinfo))
providers.append(("ip_api_in", _fetch_ip_api_in))
return providers
def get_ip_info(
session: Optional[requests.Session] = None,
*,
cached: bool = False,
) -> Optional[dict]:
"""
Look up IP/geolocation info via ipinfo.io (Lite when `ipinfo_api_key` configured)
with fallback to ip-api.in.
Returns a normalized dict with keys: `ip`, `country` (lowercase ISO2),
`country_code` (uppercase ISO2), `region`, `city`, `org`, `asn`, `as_name`,
`continent_code`, and `_provider`. Returns None if every provider fails.
Args:
session: Optional requests session. If a proxied session is passed, the
returned info reflects the proxy's exit IP. Auth headers for ipinfo
are sent per-request; never mutated onto session.headers.
cached: When True, read/write a 24h Cacher-backed entry. Use only for
local IP lookups — never with a proxied session.
"""
log = logging.getLogger("ip_info")
if cached:
cache = Cacher("global").get(CACHE_KEY)
if cache and not cache.expired and cache.data:
return cache.data
else:
cache = None
state_cache = Cacher("global").get(PROVIDER_STATE_KEY)
state: dict[str, Any] = (
state_cache.data if state_cache and not state_cache.expired and isinstance(state_cache.data, dict) else {}
)
providers = _build_providers()
now = time.time()
def _cooldown_key(item: tuple[str, Fetcher]) -> int:
info = state.get(item[0]) or {}
return 1 if (now - info.get("rate_limited_at", 0)) < RATE_LIMIT_COOLDOWN else 0
providers.sort(key=_cooldown_key)
sess = session or requests.Session()
for name, fetcher in providers:
log.debug(f"Trying IP provider: {name}")
try:
normalized = fetcher(sess)
except _RateLimited:
log.warning(f"Provider {name} returned 429 (rate limited), trying next provider")
entry = state.setdefault(name, {})
entry["rate_limited_at"] = now
entry["rate_limit_count"] = entry.get("rate_limit_count", 0) + 1
state_cache.set(state, expiration=RATE_LIMIT_COOLDOWN)
continue
except Exception as e:
log.debug(f"Provider {name} failed with exception: {e}")
continue
if not normalized:
log.debug(f"Provider {name} returned no usable data")
continue
normalized["_provider"] = name
log.debug(f"Successfully got IP info from provider: {name}")
if name in state and state[name].pop("rate_limited_at", None) is not None:
state_cache.set(state, expiration=RATE_LIMIT_COOLDOWN)
if cached and cache is not None:
cache.set(normalized, expiration=CACHE_TTL)
return normalized
log.warning("All IP geolocation providers failed")
return None
+33 -1
View File
@@ -1,9 +1,10 @@
import json import json
import subprocess import subprocess
from pathlib import Path from pathlib import Path
from typing import Union from typing import Optional, Sequence, Union
from unshackle.core import binaries from unshackle.core import binaries
from unshackle.core.console import console
def ffprobe(uri: Union[bytes, Path]) -> dict: def ffprobe(uri: Union[bytes, Path]) -> dict:
@@ -23,3 +24,34 @@ def ffprobe(uri: Union[bytes, Path]) -> dict:
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
return {} return {}
return json.loads(ff.stdout.decode("utf8")) return json.loads(ff.stdout.decode("utf8"))
def run_step(
args: Sequence[Union[str, Path]],
*,
status: Optional[str] = None,
output: Optional[Path] = None,
label: str = "subprocess step",
) -> bytes:
"""Run a CLI step that writes to `output` (when provided). Returns stderr bytes.
Raises RuntimeError with the stderr tail when the process exits non-zero, or when
`output` is given and does not exist / is empty after the run.
"""
if output is not None:
output.unlink(missing_ok=True)
str_args = [str(a) for a in args]
if status:
with console.status(status, spinner="dots"):
p = subprocess.run(str_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
else:
p = subprocess.run(str_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stderr = p.stderr or b""
bad_output = output is not None and (not output.exists() or output.stat().st_size == 0)
if p.returncode or bad_output:
if output is not None:
output.unlink(missing_ok=True)
raise RuntimeError(f"{label} failed: {stderr.decode(errors='replace')[-400:]}")
return stderr
+3 -1
View File
@@ -73,7 +73,9 @@ class TemplateFormatter:
has_left = s[0] in ".- " has_left = s[0] in ".- "
has_right = s[-1] in ".- " has_right = s[-1] in ".- "
if has_left and has_right: if has_left and has_right:
return s[0] # keep left separator if s[-1] == "-":
return s[-1]
return s[0]
return "" return ""
result = re.sub( result = re.sub(
+18
View File
@@ -5,6 +5,11 @@ tmdb_api_key: ""
# Get your free client ID at: https://simkl.com/settings/developer/ # Get your free client ID at: https://simkl.com/settings/developer/
simkl_client_id: "" simkl_client_id: ""
# Optional ipinfo.io API token. When set, unshackle uses the free Lite endpoint
# which has higher rate limits and richer IP info (ASN, org, continent).
# Get a free token at: https://ipinfo.io/signup
ipinfo_api_key: ""
# Group or Username to postfix to the end of all download filenames following a dash # Group or Username to postfix to the end of all download filenames following a dash
tag: user_tag tag: user_tag
@@ -142,6 +147,19 @@ muxing:
# false: Separate MKV per (quality, audio_codec) combination # false: Separate MKV per (quality, audio_codec) combination
# Example: Title.1080p.AAC.mkv, Title.1080p.EC3.mkv # Example: Title.1080p.AAC.mkv, Title.1080p.EC3.mkv
merge_audio: true merge_audio: true
# default_language: Override which track is flagged as the default in the muxed MKV.
# audio: BCP-47 tag of the preferred default audio track (e.g. pl, en, pt-BR).
# Wins over the title's original_language. Falls back to is_original_lang
# if no matching track is present.
# video: BCP-47 tag of the preferred default video track. Falls back to the
# original-language / first-track rule if no match is found.
# subtitle: BCP-47 tag of the preferred default subtitle track. Falls back to
# the existing rule (forced sub matching the audio language) if no
# matching subtitle is present.
# default_language:
# audio: pl
# video: pl
# subtitle: pl
# Login credentials for each Service # Login credentials for each Service
credentials: credentials: