#!/usr/bin/env python3
"""Encode native Electron CDP frames and the audio actually emitted by that renderer."""
import base64,json,pathlib,subprocess,sys
root=pathlib.Path(sys.argv[1]);output=pathlib.Path(sys.argv[2])
frames=json.loads((root/'frames.json').read_text());audio=json.loads((root/'audio.json').read_text())
lines=[]
for i,frame in enumerate(frames):
 lines.append("file '"+str((root/frame['file']).resolve()).replace("'", "'\\''")+"'")
 duration=(frames[i+1]['timestamp']-frame['timestamp']) if i+1<len(frames) else 1
 lines.append(f'duration {max(duration,0.001):.6f}')
(root/'frames.ffconcat').write_text('\n'.join(lines)+'\n')
(root/'audio.webm').write_bytes(base64.b64decode(audio['audio'].split(',',1)[1]))
offset=audio['firstAudioAt']/1000-frames[0]['timestamp']
subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-f','concat','-safe','0','-i',str(root/'frames.ffconcat'),'-itsoffset',str(offset),'-i',str(root/'audio.webm'),'-map','0:v','-map','1:a','-vf','fps=10,format=yuv420p','-c:v','libx264','-preset','fast','-crf','23','-c:a','aac','-movflags','+faststart',str(output)],check=True)
(root/'timing.json').write_text(json.dumps({'starts':audio['starts'],'videoFirstFrameAt':frames[0]['timestamp'],'audioOffsetSeconds':offset},indent=2))
print(json.dumps({'output':output.name,'starts':audio['starts'],'frames':len(frames),'audioOffsetSeconds':offset}))
