forked from kenzuya/unshackle
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:
@@ -432,14 +432,38 @@ def ffprobe_duration(url: str, session: Session | RnetSession, *, log: logging.L
|
||||
return duration
|
||||
|
||||
|
||||
def ranged_get(url: str, session: Session | RnetSession, byte_range: str) -> bytes | None:
|
||||
"""Fetch a byte range, only accepting a real 206 partial response (never a full 200 body)."""
|
||||
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.
|
||||
|
||||
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:
|
||||
res = unrecorded(session, "get", url, headers={"Range": byte_range}, timeout=PROBE_TIMEOUT)
|
||||
if getattr(res, "status_code", 0) != 206:
|
||||
return None
|
||||
content = getattr(res, "content", None)
|
||||
return content if content else None
|
||||
res = unrecorded(
|
||||
session,
|
||||
"get",
|
||||
url,
|
||||
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:
|
||||
return None
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import struct
|
||||
from collections.abc import Callable
|
||||
from collections.abc import Callable, Iterator
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from typing import TYPE_CHECKING, TypeVar
|
||||
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""
|
||||
|
||||
|
||||
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:
|
||||
"""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""
|
||||
|
||||
pmt_pid = None
|
||||
for pos in range(0, len(data) - TS_PACKET + 1, TS_PACKET):
|
||||
packet = data[pos : pos + TS_PACKET]
|
||||
if packet[0] != 0x47 or not packet[1] & 0x40:
|
||||
for packet in ts_packets(data):
|
||||
if not packet[1] & 0x40:
|
||||
continue
|
||||
if ts_pid(packet) == 0 and pmt_pid is None:
|
||||
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
|
||||
|
||||
|
||||
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:
|
||||
"""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:])
|
||||
end = len(rbsp.rstrip(b"\x00")) - 1
|
||||
i = 0
|
||||
while i < len(rbsp) and rbsp[i] != 0x80:
|
||||
while i < end:
|
||||
payload_type, i = sei_number(rbsp, i)
|
||||
payload_size, i = sei_number(rbsp, i)
|
||||
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
|
||||
|
||||
|
||||
def fragment_has_t35(data: bytes, t35: bytes) -> bool | None:
|
||||
"""Whether the first sample of an fMP4 fragment carries the T.35 SEI that ``t35`` starts, or None when the bytes
|
||||
cannot tell. ``HDR10PLUS_T35`` finds HDR10+, ``CUVA_T35`` HDR Vivid.
|
||||
def mdat_nals(data: bytes) -> Iterator[bytes]:
|
||||
"""The length-prefixed NALs of an fMP4 mdat."""
|
||||
# 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
|
||||
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.
|
||||
"""
|
||||
# 4-byte NAL lengths: reading lengthSizeMinusOne from hvcC would cost an init-segment fetch
|
||||
mdat = find_box(data, 0, len(data), b"mdat")
|
||||
if not mdat:
|
||||
return None
|
||||
pos = mdat[0]
|
||||
while pos + 6 <= len(data):
|
||||
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:
|
||||
sei, vcl_end = (23, 12) if vvc else (39, 32)
|
||||
for nal in ts_nals(data) if is_ts(data) else mdat_nals(data):
|
||||
if len(nal) < 2 or nal[0] & 0x80 or not nal[1] & 0x07:
|
||||
return None
|
||||
kind = nal[1] >> 3 if vvc else nal[0] >> 1
|
||||
if kind < vcl_end:
|
||||
return False
|
||||
if nal_type == 39:
|
||||
if pos + 4 + size > len(data):
|
||||
return None
|
||||
if sei_has_t35(data[pos + 4 : pos + 4 + size], t35):
|
||||
return True
|
||||
pos += 4 + size
|
||||
if kind == sei and sei_has_t35(nal, t35):
|
||||
return True
|
||||
return None
|
||||
|
||||
|
||||
@@ -181,11 +211,15 @@ def first_segment(track: Track, session: Session | RnetSession) -> tuple[str, in
|
||||
seg_url, byte_range = segments[0]
|
||||
return seg_url, int((byte_range or "").partition("-")[0] or 0)
|
||||
if track.descriptor == Track.Descriptor.HLS:
|
||||
res = session.get(url, timeout=PROBE_TIMEOUT)
|
||||
if getattr(res, "status_code", 0) != 200:
|
||||
return None
|
||||
if track.from_file:
|
||||
text = track.from_file.read_text(encoding="utf-8")
|
||||
else:
|
||||
res = session.get(url, timeout=PROBE_TIMEOUT)
|
||||
if getattr(res, "status_code", 0) != 200:
|
||||
return None
|
||||
text = utf8_text(res)
|
||||
offset = 0
|
||||
for line in utf8_text(res).splitlines():
|
||||
for line in text.splitlines():
|
||||
line = line.strip()
|
||||
if line.startswith("#EXT-X-BYTERANGE:") and "@" in line:
|
||||
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
|
||||
# them only when the fragment does not start inside this window.
|
||||
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:
|
||||
return None
|
||||
if is_ts(data):
|
||||
@@ -230,13 +264,13 @@ def probe_dynamic_hdr(
|
||||
workers: int,
|
||||
on_start: Callable[[], 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,
|
||||
makes an HDR10 or HLG track VIVID, and an HLG one gets ``hlg_base``; ``PROBED_RANGES`` holds which label
|
||||
each range takes. A DV track keeps its DV range and gets ``hdr10plus`` set, so selection and hybrid pairing
|
||||
are unchanged. HDR10, HLG and DV are separate ladders. A ladder with one track per resolution is sampled at
|
||||
both ends first. Two tracks at one resolution can be an HDR10 and an HDR10+ encode side by side, so such a
|
||||
are unchanged. HDR10, HLG and DV are separate ladders, and so are HEVC and VVC. A ladder with one track per
|
||||
resolution is sampled at both ends first. Two tracks at one resolution can be an HDR10 and an HDR10+ encode side by side, so such a
|
||||
ladder is probed whole. The rules are in the ``hdr10plus_probe`` section of docs/reference/configuration/download.md.
|
||||
A failed probe never changes a label. ``workers`` caps the probes in flight, and ``on_start`` runs once
|
||||
before the first.
|
||||
@@ -246,28 +280,29 @@ def probe_dynamic_hdr(
|
||||
|
||||
ladders = [
|
||||
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,
|
||||
reverse=True,
|
||||
)
|
||||
for range_ in (*PROBED_RANGES, Video.Range.DV)
|
||||
for codec in (Video.Codec.HEVC, Video.Codec.VVC)
|
||||
]
|
||||
if any(ladders) and 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:
|
||||
return None
|
||||
if is_ts(data):
|
||||
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):
|
||||
if is_ts(data) and any(reg == b"cuvv" for _, reg in ts_streams(data) or []):
|
||||
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:
|
||||
"""The range the first segment proves (HDR10P or VIVID), else None."""
|
||||
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:
|
||||
log.debug(f"{video.id}: dynamic HDR probe failed ({e})")
|
||||
return None
|
||||
@@ -317,7 +352,7 @@ def probe_audio_codecs(
|
||||
track_session = track.session or session
|
||||
segment = first_segment(track, track_session)
|
||||
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 []
|
||||
except Exception as e:
|
||||
|
||||
Reference in New Issue
Block a user