feat(core): add HDR Vivid hybrids and a MonaLisa command builder

This commit is contained in:
CodeName393
2026-12-01 15:29:03 -06:00
committed by GitHub
parent 71b8b63037
commit 90ab0ca4cb
27 changed files with 756 additions and 119 deletions
+2 -2
View File
@@ -156,7 +156,7 @@ class TrackRequest:
```
!!! note "`generate_dv` and a hand-made HYBRID"
A service that fetches the HYBRID variants itself (HDR10 and DV) must also fetch
A service that fetches the HYBRID variants itself (HDR10 or HDR Vivid, and DV) must also fetch
HDR10P when `track_request.generate_dv` is set and the title has no DV track.
unshackle prefers an HEVC HDR10+ track as the base, and measures an HDR10 base from the decoded video.
`get_tracks_for_variants` does this for you.
@@ -528,7 +528,7 @@ Each exposes `from_url(url, session=...)` (or `from_text(text, url)`) and then
Some services deliver a **separate manifest per codec/range**. The base class
provides `get_tracks_for_variants(title, fetch_fn)` to fan out over every
codec×range in the `TrackRequest`, including `HYBRID` (fetch HDR10 + DV and
codec×range in the `TrackRequest`, including `HYBRID` (fetch HDR10, or HDR Vivid when there is no HDR10, + DV and
merge) and `--best-available` skip-on-error handling:
```python
+1 -1
View File
@@ -340,7 +340,7 @@ When you give both `season` and `episode`, the server combines them into a `"{se
"bitrate": 8000, "bitrate_bps": 8000000, "width": 3840, "height": 2160,
"resolution": "2160p", "fps": "24", "range": "HDR10",
"range_display": "HDR", "scan_type": null, "closed_captions": [],
"dv_compatible_bitstream": false, "hdr10plus": false, "hdr10_base": false, "stereo": false, "language": "en",
"dv_compatible_bitstream": false, "hdr10plus": false, "hdr10_base": false, "hlg_base": false, "stereo": false, "language": "en",
"is_original_lang": true,
"name": null, "track_name": "English", "needs_repack": false, "edition": [], "note": null, "data": null,
"drm": [], "descriptor": "DASH"
+5 -5
View File
@@ -302,8 +302,8 @@ closed-caption descriptors. The relevant enums:
- **`Video.Codec`**: `AVC` (H.264), `HEVC` (H.265), `VC1`, `VP8`, `VP9`, `AV1`, `LCEVC`.
- **`Video.Range`**: `SDR`, `HLG`, `HDR10`, `HDR10P` (HDR10+), `VIVID` (HDR Vivid), `DV` (Dolby
Vision), and `HYBRID`. `HYBRID` is special: it tells the pipeline to select both an HDR10(+) base and
a DV track and merge the DV RPU onto the HDR10 track with `dovi_tool` (see
Vision), and `HYBRID`. `HYBRID` is special: it tells the pipeline to select both an HDR10(+) or PQ HDR Vivid base and
a DV track and merge the DV RPU onto the base track with `dovi_tool` (see
[Dolby Vision hybrid](#dolby-vision-and-hybrid)).
!!! note "Bitrate units"
@@ -429,7 +429,7 @@ service to talk to the platform's license server. unshackle recognizes seven DRM
| `PlayReady` | PlayReady | CDM challenge (WRM header) → license server → content keys (`.prd` device) |
| `ClearKeyCENC` | W3C `org.w3.clearkey` or W3C common PSSH over CENC | JSON KID request → JWK set; no CDM |
| `ClearKey` | HLS AES-128 | content key fetched directly from a URI; no CDM, no challenge |
| `MonaLisa` | Proprietary WASM DRM | keys extracted locally; no license server |
| `MonaLisa` | Proprietary WASM DRM | keys extracted locally; no license server. `command_builder` sets the command of the decryption backend, and `segment_decrypt=False` runs it once on the merged file |
| `BlowfishStripe` | Blowfish CBC stripe cipher | the service gives the per-track key; no CDM, no license server |
| `ClearKeyCTR` | AES-128-CTR over a whole file | the service gives the IV and licenses the content key at the licence step; no CDM, no license server |
@@ -533,9 +533,9 @@ HLS and DASH streams that carry a valid DV RPU but advertise plain HEVC, with DV
supplemental codecs (`dv_compatible_bitstream`). `--list` shows such a track as `HDR10+DV` or `HDR10P+DV`.
A service sets `hdr10_base` on a DV track that has an HDR10 base layer (DV profile 8.1), and `--list` shows it as `DV+HDR10`.
The HLS and DASH parsers set `stereo` on a stereoscopic 3D (MV-HEVC) track: an HLS `REQ-VIDEO-LAYOUT` that names `CH-STEREO`, or a DV profile 20 codec. `--list` shows it as `3D`.
**Hybrid** processing (`Video.Range.HYBRID`) selects an HDR10(+) base and a DV donor,
**Hybrid** processing (`Video.Range.HYBRID`) selects an HDR10(+) or PQ HDR Vivid base and a DV donor,
extracts the RPU with `dovi_tool`, and injects it onto the base layer, to make a single
track that carries both HDR10 metadata and the DV RPU. Both are automatic once the
track that carries both the base metadata and the DV RPU. Both are automatic once the
pipeline selects the right tracks. A service only needs to give accurate ranges.
The fixup replaces the track file with a raw HEVC file. A raw HEVC file has no duration and
+1 -1
View File
@@ -89,7 +89,7 @@ unshackle dl [OPTIONS] SERVICE [SERVICE ARGS...]
| `-rab`, `--real-audio-bitrate` | off | Same for audio (slower). |
!!! note "`HYBRID` range"
`-r HYBRID` fetches both HDR10/HDR10+ and Dolby Vision and merges them with `dovi_tool`. It requires the `dovi_tool` binary on your `PATH`.
`-r HYBRID` fetches both an HDR10/HDR10+/HDR Vivid base and Dolby Vision and merges them with `dovi_tool`. It requires the `dovi_tool` binary on your `PATH`.
### Language & subtitles
+13 -11
View File
@@ -105,7 +105,7 @@ By default a missing requested resolution is an error. Two flags change that:
A `quality` in the config counts as a requested resolution. When `--best-available` finds none of the
requested resolutions, `--worst` also picks from the lowest resolution. In hybrid mode, that is the
lowest resolution that has an HDR10 or HDR10+ base.
lowest resolution that has an HDR10, HDR10+ or HDR Vivid base.
```shell title="Never fail on a missing resolution"
unshackle dl -q 2160 --best-available EXAMPLE 0ABC123
@@ -152,7 +152,7 @@ unshackle dl -v hevc,avc EXAMPLE 81234567
| `HDR10P` | HDR10+ (`-r HDR10+` also works) |
| `VIVID` | HDR Vivid (`-r "HDR Vivid"` also works) |
| `DV` | Dolby Vision |
| `HYBRID` | Fetch both an HDR10/HDR10+ base and a DV track, then merge them |
| `HYBRID` | Fetch both an HDR10/HDR10+/HDR Vivid base and a DV track, then merge them |
```shell title="Grab HDR10 and Dolby Vision in one run"
unshackle dl -q 2160 -r HDR10,DV EXAMPLE '...'
@@ -179,18 +179,20 @@ MP4, see [3D output](output-and-naming.md#3d-output).
!!! warning "HYBRID requires dovi_tool"
`-r HYBRID` makes a single hybrid track by injecting the Dolby Vision RPU
metadata onto an HDR10/HDR10+ base layer with **dovi_tool**.
metadata onto an HDR10/HDR10+/HDR Vivid base layer with **dovi_tool**.
It requires the `dovi_tool` binary, resolved from unshackle's `binaries/` folder,
the `binaries` folder of your user data directory, or your `PATH`. A hybrid needs a DV track plus an HDR10 or
HDR10+ base. With no DV track, the title fails, unless you add `--generate-dv` (see below).
When HDR10+ is present, unshackle prefers it over HDR10 as the base layer. The base must be
HEVC; a title whose HDR10/HDR10+ tracks are all in another codec fails before it downloads.
the `binaries` folder of your user data directory, or your `PATH`. A hybrid needs a DV track plus an HDR10,
HDR10+ or HDR Vivid base. With no DV track, the title fails, unless you add `--generate-dv` (see below).
unshackle prefers HDR10+ as the base layer, then HDR10. It uses an HDR Vivid track only when the title has
no HEVC HDR10 or HDR10+ track, and only a track with a PQ base. The base and the DV track must have the
same frame rate, and the DV track must not be profile 8.4 (HLG). The base must be
HEVC; a title whose HDR10/HDR10+/HDR Vivid tracks are all in another codec fails before it downloads.
If the hybrid step fails for one resolution, unshackle logs an error, skips that resolution
and goes on with the other resolutions of the title. When no hybrid file at all was made,
the title fails.
A track that is `DV+HDR10P`, `HDR10+DV` or `HDR10P+DV` in `--list` already carries Dolby Vision and an HDR10
or HDR10+ base, so it is already a hybrid. At a resolution that has one, `-r HYBRID` selects it
A track that is `DV+HDR10P`, `HDR10+DV`, `HDR10P+DV` or `VIVID+DV` in `--list` already carries Dolby Vision and
an HDR10, HDR10+ or PQ HDR Vivid base, so it is already a hybrid. At a resolution that has one, `-r HYBRID` selects it
and muxes it as it is, with no base track and no dovi_tool step. A track that carries HDR10+
comes first, then the highest bitrate (the lowest with `--worst`). The other resolutions get a
hybrid that unshackle makes.
@@ -201,13 +203,13 @@ MP4, see [3D output](output-and-naming.md#3d-output).
#### Dolby Vision without a DV track
When a title has no DV track, `-r HYBRID --generate-dv` makes a Dolby Vision Profile 8.1 track
for its HDR10 or HDR10+ base. When a title has a DV track, unshackle uses that track and ignores
for its HDR10, HDR10+ or HDR Vivid base. When a title has a DV track, unshackle uses that track and ignores
the flag. When it has none, the flag also makes unshackle ask the service for its HDR10+ tracks.
| Base | Source of the Dolby Vision brightness values |
| --- | --- |
| HDR10+, with `hdr10plus_tool` installed | The HDR10+ metadata |
| HDR10, or HDR10+ without `hdr10plus_tool`, or an HDR10+ label with no metadata in the track | The decoded video |
| HDR10, HDR Vivid, or HDR10+ without `hdr10plus_tool`, or an HDR10+ label with no metadata in the track | The decoded video |
A track that the service labels HDR10 but that carries HDR10+ metadata counts as HDR10+
(see [`hdr10plus_probe`](../reference/configuration/download.md#hdr10plus_probe)).
+1 -1
View File
@@ -50,7 +50,7 @@ license-server handshake. The rest are special cases.
| **PlayReady** (Microsoft) | `.prd` | CDM challenge (WRM header) → license server → CDM parses → keys | shaka-packager / mp4decrypt |
| **ClearKey (CENC)**, W3C EME `org.w3.clearkey` or the W3C common PSSH | none | JSON `{"kids":[...],"type":"temporary"}` → license server returns a JWK Set. No CDM. | shaka-packager / mp4decrypt |
| **ClearKey (HLS)**, AES-128 `EXT-X-KEY` | none | Key fetched directly from a URI or `data:` URL. No CDM, no challenge. | in-process AES-CBC |
| **MonaLisa** (proprietary, WASM) | `.mld` | Ticket from the service API; keys extracted locally via WASM. No license server. | ML-Worker binary + AES-ECB, per segment |
| **MonaLisa** (proprietary, WASM) | `.mld` | Ticket from the service API; keys extracted locally via WASM. No license server. | External tool that the service names, per segment or on the whole track |
| **Blowfish stripe** | none | The service gives the per-track key. No CDM, no license server. | in-process Blowfish-CBC on every third 2048-byte chunk |
| **ClearKey (CTR)**, AES-128-CTR | none | The service gives the per-track key and IV. No CDM, no license server. | in-process AES-CTR over the whole file |
+1 -1
View File
@@ -108,7 +108,7 @@ Every variable below is valid in both output and folder templates. unshackle tak
| `quality` | Standard resolution with scan suffix | `1080p`, `2160p`, `576i` |
| `resolution` | Standard resolution number only | `1080` |
| `video` | Video codec | `H.264`, `H.265` |
| `hdr` | Dynamic-range label | `HDR`, `HDR10P`, `DV`, `DV.HDR`, `DV.HDR10P`, `HDRVivid`, `HLG` |
| `hdr` | Dynamic-range label | `HDR`, `HDR10P`, `DV`, `DV.HDR`, `DV.HDR10P`, `DV.HDRVivid`, `HDRVivid`, `HLG` |
| `hfr` | High frame rate marker (frame rate > 30) | `HFR` |
| `3d` | Stereoscopic 3D marker (MV-HEVC video) | `3D` |
| `edition` | Edition label from the track, if any | `Directors Cut` |
+1 -1
View File
@@ -46,7 +46,7 @@ When the decode fails, unshackle:
The download stops with an error instead of writing noise when no ciphertext is left to retry with, or when every vault and the CDM are used up. Without a local SQLite vault nothing remembers a flag, so the same vault serves the same pair again and the download stops there.
Per-segment decryption gives up the retry. With `decrypt_segments` on, and always with MonaLisa, the plaintext replaces each segment as it arrives, so no ciphertext is left. A failed decode then flags the pair and stops the download. The next run skips the flagged pair.
Per-segment decryption gives up the retry. With `decrypt_segments` on, and always with a MonaLisa tool that decrypts segments, the plaintext replaces each segment as it arrives, so no ciphertext is left. A failed decode then flags the pair and stops the download. The next run skips the flagged pair.
unshackle copies a content key from one vault to the others only after this check passes, so a content key that fails the check does not spread. Without FFmpeg, a content key from a vault is not copied at all. To see or clear the flags, open the SQLite file and read or delete rows in `bad_keys`.
+2 -1
View File
@@ -451,7 +451,8 @@ probes the two highest and the two lowest bitrates first:
The probe also finds HDR Vivid in HEVC HDR10 and HLG tracks. A track becomes `VIVID`, so
`-r VIVID` selects it, when its first frame carries CUVA HDR Vivid metadata, or when its MPEG-TS
program map table (PMT) has the `cuvv` registration. An HLG track never becomes `HDR10P`. An audio
program map table (PMT) has the `cuvv` registration. An HLG track never becomes `HDR10P`,
and an HDR Vivid track with an HLG base never makes a hybrid. An audio
track with no codec gets its codec from the PMT of an MPEG-TS first segment: the `AVSA`
registration or `stream_type` `0xD5` gives `Audio Vivid`. The probe has no HDR10+ result for an
MPEG-TS track.
+3 -3
View File
@@ -170,11 +170,11 @@ Put the more specific rules first, because unshackle stops at the first match.
!!! warning "Match `hdr` on the exact value"
Matching is exact, and `hdr` is a composite label for Dolby Vision titles: a DV title with
an HDR10 base layer gives `DV.HDR`, and with an HDR10+ base layer `DV.HDR10P`. Plain `DV`
does **not** match those. Name every variant you want, as the example above does. Note
an HDR10 base layer gives `DV.HDR`, with an HDR10+ base layer `DV.HDR10P`, and with an HDR Vivid base
layer `DV.HDRVivid`. Plain `DV` does **not** match those. Name every variant you want, as the example above does. Note
also that HDR10 gives `HDR`, not `HDR10`, and so does a PQ video track with no HDR10
metadata. The full set of values is `HDR`, `HDR10P`, `DV`, `DV.HDR`, `DV.HDR10P`,
`HDRVivid`, and `HLG`, as listed in the
`DV.HDRVivid`, `HDRVivid`, and `HLG`, as listed in the
[variable table](../../guide/output-and-naming.md#template-variables).
### Operators
+89 -16
View File
@@ -221,6 +221,14 @@ def make_hybrid() -> Hybrid:
return obj
def hybrid_track(path: Path, range_: Video.Range, transfer: str | None = None, **probe: Any) -> Any:
"""A downloaded track as the hybrid step reads it, with the FFprobe result given."""
colour = {"color_transfer": transfer, **probe} if transfer else probe
return SimpleNamespace(
id="b", path=path, width=None, height=2160, range=range_, sample_start=0.0, _probe_colour=lambda: colour
)
def stub_hybrid_steps(monkeypatch: pytest.MonkeyPatch, *steps: str, tool: str | None = "hdr10plus_tool") -> None:
"""Make the stream, Level 5 and inject steps (and those named) do nothing, with a fixed active area."""
for name in ("extract_stream", "level_5", "injecting", *steps):
@@ -445,7 +453,7 @@ def test_a_conversion_run_removes_its_rpus_so_the_next_base_makes_its_own(
monkeypatch.setattr(Hybrid, "convert_hdr10plus_to_dv", convert)
monkeypatch.setattr(Hybrid, "level_6", level_6)
Hybrid([SimpleNamespace(id="b", path=base, width=None, height=2160, range=Video.Range.HDR10P)], "TEST")
Hybrid([hybrid_track(base, Video.Range.HDR10P)], "TEST")
assert seen == {"stale_l6": False, "active_fraction": 0.9}
assert not (tmp_path / "RPU.bin").exists() and not (tmp_path / "RPU_L6.bin").exists()
@@ -467,12 +475,81 @@ def test_a_base_without_usable_hdr10plus_is_measured_inside_its_crop(
stub_hybrid_steps(monkeypatch, "level_6", tool=tool)
monkeypatch.setattr(Hybrid, "measure_dv", measure)
Hybrid([SimpleNamespace(id="b", path=base, width=None, height=2160, range=range_)], "TEST")
Hybrid([hybrid_track(base, range_)], "TEST")
assert seen == {"crop": (0, 100, 0, 100), "stale_l6": False}
assert not (tmp_path / "RPU.bin").exists()
@pytest.mark.parametrize("transfer", ["smpte2084", None, "arib-std-b67", "bt2020-10"])
def test_a_vivid_base_makes_a_hybrid_only_on_pq(
transfer: str | None, quiet: None, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""HDR Vivid sits on PQ or HLG, and the injected profile 8.1 RPU needs PQ."""
path = tmp_path / "base.mkv"
path.write_bytes(b"")
extracted: list[str] = []
stub_hybrid_steps(monkeypatch, "level_6", "measure_dv")
monkeypatch.setattr(Hybrid, "extract_stream", lambda self, path, type_: extracted.append(type_))
base = hybrid_track(path, Video.Range.VIVID, transfer)
if transfer == "smpte2084":
hybrid = Hybrid([base], "TEST")
assert (hybrid.hdr_type, extracted) == ("VIVID", ["HDR10"])
else:
with pytest.raises(ValueError, match="needs a PQ base"):
Hybrid([base], "TEST")
assert not extracted
@pytest.mark.parametrize(
("base", "dv", "refused"),
[
("60/1", "24/1", True),
("50/1", "25/1", True),
("24000/1001", "24/1", False),
("0/0", "24/1", False),
(None, "24/1", False),
("junk", "24/1", False),
],
)
@pytest.mark.parametrize("range_", [Video.Range.VIVID, Video.Range.HDR10])
def test_two_frame_rates_make_no_hybrid(base: str | None, dv: str, refused: bool, range_: Video.Range) -> None:
tracks = [
hybrid_track(Path("b.mp4"), range_, "smpte2084", avg_frame_rate=base),
hybrid_track(Path("d.mp4"), Video.Range.DV, avg_frame_rate=dv),
]
if refused:
with pytest.raises(ValueError, match="fps and the Dolby Vision track"):
Hybrid.check_base(*tracks)
else:
Hybrid.check_base(*tracks)
def test_a_raw_stream_has_no_frame_rate_to_compare() -> None:
base = hybrid_track(Path("b.hevc"), Video.Range.HDR10, avg_frame_rate="25/1")
Hybrid.check_base(base, hybrid_track(Path("d.mp4"), Video.Range.DV, avg_frame_rate="24/1"))
@pytest.mark.parametrize(
"probe",
[{"transfer": "arib-std-b67"}, {"side_data_list": [{"dv_profile": 8, "dv_bl_signal_compatibility_id": 4}]}],
)
def test_an_hlg_dv_track_makes_no_hybrid(probe: dict[str, Any]) -> None:
base = hybrid_track(Path("b.mp4"), Video.Range.HDR10, "smpte2084")
with pytest.raises(ValueError, match="profile 8.4"):
Hybrid.check_base(base, hybrid_track(Path("d.mp4"), Video.Range.DV, **probe))
def test_vivid_is_the_last_choice_of_hybrid_base_and_takes_no_generate_dv_range() -> None:
videos = [
video("v2160", Video.Range.VIVID),
video("h2160", Video.Range.HDR10),
video("v1080", Video.Range.VIVID, 1080),
]
assert [v.id for v in select_hybrid_bases(videos)] == ["h2160", "v1080"]
assert generated_dv_ranges([Video.Range.VIVID], True) == ([Video.Range.VIVID], [])
def test_an_hdr10plus_label_without_metadata_is_measured(
quiet: None, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
@@ -487,7 +564,7 @@ def test_an_hdr10plus_label_without_metadata_is_measured(
monkeypatch.setattr(Hybrid, "measure_dv", lambda self, crop=None: measured.append(crop))
monkeypatch.setattr(hybrid_mod, "run_step", no_metadata)
hybrid = Hybrid([SimpleNamespace(id="b", path=base, width=None, height=2160, range=Video.Range.HDR10P)], "TEST")
hybrid = Hybrid([hybrid_track(base, Video.Range.HDR10P)], "TEST")
assert measured == [(0, 100, 0, 100)] and hybrid.hdr10plus_to_dv is False
@@ -658,12 +735,8 @@ def test_a_failed_resolution_removes_its_crop_edits_and_keeps_the_dv_files(
monkeypatch.setattr(Hybrid, "injecting", failed_inject)
monkeypatch.setattr(hybrid_mod.console, "print", lambda *a, **k: None)
videos = [
SimpleNamespace(
id="b", path=tmp_path / "base.mkv", width=None, height=2160, range=Video.Range.HDR10, sample_start=0.0
),
SimpleNamespace(
id="d", path=tmp_path / "dv.mkv", width=None, height=1080, range=Video.Range.DV, sample_start=0.0
),
hybrid_track(tmp_path / "base.mkv", Video.Range.HDR10),
hybrid_track(tmp_path / "dv.mkv", Video.Range.DV),
]
with pytest.raises(ValueError):
@@ -729,7 +802,7 @@ def test_a_hybrid_that_fills_the_temp_volume_names_the_free_space_before_its_fil
stub_hybrid_steps(monkeypatch, "measure_dv", "level_6")
monkeypatch.setattr(Hybrid, "injecting", full)
monkeypatch.setattr(temp.shutil, "disk_usage", usage)
video = SimpleNamespace(id="b", path=base, width=None, height=2160, range=Video.Range.HDR10)
video = hybrid_track(base, Video.Range.HDR10)
error = hybrid_step_error([video], "TEST", "HDR10-DV-2160p.hevc") # type: ignore[list-item]
@@ -753,7 +826,7 @@ def test_a_working_hybrid_reports_no_error_and_an_exit_passes_through(monkeypatc
def test_a_title_without_a_hybrid_file_fails() -> None:
bases = [video("h2160", Video.Range.HDR10), video("h1080", Video.Range.HDR10, 1080)]
assert missing_hybrid_error(bases, 1) is None
assert missing_hybrid_error([], 0) == "No HEVC HDR10 or HDR10+ track to make a hybrid from"
assert missing_hybrid_error([], 0) == "No HEVC HDR10, HDR10+ or VIVID track to make a hybrid from"
assert missing_hybrid_error(bases, 0) == ("Every hybrid failed (2160p, 1080p), so the title has no hybrid file")
@@ -889,14 +962,14 @@ def video(
def test_hybrid_fails_with_neither_a_base_nor_dv() -> None:
assert hybrid_gate_failure([video("sdr", Video.Range.SDR)], True) == (
"HYBRID needs HDR10/HDR10+ and DV tracks, available ranges: SDR"
"HYBRID needs HDR10/HDR10+/VIVID and DV tracks, available ranges: SDR"
)
assert hybrid_gate_failure([], True) == "HYBRID needs HDR10/HDR10+ and DV tracks, available ranges: none"
assert hybrid_gate_failure([], True) == "HYBRID needs HDR10/HDR10+/VIVID and DV tracks, available ranges: none"
def test_hybrid_fails_with_dv_only() -> None:
assert hybrid_gate_failure([video("dv", Video.Range.DV)], True) == (
"HYBRID needs HDR10/HDR10+ and DV tracks, available ranges: DV"
"HYBRID needs HDR10/HDR10+/VIVID and DV tracks, available ranges: DV"
)
@@ -913,14 +986,14 @@ def test_hybrid_goes_on_with_a_base_and_dv_whatever_the_flag() -> None:
def test_hybrid_fails_up_front_when_no_base_is_hevc() -> None:
"""dovi_tool injects into HEVC, so an all-AV1 title fails before it downloads anything."""
videos = [video("av1", Video.Range.HDR10P, codec=Video.Codec.AV1), video("dv", Video.Range.DV)]
assert hybrid_gate_failure(videos, False) == "HYBRID needs an HEVC HDR10/HDR10+ base, available codecs: AV1"
assert hybrid_gate_failure(videos, False) == "HYBRID needs an HEVC HDR10/HDR10+/VIVID base, available codecs: AV1"
assert hybrid_gate_failure(videos + [video("h", Video.Range.HDR10, codec=None)], False) is None
@pytest.mark.parametrize("range_", [Video.Range.HDR10P, Video.Range.HDR10])
def test_hybrid_fails_without_dv_and_hints_at_the_flag(range_: Video.Range) -> None:
assert hybrid_gate_failure([video("v", range_)], False) == (
f"HYBRID needs HDR10/HDR10+ and DV tracks, available ranges: {range_.name}; add --generate-dv to make DV"
f"HYBRID needs HDR10/HDR10+/VIVID and DV tracks, available ranges: {range_.name}; add --generate-dv to make DV"
)
+68 -4
View File
@@ -24,8 +24,8 @@ def make_drm(monkeypatch: pytest.MonkeyPatch):
"""Build a MonaLisa with a known key; extract_keys needs a real device file, so it is skipped."""
monkeypatch.setattr(MonaLisa, "extract_keys", lambda self: None)
def build(tool: Path) -> MonaLisa:
drm = MonaLisa("ticket", Path("unused.mld"), tool)
def build(tool: Path, **kwargs) -> MonaLisa:
drm = MonaLisa("ticket", Path("unused.mld"), tool, **kwargs)
drm._kid = UUID(int=1)
drm._key = "00" * 16
return drm
@@ -79,8 +79,8 @@ def test_a_timeout_keeps_the_ciphertext_and_hides_the_key(
monkeypatch.setattr(tool_runner.subprocess, "run", hang)
drm = make_drm(tool)
with pytest.raises(RuntimeError, match="timed out") as raised:
drm.decrypt(track)
with pytest.raises(RuntimeError, match="timed out after 60s") as raised:
drm.decrypt_segment(track)
assert drm.key_pair not in str(raised.value)
assert raised.value.__suppress_context__
assert track.read_bytes() == b"cipher"
@@ -93,3 +93,67 @@ def test_a_good_run_replaces_the_file_and_drops_the_temp_output(
make_drm(tool).decrypt(track)
assert track.read_bytes() == b"plain"
assert not track.with_name("track_decrypted.mp4").exists()
@pytest.mark.parametrize("build", ["constructor", "from_ticket"])
def test_a_service_command_builder_replaces_the_default_command(
make_drm, track: Path, tool: Path, monkeypatch: pytest.MonkeyPatch, build: str
) -> None:
commands = []
def run(cmd, **kwargs):
commands.append((cmd, kwargs["timeout"]))
Path(cmd[-1]).write_bytes(b"plain")
return subprocess.CompletedProcess(cmd, 0, b"", b"")
def command(tool_path, src, dst, kid, key):
return [tool_path, f"{kid}/{key}", src, dst]
monkeypatch.setattr(tool_runner.subprocess, "run", run)
if build == "constructor":
drm = make_drm(tool, command_builder=command, segment_decrypt=False)
else:
drm = MonaLisa.from_ticket("ticket", Path("unused.mld"), tool, command, False)
drm._kid, drm._key = UUID(int=1), "00" * 16
assert not drm.supports_segment_decrypt
drm.decrypt(track)
output = track.with_name("track_decrypted.mp4")
assert commands == [([str(tool), f"{drm.kid.hex}/{drm.key}", str(track), str(output)], None)]
assert track.read_bytes() == b"plain"
@pytest.mark.parametrize("segment_decrypt", [True, False])
def test_every_in_place_file_is_decrypted(
make_drm, track: Path, tool: Path, monkeypatch: pytest.MonkeyPatch, segment_decrypt: bool
) -> None:
fake_tool(monkeypatch, b"plain")
drm = make_drm(tool, segment_decrypt=segment_decrypt)
other = track.with_name("other.mp4")
other.write_bytes(b"cipher")
drm.decrypt(track)
drm.decrypt(other)
assert (track.read_bytes(), other.read_bytes()) == (b"plain", b"plain")
assert not drm.track_decrypted
def test_a_track_that_the_service_decrypted_is_not_decrypted_again(
make_drm, track: Path, tool: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
fake_tool(monkeypatch, b"plain")
drm = make_drm(tool, segment_decrypt=False)
out = track.with_name("out.mp4")
drm.decrypt(track, out)
fake_tool(monkeypatch, b"twice")
drm.decrypt(out)
assert drm.track_decrypted and out.read_bytes() == b"plain"
def test_a_segment_tool_decrypts_every_file_it_gets_an_output_path_for(
make_drm, track: Path, tool: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
fake_tool(monkeypatch, b"plain")
drm = make_drm(tool)
outputs = [track.with_name(f"{i}.mp4") for i in range(2)]
for output in outputs:
drm.decrypt(track, output)
assert [output.read_bytes() for output in outputs] == [b"plain", b"plain"]
+77
View File
@@ -25,13 +25,16 @@ from Cryptodome.Cipher import AES
from Cryptodome.Util.Padding import pad
from pywidevine.pssh import PSSH
from tests.core.key_resolver import MemoryVault, resolver, vaults_of
from tests.core.test_hls_kid_from_init import KEY_LINE, no_kid_pssh
from tests.core.test_ism_init import piff_fragment
from unshackle.core import constants
from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.downloaders import requests as requests_downloader
from unshackle.core.drm import ClearKeyCENC, MonaLisa, Widevine
from unshackle.core.drm import cenc as cenc_module
from unshackle.core.drm import verify
from unshackle.core.events import events
from unshackle.core.manifests import DASH, HLS, ISM
from unshackle.core.manifests import dash as dash_module
@@ -366,6 +369,80 @@ def test_hls_licence_failure_cancels_the_other_tracks(server, tmp_path, monkeypa
assert ctx.statuses[-2:] == ["LICENSING", "[red]FAILED"]
@pytest.mark.parametrize("mode", ["segments", "core-whole", "service-whole", "service-whole-keeps-cipher"])
@pytest.mark.parametrize("playlist", ["plain", "discontinuity", "init"])
@pytest.mark.parametrize("hooked", [False, True])
def test_hls_monalisa_decrypts_every_segment_once(server, tmp_path, monkeypatch, mode, playlist, hooked):
"""A segment tool runs per segment, a whole-track tool on each merged block or in the service's downloader.
With the hook of dl installed, the content key resolver runs the whole-track decrypt.
"""
monkeypatch.setattr(MonaLisa, "extract_keys", lambda self: None)
monkeypatch.setattr(
HLS,
"merge_segments",
staticmethod(
lambda segments, save_path, progress=None: save_path.write_bytes(b"".join(map(Path.read_bytes, segments)))
),
)
runs: list[bytes] = []
def run_tool(self, path, output_path=None, *, timeout=None):
runs.append(path.read_bytes())
(output_path or path).write_bytes(path.read_bytes().swapcase())
monkeypatch.setattr(MonaLisa, "_execute_decrypt", run_tool)
hook = resolver(vaults_of(MemoryVault())).decrypt_verified if hooked else None
monkeypatch.setattr(verify, "DECRYPT_HOOK", hook)
parts = [b"CIPHER%d" % i + b"X" * (50 + i) for i in range(len(PARTS))]
for i, part in enumerate(parts):
server.routes[f"/part{i}.m4s"] = part
lines = ["#EXTM3U", "#EXT-X-VERSION:6", "#EXT-X-TARGETDURATION:4"]
server.routes["/init.mp4"] = b"INIT"
if playlist == "init":
lines.append('#EXT-X-MAP:URI="init.mp4"')
for i in range(len(parts)):
if playlist == "discontinuity" and i == 2:
lines.append("#EXT-X-DISCONTINUITY")
lines += ["#EXTINF:4.0,", f"part{i}.m4s"]
server.routes["/v.m3u8"] = "\n".join([*lines, "#EXT-X-ENDLIST"]).encode()
track = Video(url=f"{base(server)}v.m3u8", language="en", codec=Video.Codec.HEVC, descriptor=Video.Descriptor.HLS)
drm = MonaLisa("ticket", Path("unused.mld"), segment_decrypt=mode == "segments")
drm._kid, drm._key = KID, "00" * 16
track.drm = [drm]
if mode.startswith("service"):
def download(**kwargs):
segments = []
for status in requests_downloader(**kwargs):
if status.get("file_downloaded"):
segments.append(status["file_downloaded"])
yield status
folder = segments[0].parent
merged = folder.parent / "segments_encrypted.ts"
merged.write_bytes(b"".join(s.read_bytes() for s in sorted(segments)))
out = folder.parent / "out.mp4"
drm.decrypt(merged, out)
for segment in segments:
segment.unlink()
out.rename(folder / "000.mp4")
if mode == "service-whole":
merged.unlink()
track.downloader = download
ctx = make_ctx(tmp_path, "monalisa.mp4")
ctx.license_widevine = lambda *a, **kw: None
HLS.download_track(track, ctx)
init = b"INIT" if playlist == "init" and not mode.startswith("service") else b""
plain = b"".join(parts).swapcase()
assert ctx.save_path.read_bytes() == (init.swapcase() if mode == "core-whole" else init) + plain
expected = {"segments": len(parts), "core-whole": 2 if playlist == "discontinuity" else 1}
assert len(runs) == expected.get(mode, 1)
def test_hls_aes128_keeps_post_merge(server, tmp_path, monkeypatch):
# AES-128 with no IV attribute: each segment's IV is its media sequence number
for i, part in enumerate(PARTS):
+285
View File
@@ -0,0 +1,285 @@
"""HDR Vivid as a hybrid base: which tracks selection takes, and the file that the real tools make."""
from __future__ import annotations
import json
import logging
import re
import subprocess
from collections.abc import Callable
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import pytest
from tests.lang_selection.test_track_selection import audio, episode, kept, selection, video
from unshackle.core import binaries
from unshackle.core.config import config
from unshackle.core.constants import DownloadCancelled
from unshackle.core.mux_step import hybrid_plan
from unshackle.core.service import Service, TrackRequest
from unshackle.core.tracks import Tracks, Video
from unshackle.core.tracks import hybrid as hybrid_mod
from unshackle.core.tracks.hybrid import Hybrid
from unshackle.core.tracks.selection import Skip, hybrid_gate_failure
from unshackle.core.utils import dovi, hdr10plus
from unshackle.core.utils.subprocess import run_step
from unshackle.core.wire import deserialize_video, serialize_video_track, track_from_dict, track_to_dict
R, C = Video.Range, Video.Codec
def vid(id_: str, range_: Video.Range, height: int = 1080, codec: Video.Codec = C.HEVC, **attrs: Any) -> Video:
return video(id_, range_=range_, codec=codec, width=height * 16 // 9, height=height, bitrate=5_000_000, **attrs)
def select(videos: list[Video], ranges: list[Video.Range], **flags: Any) -> Any:
return selection(range_=ranges, **flags).select(episode(*videos, audio()), False)
def ids(outcome: Any) -> list[str]:
return kept(outcome)["video"]
def planned(outcome: Any, generate_dv: bool) -> list[str]:
"""The bases the mux step plans, from the tracks it passes: the hybrid ingredients."""
return [v.id for v in hybrid_plan([v for v in outcome.tracks.videos if v.hybrid_ingredient], generate_dv)[0]]
def dv(height: int = 1080, **attrs: Any) -> Video:
return vid("dv", R.DV, height, **attrs)
def test_vivid_is_the_base_when_the_title_has_no_hdr10() -> None:
outcome = select([vid("viv", R.VIVID), dv()], [R.HYBRID])
assert ids(outcome) == ["viv", "dv"]
assert planned(outcome, False) == ["viv"]
@pytest.mark.parametrize("codec", [C.HEVC, C.AV1])
@pytest.mark.parametrize("quality", [[], [1080]])
def test_a_taller_vivid_track_never_displaces_an_hdr10_base(codec: Video.Codec, quality: list[int]) -> None:
videos = [vid("viv", R.VIVID, 2160, codec), vid("h", R.HDR10), dv()]
assert ids(select(videos, [R.HYBRID], quality=quality)) == ["h", "dv"]
def test_a_vivid_track_that_hdr10_rules_out_is_no_base_at_its_own_resolution() -> None:
videos = [vid("viv", R.VIVID, 2160), vid("h", R.HDR10), dv()]
assert isinstance(select(videos, [R.HYBRID], quality=[2160]), Skip)
assert isinstance(select(videos, [R.HYBRID, R.VIVID], quality=[2160]), Skip)
outcome = select([vid("viv", R.VIVID, 2160), vid("h", R.HDR10), dv()], [R.HYBRID, R.VIVID])
assert {"h", "viv"} <= set(ids(outcome))
assert planned(outcome, False) == ["h"]
@pytest.mark.parametrize("bad", [{"hlg_base": True}, {"codec": C.AV1}, {"fps": 60}], ids=str)
def test_a_vivid_track_that_cannot_be_a_base_falls_back_to_the_other_range(bad: dict[str, Any]) -> None:
for extra, left in ((R.SDR, "sdr"), (R.VIVID, "viv")):
videos = [vid("viv", R.VIVID, **bad), dv(fps=24), vid("sdr", R.SDR)]
outcome = select(videos, [R.HYBRID, extra], best_available=True)
assert ids(outcome) == [left] and outcome.ranges == [extra]
assert isinstance(select(videos, [R.HYBRID]), Skip)
def test_a_taller_av1_vivid_track_does_not_take_the_height_of_the_hybrid() -> None:
assert ids(select([vid("av1", R.VIVID, 2160, C.AV1), vid("viv", R.VIVID), dv()], [R.HYBRID])) == ["viv", "dv"]
def test_the_gate_counts_a_vivid_track_only_as_a_chosen_base() -> None:
vivid = vid("viv", R.VIVID)
assert hybrid_gate_failure([vivid, dv()], False)
vivid.hybrid_ingredient = True
assert hybrid_gate_failure([vivid, dv()], False) is None
@pytest.mark.parametrize(("hlg", "native"), [(False, True), (True, False)])
def test_a_vivid_track_with_its_own_dv_is_the_hybrid_only_on_pq(hlg: bool, native: bool) -> None:
track = vid("viv", R.VIVID, dv_compatible_bitstream=True, hlg_base=hlg)
assert track.finished_hybrid is native
assert track.range_label == "VIVID+DV"
if native:
assert "viv" in ids(select([track, dv(540)], [R.HYBRID]))
def test_generate_dv_takes_a_named_vivid_track_as_a_file_and_not_as_the_base() -> None:
flags = {"generated_dv_bases": [R.HDR10], "generate_dv": True}
videos = [vid("h", R.HDR10), vid("viv", R.VIVID, 2160)]
outcome = select(videos, [R.HYBRID, R.VIVID], **flags)
assert set(ids(outcome)) == {"h", "viv"}
assert planned(outcome, True) == ["h"]
assert ids(select([vid("h", R.HDR10), vid("viv", R.VIVID, 2160)], [R.HYBRID], **flags)) == ["h"]
for quality in ([], [1080]):
videos = [vid("av1", R.HDR10, codec=C.AV1), vid("viv", R.VIVID)]
assert isinstance(select(videos, [R.HYBRID, R.VIVID], quality=quality, **flags), Skip)
@pytest.mark.parametrize(("range_", "hlg"), [(R.HDR10, False), (R.HLG, True)])
def test_the_probe_keeps_the_hlg_base_over_every_round_trip(
range_: Video.Range, hlg: bool, monkeypatch: pytest.MonkeyPatch
) -> None:
track = vid("v", range_)
monkeypatch.setattr(hdr10plus, "first_fragment", lambda *a, **k: b"")
monkeypatch.setattr(hdr10plus, "map_probes", lambda probe, items, workers: [R.VIVID for _ in items])
hdr10plus.probe_dynamic_hdr([track], None, log=logging.getLogger("test"), workers=1) # type: ignore[arg-type]
assert (track.range, track.hlg_base) == (R.VIVID, hlg)
for copy in (track_from_dict(track_to_dict(track)), deserialize_video(serialize_video_track(track))):
assert isinstance(copy, Video) and copy.hlg_base is hlg
def variants(give: dict[str, list[str] | BaseException], **request: Any) -> tuple[list[str], list[str]]:
"""The ranges that get_tracks_for_variants fetched for HYBRID, and those it kept."""
calls: list[str] = []
def fetch(title: Any, codec: Any, range_: Video.Range) -> Tracks:
calls.append(range_.name)
answer = give.get(range_.name, ValueError("none"))
if isinstance(answer, BaseException):
raise answer
return Tracks([vid(name, R[name]) for name in answer])
service: Any = SimpleNamespace(
track_request=TrackRequest(ranges=[R.HYBRID], **request), log=logging.getLogger("variants-test")
)
tracks = Service.get_tracks_for_variants(service, None, fetch) # type: ignore[arg-type]
return calls, sorted(v.range.name for v in tracks.videos)
@pytest.mark.parametrize("hdr10", [ValueError("no HDR10"), SystemExit(1), ["SDR"], []], ids=repr)
def test_hybrid_asks_for_vivid_when_hdr10_gives_no_base(hdr10: Any) -> None:
calls, found = variants({"HDR10": hdr10, "VIVID": ["VIVID"], "DV": ["DV"]})
assert calls == ["HDR10", "VIVID", "DV"]
assert {"VIVID", "DV"} <= set(found)
@pytest.mark.parametrize("gives", ["HDR10", "HDR10P", "VIVID"])
def test_hybrid_does_not_ask_for_vivid_when_hdr10_gives_a_base(gives: str) -> None:
assert variants({"HDR10": [gives], "DV": ["DV"]})[0] == ["HDR10", "DV"]
@pytest.mark.parametrize(
"vivid", [ValueError("x"), KeyError("VIVID"), SystemExit(1), OSError("403"), ["SDR"]], ids=repr
)
def test_a_failed_vivid_request_leaves_the_hdr10_error(vivid: Any) -> None:
"""A service that does not know VIVID raises, or gives its default range."""
with pytest.raises(ValueError, match="no HDR10"):
variants({"HDR10": ValueError("no HDR10"), "VIVID": vivid, "DV": ["DV"]})
assert variants({"HDR10": ValueError("no HDR10"), "VIVID": vivid}, best_available=True)[1] == []
def test_a_cancel_in_the_vivid_request_ends_the_fetch() -> None:
with pytest.raises(DownloadCancelled):
variants({"HDR10": ValueError("no HDR10"), "VIVID": DownloadCancelled(), "DV": ["DV"]})
@pytest.mark.parametrize(
("hdr_format", "name"),
[
("Dolby Vision / HDR Vivid", "DV.HDRVivid"),
("Dolby Vision / SMPTE ST 2086", "DV.HDR"),
("HDR Vivid", "HDRVivid"),
],
)
def test_a_vivid_hybrid_is_named_for_both_formats(hdr_format: str, name: str) -> None:
from tests.core.test_hdr10p_naming import hdr_tag
commercial = "HDR10" if "2086" in hdr_format else "Dolby Vision" if "Dolby" in hdr_format else "HDR Vivid"
assert hdr_tag(commercial, R.VIVID, hdr_format=hdr_format, profile="dvhe.08") == name
CUVA_SEI = bytes.fromhex(
"4e01042f260004000501000be65fffffeb4ab3331198005288011c0000ffbfeff041599988cc002944008e00007fdff7fa261980"
)
def nal_units(stream: bytes) -> list[bytes]:
return [n.rstrip(b"\x00") for n in re.split(b"\x00\x00\x01", stream)[1:]]
def is_cuva(nal: bytes) -> bool:
return (nal[0] >> 1) & 63 == 39 and nal[4:9] == CUVA_SEI[4:9]
def run(*args: Any) -> None:
run_step(args, timeout=120)
@pytest.fixture
def encode(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Callable[..., Video]:
"""Make an HDR Vivid base, or with a profile a DV track, as a downloaded MP4; skips when a tool is missing."""
if not (binaries.FFMPEG and binaries.FFProbe and binaries.DoviTool):
pytest.skip("needs ffmpeg, ffprobe and dovi_tool")
encoders = subprocess.run([str(binaries.FFMPEG), "-v", "error", "-encoders"], capture_output=True).stdout
if b"libx265" not in encoders:
pytest.skip("ffmpeg has no libx265")
monkeypatch.setattr(config.directories, "temp", tmp_path / "temp", raising=False)
(tmp_path / "temp").mkdir()
monkeypatch.setattr(hybrid_mod.console, "print", lambda *a, **k: None)
def build(name: str, transfer: str = "smpte2084", fps: int = 24, profile: str | None = None) -> Video:
raw = tmp_path / f"{name}.hevc"
params = f"log-level=error:bframes=0:repeat-headers=1:hdr10=1:colorprim=bt2020:transfer={transfer}:colormatrix=bt2020nc"
params += (
":master-display=G(13250,34500)B(7500,3000)R(34000,16000)WP(15635,16450)L(10000000,50):max-cll=1000,400"
)
source = f"testsrc2=s=320x180:r={fps}:d=0.5"
run(binaries.FFMPEG, "-v", "error", "-f", "lavfi", "-i", source, "-pix_fmt", "yuv420p10le", "-c:v", "libx265",
"-preset", "ultrafast", "-x265-params", params, raw) # fmt: skip
if profile:
rpu, meta = tmp_path / f"{name}.rpu", tmp_path / f"{name}.json"
level6 = {"max_display_mastering_luminance": 1000, "min_display_mastering_luminance": 50}
level6 |= {"max_content_light_level": 1000, "max_frame_average_light_level": 400}
meta.write_text(json.dumps({"cm_version": "V29", "profile": profile, "length": fps // 2, "level6": level6}))
dovi.generate(meta, rpu)
dovi.inject_rpu(raw, rpu, raw.with_suffix(".dv.hevc"))
raw = raw.with_suffix(".dv.hevc")
else:
stream = b""
for nal in nal_units(raw.read_bytes()):
if (nal[0] >> 1) & 63 <= 31 and nal[2] & 0x80:
stream += b"\x00\x00\x00\x01" + CUVA_SEI
stream += b"\x00\x00\x00\x01" + nal
raw.write_bytes(stream)
track = vid(name, R.DV if profile else R.VIVID, 180)
track.path = tmp_path / f"{name}.mp4"
run(binaries.FFMPEG, "-v", "error", "-fflags", "+genpts", "-r", fps, "-i", raw, "-c", "copy", "-tag:v", "hvc1",
track.path) # fmt: skip
return track
return build
@pytest.mark.parametrize("profile", ["5", "8.1", None])
def test_the_real_hybrid_is_profile_8_1_and_keeps_every_vivid_sei(
encode: Callable[..., Video], tmp_path: Path, profile: str | None
) -> None:
tracks = [encode("base")] + ([encode("dv", profile=profile)] if profile else [])
Hybrid(tracks, "EXAMPLE", output_name="out.hevc")
out = tmp_path / "temp" / "out.hevc"
nals = nal_units(out.read_bytes())
assert sum(map(is_cuva, nals)) == sum((n[0] >> 1) & 63 == 62 for n in nals) == 12
probe = subprocess.run(
[str(binaries.FFProbe), "-v", "error", "-select_streams", "v:0", "-read_intervals", "%+#1"]
+ ["-show_entries", "stream=color_transfer:frame=side_data_list", "-show_frames", "-of", "json", str(out)],
capture_output=True,
).stdout
dovi.extract_rpu(out, tmp_path / "check.rpu", mode=None)
summary = dovi.info_summary(tmp_path / "check.rpu")
assert "Profile: 8" in summary and "Frames: 12" in summary
assert b"smpte2084" in probe and b"CUVA" in probe
@pytest.mark.parametrize(
("base", "dv_track", "error"),
[
({"transfer": "arib-std-b67"}, {"profile": "8.1"}, "needs a PQ base"),
({"fps": 60}, {"profile": "5"}, "60 fps and the Dolby Vision track 24 fps"),
({}, {"profile": "8.4", "transfer": "arib-std-b67"}, "profile 8.4"),
],
ids=["hlg-base", "two-rates", "hlg-dv"],
)
def test_the_real_hybrid_refuses_what_it_would_make_wrong(
encode: Callable[..., Video], base: dict[str, Any], dv_track: dict[str, Any], error: str
) -> None:
with pytest.raises(ValueError, match=error):
Hybrid([encode("base", **base), encode("dv", **dv_track)], "EXAMPLE", output_name="out.hevc")
+6
View File
@@ -183,6 +183,7 @@ def video(**extra: Any) -> Video:
dv_compatible_bitstream=True,
hdr10plus=True,
hdr10_base=True,
hlg_base=True,
stereo=True,
id_="video-0001",
)
@@ -272,6 +273,7 @@ def track_fields(track: Any) -> dict[str, Any]:
dv_compatible_bitstream=track.dv_compatible_bitstream,
hdr10plus=track.hdr10plus,
hdr10_base=track.hdr10_base,
hlg_base=track.hlg_base,
stereo=track.stereo,
)
elif isinstance(track, Audio):
@@ -437,6 +439,7 @@ REST_VIDEO = {
"dv_compatible_bitstream": True,
"hdr10plus": True,
"hdr10_base": True,
"hlg_base": True,
"stereo": True,
"language": "en",
"is_original_lang": True,
@@ -529,6 +532,7 @@ EXPORT_VIDEO = {
"dv_compatible_bitstream": True,
"hdr10plus": True,
"hdr10_base": True,
"hlg_base": True,
"stereo": True,
}
@@ -591,6 +595,7 @@ VIDEO_FIELDS = {
"dv_compatible_bitstream": True,
"hdr10plus": True,
"hdr10_base": True,
"hlg_base": True,
"stereo": True,
}
@@ -958,6 +963,7 @@ def test_deserialize_a_track_from_an_older_server() -> None:
"dv_compatible_bitstream": False,
"hdr10plus": False,
"hdr10_base": False,
"hlg_base": False,
"stereo": False,
}
old_audio = deserialize_audio({"id": "a-old", "codec": "AAC", "atmos": True, "channels": 6})
+1 -1
View File
@@ -137,7 +137,7 @@ def test_an_lcevc_layer_is_left_out_unless_asked_for() -> None:
def test_a_failed_hybrid_falls_back_to_the_other_ranges_only_with_best_available() -> None:
ranges = [Video.Range.HYBRID, Video.Range.SDR]
failure = "HYBRID needs HDR10/HDR10+ and DV tracks, available ranges: SDR"
failure = "HYBRID needs HDR10/HDR10+/VIVID and DV tracks, available ranges: SDR"
assert selection(range_=ranges).select(standard(), False) == Skip(failure)
outcome = selection(range_=ranges, best_available=True).select(standard(), False)
assert isinstance(outcome, Kept)
+45 -4
View File
@@ -8,6 +8,7 @@ from __future__ import annotations
import base64
import logging
from collections.abc import Callable, Sequence
from pathlib import Path
from typing import Any
from uuid import UUID
@@ -44,6 +45,8 @@ class MonaLisa:
ticket: str | bytes,
device_path: Path,
tool_path: Path | None = None,
command_builder: Callable[[Path, Path, Path, str, str], Sequence[str | Path]] | None = None,
segment_decrypt: bool = True,
**kwargs: Any,
) -> None:
"""
@@ -53,6 +56,9 @@ class MonaLisa:
ticket: PSSH value from service API (base64 string or raw bytes).
device_path: Path to the CDM device file (.mld).
tool_path: Optional path to an external decryption binary.
command_builder: Optional callback `(tool_path, src, dst, kid_hex, key_hex) -> args`
that builds the decryption CLI invocation (default: `-i src -o dst -k kid:key`).
segment_decrypt: Whether the external tool supports per-segment decryption.
**kwargs: Additional metadata stored in self.data.
Raises:
@@ -65,6 +71,8 @@ class MonaLisa:
self._ticket = ticket
self._device_path = device_path
self._tool_path = tool_path
self._command_builder = command_builder
self._segment_decrypt = segment_decrypt
self._decrypted_segments: int = 0
self._kid: UUID | None = None
self._key: str | None = None
@@ -96,6 +104,8 @@ class MonaLisa:
ticket: str | bytes,
device_path: Path,
tool_path: Path | None = None,
command_builder: Callable[[Path, Path, Path, str, str], Sequence[str | Path]] | None = None,
segment_decrypt: bool = True,
) -> MonaLisa:
"""
Make a MonaLisa DRM instance from a PSSH/ticket.
@@ -104,6 +114,8 @@ class MonaLisa:
ticket: PSSH value from service API.
device_path: Path to the CDM device file (.mld).
tool_path: Optional path to an external decryption binary.
command_builder: Optional callback that builds the decryption CLI invocation.
segment_decrypt: Whether the external tool supports per-segment decryption.
Returns:
MonaLisa DRM instance with extracted keys.
@@ -112,6 +124,8 @@ class MonaLisa:
ticket=ticket,
device_path=device_path,
tool_path=tool_path,
command_builder=command_builder,
segment_decrypt=segment_decrypt,
)
@property
@@ -184,6 +198,19 @@ class MonaLisa:
return {self._kid: self._key}
return {}
@property
def supports_segment_decrypt(self) -> bool:
"""Whether the configured external tool supports per-segment decryption."""
return self._segment_decrypt
@property
def track_decrypted(self) -> bool:
"""Whether the service already decrypted the whole track into one clear segment file.
The service can keep its merged ciphertext beside that file, and the merge leaves it out.
"""
return not self._segment_decrypt and self._decrypted_segments > 0
@property
def key_pair(self) -> str:
"""The formatted ``KID:KEY`` for CLI decryptors (32hex:32hex)."""
@@ -199,13 +226,16 @@ class MonaLisa:
segment_path: Path to the segment file to decrypt.
output_path: Optional path for the decrypted output segment.
"""
self._execute_decrypt(segment_path, output_path)
self._execute_decrypt(segment_path, output_path, timeout=60)
self._decrypted_segments += 1
def decrypt(self, path: Path, output_path: Path | None = None, *, is_segment: bool = False) -> None:
"""
Decrypt a media file (segment or track) using the configured CLI tool via subprocess.
A whole-track tool runs once on a service's own merged file, which the service gives an ``output_path``.
The in-place calls of core after it do nothing.
Args:
path: Path to the target file to decrypt.
output_path: Optional path for the decrypted output file.
@@ -222,8 +252,16 @@ class MonaLisa:
return
self._execute_decrypt(path, output_path)
if output_path and not self._segment_decrypt:
self._decrypted_segments += 1
def _execute_decrypt(self, path: Path, output_path: Path | None = None) -> None:
def _execute_decrypt(
self,
path: Path,
output_path: Path | None = None,
*,
timeout: float | None = None,
) -> None:
"""Run the external tool into a temporary file, which replaces the target only on success."""
if not path or not path.exists():
raise ValueError(f"Target file does not exist: {path}")
@@ -236,10 +274,13 @@ class MonaLisa:
target_output = output_path or path
temp_out = target_output.with_stem(f"{target_output.stem}_decrypted")
cmd: Sequence[str | Path] = [self._tool_path, "-i", path, "-o", temp_out, "-k", self.key_pair]
if self._command_builder:
cmd = self._command_builder(self._tool_path, path, temp_out, self.kid.hex, self.key)
run_step(
[self._tool_path, "-i", path, "-o", temp_out, "-k", self.key_pair],
cmd,
output=temp_out,
label=f"MonaLisa decryption of {path.name}",
timeout=60,
timeout=timeout,
)
temp_out.replace(target_output)
+8 -2
View File
@@ -31,7 +31,7 @@ from unshackle.core import binaries
from unshackle.core.cdm.detect import cdm_system, cdm_type_stub, is_playready_cdm, is_widevine_cdm
from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_LICENCE_ONLY, AnyTrack
from unshackle.core.drm import DRM_T, ClearKey, ClearKeyCENC, PlayReady, Widevine
from unshackle.core.drm import DRM_T, ClearKey, ClearKeyCENC, MonaLisa, PlayReady, Widevine
from unshackle.core.drm.cenc import (
PLACEHOLDER_KIDS,
PLAYREADY_ID,
@@ -985,7 +985,7 @@ class HLS:
]
if not files:
raise ValueError(f"None of the segment files for {segment_range} exist...")
elif len(files) != range_len:
elif len(files) != range_len and not (isinstance(drm, MonaLisa) and drm.track_decrypted):
raise ValueError(f"Missing {range_len - len(files)} segment files for {segment_range}...")
if isinstance(drm, (Widevine, PlayReady)):
@@ -998,6 +998,10 @@ class HLS:
decrypt_track(drm, merged_path, license_widevine, decrypt=not segment_decrypter, track=track)
check_decrypted(track, merged_path, drm)
merged_path.rename(decrypted_path)
elif isinstance(drm, MonaLisa) and not drm.supports_segment_decrypt:
merge(to=merged_path, via=files, delete=True, include_map_data=not drm.track_decrypted)
decrypt_track(drm, merged_path, license_widevine, track=track)
merged_path.rename(decrypted_path)
else:
# AES segments must be decrypted individually before merging: each segment
# likely carries its own 16-byte padding
@@ -1141,6 +1145,8 @@ class HLS:
return sorted(segments)
segments_to_merge = find_segments_recursively(save_dir)
if isinstance(session_drm, MonaLisa) and session_drm.track_decrypted:
segments_to_merge = [file for file in segments_to_merge if file.stem.isdigit()]
log_event(
"manifest_hls_download_complete",
+4 -4
View File
@@ -94,7 +94,7 @@ def missing_hybrid_error(bases: Sequence[Video], made: int) -> str | None:
if made:
return None
if not bases:
return "No HEVC HDR10 or HDR10+ track to make a hybrid from"
return "No HEVC HDR10, HDR10+ or VIVID track to make a hybrid from"
return f"Every hybrid failed ({', '.join(f'{v.height or 0}p' for v in bases)}), so the title has no hybrid file"
@@ -247,8 +247,6 @@ def mux_title(
hybrid_mux_pool = mux_pool if mux_concurrency == 1 else extra_mux_pool
if any(r == Video.Range.HYBRID for r in range_) and title.tracks.videos:
log.info("Processing Hybrid HDR10+DV tracks...")
original_videos = list(title.tracks.videos)
standalone_videos = [v for v in original_videos if not v.hybrid_base_only]
@@ -258,6 +256,8 @@ def mux_title(
hybrid_bases, matching_dv = hybrid_plan(
[v for v in original_videos if v.hybrid_ingredient], generate_dv
)
base_label = hybrid_bases[0].range.name if hybrid_bases else "HDR10"
log.info(f"Processing Hybrid {base_label}+DV tracks...")
hybrid_base_ids.update(v.id for v in hybrid_bases)
hybrids_made = 0
for video in (v for v in original_videos if v.native_hybrid):
@@ -289,7 +289,7 @@ def mux_title(
except PermissionError:
pass # still in hybrid_temp_paths, so the final cleanup tries again
task_description = f"Multiplexing Hybrid HDR10+DV {resolution}p"
task_description = f"Multiplexing Hybrid {hdr10_track.range.name}+DV {resolution}p"
task_tracks = Tracks(title.tracks) + title.tracks.chapters + title.tracks.attachments
hybrid_track = deepcopy(hdr10_track)
+20 -4
View File
@@ -18,6 +18,7 @@ from rich.rule import Rule
from unshackle.core.cacher import Cacher
from unshackle.core.config import config
from unshackle.core.console import console, prompt_user, show_notice, show_qr
from unshackle.core.constants import DownloadCancelled
from unshackle.core.credential import Credential
from unshackle.core.launch import launch_keys
from unshackle.core.proxies.resolve import pick_proxy
@@ -38,7 +39,7 @@ from unshackle.core.title_cacher import TitleCacher
from unshackle.core.title_source import TitleSource
from unshackle.core.titles import Title_T, Titles_T, remap_titles
from unshackle.core.tracks import Chapters, Tracks
from unshackle.core.tracks.video import Video
from unshackle.core.tracks.video import HYBRID_BASE_RANGES, Video
from unshackle.core.utils import run_proxy
from unshackle.core.utils.ip_info import get_ip_info, verify_proxy_exit
@@ -320,15 +321,30 @@ class Service(TitleSource):
for range_val in ranges:
if range_val == Video.Range.HYBRID:
# HYBRID: fetch HDR10 first, then DV
# HYBRID: fetch HDR10 first (VIVID when there is none), then DV
for codec_val in codecs:
hdr_error: ValueError | SystemExit | None = None
try:
hdr_tracks = fetch_fn(title, codec=codec_val, range_=Video.Range.HDR10)
except (ValueError, SystemExit) as e:
hdr_error, hdr_tracks = e, Tracks()
if not any(v.range in HYBRID_BASE_RANGES for v in hdr_tracks.videos):
try:
vivid_tracks = fetch_fn(title, codec=codec_val, range_=Video.Range.VIVID)
except DownloadCancelled:
raise
except (Exception, SystemExit) as e:
self.log.debug(f"No HDR Vivid manifest for HYBRID: {e!r}")
vivid_tracks = Tracks()
if any(v.range == Video.Range.VIVID for v in vivid_tracks.videos):
if not hdr_error:
merge(hdr_tracks)
hdr_error, hdr_tracks = None, vivid_tracks
if hdr_error:
if self.track_request.best_available:
self.log.warning(f" - HDR10 not available for HYBRID, skipping ({e})")
self.log.warning(f" - HDR10 not available for HYBRID, skipping ({hdr_error})")
continue
raise
raise hdr_error
merge(hdr_tracks)
try:
+2
View File
@@ -147,6 +147,8 @@ class Title:
and profile.startswith(("dvhe.07", "dvhe.08"))
):
base_layer = "HDR"
if "HDR Vivid" in primary_video_track.hdr_format:
base_layer = DYNAMIC_RANGE_MAP["HDR Vivid"]
if base_layer and base_layer != "DV":
context["hdr"] += f".{base_layer}"
elif (primary_video_track.hdr_format or "").startswith("HDR Vivid"):
+56 -22
View File
@@ -7,6 +7,8 @@ import tempfile
from collections import Counter
from collections.abc import Iterable
from concurrent import futures
from contextlib import suppress
from fractions import Fraction
from itertools import pairwise
from pathlib import Path
from typing import TYPE_CHECKING, Any
@@ -203,6 +205,16 @@ def hdr10plus_shots(metadata: dict, active_fraction: float = 1.0) -> list[dict]:
return shots
def frame_rates(video: "Video", stream: dict[str, Any]) -> list[float]:
"""The average and base frame rates FFprobe read; [0.0] when it has none, or for a raw stream, which has no clock."""
rates = []
if not video.path or video.path.suffix.lower() not in (".hevc", ".h265", ".265"):
for name in ("avg_frame_rate", "r_frame_rate"):
with suppress(ValueError, ZeroDivisionError):
rates.append(float(Fraction(stream.get(name) or "0")))
return [rate for rate in rates if rate] or [0.0]
class NoHDR10PlusMetadata(ValueError):
"""A track labelled HDR10+ carries no HDR10+ metadata."""
@@ -212,13 +224,13 @@ class Hybrid:
self.log = logging.getLogger("hybrid")
"""
Takes the Dolby Vision and HDR10(+) streams out of the VideoTracks.
It will then attempt to inject the Dolby Vision metadata layer to the HDR10(+) stream.
Takes the Dolby Vision and HDR10(+) or PQ HDR Vivid streams out of the VideoTracks.
It will then attempt to inject the Dolby Vision metadata layer to the base stream.
If no DV track is available, it makes the DV from the HDR10+ metadata, or from the
decoded video when there is no HDR10+ or no hdr10plus_tool.
"""
global directories
from unshackle.core.tracks import Video
from unshackle.core.tracks.video import HYBRID_BASE_RANGES, Video
self.videos = videos
self.source = source
@@ -228,16 +240,15 @@ class Hybrid:
self.hdr10plus_to_dv = False
self.hdr10plus_file = "HDR10Plus.json"
hdr10_track = next((v for v in videos if v.range == Video.Range.HDR10), None)
hdr10p_track = next((v for v in videos if v.range == Video.Range.HDR10P), None)
track_for_res = hdr10_track or hdr10p_track
base_video = next((v for v in videos if v.range in HYBRID_BASE_RANGES), None)
self.resolution = (
f"{standard_resolution(track_for_res.width, track_for_res.height)}p"
if track_for_res and track_for_res.height
f"{standard_resolution(base_video.width, base_video.height)}p"
if base_video and base_video.height
else "Unknown"
)
base_label = base_video.range.name if base_video else "HDR10"
console.print(Padding(Rule(f"[rule.text]HDR10+DV Hybrid ({self.resolution})"), (1, 2)))
console.print(Padding(Rule(f"[rule.text]{base_label}+DV Hybrid ({self.resolution})"), (1, 2)))
log_event(
"hybrid_init",
@@ -255,12 +266,13 @@ class Hybrid:
if not video.path or not os.path.exists(video.path):
raise ValueError(f"Video track {video.id} was not downloaded before injection.")
has_dv = any(video.range == Video.Range.DV for video in self.videos)
has_hdr10 = any(video.range == Video.Range.HDR10 for video in self.videos)
dv_video = next((v for v in videos if v.range == Video.Range.DV), None)
has_dv = dv_video is not None
has_hdr10p = any(video.range == Video.Range.HDR10P for video in self.videos)
if not has_hdr10 and not has_hdr10p:
raise ValueError("No HDR10 or HDR10+ track available for hybrid processing.")
if not base_video:
raise ValueError("No HDR10, HDR10+ or VIVID track available for hybrid processing.")
self.check_base(base_video, dv_video)
if not has_dv:
self.hdr10plus_to_dv = has_hdr10p and bool(HDR10PlusTool)
@@ -277,17 +289,14 @@ class Hybrid:
if not save_path or not os.path.exists(save_path):
raise ValueError(f"Video track {video.id} was not downloaded or path not found: {save_path}")
if video.range == Video.Range.HDR10:
if video.range in HYBRID_BASE_RANGES:
self.extract_stream(save_path, "HDR10")
elif video.range == Video.Range.HDR10P:
self.extract_stream(save_path, "HDR10")
self.hdr_type = "HDR10+"
self.hdr_type = "HDR10+" if video.range == Video.Range.HDR10P else video.range.name
elif video.range == Video.Range.DV:
if not os.path.isfile(config.directories.temp / "DV.hevc"):
self.extract_stream(save_path, "DV")
base_video = next((v for v in videos if v.range in (Video.Range.HDR10, Video.Range.HDR10P)), None)
area = self.detect_active_area(base_video.path) if base_video and base_video.path else None
area = self.detect_active_area(base_video.path) if base_video.path else None
if not has_dv:
# a base that failed earlier in this title can leave its edited RPUs, which level_5/level_6 reuse
@@ -302,8 +311,7 @@ class Hybrid:
self.hdr10plus_to_dv = False
else:
self.convert_hdr10plus_to_dv(area[1] if area else 1.0)
if has_dv:
dv_video = next(v for v in videos if v.range == Video.Range.DV)
if dv_video:
self.extract_rpu(dv_video)
if os.path.isfile(config.directories.temp / "RPU_UNT.bin"):
self.rpu_file = "RPU_UNT.bin"
@@ -315,7 +323,7 @@ class Hybrid:
self.measure_dv(area[0] if area else None)
self.level_6()
if base_video and has_dv:
if dv_video:
self.align_rpu(base_video, dv_video)
if area:
self.level_5(area[0])
@@ -349,6 +357,32 @@ class Hybrid:
)
self.log.info("✓ Injection Completed")
@staticmethod
def check_base(base: "Video", dv: "Video | None") -> None:
"""Raise ValueError for a VIVID base that is not PQ, a DV track made for HLG, or two frame rates.
The injected RPU is profile 8.1, which needs a PQ base, and dovi_tool exits 0 when the RPU count does
not fit the base. The rates come from the files, because a manifest can give one rate for every track.
"""
from unshackle.core.tracks.video import HDR_TRANSFER, Video, same_frame_rate
vivid = base.range == Video.Range.VIVID
if not vivid and not dv:
return
stream = base._probe_colour()
transfer = stream.get("color_transfer")
if vivid and transfer != HDR_TRANSFER[Video.Range.HDR10]:
raise ValueError(f"A VIVID hybrid needs a PQ base, not {transfer or 'an untagged one'}")
if not dv:
return
dv_stream = dv._probe_colour()
compatibility = [data.get("dv_bl_signal_compatibility_id") for data in dv_stream.get("side_data_list", [])]
if 4 in compatibility or dv_stream.get("color_transfer") == HDR_TRANSFER[Video.Range.HLG]:
raise ValueError("The Dolby Vision track is profile 8.4 (HLG), and a hybrid needs a PQ one")
base_rates, dv_rates = frame_rates(base, stream), frame_rates(dv, dv_stream)
if not any(same_frame_rate(a, b) for a in base_rates for b in dv_rates):
raise ValueError(f"The base has {base_rates[0]:g} fps and the Dolby Vision track {dv_rates[0]:g} fps")
def extract_stream(self, save_path: Path, type_: str) -> None:
output = Path(config.directories.temp / f"{type_}.hevc")
try:
+21 -20
View File
@@ -16,7 +16,7 @@ from unshackle.core.tracks.audio import Audio
from unshackle.core.tracks.chapter import Chapter
from unshackle.core.tracks.chapters import Chapters
from unshackle.core.tracks.tracks import Tracks, at_resolution, select_videos
from unshackle.core.tracks.video import Video
from unshackle.core.tracks.video import HDR10_RANGES, HYBRID_BASE_RANGES, Video
from unshackle.core.utilities import (
as_requested,
embedded_audio_langs,
@@ -31,8 +31,6 @@ from unshackle.core.utilities import (
log = logging.getLogger("download")
HYBRID_BASE_RANGES = (Video.Range.HDR10P, Video.Range.HDR10)
def generated_dv_ranges(
range_: Sequence[Video.Range], generate_dv: bool
@@ -43,7 +41,7 @@ def generated_dv_ranges(
the flag is off, HYBRID or DV is in the ranges, or no base range is. The service still gets the
ranges the user gave, so it fetches no DV track.
"""
bases = [r for r in range_ if r in HYBRID_BASE_RANGES]
bases = [r for r in range_ if r in HDR10_RANGES]
if not generate_dv or not bases or Video.Range.HYBRID in range_ or Video.Range.DV in range_:
return list(range_), []
return [Video.Range.HYBRID, *(r for r in range_ if r not in bases)], bases
@@ -217,7 +215,9 @@ class TrackSelection:
title.tracks.select_video(lambda x: x.codec != Video.Codec.LCEVC)
if keep_videos and self.generated_dv_bases:
title.tracks.videos = keep_generated_dv_bases(title.tracks.videos, self.generated_dv_bases)
title.tracks.videos = keep_generated_dv_bases(
title.tracks.videos, [*self.generated_dv_bases, *range_]
)
if not any(v.range in self.generated_dv_bases for v in title.tracks.videos):
return Skip(f"There's no {', '.join(r.name for r in self.generated_dv_bases)} Video Track...")
@@ -305,16 +305,14 @@ class TrackSelection:
has_hybrid = any(r == Video.Range.HYBRID for r in range_)
non_hybrid_ranges: list[Video.Range] = [r for r in range_ if r != Video.Range.HYBRID]
effective_quality = self.quality
hybrid_pool, non_hybrid_tracks = Tracks.partition_hybrid_videos(title.tracks.videos, non_hybrid_ranges)
if self.generated_dv_bases:
hybrid_pool = [v for v in hybrid_pool if v.range in self.generated_dv_bases]
if keep_videos and self.quality:
missing_resolutions = []
if has_hybrid:
hybrid_candidate_tracks, non_hybrid_tracks = Tracks.partition_hybrid_videos(
title.tracks.videos, non_hybrid_ranges
)
# only ranges that can actually be delivered count towards "present"
deliverable_pool = hybrid_candidate_tracks + [
v for v in non_hybrid_tracks if v.range in non_hybrid_ranges
]
deliverable_pool = hybrid_pool + [v for v in non_hybrid_tracks if v.range in non_hybrid_ranges]
for resolution in self.quality:
if any(at_resolution(v, resolution) for v in deliverable_pool):
continue
@@ -326,9 +324,9 @@ class TrackSelection:
effective_quality = []
else:
hybrid_filter = title.tracks.select_hybrid(
hybrid_candidate_tracks, self.quality, worst=self.worst, generate_dv=self.generate_dv
hybrid_pool, self.quality, worst=self.worst, generate_dv=self.generate_dv
)
hybrid_selected = list(filter(hybrid_filter, hybrid_candidate_tracks))
hybrid_selected = list(filter(hybrid_filter, hybrid_pool))
if non_hybrid_ranges and non_hybrid_tracks:
non_hybrid_selected = [
@@ -372,6 +370,7 @@ class TrackSelection:
hybrid_candidate_tracks, non_hybrid_tracks = Tracks.partition_hybrid_videos(
title.tracks.videos, non_hybrid_ranges
)
hybrid_candidate_tracks = [v for v in hybrid_candidate_tracks if v in hybrid_pool]
hybrid_quality = effective_quality
if not hybrid_quality:
@@ -655,15 +654,15 @@ def select_best_audio(
def select_hybrid_bases(videos: Sequence[Video]) -> list[Video]:
"""The HDR10 or HDR10+ track that is the hybrid base for each height, tallest first.
"""The HDR10+, HDR10 or VIVID track that is the hybrid base for each height, tallest first.
Only HEVC tracks qualify, because dovi_tool injects the RPU into an HEVC stream. HDR10+ comes before
HDR10 at one height.
Only HEVC tracks qualify, because dovi_tool injects the RPU into an HEVC stream. Priority at one
height is HDR10+ > HDR10 > VIVID.
"""
bases: dict[int, Video] = {}
for video in sorted(
(v for v in videos if v.range in HYBRID_BASE_RANGES and v.codec in (Video.Codec.HEVC, None)),
key=lambda v: (v.height or 0, v.range == Video.Range.HDR10P),
key=lambda v: (v.height or 0, -HYBRID_BASE_RANGES.index(v.range)),
reverse=True,
):
bases.setdefault(video.height or 0, video)
@@ -679,17 +678,19 @@ def hybrid_gate_failure(videos: Sequence[Video], generate_dv: bool) -> str | Non
"""The message that stops HYBRID for these selected videos, or None when it can go on."""
if any(v.native_hybrid for v in videos):
return None
hdr_tracks = [v for v in videos if v.range in HYBRID_BASE_RANGES]
hdr_tracks = [
v for v in videos if v.range in HYBRID_BASE_RANGES and (v.range != Video.Range.VIVID or v.hybrid_ingredient)
]
base_tracks = [v for v in hdr_tracks if v.codec in (Video.Codec.HEVC, None)]
dv_tracks = [v for v in videos if v.range == Video.Range.DV]
ranges = ", ".join(sorted(set(v.range.name for v in videos))) or "none"
missing = f"HYBRID needs HDR10/HDR10+ and DV tracks, available ranges: {ranges}"
missing = f"HYBRID needs HDR10/HDR10+/VIVID and DV tracks, available ranges: {ranges}"
if not hdr_tracks:
return missing
if not base_tracks:
codecs = sorted(set(v.codec.name for v in hdr_tracks if v.codec))
return f"HYBRID needs an HEVC HDR10/HDR10+ base, available codecs: {', '.join(codecs)}"
return f"HYBRID needs an HEVC HDR10/HDR10+/VIVID base, available codecs: {', '.join(codecs)}"
if not dv_tracks and not generate_dv:
return f"{missing}; add --generate-dv to make DV"
return None
+20 -6
View File
@@ -35,7 +35,7 @@ from unshackle.core.tracks.track import (
has_mp4_only_audio_entry,
prepare_for_mp4box,
)
from unshackle.core.tracks.video import Video
from unshackle.core.tracks.video import HDR10_RANGES, HYBRID_BASE_RANGES, Video, same_frame_rate
from unshackle.core.utilities import (
FPS,
is_close_match,
@@ -605,13 +605,28 @@ class Tracks:
) -> tuple[list[Video], list[Video]]:
"""Split videos into hybrid-ingredient candidates and the standalone-deliverable pool.
HDR10/HDR10+/DV tracks are hybrid ingredients. They only enter the standalone
HDR10/HDR10+/VIVID/DV tracks are hybrid ingredients. They only enter the standalone
pool when the user explicitly requested their range alongside HYBRID, so for
example `-r HYBRID` muxes only the hybrid while `-r HYBRID,HDR10P` also delivers
HDR10+. A 3D track is never an ingredient: dovi_tool does not handle a second view.
A VIVID track to build on must be HEVC, PQ and of the frame rate of a DV track, with no HEVC
HDR10 or HDR10+ track in the title: those always have the PQ base that the hybrid needs. Call it
before a filter by height, or a VIVID track that another height rules out counts as a base.
"""
ingredient_ranges = (Video.Range.HDR10, Video.Range.HDR10P, Video.Range.DV)
ingredient_ranges = (*HYBRID_BASE_RANGES, Video.Range.DV)
hybrid_candidates = [v for v in videos if v.range in ingredient_ranges and not v.stereo]
hevc = (Video.Codec.HEVC, None)
dv_rates = [v.fps for v in hybrid_candidates if v.range == Video.Range.DV] or [None]
has_pq_base = any(v.range in HDR10_RANGES and v.codec in hevc for v in hybrid_candidates)
def usable(v: Video) -> bool:
if v.range != Video.Range.VIVID or v.finished_hybrid:
return True
if has_pq_base or v.hlg_base or v.codec not in hevc:
return False
return any(same_frame_rate(v.fps, rate) for rate in dv_rates)
hybrid_candidates = [v for v in hybrid_candidates if usable(v)]
non_hybrid = [v for v in videos if v.range not in ingredient_ranges or v.range in non_hybrid_ranges]
return hybrid_candidates, non_hybrid
@@ -633,7 +648,7 @@ class Tracks:
) -> Callable[[Video], bool]:
"""A filter for the hybrid ingredients of each resolution. It sets ``native_hybrid`` on every track.
A track that already carries DV and an HDR10 or HDR10+ base (DV+HDR10P, HDR10+DV, HDR10P+DV) is a finished
A track that already carries DV and a PQ base (DV+HDR10P, HDR10+DV, HDR10P+DV, VIVID+DV) is a finished
hybrid, so its resolution takes that track and no base. One that carries HDR10+ comes first. The other
resolutions get a base only when a DV track can give it an RPU, or with ``generate_dv``. Each pick follows
``pick_video``, and the DV track is the lowest one, the best of that height.
@@ -654,9 +669,8 @@ class Tracks:
# Prefer HDR10+ over HDR10 as the base layer (preserves dynamic metadata).
# Only an HEVC base qualifies, because dovi_tool injects the RPU into an HEVC stream.
base_ranges = (Video.Range.HDR10P, Video.Range.HDR10)
base_tracks = []
for range_type in base_ranges:
for range_type in HYBRID_BASE_RANGES:
base_tracks = [
v
for v in tracks
+14 -4
View File
@@ -230,6 +230,7 @@ class Video(Track):
dv_compatible_bitstream: bool = False,
hdr10plus: bool = False,
hdr10_base: bool = False,
hlg_base: bool = False,
stereo: bool = False,
**kwargs: Any,
) -> None:
@@ -252,6 +253,7 @@ class Video(Track):
A zero denominator gives no fps.
hdr10plus: The DV track also carries HDR10+ metadata. The HDR10+ probe sets it.
hdr10_base: The DV track has an HDR10 base layer, as DV profile 8.1 does.
hlg_base: The HDR Vivid track has an HLG base. The HDR10+ probe sets it.
stereo: The track is stereoscopic 3D (MV-HEVC), with a second view for the other eye.
Note: If codec, bitrate, width, height, or fps is not specified, unshackle can
@@ -308,6 +310,7 @@ class Video(Track):
self.dv_compatible_bitstream = dv_compatible_bitstream
self.hdr10plus = hdr10plus
self.hdr10_base = hdr10_base
self.hlg_base = hlg_base
self.stereo = stereo
self.hybrid_base_only = False
self.hybrid_ingredient = False
@@ -348,10 +351,10 @@ class Video(Track):
@property
def finished_hybrid(self) -> bool:
"""Whether the track already carries DV and an HDR10 or HDR10+ base, so ``-r HYBRID`` needs no build."""
"""Whether the track carries DV and an HDR10, HDR10+ or PQ HDR Vivid base, so ``-r HYBRID`` needs no build."""
if self.range == Video.Range.DV:
return self.hdr10plus
return self.dv_compatible_bitstream and self.range in (Video.Range.HDR10, Video.Range.HDR10P)
return self.dv_compatible_bitstream and self.range in HYBRID_BASE_RANGES and not self.hlg_base
@property
def range_label(self) -> str:
@@ -612,7 +615,7 @@ class Video(Track):
return [arg for flag, value in opts.items() for arg in (flag, f"{track_id}:{value}")]
def _probe_colour(self) -> dict[str, Any]:
"""Return the FFprobe colour transfer and side data of the first video track, or {} when it cannot probe."""
"""The FFprobe colour transfer, frame rates and side data of the first video track, or {} when it cannot probe."""
if not binaries.FFProbe or not self.path or not self.path.exists():
return {}
probe_start = time.monotonic()
@@ -627,7 +630,7 @@ class Video(Track):
"-select_streams",
"v:0",
"-show_entries",
"stream=color_transfer:stream_side_data",
"stream=color_transfer,avg_frame_rate,r_frame_rate:stream_side_data",
"-of",
"json",
str(self.path),
@@ -802,10 +805,17 @@ class Video(Track):
return True
def same_frame_rate(a: float | None, b: float | None) -> bool:
"""Whether two frame rates can be one encode (23.976 and 24 can); an unknown rate matches any."""
return not a or not b or abs(float(a) - float(b)) <= 0.5
PROBED_RANGES = {
Video.Range.HDR10: (Video.Range.HDR10P, Video.Range.VIVID),
Video.Range.HLG: (Video.Range.VIVID,),
}
HDR10_RANGES = (Video.Range.HDR10P, Video.Range.HDR10)
HYBRID_BASE_RANGES = (*HDR10_RANGES, Video.Range.VIVID)
HDR_TRANSFER = {
Video.Range.HDR10: "smpte2084",
Video.Range.HDR10P: "smpte2084",
+6 -5
View File
@@ -233,11 +233,11 @@ def probe_dynamic_hdr(
"""Relabel HEVC tracks by the dynamic HDR metadata of their first sample, and flag DV tracks with HDR10+.
HDR10+ SEI makes an HDR10 track HDR10P. CUVA SEI, or the ``cuvv`` registration of an MPEG-TS stream,
makes an HDR10 or HLG track VIVID; ``PROBED_RANGES`` holds which label each range takes. A DV track
keeps its DV range and gets ``hdr10plus`` set, so selection and hybrid pairing are unchanged. HDR10,
HLG and DV are separate ladders. A ladder with one track per resolution is sampled at both ends first.
Two tracks at one resolution can be an HDR10 and an HDR10+ encode side by side, so such a ladder is
probed whole. The rules are in the ``hdr10plus_probe`` section of docs/reference/configuration/download.md.
makes an HDR10 or HLG track VIVID, and an HLG one gets ``hlg_base``; ``PROBED_RANGES`` holds which label
each range takes. A DV track keeps its DV range and gets ``hdr10plus`` set, so selection and hybrid pairing
are unchanged. HDR10, HLG and DV are separate ladders. A ladder with one track per resolution is sampled at
both ends first. Two tracks at one resolution can be an HDR10 and an HDR10+ encode side by side, so such a
ladder is probed whole. The rules are in the ``hdr10plus_probe`` section of docs/reference/configuration/download.md.
A failed probe never changes a label. ``workers`` caps the probes in flight, and ``on_start`` runs once
before the first.
"""
@@ -299,6 +299,7 @@ def probe_dynamic_hdr(
if video.range == Video.Range.DV:
video.hdr10plus = video.hdr10plus or label == Video.Range.HDR10P
elif label in PROBED_RANGES.get(video.range, ()):
video.hlg_base = video.range == Video.Range.HLG
video.range = label
+4
View File
@@ -685,6 +685,7 @@ def serialize_video_track(track: Video, include_url: bool = False) -> dict[str,
"dv_compatible_bitstream": bool(getattr(track, "dv_compatible_bitstream", False)),
"hdr10plus": bool(getattr(track, "hdr10plus", False)),
"hdr10_base": bool(getattr(track, "hdr10_base", False)),
"hlg_base": bool(getattr(track, "hlg_base", False)),
"stereo": bool(getattr(track, "stereo", False)),
}
result.update(serialize_track_common(track))
@@ -796,6 +797,7 @@ def deserialize_video(data: dict[str, Any]) -> Video:
dv_compatible_bitstream=bool(data.get("dv_compatible_bitstream", False)),
hdr10plus=bool(data.get("hdr10plus", False)),
hdr10_base=bool(data.get("hdr10_base", False)),
hlg_base=bool(data.get("hlg_base", False)),
stereo=bool(data.get("stereo", False)),
)
@@ -884,6 +886,7 @@ def track_to_dict(track: Track) -> dict[str, Any]:
"dv_compatible_bitstream": track.dv_compatible_bitstream,
"hdr10plus": track.hdr10plus,
"hdr10_base": track.hdr10_base,
"hlg_base": track.hlg_base,
"stereo": track.stereo,
}
)
@@ -932,6 +935,7 @@ def track_from_dict(data: dict[str, Any]) -> Video | Audio | Subtitle:
dv_compatible_bitstream=data.get("dv_compatible_bitstream", False),
hdr10plus=data.get("hdr10plus", False),
hdr10_base=data.get("hdr10_base", False),
hlg_base=data.get("hlg_base", False),
stereo=data.get("stereo", False),
)
if kind is Audio: