<?
/*
 * (C) 2008 Christopher Olsen <cwolsen@domainatlantic.com>
 *
 * $Id$
 */
include ("include/config.php");

$brTarget = "2M";
$brMax = "2.5M";

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

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

$query = "SELECT * FROM videos_pending v INNER JOIN users u ON v.oid = u.uid WHERE encoded = 0";
$result = $db->query($query);

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

  exec("/usr/local/bin/mediainfo --Inform=\"Video;%Width%,%Height%,%BitRate%,%FrameRate%,%Duration/String3%,%DisplayAspectRatio%\" /media/incoming/" . $qData['file'], $mediaInfo);

  $vData = explode(",", $mediaInfo[0]);

  if ($vData[5] == "" && substr($qData['file'], - 3) != "m2v") {
    $sar = ":force_original_aspect_ratio=1";
  }
  else {
    $sar = ",setsar=sar=" . $vData[5] . ",setdar=dar=16/9";
  }

  $mWidth = $vData[0];
  $mHeight = $vData[1];
  $mBitRate = $vData[2];
  $mFrameRate = $vData[3];

  $re1 = '(\\d+)'; // Integer Number 1
  $re2 = '.*?'; // Non-greedy match on filler
  $re3 = '(\\d+)'; // Integer Number 2
  $re4 = '.*?'; // Non-greedy match on filler
  $re5 = '(\\d+)'; // Integer Number 3
  $re6 = '.*?'; // Non-greedy match on filler
  $re7 = '(\\d+)'; // Integer Number 4

  if ($c = preg_match_all("/" . $re1 . $re2 . $re3 . $re4 . $re5 . $re6 . $re7 . "/is", $vData[4], $matches)) {
    $mDuration = ($matches[1][0] * 3600) + ($matches[2][0] * 60) + $matches[3][0] + ("0." . $matches[4][0]);
  }

  unset($mediaInfo);

  if (($mWidth == 0) || ($mHeight == 0)) {
    print "[" . json_encode($vData) . "]\n";
    $mType = 2;
    $encode = "/usr/local/bin/ffmpeg -loop_input -i \"/usr/tuve/assets/UbixCube.gif\" -i \"/media/incoming/" . $qData['file'] . "\" -vf \"scale=w=800:h=450:force_original_aspect_ratio=1,pad=800:450:(ow-iw)/2:(oh-ih)/2\" -ar 44100 -ac 2 -ab 128k -t $mDuration -r 0.5 -f flv -y \"/media/tmp/" . $qData['file'] . ".flv\"";
    $res = system($encode, $retVal);
    if ($retVal == 1)
      doExcite($encode, $qData[vid]);
  }
  else if ($mDuration > 0) {
    $mType = 1;

    $encode = "/usr/local/bin/ffmpeg -i \"/media/incoming/" . $qData['file'] . "\" -c:v libx264 -vf \"scale=w=800:h=450" . $sar . ",pad=800:450:(ow-iw)/2:(oh-ih)/2\" -b:v " . $brTarget . " -maxrate " . $brMax . " -bufsize 4M -preset veryfast -pass 1 -f flv -an -y /dev/null";

    print("[$encode]");

    $res = system($encode, $retVal);

    if ($retVal == 1)
      doExit($encode, $qData['vid']);

    $encode = "/usr/local/bin/ffmpeg -i \"/media/incoming/" . $qData['file'] . "\" -c:v libx264 -vf \"scale=w=800:h=450" . $sar . ",pad=800:450:(ow-iw)/2:(oh-ih)/2\" -b:v " . $brTarget . " -maxrate " . $brMax . " -bufsize 4M -preset veryfast -c:a mp3 -b:a 128k -pass 2 -f flv -y \"/media/tmp/" . $qData['file'] . ".flv\"";

    print("[$encode]");

    $res = system($encode, $retVal);

    if ($retVal == 1)
      doExit($encode, $qData['vid']);
  }

  system("/bin/mv \"/media/tmp/" . $qData['file'] . ".flv\" \"/red5/webapps/oflaDemo/streams/" . $qData['file'] . ".flv\"");
  system("/usr/sbin/chown tuve:www \"/red5/webapps/oflaDemo/streams/" . $qData['file'] . ".flv\"");

  /* Update The videos_pending Table */
  $query = "UPDATE videos_pending SET encoded = 1 WHERE vid = " . $qData['vid'];
  $db->query($query);

  /* Insert The Video Into The System */
  $uDate = time();
  $query = "INSERT INTO videos (artist,title,genre,file,rating,classification,oid,mType,length,width,height,added) VALUES(\"" . $qData['artist'] . "\",\"" . $qData['title'] . "\",\"" . $qData['genre'] . "\",\"" . $qData['file'] . ".flv\"," . $qData['rating'] . "," . (($qData['classification'] > 0) ? $qData['classification'] : 1) . "," . $qData['oid'] . ",$mType,$mDuration,800,450,$uDate)";
  print "[$query]";
  $res = $db->query($query);
  if (! $res) {
    echo "Encoding Failed!\n";
    $eStatus = "Failed";
  }
  else
    $eStatus = "Successful";

  $headers = 'MIME-Version: 1.0' . "\r\n";
  $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
  $headers .= 'From: TUve Support <tuve@tuve.tv>' . "\r\n";

  $message = "New Video Encoded: " . $qData['artist'] . " - " . $qData['title'] . "<BR><BR>Your video is now ready for viewing.<BR>Sincerely,<BR>The TUve Staff<BR>\n";
  mail("Christopher Olsen <cwolsen@domainatlantic.com>", "Media Encoding $eStatus", $message, $headers);

  mail($qData['firstname'] . " " . $qData['lastname'] . " <" . $qData['email'] . ">", "Media Encoded", $message, $headers);

  system("/bin/mv \"/media/incoming/" . $qData['file'] . "\" /media/orig");
}
system("/bin/rm /tmp/cron2.php.lock");

function doExit($errorStr, $vid_id, $error_code = 0) {
  global $db;

  /* Update The videos_pending Table */
  $query = "UPDATE videos_pending SET encoded = 2, error_code = " . $error_code . ", error_msg = \"" . $errorStr . "\" WHERE vid = $vid_id";
  $db->query($query);

  print("Error: $errorStr\n");

  exit(0);
}
?>
