import wave,io
data = open(r"C:/Users/vikto/Documents/Claude/rt-4d/radio-spi-dump.bin","rb").read()
out=io.open(r"C:/Users/vikto/Documents/Claude/rt-4d/analyze/out8.txt","w",encoding="utf-8")

# BLOB2 audio extent
i=0x352000; run=0; endaud=None
while i<0x3e0000:
    if data[i]==0xff:
        run+=1
        if run>=4096: endaud=i-run+1; break
    else: run=0
    i+=1
out.write("audio region 0x352000 .. %s (len %#x)\n"%(hex(endaud),endaud-0x352000))

# check for an index/header at very start of blob2 or just before it (0x351000?)
def hx(off,n=64):
    s=""
    for j in range(0,n,16):
        ch=data[off+j:off+j+16]
        s+="%08x  %s  %s\n"%(off+j,' '.join('%02x'%b for b in ch),''.join(chr(b) if 32<=b<127 else '.' for b in ch))
    return s
out.write("\nBefore audio (0x351f80):\n"+hx(0x351f80,0x80))

# 8-bit unsigned PCM -> wav, first 64KB as a listen-test
seg=data[0x352000:0x352000+0x10000]
w=wave.open(r"C:/Users/vikto/Documents/Claude/rt-4d/analyze/blob2_sample.wav","wb")
w.setnchannels(1); w.setsampwidth(1); w.setframerate(8000)
w.writeframes(seg)
w.close()
out.write("\nwrote blob2_sample.wav (8kHz u8, 64KB)\n")

# statistics: measure how 'audio-like' - mean near 128, derivative small
import statistics
vals=list(seg)
out.write("mean=%.1f min=%d max=%d stdev=%.1f\n"%(statistics.mean(vals),min(vals),max(vals),statistics.pstdev(vals)))
# fraction of adjacent-sample diffs <=8 (smoothness)
sm=sum(1 for k in range(len(vals)-1) if abs(vals[k]-vals[k+1])<=8)
out.write("smoothness (|diff|<=8): %.3f\n"%(sm/(len(vals)-1)))

# Total audio size and rough duration at 8k/16k
alen=endaud-0x352000
out.write("audio bytes=%d  @8kHz=%.1fs  @16kHz=%.1fs\n"%(alen,alen/8000,alen/16000))
out.close()
print("done")
