feat(hdr): find HDR Vivid and HDR10+ SEI in MPEG-TS and VVC tracks, read local HLS playlists and accept a 200 probe body

This commit is contained in:
imSp4rky
2026-12-02 09:43:50 -07:00
parent c7a3febf88
commit ccdd14c845
6 changed files with 307 additions and 76 deletions
+1 -11
View File
@@ -5,22 +5,12 @@ from typing import Any
from pymediainfo import MediaInfo
from tests.core.test_hdr10plus_probe import ts
from tests.core.test_hdr10plus_probe import media_packet, ts
from unshackle.commands.dl import take_unmuxable_audio
from unshackle.core.placement import no_mux_extension, track_file_suffix
from unshackle.core.tracks import Audio, Tracks, Video
def media_packet(pid: int, payload: bytes, start: bool) -> bytes:
"""One TS packet carrying ``payload``, padded with adaptation-field stuffing as packagers do."""
stuffing = 184 - len(payload)
flags = 0x40 if start else 0x00
if stuffing:
field = bytes([stuffing - 1]) + (b"\x00" + b"\xff" * (stuffing - 2) if stuffing > 1 else b"")
return bytes([0x47, flags | pid >> 8, pid & 0xFF, 0x30]) + field + payload
return bytes([0x47, flags | pid >> 8, pid & 0xFF, 0x10]) + payload
def audio_vivid_ts(frames: list[bytes]) -> bytes:
"""A PAT, a PMT with one Audio Vivid stream on PID 0x100, and one PES per frame."""
data = ts((0xD5, b""))
+189 -10
View File
@@ -1,9 +1,13 @@
import io
import logging
import struct
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import pytest
import requests
from requests.adapters import BaseAdapter
from tests.core.test_export_name import video
from unshackle.core.config import Config, config
@@ -12,7 +16,8 @@ from unshackle.core.manifests.snapshot import match_track
from unshackle.core.remote_service import RemoteService
from unshackle.core.tracks import Audio, Video
from unshackle.core.utils import hdr10plus
from unshackle.core.utils.hdr10plus import HDR10PLUS_T35, TS_PACKET, fragment_has_t35
from unshackle.core.utils.bitrate import ranged_get
from unshackle.core.utils.hdr10plus import CUVA_T35, HDR10PLUS_T35, PROBE_BYTES, TS_PACKET, fragment_has_t35
from unshackle.core.wire import track_from_dict, track_to_dict
@@ -82,7 +87,7 @@ def probe(monkeypatch: pytest.MonkeyPatch, videos: list[Any]) -> list[str]:
return video.id[-1].encode()
monkeypatch.setattr(hdr10plus, "first_fragment", fake_fragment)
monkeypatch.setattr(hdr10plus, "fragment_has_t35", lambda data, t35: t35 == HDR10PLUS_T35 and data == b"+")
monkeypatch.setattr(hdr10plus, "fragment_has_t35", lambda data, t35, vvc: t35 == HDR10PLUS_T35 and data == b"+")
hdr10plus.probe_dynamic_hdr(videos, None, log=logging.getLogger("test"), workers=4) # type: ignore[arg-type]
return probed
@@ -152,7 +157,7 @@ def test_first_fragment_skips_the_header_boxes_of_a_one_file_track(monkeypatch:
media = fragment(nal(32, b"vps"), sei(4, HDR10PLUS_T35 + b"\x00" * 8), nal(1, b"\xff" * 64))
data = box(b"ftyp", b"isom") + box(b"moov", b"\x00" * 100_000) + box(b"sidx", b"\x00" * 40) + media
def fake_get(url: str, session: Any, byte_range: str) -> bytes:
def fake_get(url: str, session: Any, byte_range: str, accept_200: bool) -> bytes:
start, end = (int(x) for x in byte_range.removeprefix("bytes=").split("-"))
return data[start : end + 1]
@@ -164,7 +169,7 @@ def test_first_fragment_skips_the_header_boxes_of_a_one_file_track(monkeypatch:
def test_first_segment_of_an_hls_playlist_keeps_its_byte_offset() -> None:
playlist = '#EXTM3U\n#EXT-X-MAP:URI="init.mp4"\n#EXTINF:6.0,\n#EXT-X-BYTERANGE:5000@1200\nmedia.mp4\n'
session = SimpleNamespace(get=lambda url, timeout: SimpleNamespace(status_code=200, text=playlist))
track = SimpleNamespace(url="https://cdn/v/index.m3u8", data={}, descriptor=Video.Descriptor.HLS)
track = SimpleNamespace(url="https://cdn/v/index.m3u8", data={}, descriptor=Video.Descriptor.HLS, from_file=None)
assert hdr10plus.first_segment(track, session) == ("https://cdn/v/media.mp4", 1200) # type: ignore[arg-type]
@@ -209,16 +214,16 @@ def test_a_quoted_hdr10plus_probe_value_is_an_error() -> None:
def test_a_fragment_inside_the_first_window_needs_one_request(monkeypatch: pytest.MonkeyPatch) -> None:
media = fragment(nal(32, b"vps"), sei(4, HDR10PLUS_T35 + b"\x00" * 8), nal(1, b"\xff" * 64))
data = box(b"sidx", b"\x00" * 40) + media
requests: list[str] = []
ranges_asked: list[str] = []
def fake_get(url: str, session: Any, byte_range: str) -> bytes:
requests.append(byte_range)
def fake_get(url: str, session: Any, byte_range: str, accept_200: bool) -> bytes:
ranges_asked.append(byte_range)
return data
monkeypatch.setattr(hdr10plus, "first_segment", lambda track, session: ("https://cdn/v.mp4", 0))
monkeypatch.setattr(hdr10plus, "ranged_get", fake_get)
assert fragment_has_t35(hdr10plus.first_fragment(hevc("v", 2160), None) or b"", HDR10PLUS_T35) is True # type: ignore[arg-type]
assert len(requests) == 1
assert len(ranges_asked) == 1
def test_a_quoted_dl_workers_value_works_like_the_cli(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -261,7 +266,7 @@ def test_ts_streams_reads_the_pmt_stream_types_and_registrations() -> None:
def serve_segments(monkeypatch: pytest.MonkeyPatch, segments: dict[str, bytes]) -> None:
"""Serve each track's first segment through the real first_fragment, keyed by track id."""
monkeypatch.setattr(hdr10plus, "first_segment", lambda track, session: (track.id, 0))
monkeypatch.setattr(hdr10plus, "ranged_get", lambda url, session, byte_range: segments[url])
monkeypatch.setattr(hdr10plus, "ranged_get", lambda url, session, byte_range, accept_200: segments[url])
def test_a_cuvv_registered_ts_track_becomes_vivid(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -300,7 +305,7 @@ def test_ts_streams_skips_program_zero_and_survives_bad_lengths() -> None:
def test_audio_without_a_codec_takes_it_from_the_ts_stream_type(monkeypatch: pytest.MonkeyPatch) -> None:
fetched: list[tuple[str, str]] = []
def fake_get(url: str, session: Any, byte_range: str) -> bytes:
def fake_get(url: str, session: Any, byte_range: str, accept_200: bool) -> bytes:
fetched.append((url, byte_range))
return ts((0xD5, b""))
@@ -349,3 +354,177 @@ def test_probed_tracks_probes_codecless_audio_without_video(monkeypatch: pytest.
service.session = None
hdr10plus.probed_tracks(service, None, workers=2) # type: ignore[arg-type]
assert calls == [1]
def annexb(*nals: bytes) -> bytes:
"""Length-prefixed NALs as an Annex-B byte stream."""
return b"".join(b"\x00\x00\x00\x01" + n[4:] for n in nals)
def vvc_nal(nal_type: int, payload: bytes) -> bytes:
data = bytes([0, nal_type << 3 | 1]) + payload
return struct.pack(">I", len(data)) + data
def vvc_sei(payload_type: int, payload: bytes) -> bytes:
return vvc_nal(23, bytes([payload_type, len(payload)]) + payload + b"\x80")
def media_packet(pid: int, payload: bytes, start: bool) -> bytes:
"""One TS packet carrying ``payload``, padded with adaptation-field stuffing as packagers do."""
stuffing = 184 - len(payload)
flags = 0x40 if start else 0x00
if stuffing:
field = bytes([stuffing - 1]) + (b"\x00" + b"\xff" * (stuffing - 2) if stuffing > 1 else b"")
return bytes([0x47, flags | pid >> 8, pid & 0xFF, 0x30]) + field + payload
return bytes([0x47, flags | pid >> 8, pid & 0xFF, 0x10]) + payload
def pes(pid: int, es: bytes) -> bytes:
"""``es`` as one video PES cut into TS packets."""
data = b"\x00\x00\x01\xe0\x00\x00\x80\x80\x05\x21\x00\x01\x00\x01" + es
return b"".join(media_packet(pid, data[i : i + 184], i == 0) for i in range(0, len(data), 184))
def ts_segment(streams: tuple[tuple[int, bytes], ...], *nals: bytes, size: int = 0) -> bytes:
"""A PAT, a PMT, the first video PES on PID 0x100 and null packets up to ``size`` bytes."""
data = ts(*streams) + pes(0x100, annexb(*nals))
return data + (b"\x47\x1f\xff\x10" + b"\xff" * 184) * max(0, (size - len(data)) // 188)
def access_unit(*seis: bytes) -> tuple[bytes, ...]:
"""HEVC NALs in the order of a real HDR Vivid stream: unspecified types 56 and 48 first, then the SEIs and VCL."""
return (
nal(56, b"\x01" * 8),
nal(48, b"\x02" * 8),
sei(5, b"\x11" * 200),
*seis,
nal(32, b"vps"),
nal(33, b"sps"),
nal(34, b"pps"),
nal(20, b"\xff" * 300),
)
class Body(io.BytesIO):
"""A response body that remembers how far it was read."""
read_to = 0
def read(self, size: int | None = -1) -> bytes:
data = super().read(size)
self.read_to = self.tell()
return data
class FullBodyAdapter(BaseAdapter):
"""Answers every request with 200 and the whole body, as a CDN that ignores the Range header."""
def __init__(self, bodies: dict[str, bytes]) -> None:
super().__init__()
self.bodies = bodies
self.raws: list[Body] = []
def send(self, request: requests.PreparedRequest, **kwargs: Any) -> requests.Response:
response = requests.Response()
response.status_code = 200 if request.url in self.bodies else 404
response.raw = Body(self.bodies.get(str(request.url), b""))
response.url = str(request.url)
response.request = request
self.raws.append(response.raw)
return response
def close(self) -> None:
pass
def test_a_vivid_ts_track_with_a_local_playlist_and_a_cdn_that_ignores_range(tmp_path: Path) -> None:
cuva = sei(4, CUVA_T35 + b"\x00" * 16)
mastering = sei(137, b"\x01" * 24)
adapter = FullBodyAdapter(
{
"https://cdn.example/v/vivid.ts": ts_segment(
((0x24, b""), (0x0F, b"")), *access_unit(mastering, cuva), size=4 * PROBE_BYTES
),
"https://cdn.example/v/dv.ts": ts_segment(
((0x24, b"DOVI"),), *access_unit(mastering), size=4 * PROBE_BYTES
),
}
)
session = requests.Session()
session.mount("https://cdn.example/", adapter)
videos = []
for name, range_ in (("vivid", Video.Range.HDR10), ("dv", Video.Range.DV)):
playlist = tmp_path / f"{name}.m3u8"
playlist.write_text(f"#EXTM3U\n#EXTINF:6.0,\nhttps://cdn.example/v/{name}.ts\n#EXT-X-ENDLIST\n")
videos.append(
Video(
url=playlist.as_uri(),
language="zh",
descriptor=Video.Descriptor.HLS,
codec=Video.Codec.HEVC,
range_=range_,
width=3840,
height=2160,
from_file=playlist,
)
)
sdr = Video(url="https://cdn.example/v/sdr.m3u8", language="zh", codec=Video.Codec.HEVC, range_=Video.Range.SDR)
hdr10plus.probe_dynamic_hdr([*videos, sdr], session, log=logging.getLogger("test"), workers=2)
assert [v.range for v in (*videos, sdr)] == [Video.Range.VIVID, Video.Range.DV, Video.Range.SDR]
assert not videos[1].hdr10plus
assert len(adapter.raws) == 2 and all(raw.closed and raw.read_to <= PROBE_BYTES for raw in adapter.raws)
def test_hdr10plus_sei_in_a_ts_segment_makes_hdr10p() -> None:
data = ts_segment(((0x24, b""),), *access_unit(sei(4, HDR10PLUS_T35 + b"\x00" * 8)))
assert fragment_has_t35(data, HDR10PLUS_T35) is True
assert fragment_has_t35(data, CUVA_T35) is False
assert fragment_has_t35(ts_segment(((0x0F, b""),), *access_unit()), CUVA_T35) is None
def test_vvc_cuva_sei_is_found_in_ts_and_fmp4() -> None:
nals = (vvc_nal(14, b"vps"), vvc_sei(4, CUVA_T35 + b"\x00" * 8), vvc_nal(8, b"\xff" * 64))
for data in (ts_segment(((0x33, b""),), *nals), fragment(*nals)):
assert fragment_has_t35(data, CUVA_T35, vvc=True) is True
assert fragment_has_t35(data, CUVA_T35) is not True
assert fragment_has_t35(fragment(vvc_nal(8, b"\xff"), vvc_sei(4, CUVA_T35)), CUVA_T35, vvc=True) is False
def test_a_vvc_hdr10_track_is_probed(monkeypatch: pytest.MonkeyPatch) -> None:
serve_segments(monkeypatch, {"v": fragment(vvc_sei(4, CUVA_T35 + b"\x00" * 8), vvc_nal(8, b"\xff" * 64))})
video = hevc("v", 2160)
video.codec = Video.Codec.VVC
hdr10plus.probe_dynamic_hdr([video], None, log=logging.getLogger("test"), workers=1) # type: ignore[arg-type]
assert video.range == Video.Range.VIVID
@pytest.mark.parametrize(
("byte_range", "accept_200", "expected"),
[("bytes=0-3", False, None), ("bytes=0-3", True, b"0123"), ("bytes=4-7", True, None)],
)
def test_ranged_get_takes_a_200_body_only_when_accepted(
byte_range: str, accept_200: bool, expected: bytes | None
) -> None:
adapter = FullBodyAdapter({"https://cdn.example/a.ts": b"0123456789"})
session = requests.Session()
session.mount("https://cdn.example/", adapter)
assert ranged_get("https://cdn.example/a.ts", session, byte_range, accept_200) == expected
def test_unspecified_nal_types_before_the_sei_do_not_end_the_fmp4_walk() -> None:
assert fragment_has_t35(fragment(*access_unit(sei(4, CUVA_T35 + b"\x00" * 8))), CUVA_T35) is True
def test_a_t35_message_after_a_payload_type_128_message_is_found() -> None:
sop = bytes([128, 2, 0x11, 0x22])
t35 = bytes([4, len(CUVA_T35) + 4]) + CUVA_T35 + b"\x00" * 4
data = nal(39, sop + t35 + b"\x80")
assert fragment_has_t35(fragment(data, nal(1, b"\xff")), CUVA_T35) is True
def test_hevc_and_vvc_tracks_are_separate_ladders(monkeypatch: pytest.MonkeyPatch) -> None:
videos = [hevc(f"v{i}{mark}", 2160 - 100 * i, 100 - i) for i, mark in enumerate("++-++")]
videos[2].codec = Video.Codec.VVC
assert len(probe(monkeypatch, videos)) == 5
assert ranges(videos) == "++-++"