<?
/* Main include info */
include ("include/config.php");
include_once ('include/FLV/FLV/FLV.php');

define('AUDIO_FRAME_INTERVAL', 3);

if (file_exists("/tmp/cron.php.lock"))
  exit(0);

system("/usr/bin/touch /tmp/cron.php.lock");

$query = "SELECT vid,file,length,width,height,thumb,thumbFrame,mType,status FROM videos WHERE status != 6 ORDER BY vid";
// $result = mysql_query($query);

$result = $db->query($query);

/*
 * for ($i = 0; $i < mysql_numrows($result); $i ++) {
 * $file = mysql_result($result, $i, 'file');
 * $len = mysql_result($result, $i, 'length');
 * $width = mysql_result($result, $i, 'width');
 * $height = mysql_result($result, $i, 'height');
 * $thumb = mysql_result($result, $i, 'thumb');
 * $thumbFrame = mysql_result($result, $i, 'thumbFrame');
 * $mType = mysql_result($result, $i, 'mType');
 * $vid = mysql_result($result, $i, 'vid');
 * $status = mysql_result($result, $i, 'status');
 */

while ($qData = $result->fetch_assoc()) {

  if ($qData['status'] == 5) {
    print "status 5!!";
    /*
     * system("/usr/bin/scp www@utopia.ubixonline.com:./$file /media/streams/");
     * system("/usr/bin/scp \"/media/streams/$file\" tuploads@tuve.ubixonline.com:.");
     * $query = "UPDATE videos SET status = 0 WHERE vid = $vid";
     * mysql_query($query);
     */
  }

  if (($qData['len'] <= 1) || ($qData['width'] <= 1) || ($qData['height'] <= 1)) {
    $flv = new FLV();
    print "File: " . $qData['file'] . "\n";
    $meta = array();
    $meta['metadatacreator'] = 'FLV Tools for PHP v0.1 by DrSlump';
    $meta['metadatadate'] = gmdate('Y-m-d\TH:i:s') . '.000Z';
    $meta['keyframes'] = array();
    $meta['keyframes']['filepositions'] = array();
    $meta['keyframes']['times'] = array();
    $skipTagTypes = array();

    $flv->open("/home/tuve/streams/" . $qData['file']);

    while ($tag = $flv->getTag($skipTagTypes)) {
      $ts = number_format($tag->timestamp / 1000, 3, '.', '');

      if ($tag->timestamp > 0)
        $meta['lasttimestamp'] = $ts;

      switch ($tag->type) {
        case FLV_Tag::TYPE_VIDEO:
          // Optimization, extract the frametype without analyzing the tag body
          if ((ord($tag->body[0]) >> 4) == FLV_Tag_Video::FRAME_KEYFRAME) {
            $meta['keyframes']['filepositions'][] = $flv->getTagOffset();
            $meta['keyframes']['times'][] = $ts;
          }

          if (! in_array(FLV_TAG::TYPE_VIDEO, $skipTagTypes)) {
            $meta['width'] = $tag->width;
            $meta['height'] = $tag->height;
            $meta['videocodecid'] = $tag->codec;
            array_push($skipTagTypes, FLV_Tag::TYPE_VIDEO);
          }
          break;
        case FLV_Tag::TYPE_AUDIO:
          if ($ts - $oldTs > AUDIO_FRAME_INTERVAL) {
            $meta['audioframes']['filepositions'][] = $flv->getTagOffset();
            $meta['audioframes']['times'][] = $ts;
            $oldTs = $ts;
          }
          if (! in_array(FLV_Tag::TYPE_AUDIO, $skipTagTypes)) {
            $meta['audiocodecid'] = $tag->codec;
            $meta['audiofreqid'] = $tag->frequency;
            $meta['audiodepthid'] = $tag->depth;
            $meta['audiomodeid'] = $tag->mode;
            array_push($skipTagTypes, FLV_Tag::TYPE_AUDIO);
          }
          break;
        case FLV_Tag::TYPE_DATA:
          if ($tag->name == 'onMetaData') {
            $fileMetaPos = $pos;
            $fileMetaSize = $tag->size;
            $fileMeta = $tag->value;
          }
          break;
      }

      // Does it actually help with memory allocation?
      unset($tag);
    }
    $len = $meta['lasttimestamp'];
    $width = $meta['width'];
    $height = $meta['height'];
    print "Len: $len\nWidth: $width\nHeight: $height\n\n";

    if (($width == "") || ($height == "")) {
      $qry = "UPDATE videos SET length = $len,width = 400,height = 300,mType = 2 WHERE vid = " . $qData['vid'];
      $mType = 2;
    } else
      $qry = "UPDATE videos SET length = $len,width = $width,height = $height WHERE vid = " . $qData['vid'];
    print("$qry:");
    print mysql_query($qry);
    unset($meta);
    unset($skipTagTypes);
    unset($flv);
  }
  if (($qData['thumb'] == "") || ($qData['thumbFrame'] == "")) {
    if ($qData['thumbFrame'] == "")
      $thumbFrame = 1;
    print "File: " . $qData['file'] . "\nThumb: " . $qData['file'] . ".jpg\nthumbFrame: " . $qData['thumbFrame'] . "\n\n";

    if ($mType == 1) {
      $cmd = "/usr/local/bin/ffmpeg -i \"/home/tuve/streams/" . $qData['file'] . "\" -t 0.001 -ss " . $qData['thumbFrame'] . " -vframes 1 -f mjpeg -y /tmp/1.jpg";
      system($cmd);
      $cmd = "/bin/mv /tmp/1.jpg \"/home/tuve/images/" . $qData['file'] . ".jpg\"";
      system($cmd);

      // $cmd = "/usr/bin/scp \"/home/tuve/images/" . $qData['file'] . ".jpg\" tuve@creation.ubixonline.com:/usr/web/sites/ubixonline.com/docroot/images/thumbs/";
      // system($cmd);

      $thumb = $qData['file'] . ".jpg";

      $query = "UPDATE videos SET thumb = \"http://tuve.brainchurts.com/images/thumbs/" . $thumb . "\",thumbFrame = " . $qData['thumbFrame'] . " WHERE vid = " . $qData['vid'];
    } else
      $query = "UPDATE videos SET thumb = \"http://tuve.brainchurts.com/images/sb/none.gif\",thumbFrame = " . $qData['thumbFrame'] . " WHERE vid = " . $qData['vid'];

    // mysql_query($query);
    $db->query($query);
  }
}

system("/bin/rm /tmp/cron.php.lock");

?>
