#!/usr/bin/env php
<?php

// Load options
if (count($argv) != 2) {
  echo "Usage: makegop <basename>\n";
  return 1;
}
$name = array_shift($argv);
$base = array_shift($argv);

$cmd = sprintf('mpeg_stat -offsets %1$s.off %1$s.m1v 2>&1', $base);
$out = Array();
$ret = 0;
exec($cmd, $out, $ret);
if (0 != $ret) {
  printf("Command exited with status %u: %s\n", $ret, $cmd);
  printf("%s\n", implode("\n", $out));
  return 1;
}

$out = preg_grep('/frames: ([0-9]*)\./', $out);
preg_match('/frames: ([0-9]*)\./', array_shift($out), $regs);
$frames = $regs[1];

printf("frames=%u\n", $frames);

$stat = fopen(sprintf("%s.off", $base),"r");
$gop = fopen(sprintf("%s.gop", $base), "w");

$frame = 0;
while ($line = fgets($stat, 4096)) {
  $stuff = explode(" ", $line);
  switch ($stuff[0]) {
    case "picture":
      $frame++;
      break;
    case "gop":
      if ($frame) {
        $point = (((int) $stuff[1]) / 8 - 140);
//        printf("%u: %u\n", $frame, $point);
        fwrite($gop, pack('VV', $frame, $point), 8);
      }
      break;
    default:
      break;
  }
}

fclose($gop);
fclose($stat);
return 0;

?>