"""A synthetic BBTS file and its cipher, built from scratch so the tests need no real media. The cipher here is a slow, plain reading of the format; the decrypter under test never builds its own input. """ from __future__ import annotations import hashlib import re from Cryptodome.Cipher import AES KEY = bytes.fromhex("00112233445566778899aabbccddeeff") IVS = (bytes.fromhex("0123456789abcdef0123456789abcdef"), bytes.fromhex("fedcba9876543210fedcba9876543210")) HEVC, H264, AAC = 0x24, 0x1B, 0x0F SC3, SC4 = b"\x00\x00\x01", b"\x00\x00\x00\x01" # SHA-256 of what the bbtsdecrypt binary wrote for bbts(video_type), so CI needs no binary. GOLDEN = { HEVC: "b2d70cf98ca9b08b94363c627266da9c31ed07f08acf2ac3d2645ca9cff0366a", H264: "0f2bb9586781768f086d9a6d05ec09466453ee9e53557fa6ad6d09598be2e8b3", } def noise(seed: str, size: int) -> bytes: """Deterministic bytes with no zero byte.""" out = b"".join(hashlib.sha256(f"{seed}{i}".encode()).digest() for i in range(size // 32 + 1))[:size] return out.replace(b"\x00", b"\x5a") def crc32_mpeg(data: bytes) -> int: crc = 0xFFFFFFFF for byte in data: crc ^= byte << 24 for _ in range(8): crc = ((crc << 1) ^ 0x104C11DB7) if crc & 0x80000000 else crc << 1 return crc & 0xFFFFFFFF def encrypt(payload: bytes, iv: bytes) -> bytes: """Encrypt a NAL payload: all but its last 2 bytes, block by block, then escape the result for the byte stream.""" ecb = AES.new(KEY, AES.MODE_ECB) counter = int.from_bytes(iv[:12] + bytes(4), "big") body, out = payload[:-2], bytearray() for n, at in enumerate(range(0, len(body), 16)): counter += 1 block = counter.to_bytes(16, "big") if n % 10 == 0 or len(body) - at <= 16: block = ecb.encrypt(block) out += bytes(a ^ b for a, b in zip(body[at : at + 16], block, strict=False)) return re.sub(b"\x00\x00(?=[\x00-\x03])", b"\x00\x00\x03", bytes(out) + payload[-2:]) def section(table_id: int, body: bytes) -> bytes: """A long-form PSI section with its CRC.""" data = bytes([table_id]) + (0xB000 | (len(body) + 9)).to_bytes(2, "big") + b"\x00\x01\xc1\x00\x00" + body return data + crc32_mpeg(data).to_bytes(4, "big") def psi_packet(pid: int, data: bytes) -> bytes: payload = b"\x00" + data return bytes([0x47, 0x40 | pid >> 8, pid & 0xFF, 0x10]) + payload + b"\xff" * (184 - len(payload)) def sdt(iv: bytes, name_format: str) -> bytes: """An SDT whose service name is ``name_format`` with the IV in it.""" name = name_format.format(iv=iv.hex()).encode() descriptor = bytes([0x48, 3 + 7 + len(name), 0x01, 7]) + b"EXAMPLE" + bytes([len(name)]) + name service = b"\x00\x01\xfc" + (0x8000 | len(descriptor)).to_bytes(2, "big") + descriptor return psi_packet(0x11, section(0x42, b"\x00\x01\xff" + service)) def pmt(video_type: int) -> bytes: """A PMT with the video stream, an AAC stream and an H.264 stream on another PID.""" streams = bytes([video_type, 0xE1, 0x00, 0xF0, 0x00, AAC, 0xE1, 0x01, 0xF0, 0x00, H264, 0xE1, 0x02, 0xF0, 0x00]) return psi_packet(0x1000, section(0x02, b"\xe1\x00\xf0\x00" + streams)) PAT = psi_packet(0, section(0x00, b"\x00\x01\xf0\x00")) def packets(pid: int, pes: bytes, counter: list[int], last: int) -> list[bytes]: """Cut a PES packet into TS packets, the last of which carries ``last`` bytes after adaptation-field stuffing.""" sizes = [184] * ((len(pes) - last) // 184) + [last] assert sum(sizes) == len(pes), "the PES does not end on the asked size" out, at = [], 0 for size in sizes: chunk, at = pes[at : at + size], at + size start = 0x40 if at == size else 0 head = bytes([0x47, start | pid >> 8, pid & 0xFF, (0x10 if size == 184 else 0x30) | counter[0] % 16]) counter[0] += 1 stuffing = 183 - size field = b"" if size == 184 else bytes([stuffing]) + (b"\x00" + b"\xff" * (stuffing - 1) if stuffing else b"") out.append(head + field + chunk) return out def pes(stream_id: int, es: bytes) -> bytes: return SC3 + bytes([stream_id]) + b"\x00\x00\x80\x80\x05\x21\x00\x01\x00\x01" + es def with_zero_runs(seed: str, size: int) -> bytes: """Bytes whose zero runs make the cipher hold emulation-prevention bytes.""" data = bytearray(noise(seed, size)) for at in range(20, size - 8, 37): data[at : at + 5] = bytes(5) return bytes(data) def nal_units(seed: str, iv: bytes, h264: bool) -> bytes: """An access unit: a delimiter, a SEI and an RPU with the 4 bytes the cipher appends, slices, and a short NAL.""" aud, sei, slice_ = (b"\x09", b"\x06", b"\x65") if h264 else (b"\x46\x01", b"\x4e\x01", b"\x02\x01") rpu = b"\x19" + noise(seed + "r", 40) rpu += crc32_mpeg(rpu[1:]).to_bytes(4, "big") + b"\x80" units = [ SC4 + aud + encrypt(b"\x50" + noise(seed + "a", 4), iv), SC3 + sei + encrypt(b"\x05\x04\xaa\xbb\xcc\xdd\xff\x01\x02\x11\x22\x80" + noise(seed + "s", 4), iv), SC3 + slice_ + encrypt(with_zero_runs(seed + "l", 300) + b"\x00", iv), SC4 + slice_ + encrypt(noise(seed + "m", 2), iv), SC3 + slice_ + encrypt(noise(seed + "n", 161), iv), ] if not h264: units.insert(2, SC3 + b"\x7c\x01" + encrypt(rpu + noise(seed + "p", 4), iv)) return b"".join(units) def timestamp(ticks: int) -> bytes: """A PES PTS field of ``ticks`` at 90 kHz.""" return bytes( [ 0x21 | ticks >> 29 & 0x0E, ticks >> 22 & 0xFF, ticks >> 14 & 0xFE | 1, ticks >> 7 & 0xFF, ticks << 1 & 0xFE | 1, ] ) def bbts_segments(es: bytes, iv: bytes, frames: int, fps: int) -> list[bytes]: """BBTS segments of ``frames`` pictures each, from an Annex B HEVC stream with a delimiter before each picture. Each segment opens with its tables, and each picture is one video PES packet with only a PTS. """ pictures: list[list[bytes]] = [] for nal in es.split(SC3)[1:]: if nal[0] >> 1 & 0x3F == 35: pictures.append([]) pictures[-1].append(nal.rstrip(b"\x00")) hevc_pmt = psi_packet(0x1000, section(0x02, b"\xe1\x00\xf0\x00" + bytes([HEVC, 0xE1, 0x00, 0xF0, 0x00]))) segments, counter = [], [0] for first in range(0, len(pictures), frames): out = [PAT, hevc_pmt, sdt(iv, "a0|mdcm|s1:9:10|e1|v{iv}|f1|gv|q")] for n, picture in enumerate(pictures[first : first + frames], first): es_out = b"".join(SC4 + nal[:2] + (encrypt(nal[2:], iv) if len(nal) > 4 else nal[2:]) for nal in picture) packet = SC3 + b"\xe0\x00\x00\x80\x80\x05" + timestamp(90000 * (n + 1) // fps) + es_out out += packets(0x100, packet, counter, len(packet) % 184 or 184) segments.append(b"".join(out)) return segments def bbts( video_type: int = HEVC, pmt_first: bool = False, name_format: str = "a0|mdcm|s1:9:10|e1|v{iv}|f1|gv|q" ) -> bytes: """Two segments with their own IV, each with SDT, PMT, two video PES packets and an audio PES packet between them. ``pmt_first`` puts the PMT before the SDT; ``name_format`` is the service name that holds the IV. The first video PES ends in a packet of 6 bytes, so the bytes the decrypter drops empty that packet; the second ends in a packet whose adaptation field is only its length byte. """ counters: list[list[int]] = [[0], [0]] out = [] for n, iv in enumerate(IVS): tables = ( [PAT, pmt(video_type), sdt(iv, name_format)] if pmt_first else [PAT, sdt(iv, name_format), pmt(video_type)] ) out += tables for k, last in ((0, 6), (1, 183)): es = nal_units(f"v{n}{k}", iv, video_type == H264) head = b"\x01" if video_type == H264 else b"\x02\x01" filler = (last - len(pes(0xE0, es)) - 3 - len(head)) % 184 + 184 es += SC3 + head + noise(f"f{n}{k}", filler) out += packets(0x100, pes(0xE0, es), counters[0], last) if k == 0: audio = pes(0xC0, noise(f"a{n}", 400)) out += packets(0x101, audio, counters[1], len(audio) % 184) return b"".join(out)