<?
/*
 * (C) 2008 Christopher Olsen <cwolsen@domainatlantic.com>
 *
 * $Id$
 */
// ini_set('include_path',"/home/tuve/include/");
include ("include/config.php");

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 = mysql_query($query);
$result = $db->query($query);

/*
 * if (mysql_num_rows($result) > 0) {
 * $vid = mysql_result($result,0,'vid');
 * $file = mysql_result($result,0,'file');
 * $artist = mysql_result($result,0,'artist');
 * $title = mysql_result($result,0,'title');
 * $genre = mysql_result($result,0,'genre');
 * $rid = mysql_result($result,0,'rating');
 * $cid = mysql_result($result,0,'classification');
 * $oid = mysql_result($result,0,'oid');
 */

if ($qData = $result->fetch_assoc()) {
  $movie = new ffmpeg_movie("/usr/web/uploads/" . $qData['file']);

  $oW = $movie->getFrameWidth();
  $oH = $movie->getFrameHeight();
  $oLen = $movie->getDuration();

  print("W: $oW H: $oH");

  if (($oW == 0) || ($oH == 0)) {
    $mType = 2;
    $encode = "/usr/local/bin/ffmpeg -loop_input -i \"/usr/home/reddawg/UbixCube.gif\" -i \"/usr/web/uploads/" . $qData['file'] . "\" -ar 44100 -ac 2 -ab 128k -t $oLen -r 0.5 -f flv -y \"/media/streams/" . $qData['file'] . ".flv\"";
    print("[$encode]");
    $res = system($encode);
  } else {
    $mType = 1;
    $hRat = 300 / $oH;
    $wRat = 400 / $oW;

    if ($oH == $oW) {
      $nH = 300;
      $nW = 400;
    } else if ($hRat < $wRat) {
      $rat = $hRat;
      $nW = floor($oW * $rat);

      if (($nW % 2) != 0x0)
        $nW --;

      $pad = floor((400 - $nW) / 2);

      if (($pad % 2) != 0x0)
        $pad ++;

      if ($pad > 1)
        $pad_str = "-padleft $pad -padright $pad ";
      else
        $pad_str = "";
      $nH = 300;
      // $nW = 400 - ($pad * 2);
    } else {
      $rat = $wRat;
      $nH = floor($oH * $rat);

      if (($nH % 2) != 0x0)
        $nH --;

      $pad = floor((300 - $nH) / 2);

      if (($pad % 2) != 0x0)
        $pad ++;

      if ($pad > 1)
        $pad_str = "-padtop $pad -padbottom $pad ";
      else
        $pad_str = "";
      // $nH = 300 - ($pad * 2);
      $nW = 400;
    }

    // old -g 250 -i_qfactor 0.71 -gblur 0.9
    // $vidParams "-deinterlace -g 250 -qcomp 0.6 -qdiff 4 -i_qfactor 0.71428572 -b_qfactor 0.76923078 -bt 200k -b 360k -r 25";
    $vidParams = "-deinterlace -g 250 -qcomp 0.6 -qdiff 4 -i_qfactor 0.71 -umv -aic -sc_threshold 10000 -bt 200k -b 360k -r 25";

    $encode = "/usr/local/bin/ffmpeg -i \"/usr/web/uploads/" . $qData['file'] . "\" -an $pad_str $vidParams -f flv -s " . $nW . "x" . $nH . " -pass 1 -passlogfile /tmp/pass_monkey -y \"/media/tmp/" . $qData['file'] . ".flv\"";

    print("[$encode]");

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

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

    $encode = "/usr/local/bin/ffmpeg -i \"/usr/web/uploads/" . $qData['file'] . "\" -ar 44100 -ac 2 -ab 128k $pad_str $vidParams -f flv -s " . $nW . "x" . $nH . " -pass 2 -passlogfile /tmp/pass_monkey -y \"/media/tmp/" . $qData['file'] . ".flv\"";

    print("[$encode]");

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

    if ($retVal == 1)
      doExit($encode, $data['vid']);
    print($res);
    system("rm -fr /tmp/pass_monkey*");
  }
  system("/bin/mv \"/media/tmp/" . $qData['file'] . ".flv\" \"/usr/home/tuve/streams/" . $qData['file'] . ".flv\"");
  system("/usr/sbin/chown tuve:www \"/usr/home/tuve/streams/" . $qData['file'] . ".flv\"");

  /* Move The File To The Mirrors */
  /* No more mirrors */
  // system("/usr/bin/scp \"/media/streams/$file.flv\" www@utopia.ubixonline.com:.");
  // system("/usr/bin/scp \"/media/streams/$file.flv\" tuploads@tuve.ubixonline.com:.");

  /* Update The videos_pending Table */
  $query = "UPDATE videos_pending SET encoded = 1 WHERE vid = " . $qData['vid'];
  // mysql_query($query);
  $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(\"$artist\",\"$title\",\"$genre\",\"$file.flv\",$rid,$cid,$oid,$mType,$oLen,400,300,$uDate)";
  print "[$query]";
  // $res = mysql_query($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);

  /*
   * $fname = mysql_result($result, 0, 'firstname');
   * $lname = mysql_result($result, 0, 'lastname');
   * $email = mysql_result($result, 0, 'email');
   */
  mail($qData['firstname'] . " " . $qData['lastname'] . " <" . $qData['email'] . ">", "Media Encoded", $message, $headers);

  system("/bin/mv \"/usr/web/uploads/" . $qData['file'] . "\" /usr/home/tuve/encoded");
}
system("/bin/rm /tmp/cron2.php.lock");

function doExit($errorStr, $vid_id)
{
  /* Update The videos_pending Table */
  $query = "UPDATE videos_pending SET encoded = 2 WHERE vid = $vid_id";
  // mysql_query($query);
  $db->query($query);
  print("Error: $errorStr\n");
  exit(0);
}
?>
