mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-02 22:15:12 +00:00
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:
@@ -568,7 +568,7 @@ for a thorough demonstration.
|
|||||||
HDR10+ is a **bitstream (SEI)** feature, and many manifests label an HDR10+
|
HDR10+ is a **bitstream (SEI)** feature, and many manifests label an HDR10+
|
||||||
variant as plain HDR10. Before unshackle lists or selects tracks, the
|
variant as plain HDR10. Before unshackle lists or selects tracks, the
|
||||||
[`hdr10plus_probe`](../reference/configuration/download.md#hdr10plus_probe)
|
[`hdr10plus_probe`](../reference/configuration/download.md#hdr10plus_probe)
|
||||||
reads the first fragment of each HEVC HDR10 track and changes `video.range` to
|
reads the first fragment of each HEVC and VVC HDR10 track and changes `video.range` to
|
||||||
HDR10+ when the fragment carries HDR10+ metadata. Set `video.range` yourself
|
HDR10+ when the fragment carries HDR10+ metadata. Set `video.range` yourself
|
||||||
only when the probe cannot read the fragment, for example an ISM track whose
|
only when the probe cannot read the fragment, for example an ISM track whose
|
||||||
SEI is encrypted, or when the platform gives a reliable signal of its own.
|
SEI is encrypted, or when the platform gives a reliable signal of its own.
|
||||||
|
|||||||
@@ -463,7 +463,8 @@ dual_multi_mode: strict
|
|||||||
- **Type:** `bool` · **Default:** `true`
|
- **Type:** `bool` · **Default:** `true`
|
||||||
|
|
||||||
Find the HDR10+ tracks that a service labels as HDR10. Before unshackle lists or selects tracks, it
|
Find the HDR10+ tracks that a service labels as HDR10. Before unshackle lists or selects tracks, it
|
||||||
reads the first fragment of HEVC HDR10 tracks from DASH, HLS fMP4 and one-file sources. A track
|
reads the first fragment of HEVC and VVC (H.266) HDR10 tracks from DASH, HLS (fMP4 and MPEG-TS) and one-file
|
||||||
|
sources. A track
|
||||||
whose first frame carries HDR10+ (SMPTE ST 2094-40) metadata becomes `HDR10P`. Then `-r HDR10P`,
|
whose first frame carries HDR10+ (SMPTE ST 2094-40) metadata becomes `HDR10P`. Then `-r HDR10P`,
|
||||||
`--list` and [`--generate-dv`](../../guide/downloading.md#dolby-vision-without-a-dv-track) use it.
|
`--list` and [`--generate-dv`](../../guide/downloading.md#dolby-vision-without-a-dv-track) use it.
|
||||||
|
|
||||||
@@ -482,17 +483,19 @@ probes the two highest and the two lowest bitrates first:
|
|||||||
| Some carry HDR10+ | The title has HDR10 and HDR10+ encodes side by side, so unshackle probes every track. |
|
| Some carry HDR10+ | The title has HDR10 and HDR10+ encodes side by side, so unshackle probes every track. |
|
||||||
| None carry HDR10+ | Every track stays `HDR10`. |
|
| None carry HDR10+ | Every track stays `HDR10`. |
|
||||||
|
|
||||||
The probe also finds HDR Vivid in HEVC HDR10 and HLG tracks. A track becomes `VIVID`, so
|
The probe also finds HDR Vivid in HEVC and VVC 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
|
`-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`,
|
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
|
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`
|
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
|
registration or `stream_type` `0xD5` gives `Audio Vivid`. In an MPEG-TS segment, the probe reads the SEI of the
|
||||||
MPEG-TS track.
|
first video frame, so it also finds HDR10+ and HDR Vivid metadata in a track with no `cuvv` registration.
|
||||||
|
|
||||||
A probe that fails, or a fragment whose metadata is encrypted, keeps the label from the service.
|
A probe that fails, or a fragment whose metadata is encrypted, keeps the label from the service.
|
||||||
unshackle does not probe ISM tracks. Each probe makes one to three small requests: the 64 KiB
|
unshackle does not probe ISM tracks. Each probe makes one to three small requests: the 64 KiB
|
||||||
fragment, plus the playlist of an HLS track or the header of a one-file track. The probes run in
|
fragment, plus the playlist of an HLS track or the header of a one-file track. An HLS playlist that the service
|
||||||
|
saved as a local file needs no request. When a server sends the whole file for a request from byte 0, unshackle
|
||||||
|
reads only the first 64 KiB and closes the connection. The probes run in
|
||||||
parallel, with no more at a time than `--workers` (or `dl.workers`) sets for a track download.
|
parallel, with no more at a time than `--workers` (or `dl.workers`) sets for a track download.
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
|
|||||||
@@ -5,22 +5,12 @@ from typing import Any
|
|||||||
|
|
||||||
from pymediainfo import MediaInfo
|
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.commands.dl import take_unmuxable_audio
|
||||||
from unshackle.core.placement import no_mux_extension, track_file_suffix
|
from unshackle.core.placement import no_mux_extension, track_file_suffix
|
||||||
from unshackle.core.tracks import Audio, Tracks, Video
|
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:
|
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."""
|
"""A PAT, a PMT with one Audio Vivid stream on PID 0x100, and one PES per frame."""
|
||||||
data = ts((0xD5, b""))
|
data = ts((0xD5, b""))
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
|
import io
|
||||||
import logging
|
import logging
|
||||||
import struct
|
import struct
|
||||||
|
from pathlib import Path
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
import requests
|
||||||
|
from requests.adapters import BaseAdapter
|
||||||
|
|
||||||
from tests.core.test_export_name import video
|
from tests.core.test_export_name import video
|
||||||
from unshackle.core.config import Config, config
|
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.remote_service import RemoteService
|
||||||
from unshackle.core.tracks import Audio, Video
|
from unshackle.core.tracks import Audio, Video
|
||||||
from unshackle.core.utils import hdr10plus
|
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
|
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()
|
return video.id[-1].encode()
|
||||||
|
|
||||||
monkeypatch.setattr(hdr10plus, "first_fragment", fake_fragment)
|
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]
|
hdr10plus.probe_dynamic_hdr(videos, None, log=logging.getLogger("test"), workers=4) # type: ignore[arg-type]
|
||||||
return probed
|
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))
|
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
|
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("-"))
|
start, end = (int(x) for x in byte_range.removeprefix("bytes=").split("-"))
|
||||||
return data[start : end + 1]
|
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:
|
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'
|
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))
|
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]
|
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:
|
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))
|
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
|
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:
|
def fake_get(url: str, session: Any, byte_range: str, accept_200: bool) -> bytes:
|
||||||
requests.append(byte_range)
|
ranges_asked.append(byte_range)
|
||||||
return data
|
return data
|
||||||
|
|
||||||
monkeypatch.setattr(hdr10plus, "first_segment", lambda track, session: ("https://cdn/v.mp4", 0))
|
monkeypatch.setattr(hdr10plus, "first_segment", lambda track, session: ("https://cdn/v.mp4", 0))
|
||||||
monkeypatch.setattr(hdr10plus, "ranged_get", fake_get)
|
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 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:
|
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:
|
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."""
|
"""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, "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:
|
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:
|
def test_audio_without_a_codec_takes_it_from_the_ts_stream_type(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
fetched: list[tuple[str, str]] = []
|
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))
|
fetched.append((url, byte_range))
|
||||||
return ts((0xD5, b""))
|
return ts((0xD5, b""))
|
||||||
|
|
||||||
@@ -349,3 +354,177 @@ def test_probed_tracks_probes_codecless_audio_without_video(monkeypatch: pytest.
|
|||||||
service.session = None
|
service.session = None
|
||||||
hdr10plus.probed_tracks(service, None, workers=2) # type: ignore[arg-type]
|
hdr10plus.probed_tracks(service, None, workers=2) # type: ignore[arg-type]
|
||||||
assert calls == [1]
|
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) == "++-++"
|
||||||
|
|||||||
@@ -432,14 +432,38 @@ def ffprobe_duration(url: str, session: Session | RnetSession, *, log: logging.L
|
|||||||
return duration
|
return duration
|
||||||
|
|
||||||
|
|
||||||
def ranged_get(url: str, session: Session | RnetSession, byte_range: str) -> bytes | None:
|
def ranged_get(url: str, session: Session | RnetSession, byte_range: str, accept_200: bool = False) -> bytes | None:
|
||||||
"""Fetch a byte range, only accepting a real 206 partial response (never a full 200 body)."""
|
"""Fetch a byte range, only accepting a real 206 partial response.
|
||||||
|
|
||||||
|
With ``accept_200``, a 200 answer to a range from byte 0 gives the start of its body up to the range end. The
|
||||||
|
read streams the body and closes the response at that point.
|
||||||
|
"""
|
||||||
try:
|
try:
|
||||||
res = unrecorded(session, "get", url, headers={"Range": byte_range}, timeout=PROBE_TIMEOUT)
|
res = unrecorded(
|
||||||
if getattr(res, "status_code", 0) != 206:
|
session,
|
||||||
return None
|
"get",
|
||||||
content = getattr(res, "content", None)
|
url,
|
||||||
return content if content else None
|
headers={"Range": byte_range},
|
||||||
|
timeout=PROBE_TIMEOUT,
|
||||||
|
stream=accept_200,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
status = getattr(res, "status_code", 0)
|
||||||
|
if accept_200 and status == 200 and byte_range.startswith("bytes=0-"):
|
||||||
|
size = int(byte_range.partition("-")[2]) + 1
|
||||||
|
body = bytearray()
|
||||||
|
for chunk in res.iter_content(size):
|
||||||
|
body += chunk
|
||||||
|
if len(body) >= size:
|
||||||
|
break
|
||||||
|
return bytes(body[:size]) or None
|
||||||
|
if status != 206:
|
||||||
|
return None
|
||||||
|
content = getattr(res, "content", None)
|
||||||
|
return content if content else None
|
||||||
|
finally:
|
||||||
|
if accept_200:
|
||||||
|
res.close()
|
||||||
except Exception:
|
except Exception:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import logging
|
import logging
|
||||||
import struct
|
import struct
|
||||||
from collections.abc import Callable
|
from collections.abc import Callable, Iterator
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
from typing import TYPE_CHECKING, TypeVar
|
from typing import TYPE_CHECKING, TypeVar
|
||||||
from urllib.parse import urljoin
|
from urllib.parse import urljoin
|
||||||
@@ -57,6 +57,13 @@ def ts_payload(packet: bytes) -> bytes:
|
|||||||
return packet[5 + packet[4] if adaptation & 2 else 4 :] if adaptation & 1 else b""
|
return packet[5 + packet[4] if adaptation & 2 else 4 :] if adaptation & 1 else b""
|
||||||
|
|
||||||
|
|
||||||
|
def ts_packets(data: bytes) -> Iterator[bytes]:
|
||||||
|
"""The 188-byte packets of ``data`` that start with the sync byte."""
|
||||||
|
for pos in range(0, len(data) - TS_PACKET + 1, TS_PACKET):
|
||||||
|
if data[pos] == 0x47:
|
||||||
|
yield data[pos : pos + TS_PACKET]
|
||||||
|
|
||||||
|
|
||||||
def ts_pmt(data: bytes) -> list[tuple[int, int, bytes]] | None:
|
def ts_pmt(data: bytes) -> list[tuple[int, int, bytes]] | None:
|
||||||
"""The PID, ``stream_type`` and registration format identifier of each PMT entry, or None without a PMT.
|
"""The PID, ``stream_type`` and registration format identifier of each PMT entry, or None without a PMT.
|
||||||
|
|
||||||
@@ -77,9 +84,8 @@ def ts_pmt(data: bytes) -> list[tuple[int, int, bytes]] | None:
|
|||||||
return body if len(body) >= 12 and body[0] == table_id else b""
|
return body if len(body) >= 12 and body[0] == table_id else b""
|
||||||
|
|
||||||
pmt_pid = None
|
pmt_pid = None
|
||||||
for pos in range(0, len(data) - TS_PACKET + 1, TS_PACKET):
|
for packet in ts_packets(data):
|
||||||
packet = data[pos : pos + TS_PACKET]
|
if not packet[1] & 0x40:
|
||||||
if packet[0] != 0x47 or not packet[1] & 0x40:
|
|
||||||
continue
|
continue
|
||||||
if ts_pid(packet) == 0 and pmt_pid is None:
|
if ts_pid(packet) == 0 and pmt_pid is None:
|
||||||
pat = section(packet, 0x00)
|
pat = section(packet, 0x00)
|
||||||
@@ -113,11 +119,25 @@ def sei_number(rbsp: bytes, i: int) -> tuple[int | None, int]:
|
|||||||
return value + rbsp[i], i + 1
|
return value + rbsp[i], i + 1
|
||||||
|
|
||||||
|
|
||||||
|
def ts_elementary(data: bytes, pid: int) -> bytes:
|
||||||
|
"""The payload bytes of ``pid`` in the packets of ``data``, joined and without their PES headers."""
|
||||||
|
stream = bytearray()
|
||||||
|
for packet in ts_packets(data):
|
||||||
|
if ts_pid(packet) != pid:
|
||||||
|
continue
|
||||||
|
payload = ts_payload(packet)
|
||||||
|
if packet[1] & 0x40 and payload[:3] == b"\x00\x00\x01" and len(payload) >= 9:
|
||||||
|
payload = payload[9 + payload[8] :]
|
||||||
|
stream += payload
|
||||||
|
return bytes(stream)
|
||||||
|
|
||||||
|
|
||||||
def sei_has_t35(nal: bytes, t35: bytes) -> bool:
|
def sei_has_t35(nal: bytes, t35: bytes) -> bool:
|
||||||
"""Whether an HEVC SEI NAL holds the T.35 message that ``t35`` starts."""
|
"""Whether an HEVC or VVC SEI NAL holds the T.35 message that ``t35`` starts."""
|
||||||
rbsp = remove_emulation_prevention(nal[2:])
|
rbsp = remove_emulation_prevention(nal[2:])
|
||||||
|
end = len(rbsp.rstrip(b"\x00")) - 1
|
||||||
i = 0
|
i = 0
|
||||||
while i < len(rbsp) and rbsp[i] != 0x80:
|
while i < end:
|
||||||
payload_type, i = sei_number(rbsp, i)
|
payload_type, i = sei_number(rbsp, i)
|
||||||
payload_size, i = sei_number(rbsp, i)
|
payload_size, i = sei_number(rbsp, i)
|
||||||
if payload_type is None or payload_size is None:
|
if payload_type is None or payload_size is None:
|
||||||
@@ -128,32 +148,42 @@ def sei_has_t35(nal: bytes, t35: bytes) -> bool:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def fragment_has_t35(data: bytes, t35: bytes) -> bool | None:
|
def mdat_nals(data: bytes) -> Iterator[bytes]:
|
||||||
"""Whether the first sample of an fMP4 fragment carries the T.35 SEI that ``t35`` starts, or None when the bytes
|
"""The length-prefixed NALs of an fMP4 mdat."""
|
||||||
cannot tell. ``HDR10PLUS_T35`` finds HDR10+, ``CUVA_T35`` HDR Vivid.
|
# 4-byte NAL lengths: reading lengthSizeMinusOne from hvcC would cost an init-segment fetch
|
||||||
|
mdat = find_box(data, 0, len(data), b"mdat")
|
||||||
|
pos = mdat[0] if mdat else len(data)
|
||||||
|
while pos + 6 <= len(data):
|
||||||
|
size = struct.unpack(">I", data[pos : pos + 4])[0]
|
||||||
|
yield data[pos + 4 : pos + 4 + size]
|
||||||
|
pos += 4 + size
|
||||||
|
|
||||||
|
|
||||||
|
def ts_nals(data: bytes) -> Iterator[bytes]:
|
||||||
|
"""The Annex-B NALs of the HEVC or VVC stream that the PMT of an MPEG-TS segment lists."""
|
||||||
|
pid = next((pid for pid, stream_type, _ in ts_pmt(data) or [] if stream_type in (0x24, 0x33)), None)
|
||||||
|
stream = b"" if pid is None else ts_elementary(data, pid)
|
||||||
|
yield from stream.split(b"\x00\x00\x01")[1:]
|
||||||
|
|
||||||
|
|
||||||
|
def fragment_has_t35(data: bytes, t35: bytes, vvc: bool = False) -> bool | None:
|
||||||
|
"""Whether the first sample of an fMP4 fragment, or the first access unit of an MPEG-TS segment, carries the
|
||||||
|
T.35 SEI that ``t35`` starts, or None when the bytes cannot tell. ``HDR10PLUS_T35`` finds HDR10+,
|
||||||
|
``CUVA_T35`` HDR Vivid, and ``vvc`` reads H.266 NAL headers.
|
||||||
|
|
||||||
The walk ends at the first VCL NAL, because a prefix SEI comes before it. CENC and cbcs keep
|
The walk ends at the first VCL NAL, because a prefix SEI comes before it. CENC and cbcs keep
|
||||||
non-VCL NALs and every NAL length in the clear, so this needs no content key. A sample that is
|
non-VCL NALs and every NAL length in the clear, so this needs no content key. A sample that is
|
||||||
encrypted whole can read as False as well as None; both leave the label alone.
|
encrypted whole can read as False as well as None; both leave the label alone.
|
||||||
"""
|
"""
|
||||||
# 4-byte NAL lengths: reading lengthSizeMinusOne from hvcC would cost an init-segment fetch
|
sei, vcl_end = (23, 12) if vvc else (39, 32)
|
||||||
mdat = find_box(data, 0, len(data), b"mdat")
|
for nal in ts_nals(data) if is_ts(data) else mdat_nals(data):
|
||||||
if not mdat:
|
if len(nal) < 2 or nal[0] & 0x80 or not nal[1] & 0x07:
|
||||||
return None
|
return None
|
||||||
pos = mdat[0]
|
kind = nal[1] >> 3 if vvc else nal[0] >> 1
|
||||||
while pos + 6 <= len(data):
|
if kind < vcl_end:
|
||||||
size = struct.unpack(">I", data[pos : pos + 4])[0]
|
|
||||||
nal_type = (data[pos + 4] >> 1) & 0x3F
|
|
||||||
if size < 2 or nal_type >= 48:
|
|
||||||
return None # not a NAL: the sample is fully encrypted or the walk lost sync
|
|
||||||
if nal_type < 32:
|
|
||||||
return False
|
return False
|
||||||
if nal_type == 39:
|
if kind == sei and sei_has_t35(nal, t35):
|
||||||
if pos + 4 + size > len(data):
|
return True
|
||||||
return None
|
|
||||||
if sei_has_t35(data[pos + 4 : pos + 4 + size], t35):
|
|
||||||
return True
|
|
||||||
pos += 4 + size
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
@@ -181,11 +211,15 @@ def first_segment(track: Track, session: Session | RnetSession) -> tuple[str, in
|
|||||||
seg_url, byte_range = segments[0]
|
seg_url, byte_range = segments[0]
|
||||||
return seg_url, int((byte_range or "").partition("-")[0] or 0)
|
return seg_url, int((byte_range or "").partition("-")[0] or 0)
|
||||||
if track.descriptor == Track.Descriptor.HLS:
|
if track.descriptor == Track.Descriptor.HLS:
|
||||||
res = session.get(url, timeout=PROBE_TIMEOUT)
|
if track.from_file:
|
||||||
if getattr(res, "status_code", 0) != 200:
|
text = track.from_file.read_text(encoding="utf-8")
|
||||||
return None
|
else:
|
||||||
|
res = session.get(url, timeout=PROBE_TIMEOUT)
|
||||||
|
if getattr(res, "status_code", 0) != 200:
|
||||||
|
return None
|
||||||
|
text = utf8_text(res)
|
||||||
offset = 0
|
offset = 0
|
||||||
for line in utf8_text(res).splitlines():
|
for line in text.splitlines():
|
||||||
line = line.strip()
|
line = line.strip()
|
||||||
if line.startswith("#EXT-X-BYTERANGE:") and "@" in line:
|
if line.startswith("#EXT-X-BYTERANGE:") and "@" in line:
|
||||||
offset = int(line.rpartition("@")[2])
|
offset = int(line.rpartition("@")[2])
|
||||||
@@ -206,7 +240,7 @@ def first_fragment(track: Track, session: Session | RnetSession) -> bytes | None
|
|||||||
# A one-file track opens with ftyp, moov and sidx, which can outgrow PROBE_BYTES. Fetch again past
|
# A one-file track opens with ftyp, moov and sidx, which can outgrow PROBE_BYTES. Fetch again past
|
||||||
# them only when the fragment does not start inside this window.
|
# them only when the fragment does not start inside this window.
|
||||||
for _ in range(4):
|
for _ in range(4):
|
||||||
data = ranged_get(url, session, f"bytes={start}-{start + PROBE_BYTES - 1}")
|
data = ranged_get(url, session, f"bytes={start}-{start + PROBE_BYTES - 1}", accept_200=True)
|
||||||
if not data:
|
if not data:
|
||||||
return None
|
return None
|
||||||
if is_ts(data):
|
if is_ts(data):
|
||||||
@@ -230,13 +264,13 @@ def probe_dynamic_hdr(
|
|||||||
workers: int,
|
workers: int,
|
||||||
on_start: Callable[[], None] | None = None,
|
on_start: Callable[[], None] | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Relabel HEVC tracks by the dynamic HDR metadata of their first sample, and flag DV tracks with HDR10+.
|
"""Relabel HEVC and VVC 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,
|
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, and an HLG one gets ``hlg_base``; ``PROBED_RANGES`` holds which label
|
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
|
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
|
are unchanged. HDR10, HLG and DV are separate ladders, and so are HEVC and VVC. A ladder with one track per
|
||||||
both ends first. Two tracks at one resolution can be an HDR10 and an HDR10+ encode side by side, so such a
|
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.
|
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
|
A failed probe never changes a label. ``workers`` caps the probes in flight, and ``on_start`` runs once
|
||||||
before the first.
|
before the first.
|
||||||
@@ -246,28 +280,29 @@ def probe_dynamic_hdr(
|
|||||||
|
|
||||||
ladders = [
|
ladders = [
|
||||||
sorted(
|
sorted(
|
||||||
(v for v in videos if v.range == range_ and v.codec == Video.Codec.HEVC),
|
(v for v in videos if v.range == range_ and v.codec == codec),
|
||||||
key=lambda v: v.bitrate or 0,
|
key=lambda v: v.bitrate or 0,
|
||||||
reverse=True,
|
reverse=True,
|
||||||
)
|
)
|
||||||
for range_ in (*PROBED_RANGES, Video.Range.DV)
|
for range_ in (*PROBED_RANGES, Video.Range.DV)
|
||||||
|
for codec in (Video.Codec.HEVC, Video.Codec.VVC)
|
||||||
]
|
]
|
||||||
if any(ladders) and on_start:
|
if any(ladders) and on_start:
|
||||||
on_start()
|
on_start()
|
||||||
|
|
||||||
def proven(data: bytes | None) -> Video.Range | None:
|
def proven(data: bytes | None, vvc: bool) -> Video.Range | None:
|
||||||
if not data:
|
if not data:
|
||||||
return None
|
return None
|
||||||
if is_ts(data):
|
if is_ts(data) and any(reg == b"cuvv" for _, reg in ts_streams(data) or []):
|
||||||
return Video.Range.VIVID if any(reg == b"cuvv" for _, reg in ts_streams(data) or []) else None
|
|
||||||
if fragment_has_t35(data, CUVA_T35):
|
|
||||||
return Video.Range.VIVID
|
return Video.Range.VIVID
|
||||||
return Video.Range.HDR10P if fragment_has_t35(data, HDR10PLUS_T35) else None
|
if fragment_has_t35(data, CUVA_T35, vvc):
|
||||||
|
return Video.Range.VIVID
|
||||||
|
return Video.Range.HDR10P if fragment_has_t35(data, HDR10PLUS_T35, vvc) else None
|
||||||
|
|
||||||
def probe(video: Video) -> Video.Range | None:
|
def probe(video: Video) -> Video.Range | None:
|
||||||
"""The range the first segment proves (HDR10P or VIVID), else None."""
|
"""The range the first segment proves (HDR10P or VIVID), else None."""
|
||||||
try:
|
try:
|
||||||
found = proven(first_fragment(video, video.session or session))
|
found = proven(first_fragment(video, video.session or session), video.codec == Video.Codec.VVC)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log.debug(f"{video.id}: dynamic HDR probe failed ({e})")
|
log.debug(f"{video.id}: dynamic HDR probe failed ({e})")
|
||||||
return None
|
return None
|
||||||
@@ -317,7 +352,7 @@ def probe_audio_codecs(
|
|||||||
track_session = track.session or session
|
track_session = track.session or session
|
||||||
segment = first_segment(track, track_session)
|
segment = first_segment(track, track_session)
|
||||||
data = segment and ranged_get(
|
data = segment and ranged_get(
|
||||||
segment[0], track_session, f"bytes={segment[1]}-{segment[1] + TS_PROBE_BYTES - 1}"
|
segment[0], track_session, f"bytes={segment[1]}-{segment[1] + TS_PROBE_BYTES - 1}", accept_200=True
|
||||||
)
|
)
|
||||||
streams = (ts_streams(data) if data and is_ts(data) else None) or []
|
streams = (ts_streams(data) if data and is_ts(data) else None) or []
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|||||||
Reference in New Issue
Block a user