mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-01 21:45:10 +00:00
286 lines
13 KiB
Python
286 lines
13 KiB
Python
"""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")
|