from PIL import Image,ImageDraw,ImageFont
import subprocess,threading,time,textwrap
class Recording:
 def __init__(self,path,title,lines):
  self.path=path; self.title=title; self.lines=lines; self.stop=threading.Event()
  self.font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18)
  self.ff=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pixel_format','rgb24','-video_size','1600x1200','-framerate','2','-i','-','-c:v','libx264','-preset','ultrafast','-crf','24','-pix_fmt','yuv420p',str(path)],stdin=subprocess.PIPE)
  self.thread=threading.Thread(target=self.run); self.thread.start()
 def frame(self):
  im=Image.new('RGB',(1600,1200),'#101820'); d=ImageDraw.Draw(im)
  d.text((32,24),self.title,font=self.font,fill='#72d4df')
  wrapped=[]
  for line in '\n'.join(self.lines).splitlines(): wrapped.extend(textwrap.wrap(line,140,replace_whitespace=False) or [''])
  for i,line in enumerate(wrapped[-44:]):d.text((32,80+i*24),line,font=self.font,fill='#e4eaf0')
  return im
 def run(self):
  while not self.stop.is_set():self.ff.stdin.write(self.frame().tobytes()); self.stop.wait(.5)
 def close(self):
  time.sleep(2)
  first=self.frame(); time.sleep(.5); second=self.frame()
  assert first.tobytes()==second.tobytes()
  second.save(self.path.with_suffix('.png'))
  self.stop.set(); self.thread.join(); self.ff.stdin.close(); self.ff.wait()
