#!/usr/bin/env python3
"""Reassemble tshark-extracted Opus payloads into a playable .opus file.

Steps (the ones the blog post teaches):
  1. tshark reads the pcap and prints each RTP payload as hex:
       tshark -r demo_rtp_opus.pcap -d udp.port==5004,rtp -T fields -e rtp.payload > payloads.txt
  2. this script reads payloads.txt, wraps the packets back into an Ogg
     container (OpusHead + packets) and writes out.opus
  3. ffmpeg / ffplay / afplay can then replay it.

The tricky bit this script hides is the Ogg CRC: Ogg uses an MSB-first
CRC-32 (poly 0x04c11db7), not the zlib/crc32() reflected variant.
"""
import struct, sys
from pathlib import Path

def ogg_pages(path):
    data = Path(path).read_bytes()
    pos = 0
    while pos + 27 <= len(data):
        nseg = data[pos+26]
        segs = data[pos+27:pos+27+nseg]
        body = pos + 27 + nseg
        i, pkts = 0, []
        while i < nseg:
            size = 0
            while i < nseg and segs[i] == 255:
                size += 255; i += 1
            if i < nseg:
                size += segs[i]; i += 1
            pkts.append(data[body:body+size])
            body += size
        yield data[pos:pos+27+nseg]  # page bytes (for BOS extraction)
        pos = body

def ogg_opus_head(src_opus):
    """Pull the real OpusHead (and OpusTags) from a source .opus so
    channels/pre-skip/comment header match what the encoder wrote."""
    data = Path(src_opus).read_bytes()
    head = tags = None
    pos = 0
    while pos + 27 <= len(data):
        nseg = data[pos+26]
        segs = data[pos+27:pos+27+nseg]
        body = pos + 27 + nseg
        i = 0
        while i < nseg:
            size = 0
            while i < nseg and segs[i] == 255:
                size += 255; i += 1
            if i < nseg:
                size += segs[i]; i += 1
            pkt = data[body:body+size]
            if pkt.startswith(b'OpusHead'):
                head = pkt
            elif pkt.startswith(b'OpusTags'):
                tags = pkt
            body += size
        pos = body
    if head is None:
        raise ValueError('no OpusHead found')
    return head, tags

def ogg_crc(data):
    table = []; poly = 0x04c11db7
    for i in range(256):
        r = i << 24
        for _ in range(8):
            r = ((r << 1) ^ poly) & 0xffffffff if r & 0x80000000 else (r << 1) & 0xffffffff
        table.append(r)
    crc = 0
    for b in data:
        crc = ((crc << 8) & 0xffffffff) ^ table[((crc >> 24) & 0xff) ^ b]
    return crc & 0xffffffff

def page(packets, serial, seq, granule, header_type):
    body = b''.join(packets)
    lacing = []
    for p in packets:
        n = len(p)
        while n >= 255:
            lacing.append(255); n -= 255
        lacing.append(n)
    pref = (b'OggS' + bytes([0, header_type]) + struct.pack('<q', granule)
            + struct.pack('<II', serial, seq) + struct.pack('<I', 0) + bytes([len(lacing)])
            + bytes(lacing))
    crc = ogg_crc(pref[:22] + b'\x00\x00\x00\x00' + pref[26:] + body)
    return pref[:22] + struct.pack('<I', crc) + pref[26:] + body

def mux(head, audio, out, tags=None):
    serial = 0x11223344
    with open(out, 'wb') as f:
        f.write(page([head], serial, 0, -1, 0x02))            # BOS: OpusHead
        seq = 1
        if tags:
            f.write(page([tags], serial, seq, 0, 0))          # comment header
            seq += 1
        granule = 0
        for pkt in audio:
            f.write(page([pkt], serial, seq, granule + 960, 0))  # one page per frame
            seq += 1
            granule += 960

def main():
    payloads_txt = sys.argv[1] if len(sys.argv) > 1 else 'payloads.txt'
    out = sys.argv[2] if len(sys.argv) > 2 else 'out.opus'
    src_opus = sys.argv[3] if len(sys.argv) > 3 else 'demo.opus'
    head, tags = ogg_opus_head(src_opus)  # real OpusHead + OpusTags
    audio = [bytes.fromhex(l.strip()) for l in Path(payloads_txt).read_text().splitlines() if l.strip()]
    print('packets:', len(audio))
    mux(head, audio, out, tags)
    print('wrote', out)

if __name__ == '__main__':
    main()
