#!/usr/bin/env python3
"""NFSINTRO_EN.AVI -> WAV directly (no temp file).

Two stages, one process:

1. Extract the raw ADPCM stream by walking the movi LIST body chunk-by-chunk,
   collecting every audio chunk (tag '01wb') in file order and concatenating
   their payloads. This is used rather than the idx1 index because this AVI's
   idx1 is corrupt: its first '01wb' entry carries offset 0x4 (the RIFF header)
   instead of the real chunk offset 0x808. Walking the movi body sidesteps the
   bad index entirely.

2. Decode Sony PS-ADPCM (VAG / bSound MultiStream) directly from the collected
   bytes to int16 samples and write a RIFF/WAVE file. The bSound stream is
   PS-ADPCM: 16-byte frames, 28 samples/frame, 2nd-order IIR with a fixed
   5-entry coefficient table. The frame header byte 0 encodes the coefficient
   index (high nibble) and a scale/shift (low nibble); byte 1 is a loop/end
   flag. See vgmstream src/coding/psx_decoder.c (decode_psx).
"""
import struct
import sys

# PS-ADPCM coefficient table (float, as in the spec / vgmstream decode_psx).
COEFS = [
    (0.0, 0.0),
    (0.9375, 0.0),        # 60/64
    (1.796875, -0.8125),  # 115/64, -52/64
    (1.53125, -0.859375), # 98/64, -55/64
    (1.90625, -0.9375),   # 122/64, -60/64
]
FRAME = 16
BLOCK = 2048 * FRAME
BLOCK_FRAMES = 2048  # frames per channel-interleave block
SPF = 28  # samples per frame


def extract_pcm(data):
    """Concatenate every '01wb' audio chunk in the movi LIST body."""
    movi = data.find(b'LIST')
    while movi >= 0:
        if data[movi + 8:movi + 12] == b'movi':
            body_start = movi + 12
            body_size = struct.unpack('<I', data[movi + 4:movi + 8])[0] - 4  # minus 'movi'
            body_end = body_start + body_size
            break
        movi = data.find(b'LIST', movi + 4)
    assert movi >= 0, 'no movi LIST found'

    buf = bytearray()
    count = 0
    o = body_start
    while o + 8 <= body_end:
        tag = data[o:o + 4]
        sz = struct.unpack('<I', data[o + 4:o + 8])[0]
        if sz < 0 or o + 8 + sz > body_end + 1:
            break  # malformed, stop
        if tag == b'01wb':          # audio, stream id 1
            buf += data[o + 8:o + 8 + sz]
            count += 1
        o += 8 + sz + (sz & 1)      # AVI chunks are 2-byte aligned
    return bytes(buf), count


def clamp16(s):
    return max(-32768, min(32767, s))


def decode_psadpcm(data):
    """Decode raw PS-ADPCM bytes to interleaved int16 stereo samples (L,R,...).

    The bSound stream stores the two channels in alternating 2048-frame blocks:
    a left block, then a right block, then left, then right, ... Decode each
    frame into a per-channel buffer (selected by block parity) and interleave
    the two buffers at the end so the result is L,R,L,R,...
    """
    left = []
    right = []
    h1 = h2 = 0
    i = 0
    n = len(data)

    while i + FRAME <= n:
        f = data[i:i + FRAME]
        coef = (f[0] >> 4) & 0xF
        shift = f[0] & 0xF
        flag = f[1] & 0xF
        if coef > 4:
            coef = 0
        if shift > 12:
            shift = 9
        shift = 20 - shift
        c0, c1 = COEFS[coef]
        # block parity selects the channel buffer: 0 = left, 1 = right
        buf = left if ((i // FRAME) // BLOCK_FRAMES) & 1 == 0 else right
        for j in range(SPF):
            if flag < 7:
                nib = f[2 + (j >> 1)]
                n4 = (nib >> 4) if (j & 1) else (nib & 0xF)
                if n4 >= 8:
                    n4 -= 16
                s = (n4 << shift) + int(round((c0 * h1 + c1 * h2) * 256.0))
                s >>= 8
            else:
                s = 0
            s = clamp16(s)
            buf.append(s)
            h2 = h1
            h1 = s
        i += FRAME

    # interleave left/right sample by sample into L,R,L,R,...
    m = min(len(left), len(right))
    out = []
    for k in range(m):
        out.append(left[k])
        out.append(right[k])
    return out


def write_wav(path, samples, rate=48000, channels=2):
    data = b"".join(struct.pack("<h", s) for s in samples)
    with open(path, "wb") as w:
        w.write(b"RIFF")
        w.write(struct.pack("<I", 36 + len(data)))
        w.write(b"WAVEfmt ")
        w.write(struct.pack("<IHHIIHH", 16, 1, channels, rate,
                            rate * channels * 2, channels * 2, 16))
        w.write(b"data")
        w.write(struct.pack("<I", len(data)))
        w.write(data)


def main():
    if len(sys.argv) < 2:
        print(__doc__)
        print("usage: avi_to_wav.py <avi_file> [out.wav] [rate]")
        sys.exit(1)
    fn = sys.argv[1]
    out = sys.argv[2] if len(sys.argv) > 2 else "out.wav"
    rate = int(sys.argv[3]) if len(sys.argv) > 3 else 44100

    data = open(fn, 'rb').read()
    pcm, count = extract_pcm(data)
    samples = decode_psadpcm(pcm)
    write_wav(out, samples, rate)
    print('audio chunks: %d' % count)
    print('%d samples -> %s (%d Hz)' % (len(samples), out, rate))


if __name__ == "__main__":
    main()
