from PIL import Image, ImageDraw
import subprocess,sys
src,out,start,end,low,high=sys.argv[1:]
start,end,low,high=map(float,(start,end,low,high))
w,h,fps=1280,800,25
read=subprocess.Popen(['ffmpeg','-loglevel','error','-ss',str(start),'-i',src,'-t',str(end-start),'-vf','fps=25','-f','rawvideo','-pix_fmt','rgb24','pipe:1'],stdout=subprocess.PIPE)
write=subprocess.Popen(['ffmpeg','-loglevel','error','-y','-f','rawvideo','-pix_fmt','rgb24','-s','1280x800','-r','25','-i','pipe:0','-c:v','libx264','-pix_fmt','yuv420p',out],stdin=subprocess.PIPE)
def red(im,box):
 return sum(r>180 and r-g>70 and r-b>50 for r,g,b in im.crop(box).getdata())>20
n=0
while True:
 data=read.stdout.read(w*h*3)
 if len(data)!=w*h*3: break
 t=start+n/fps
 if low<=t<=high:
  im=Image.frombytes('RGB',(w,h),data); d=ImageDraw.Draw(im)
  if red(im,(800,515,870,535)):
   boxes=[(407,331,880,370)]
  elif red(im,(1025,662,1168,694)):
   boxes=[(350,307,1000,326),(350,531,705,567)]
  else:
   boxes=[(378,486,1030,507)]
  for box in boxes: d.rectangle(box,fill='black')
  data=im.tobytes()
 write.stdin.write(data); n+=1
write.stdin.close(); read.wait(); write.wait()
