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