from pathlib import Path
import wave,struct,math,json,hashlib
from fractions import Fraction
out=Path(__file__).parent
def signal(rate,frames):return b''.join(struct.pack('<h',round(4095*math.sin(2*math.pi*220*i/rate))) for i in range(frames))
pcm=signal(44100,88200)
cases=[('reference',44100,1,pcm),('label-48000',48000,1,pcm),('label-22050',22050,1,pcm),('constructed-48000',48000,1,signal(48000,96000)),('stereo-duplicate',44100,2,b''.join(pcm[i:i+2]*2 for i in range(0,len(pcm),2)))]
rows=[]
for name,rate,channels,data in cases:
 path=out/('sample-rate-'+name+'.wav')
 with wave.open(str(path),'wb') as w:
  w.setnchannels(channels);w.setsampwidth(2);w.setframerate(rate);w.writeframes(data)
 with wave.open(str(path),'rb') as w:
  frames=w.getnframes();stored_rate=w.getframerate();stored_channels=w.getnchannels();decoded=w.readframes(frames)
 assert decoded==data and stored_rate==rate and stored_channels==channels
 exact=Fraction(frames,rate)
 rows.append({'case':name,'file':path.name,'sample_rate_hz':rate,'channels':channels,'frames':frames,'duration_fraction_seconds':str(exact),'duration_seconds':float(exact),'pcm_bytes':len(decoded),'same_pcm_as_reference':decoded==pcm,'pcm_sha256':hashlib.sha256(decoded).hexdigest(),'file_sha256':hashlib.sha256(path.read_bytes()).hexdigest()})
assert [r['duration_fraction_seconds'] for r in rows]==['2','147/80','4','2','2']
assert [r['same_pcm_as_reference'] for r in rows]==[True,True,True,False,False]
assert rows[0]['frames']==rows[4]['frames'] and rows[4]['pcm_bytes']==2*rows[0]['pcm_bytes']
(out/'sample-rate-results.json').write_text(json.dumps(rows,indent=2))
print(json.dumps(rows))
