fix(ism): repair synthesized init and verify fragments decrypted

UNITY_MATRIX emitted 11 int32s instead of 9, oversizing mvhd/tkhd so pymp4 desynced and fTTML subtitles yielded no cues. Also rewrites PIFF senc to CENC so shaka can decrypt Smooth, labels HEV1 as hev1, and raises when a fragment survives decryption still carrying a sample-encryption box.
This commit is contained in:
imSp4rky
2026-07-25 15:55:31 -06:00
parent b7029c343e
commit d60d8abf53
8 changed files with 609 additions and 12 deletions
+3 -1
View File
@@ -67,7 +67,7 @@ from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
from unshackle.core.tracks.attachment import Attachment
from unshackle.core.tracks.dv_fixup import apply_dv_fixup
from unshackle.core.tracks.hybrid import Hybrid
from unshackle.core.tracks.track import has_encrypted_sample_entry
from unshackle.core.tracks.track import assert_fragments_decrypted, has_encrypted_sample_entry
from unshackle.core.utilities import (
find_font_with_fallbacks,
find_missing_langs,
@@ -3088,6 +3088,8 @@ class dl:
if drm and hasattr(drm, "decrypt"):
drm.decrypt(track.path)
if not isinstance(drm, MonaLisa):
# MonaLisa decrypts per segment; its decrypt() here is a no-op
assert_fragments_decrypted(track.path)
has_decrypted = True
events.emit(events.Types.TRACK_REPACKED, track=track)
else:
+2
View File
@@ -28,6 +28,7 @@ from unshackle.core.drm import DRM_T, ClearKeyCENC, PlayReady, Widevine
from unshackle.core.events import events
from unshackle.core.session import RnetSession
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video
from unshackle.core.tracks.track import assert_fragments_decrypted
from unshackle.core.utilities import is_close_match, log_event, try_ensure_utf8
from unshackle.core.utils.redact import safe_display_url
from unshackle.core.utils.xml import load_xml
@@ -570,6 +571,7 @@ class DASH:
if drm:
progress(downloaded="Decrypting", completed=0, total=None)
drm.decrypt(save_path)
assert_fragments_decrypted(save_path)
track.drm = None
events.emit(events.Types.TRACK_DECRYPTED, track=track, drm=drm, segment=None)
progress(downloaded="Decrypted", completed=100, total=100)
+2
View File
@@ -33,6 +33,7 @@ from unshackle.core.drm import DRM_T, ClearKey, MonaLisa, PlayReady, Widevine
from unshackle.core.events import events
from unshackle.core.session import RnetResponse, RnetSession
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video
from unshackle.core.tracks.track import assert_fragments_decrypted
from unshackle.core.utilities import get_extension, is_close_match, log_event, try_ensure_utf8
from unshackle.core.utils.redact import safe_display_url
from unshackle.core.utils.subprocess import log_tool_run
@@ -794,6 +795,7 @@ class HLS:
# with widevine we can merge all segments and decrypt once
merge(to=merged_path, via=files, delete=True, include_map_data=True)
drm.decrypt(merged_path)
assert_fragments_decrypted(merged_path)
merged_path.rename(decrypted_path)
else:
# with other drm we must decrypt separately and then merge them
+7
View File
@@ -22,11 +22,13 @@ from unshackle.core.events import events
from unshackle.core.manifests.ism_init import (
build_init_segment,
parse_codec_private_data_vui,
piff_senc_to_cenc,
read_per_sample_iv_size,
read_track_id,
)
from unshackle.core.session import RnetSession
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Track, Tracks, Video
from unshackle.core.tracks.track import assert_fragments_decrypted
from unshackle.core.utilities import log_event, try_ensure_utf8
from unshackle.core.utils.redact import safe_display_url
from unshackle.core.utils.xml import load_xml
@@ -521,6 +523,7 @@ class ISM:
init_segment = ISM._init_segment(track, session_drm, first_segment)
if init_segment:
f.write(init_segment)
iv_size = (read_per_sample_iv_size(first_segment) if session_drm and first_segment else None) or 8
for index, segment_file in enumerate(segments_to_merge):
if is_text_subtitle:
# first segment was already read for the init synthesis, reuse it
@@ -533,6 +536,9 @@ class ISM:
.encode("utf8")
)
f.write(segment_data)
elif session_drm:
segment_data = first_segment if index == 0 and first_segment else segment_file.read_bytes()
f.write(piff_senc_to_cenc(segment_data, iv_size))
elif index == 0 and first_segment:
f.write(first_segment)
else:
@@ -547,6 +553,7 @@ class ISM:
if session_drm:
progress(downloaded="Decrypting", completed=0, total=None)
session_drm.decrypt(save_path)
assert_fragments_decrypted(save_path)
track.drm = None
events.emit(events.Types.TRACK_DECRYPTED, track=track, drm=session_drm, segment=None)
progress(downloaded="Decrypted", completed=100, total=100)
+97 -11
View File
@@ -8,6 +8,10 @@ sends a ``moov``. The init box must be reconstructed from the manifest's
or decryptor such as shaka-packager can parse the stream. Ported from yt-dlp's
``write_piff_header`` and N_m3u8DL-RE's ``MSSMoovProcessor`` with HEVC, Dolby
Vision, EC-3, TTML and CENC (PIFF) support.
``piff_senc_to_cenc`` rewrites the fragments themselves, which neither port does:
shaka-packager cannot read the PIFF sample-encryption box, so its payload is
retagged as a standard ``senc``.
"""
from __future__ import annotations
@@ -28,13 +32,14 @@ u1616 = struct.Struct(">Hxx")
s32 = struct.Struct(">i")
# 3x3 transformation matrix (identity), as stored in tkhd/mvhd.
# Exactly 9 int32s; extras shift every field after it and desync pymp4.
UNITY_MATRIX = (
s32.pack(0x10000)
+ s32.pack(0) * 3
+ s32.pack(0) * 2
+ s32.pack(0)
+ s32.pack(0x10000)
+ s32.pack(0) * 2
+ s32.pack(0) * 2
+ s32.pack(0)
+ s32.pack(0x40000000)
)
@@ -308,7 +313,13 @@ def parse_codec_private_data_colour(fourcc: str, codec_private_data: bytes) -> O
def iter_boxes(data: bytes, start: int, end: int) -> Iterator[tuple[bytes, Optional[bytes], int, int]]:
"""Yield (type, uuid_usertype, payload_start, box_end) for each child box."""
"""Yield (type, uuid_usertype, payload_start, box_end) for each child box.
Stops silently at the first box whose declared size cannot be walked. A short
result therefore reports how far the walk got, and a caller counting survivors
should treat it as unverified. box_end may exceed end when the declared size
overruns; clamp it before slicing.
"""
offset = start
while offset + 8 <= end:
size = struct.unpack(">I", data[offset : offset + 4])[0]
@@ -319,7 +330,7 @@ def iter_boxes(data: bytes, start: int, end: int) -> Iterator[tuple[bytes, Optio
header = 16
if size == 0:
size = end - offset
if size < 8: # corrupt box header; stop rather than loop forever
if size < header: # size below the consumed header desyncs the walk; stop
return
usertype = None
if box_type == b"uuid" and offset + header + 16 <= end:
@@ -426,6 +437,74 @@ def read_per_sample_iv_size(fragment: bytes) -> Optional[int]:
return None
def piff_senc_to_cenc(fragment: bytes, iv_size: int = 8) -> bytes:
"""Rewrite a fragment's moof/traf PIFF sample-encryption uuid boxes as standard 'senc'.
shaka-packager does not consume the PIFF uuid form. It finds no per-sample IVs, falls
through to the constant-IV path, and aborts with "IV cannot be empty". mp4decrypt
accepts either form, and the payloads are identical once the optional override header
is stripped, so emitting 'senc' serves both decrypters.
The rewrite preserves length: bytes reclaimed from the uuid header become a 'free' box.
The moof's byte length must stay the same. trun's data_offset resolves against tfhd's
base_data_offset (the moof start only when that field is absent), so moving the sample
data misaligns decryption and yields plausible garbage with no error.
iv_size is the default_Per_Sample_IV_Size the init segment's tenc declares, read from
the first fragment by read_per_sample_iv_size. This function skips any fragment whose
override disagrees, since tenc is the only IV width a CENC decrypter consults and a
mismatch misparses every IV.
"""
out: Optional[bytearray] = None
limit = len(fragment)
trafs = [
(body, min(box_end, limit))
for moof_type, _, moof_body, moof_end in iter_boxes(fragment, 0, limit)
if moof_type == b"moof"
for box_type, _, body, box_end in iter_boxes(fragment, moof_body, min(moof_end, limit))
if box_type == b"traf"
]
for traf_body, traf_end in trafs:
# a second senc would leave the decrypter to choose between them
if any(bt == b"senc" for bt, _, _, _ in iter_boxes(fragment, traf_body, traf_end)):
continue
offset = traf_body
while offset + 8 <= traf_end:
size = struct.unpack(">I", fragment[offset : offset + 4])[0]
if size < 8 or offset + size > traf_end:
break
if (
size >= 28
and fragment[offset + 4 : offset + 8] == b"uuid"
and fragment[offset + 8 : offset + 24] == PIFF_SENC_UUID
):
version = fragment[offset + 24]
flags = int.from_bytes(fragment[offset + 25 : offset + 28], "big")
# flag 0x1 = PIFF override header: AlgorithmID(3) + IV_size(1) + KID(16)
strip = 20 if flags & 0x1 else 0
# AlgorithmID 2 is AES-CBC and a stray IV width misparses every IV; leave
# either alone so the decrypter fails loudly on a form it cannot handle
if (
strip
and (
size < 28 + strip # short-circuits before reading the override fields
or int.from_bytes(fragment[offset + 28 : offset + 31], "big") != 1
or fragment[offset + 31] != iv_size
)
):
offset += size
continue
if offset + 28 + strip <= offset + size:
senc = full_box(b"senc", version, flags & ~0x1, fragment[offset + 28 + strip : offset + size])
pad = size - len(senc)
if pad >= 8:
if out is None:
out = bytearray(fragment)
out[offset : offset + size] = senc + box(b"free", bytes(pad - 8))
offset += size
return bytes(out) if out is not None else fragment
def build_avcc(codec_private_data: bytes, nal_length_size: int = 4) -> bytes:
"""Build an avcC (AVC decoder config) box from SPS+PPS CodecPrivateData."""
nals = split_nal_units(codec_private_data)
@@ -582,7 +661,7 @@ def build_sinf(
schm = full_box(b"schm", 0, 0, b"cenc" + u32.pack(0x00010000))
tenc_payload = (
u8.pack(0) # reserved
+ u8.pack(0) # default_crypt_byte_block / skip_byte_block (cenc)
+ u8.pack(0) # reserved in v0 (crypt/skip nibbles are v1 only)
+ u8.pack(1) # default_isProtected
+ u8.pack(0 if constant_iv else iv_size) # default_Per_Sample_IV_Size
+ kid # default_KID (16 bytes)
@@ -616,8 +695,10 @@ def build_init_segment(
Build a complete ftyp + moov initialization segment.
stream_type: "video" | "audio" | "text".
fourcc: Smooth FourCC ("H264"/"AVC1"/"DAVC", "HVC1"/"HEV1", "DVHE"/"DVH1",
"AACL"/"AACH", "EC-3", "TTML").
fourcc: Smooth FourCC ("H264"/"AVC1"/"DAVC", "HVC1"/"HEV1"/"HEVC"/"H265",
"DVHE"/"DVH1", "AACL"/"AACH"/"AAC", "EC-3", "TTML"/"STPP"/"DFXP").
Only "HEV1" yields an hev1 sample entry; the rest of that group yield
hvc1, which requires its parameter sets in the sample entry.
codec_private_data: hex string from the manifest QualityLevel.
nal_length_size: manifest NALUnitLengthField (bytes per NAL length prefix).
kid: 16-byte default key id; when set, the sample entry is wrapped for CENC.
@@ -638,6 +719,7 @@ def build_init_segment(
ftyp = box(b"ftyp", b"isml" + u32.pack(1) + b"iso5" + b"iso6" + b"piff" + b"msdh")
# --- mvhd ---
# version 1: at the 10 MHz ISM timescale a 32-bit duration overflows after ~429s
mvhd = full_box(
b"mvhd",
1,
@@ -724,7 +806,10 @@ def build_init_segment(
codec_fourcc = b"avc1"
elif fourcc in ("HVC1", "HEV1", "HEVC", "H265"):
config_box = build_hvcc(cpd, nal_length_size)
codec_fourcc = b"hvc1"
# hev1 permits in-band parameter sets where hvc1 requires them in the
# sample entry, so relabelling hev1 as hvc1 misdescribes the stream
# (and the frma inside sinf).
codec_fourcc = b"hev1" if fourcc == "HEV1" else b"hvc1"
elif fourcc in ("DVHE", "DVH1"):
# Dolby Vision over HEVC: same hvcC config, dvh1 sample entry.
config_box = build_hvcc(cpd, nal_length_size)
@@ -773,9 +858,10 @@ def build_init_segment(
else:
raise NotImplementedError(f"Unsupported text FourCC: {fourcc}")
# Fragments may set tfhd sample_description_index=2 (server inits carry a second,
# identical entry). A lone entry leaves that dangling: mp4decrypt skips those
# fragments and demuxers stop after the first.
# Fragments may set tfhd sample_description_index=2. A lone entry leaves that
# dangling: mp4decrypt skips those fragments and demuxers stop after the first.
# We duplicate entry 1; a manifest carries one CodecPrivateData, so there is no
# second config to build. The server's larger second entry only repeats its VPS.
stsd = full_box(b"stsd", 0, 0, u32.pack(2) + sample_entry_box * 2)
# --- empty sample tables (fragmented: real samples live in moof/traf) ---
+105
View File
@@ -100,6 +100,110 @@ def has_encrypted_sample_entry(path: Path) -> bool:
return False
def _senc_protects_samples(buf: bytes, body: int, end: int) -> bool:
"""True if a senc/PIFF-uuid box describes protected samples.
An empty senc (sample_count 0) sits on a genuinely clear fragment, so treating it as
a skipped one would raise on a healthy file. Field order follows
read_per_sample_iv_size.
"""
flags = int.from_bytes(buf[body + 1 : body + 4], "big")
pos = body + 4 + (20 if flags & 0x1 else 0) # PIFF override: AlgorithmID(3)+IV_size(1)+KID(16)
if pos + 4 > end:
return False
return int.from_bytes(buf[pos : pos + 4], "big") > 0
def _moof_still_encrypted(moof: bytes) -> bool:
# structural walk: a 4CC byte scan collides with trun payload
from unshackle.core.manifests.ism_init import PIFF_SENC_UUID, iter_boxes
body = 16 if int.from_bytes(moof[:4], "big") == 1 else 8
for box_type, _, traf_body, traf_end in iter_boxes(moof, body, len(moof)):
if box_type != b"traf":
continue
for child, usertype, child_body, child_end in iter_boxes(moof, traf_body, traf_end):
if child == b"senc" or (child == b"uuid" and usertype == PIFF_SENC_UUID):
if _senc_protects_samples(moof, child_body, child_end):
return True
return False
def assert_fragments_decrypted(path: Path) -> None:
"""Raise if any fragment survived decryption still carrying a sample-encryption box.
mp4decrypt strips senc from every fragment it processes and leaves it on the ones it
skips, so a survivor marks a silent skip. One cause is a tfhd.sample_description_index
dangling past the stsd entry count, which mp4decrypt reports as success (exit 0, no
stderr) while leaving the payload as ciphertext. Unlike has_encrypted_sample_entry
(moov-scoped) this is fragment-scoped; the moov comes out clean in that failure.
The guarantee runs in one direction: a survivor proves a skip, while a clean pass is
only as good as the decrypter's own behaviour. shaka-packager (the default
`decryption` backend) remuxes into a single fragment and drops senc whether or not it
decrypted, so this cannot fire on shaka output. The walk is unbuffered and reads only
box headers; it seeks over mdat and never reads it. A malformed box size aborts the
walk with a warning and returns normally, so a file this function cannot parse is
never escalated into a raise. The logged warning is the only signal of that; a caller
sees the same silent return it gets from a verified clean file.
"""
surviving = 0
total = 0
first_offset = None
try:
file_size = path.stat().st_size
with path.open("rb", buffering=0) as f:
start = 0
while start + 8 <= file_size:
f.seek(start)
header = f.read(8)
if len(header) < 8:
break
size = int.from_bytes(header[:4], "big")
box_header = 8
if size == 1: # 64-bit largesize
large = f.read(8)
if len(large) < 8:
break
size = int.from_bytes(large, "big")
box_header = 16
elif size == 0: # box runs to EOF
size = file_size - start
# below the consumed header the cursor stalls and desyncs onto payload
if size < box_header or start + size > file_size:
logging.getLogger("track").warning(
f"{path.name}: malformed box size at offset {start}; cannot verify the "
"remaining fragments were decrypted."
)
break
if header[4:8] == b"moof":
total += 1
f.seek(start)
if _moof_still_encrypted(f.read(size)):
surviving += 1
if first_offset is None:
first_offset = start
start += size
except Exception as e:
logging.getLogger("track").warning(f"{path.name}: fragment decryption check did not complete ({e}).")
return
if surviving:
log_event(
"decrypt_fragments_still_encrypted",
level="ERROR",
message=f"{surviving}/{total} fragments still encrypted after decryption",
file=path.name,
surviving=surviving,
total=total,
first_offset=first_offset,
)
raise ValueError(
f"{path.name}: {surviving}/{total} fragment(s) still encrypted after decryption (first at "
f"byte {first_offset}). The decrypt tool skipped them silently, so check "
f"tfhd.sample_description_index against the stsd entry count in the init segment."
)
@dataclass
class DownloadContext:
"""Shared arguments passed to each manifest's ``download_track``."""
@@ -428,6 +532,7 @@ class Track:
if drm:
progress(downloaded="Decrypting", completed=0, total=None)
drm.decrypt(save_path)
assert_fragments_decrypted(save_path)
self.drm = None
events.emit(events.Types.TRACK_DECRYPTED, track=self, drm=drm, segment=None)
progress(downloaded="Decrypted", completed=100, total=100)