#!/usr/bin/env python3
"""Reproducible, guarded audio fixes for the pinned EKA2L1 Web core.

The shipped core's function 3797 fills each AudioWorklet ring to its 500 ms
capacity. Keep that allocation and its read/write cursor protocol unchanged,
but stop requesting more PCM when 60 ms is already queued. One whole producer
block may exceed this target; no samples are dropped or played faster.
The fallback producer's two 150 ms comparisons become 60 ms, too.

Usage: python tools/patch-audio-lead.py ORIGINAL.wasm OUTPUT.wasm
Original is available at Git commit a865f09b325aefaf96691a693eb10072e16ee215.
Function 10442 is player_tsf::play. A fresh Web audio stream reports pausing,
so the old resume shortcut starts output without assigning playing_message_.
Only use that shortcut when playing_message_ is non-null. The first play then
initializes the original MIDI sequence and song clock via the existing path.
Equivalent source fix: if (output_ && output_->is_pausing() && playing_message_).
Only these two function bodies and enclosing length fields may change.
"""
import hashlib, struct, sys
from pathlib import Path

def read_u(data, p):
    n = shift = 0
    while True:
        b = data[p]; p += 1; n |= (b & 127) << shift
        if b < 128: return n, p
        shift += 7

def u(n):
    out = bytearray()
    while n >= 128: out.append((n & 127) | 128); n >>= 7
    out.append(n)
    return bytes(out)

def patch(src):
    expected = '850ab2fcd0cc53b53affaa9e6300ea2128af17a76d968ac8e478d18920b7fcf5'
    assert hashlib.sha256(src).hexdigest() == expected, 'Unexpected core version; do not patch'
    out = bytearray(src[:8]); p = 8; patched = 0
    while p < len(src):
        section = src[p]; p += 1
        size, p = read_u(src, p); data = src[p:p+size]; p += size
        if section == 10:
            count, q = read_u(data, 0); result = bytearray(u(count))
            for i in range(count):
                length, q = read_u(data, q); body = data[q:q+length]; q += length
                # This pinned module has 502 imported functions.
                if i + 502 == 3797:
                    # wr = atomic_load(ctrl); guard before the existing capacity check.
                    before = bytes.fromhex('200028023c2201fe10020021032001fe10020420036b200028024c6a2007490d02')
                    # if ((wr - atomic_load(ctrl + 4)) >= rate * 3 / 50) break;
                    guard = bytes.fromhex('20032001fe1002046b200028020c41036c41326e4f0d02')
                    prefix = bytes.fromhex('200028023c2201fe1002002103')
                    assert body.count(before) == 1, 'Audio ring loop changed'
                    body = body.replace(before, prefix + guard + before[len(prefix):])
                    old = b'\x44' + struct.pack('<d', 0.15)
                    new = b'\x44' + struct.pack('<d', 0.06)
                    assert body.count(old) == 2, 'Fallback thresholds changed'
                    body = body.replace(old, new); patched += 1
                if i + 502 == 10442:
                    # Inside the resume-only block: no active song -> normal first play.
                    before = bytes.fromhex('024002400240200028024c2201450d0020012001280200280218110100450d00')
                    guard = bytes.fromhex('2000280270450d00')
                    assert body.count(before) == 1, 'MIDI play entry changed'
                    body = body.replace(before, before[:6] + guard + before[6:])
                    patched += 1
                result += u(len(body)) + body
            assert q == len(data)
            data = result
        out += bytes([section]) + u(len(data)) + data
    assert patched == 2, 'Expected both audio patches'
    return bytes(out)

if __name__ == '__main__':
    source, target = map(Path, sys.argv[1:])
    output = patch(source.read_bytes()); target.write_bytes(output)
    print('Audio producer lead target: 500 ms ring / 150 ms fallback -> 60 ms + one PCM block')
    print('MIDI: initialize the song on first play; preserve active-song resume')
    print('SHA256', hashlib.sha256(output).hexdigest())
