"""Authored gain exercise; Python standard library only. Run in an empty directory.
This script is not an AI generator, listening test or loudness meter.
"""
from pathlib import Path
import math,struct,wave,csv,hashlib
out=Path.cwd();rate=24000;frames=48000
a=[int(4000*math.sin(2*math.pi*440*n/rate)) for n in range(frames)]
b=[2*x for x in a];c=[int(.5*x) for x in b];assert a==c
rows=[]
for kind,samples,gain in [('reference',a,1),('double',b,2),('matched',c,.5)]:
 name=f'level-record-{kind}.wav'
 with wave.open(str(out/name),'wb') as w:
  w.setparams((1,2,rate,frames,'NONE','not compressed'));w.writeframes(struct.pack('<'+'h'*frames,*samples))
 rms=math.sqrt(sum(x*x for x in samples)/frames)
 rows.append({'file':name,'sample_rate':rate,'frames':frames,'peak_integer':max(map(abs,samples)),'rms_integer':rms,'rms_dbfs_divisor_32768':20*math.log10(rms/32768),'construction_gain':gain,'sha256':hashlib.sha256((out/name).read_bytes()).hexdigest()})
with (out/'level-record-measurements.csv').open('w',newline='',encoding='utf-8') as f:
 w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
print('Three authored WAVs and measurement CSV written to',out)
