#!/usr/bin/python

import sys
import subprocess as sp
import numpy as np

if len(sys.argv) != 4 and len(sys.argv) != 5: # 5 means not using idx
    print("Usage : {} <input bin> <input idx> <output vid>".format(sys.argv[0]))
    print("  e.g., {} data/video0.bin result0.out result0.mp4".format(sys.argv[0]))
    sys.exit(1)

FFMPEG_BIN = "/scratch/share/apss17/vr_data/ffmpeg"

with open(sys.argv[2]) as fidx:
    idxs = map(int, fidx.read().splitlines())

N = len(idxs)
H = 1080
W = 1920
C = 3

if len(sys.argv) == 5:
    idxs = range(N)

command = [ FFMPEG_BIN,
        '-y', # (optional) overwrite output file if it exists
        '-f', 'rawvideo',
        '-vcodec','rawvideo',
        '-s', '{}x{}'.format(W, H), # size of one frame
        '-pix_fmt', 'rgb24',
        '-r', '30', # frames per second
        '-i', '-', # The imput comes from a pipe
        '-an', # Tells FFMPEG not to expect any audio
        '-vcodec', 'mpeg4',
        sys.argv[3] ]

pipe = sp.Popen( command, stdin=sp.PIPE)

with open(sys.argv[1], "rb") as fbin:
    rawvideo = fbin.read()
    for idx in idxs:
        pipe.stdin.write(rawvideo[idx * H * W * C : (idx + 1) * H * W * C])
