# Recover an interrupted MP4's existing AVCC payload; no frames are generated or replaced.
# A five-second reference encoded with identical x264 settings supplies codec parameters only.
import sys,re,struct,subprocess
from pathlib import Path
root=Path(sys.argv[1])
subprocess.run(['ffmpeg','-y','-loglevel','error','-loop','1','-framerate','1','-i',str(root/'latest.png'),'-t','5','-c:v','libx264','-preset','ultrafast','-crf','25','-pix_fmt','yuv420p',str(root/'reference.mp4')],check=True)
subprocess.run(['ffmpeg','-y','-loglevel','error','-i',str(root/'reference.mp4'),'-c:v','copy','-bsf:v','h264_mp4toannexb','-f','h264',str(root/'reference.h264')],check=True)
units=re.split(b'\x00\x00\x00\x01|\x00\x00\x01',(root/'reference.h264').read_bytes())
headers=[u for u in units if u and u[0]&31 in [7,8]][:2]
data=(root/'server-observation.mp4').read_bytes()
assert data[44:48]==b'mdat'
pos=48
with (root/'recovered.h264').open('wb') as out:
 for h in headers:out.write(b'\x00\x00\x00\x01'+h)
 while pos+4<=len(data):
  n=struct.unpack('>I',data[pos:pos+4])[0];pos+=4
  if n==0 or pos+n>len(data):break
  out.write(b'\x00\x00\x00\x01'+data[pos:pos+n]);pos+=n
subprocess.run(['ffmpeg','-y','-loglevel','warning','-r','1','-i',str(root/'recovered.h264'),'-c:v','copy','-movflags','+faststart',str(root/'server-observation-recovered.mp4')],check=True)
