Plugin Directory


Ignore:
Timestamp:
02/20/2012 10:00:46 PM (13 years ago)
Author:
kylegilman
Message:

Version 2.0 with multiple security fixes and UI improvements

Location:
video-embed-thumbnail-generator/trunk
Files:
2 added
6 edited

Legend:

Unmodified
Added
Removed
  • video-embed-thumbnail-generator/trunk/kg_callffmpeg.php

    r486697 r507924  
    11<?php
    2 
    3 $ffmpegPath = $_POST['ffmpeg']."/ffmpeg";
    4 $encodemobile = $_POST['encodemobile'];
    5 $encodeogg = $_POST['encodeogg'];
    6 $encodewebm = $_POST['encodewebm'];
    7 $movieurl = $_POST['movieurl'];
    8 $numberofthumbs = $_POST['numberofthumbs'];
    9 //$randomize = $_POST['randomize'];
    10 $action = $_POST['action'];
    11 $poster = $_POST['poster'];
    12 $uploads['path'] = $_POST['uploads_path'];
    13 $uploads['url'] = $_POST['uploads_url'];
    14 $uploads['basedir'] = $_POST['uploads_basedir'];
    15 $postID = $_POST['attachmentID'];
    16 $thumbtimecode = $_POST['thumbtimecode'];
    17 $dofirstframe = $_POST['dofirstframe'];
    18 $generate_button = $_POST['generate_button'];
    19 
    20 $moviefilepath = str_replace(" ", "%20", $movieurl);
     2global $ffmpegPath;
     3$ffmpegPath = get_option('wp_FMP_ffmpeg')."/ffmpeg";
     4$mobile_res = get_option('wp_FMP_mobile_res');
     5$uploads = wp_upload_dir();
     6if (isset($_POST['encodemobile'])) { $encodemobile = $_POST['encodemobile']; }
     7if (isset($_POST['encodeogg'])) { $encodeogg = $_POST['encodeogg']; }
     8if (isset($_POST['encodewebm'])) { $encodewebm = $_POST['encodewebm']; }
     9if (isset($_POST['movieurl'])) { $movieurl = $_POST['movieurl']; }
     10if (isset($_POST['numberofthumbs'])) { $numberofthumbs = $_POST['numberofthumbs']; }
     11if (isset($_POST['thumbnumber'])) { $i = $_POST['thumbnumber']; }
     12if (isset($_POST['thumbnumberplusincreaser'])) { $iincreaser = $_POST['thumbnumberplusincreaser']; }
     13if (isset($_POST['ffmpeg_action'])) { $action = $_POST['ffmpeg_action']; }
     14if (isset($_POST['poster'])) { $poster = $_POST['poster']; }
     15if (isset($_POST['attachmentID'])) { $postID = $_POST['attachmentID']; }
     16if (isset($_POST['thumbtimecode'])) { $thumbtimecode = $_POST['thumbtimecode']; }
     17if (isset($_POST['dofirstframe'])) { $dofirstframe = $_POST['dofirstframe']; }
     18if (isset($_POST['generate_button'])) { $generate_button = $_POST['generate_button']; }
     19
     20if ($postID != "singleurl") { $moviefilepath = get_attached_file($postID); }
     21else { $moviefilepath = str_replace(" ", "%20", $movieurl); }
    2122$movie_extension = pathinfo(parse_url($movieurl, PHP_URL_PATH), PATHINFO_EXTENSION);
    2223$moviefilebasename = basename($movieurl,'.'.$movie_extension);
    2324$thumbnailfilebase = $uploads['url']."/thumb_tmp/".$moviefilebasename;
     25
    2426
    2527class Process{
     
    3436    }
    3537    private function runCom(){
    36         $command = 'nohup '.$this->command.' > /dev/null 2>&1 & echo $!';
    37         //$command = 'nohup '.$this->command.' 1> /home/kylegilm/output.txt 2>&1';
    38         exec($command ,$op);
    39         $this->pid = (int)$op[0];
     38
     39           //$command = 'nohup '.$this->command.' > /dev/null 2>&1 & echo $!'; //this is the original command
     40
     41           $sys = strtoupper(PHP_OS); // Get OS Name
     42           if(substr($sys,0,3) == "WIN") {
     43            $command = $this->command;
     44        $this->OS = "windows";
     45           } //exec this way if it's Windows
     46
     47           else {
     48        $command = 'nohup '.$this->command;
     49        $this->OS = "linux";
     50       }
     51
     52           exec($command ,$op);
     53           $this->output = $op;
     54           if(substr($sys,0,3) != "WIN") { $this->pid = (int)$op[0]; }
    4055    }
    4156
     
    7893function get_video_dimensions($video = false) {
    7994    global $ffmpegPath;
     95
    8096    $command = $ffmpegPath . ' -i "' . $video . '" -vstats 2>&1';
    8197
    8298    exec ( $command, $output );
     99    $lastline = end($output);
     100    $lastline = prev($output)."<br />".$lastline; 
    83101    $output = implode("\n", $output);
    84102
     
    93111        preg_match('/configuration: (.*?)\n/', $output, $matches);
    94112        $configuration = $matches[1];
    95         return array ('width' => $width, 'height' => $height, 'duration' => $duration, 'configuration' => $configuration );
     113        preg_match('/rotate          : (.*?)\n/', $output, $matches);
     114        if ( array_key_exists(1, $matches) == true ) { $rotate = $matches[1]; }
     115        else $rotate = "0";
     116        return array ('width' => $width, 'height' => $height, 'duration' => $duration, 'configuration' => $configuration, 'rotate' => $rotate, 'worked'=>true );
    96117    } else {
    97         return false;
     118        return array ('output'=>$lastline, 'worked'=>false);
    98119    }
    99120
    100121}
    101122
    102 function rrmdir($dir) {
    103    if (is_dir($dir)) {
    104      $objects = scandir($dir);
    105      foreach ($objects as $object) {
    106        if ($object != "." && $object != "..") {
    107          if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
    108        }
    109      }
    110      reset($objects);
    111      rmdir($dir);
    112    }
    113 }
    114 
    115 
    116 if ($action == generate || $action == encode ) {
    117 
    118     exec($ffmpegPath.' /dev/null 2>&1', $output, $returnvalue); //attempt to execute FFMPEG
    119 
    120     if ($returnvalue < 126 ) { //if FFMPEG executed
     123if ($action == "generate" || $action == "encode" ) {
     124
     125    //exec($ffmpegPath.' /dev/null 2>&1', $output, $returnvalue); //attempt to execute FFMPEG
     126    $ffmpeg_info = kg_check_ffmpeg_exists();
     127
     128    if ( $ffmpeg_info['ffmpeg_exists'] == true ) { //if FFMPEG executed
    121129
    122130        $movie_info = get_video_dimensions($moviefilepath);
    123131
    124         if ($movie_info != false) { //if FFMPEG was able to open the file
     132        if ($movie_info['worked'] == true) { //if FFMPEG was able to open the file
    125133
    126134            $movie_duration_hours = intval(substr($movie_info['duration'], -11, 2));
     
    131139            $movie_height = $movie_info['height'];
    132140
    133             if ($action == generate) {
    134 
    135                 //rrmdir($uploads['path'].'/thumb_tmp');
     141            switch ($movie_info['rotate']) {
     142                case "90": $movie_rotate = '-vf "transpose=1"'; break;
     143                case "180": $movie_rotate = '-vf "hflip,vflip"'; break;
     144                case "270": $movie_rotate = '-vf "transpose=2"'; break;
     145                default: $movie_rotate = ""; break;
     146            }
     147
     148            if ($action == "generate") {
     149
    136150                if (!file_exists($uploads['path'].'/thumb_tmp')) { mkdir($uploads['path'].'/thumb_tmp'); }
    137151
    138152                $thumbnailheight = strval(round(floatval($movie_height) / floatval($movie_width) * 200));
     153
     154                switch ($movie_info['rotate']) { //if it's a sideways iPhone video
     155                    case "90";
     156                    case "270": $thumbnailheight = strval(round(floatval($movie_width) / floatval($movie_height) * 200));
     157                }
     158
    139159                $jpgpath = $uploads['path']."/thumb_tmp/";
    140 
    141                 $i = 1;
    142                 $increaser = 0;
    143 
    144                 $thumbnaildisplaycode = '<p><strong>Choose Thumbnail:</strong></p><div style="border-style:solid; border-color:#ccc; border-width:1px; width:425px; text-align:center; margin-bottom:10px; padding:5px;">';
    145 
    146                 while ($i <= $numberofthumbs) {
    147160               
    148                     $iincreaser = $i + $increaser;
    149                     $movieoffset = round(($movie_duration_seconds * $iincreaser) / ($numberofthumbs * 2));
    150 
    151                     if ($generate_button == "random") { //adjust offset random amount
    152                         $movieoffset = $movieoffset - rand(0, round($movie_duration_seconds / $numberofthumbs));
    153                     }
    154 
    155                     if ($thumbtimecode) { //if a specific thumbnail timecode is set
    156                         if ($thumbtimecode == "firstframe") { $thumbtimecode = "0"; }
    157                         $timecode_array = explode(":", $thumbtimecode);
    158                         $timecode_array = array_reverse($timecode_array);
    159                         $thumbtimecode = $timecode_array[0] + ($timecode_array[1] * 60) + ($timecode_array[2] * 3600);
    160                         $movieoffset = $thumbtimecode;
    161                         $i = $numberofthumbs + 1;
    162                     }
    163 
    164                     if ($dofirstframe == "true" && $i == 1) {
    165                         $movieoffset = "0";
    166                     }
    167 
    168                     $thumbnailfilename[$i] = $jpgpath.$moviefilebasename."_thumb".$i.".jpg";
    169                     $thumbnailfilename[$i] = str_replace(" ", "_", $thumbnailfilename[$i]);
    170                     $ffmpeg_options = '-y -ss '.$movieoffset.' -i "'.$moviefilepath.'" -vframes 1 "'.$thumbnailfilename[$i].'"';
    171                     $thumbnailurl = $thumbnailfilebase."_thumb".$i.'.jpg';
    172                     $thumbnailurl = str_replace(" ", "_", $thumbnailurl);
    173 
    174                     exec($ffmpegPath." ".$ffmpeg_options);
    175 
    176                     if (floatval($movieoffset) > 60) {
    177                         $movieoffset_minutes = sprintf("%02s", intval(intval($movieoffset) / 60) );
    178                         $movieoffset_seconds = sprintf("%02s", round(fmod( floatval($movieoffset), 60), 2) );
    179                         $movieoffset_display = $movieoffset_minutes.":".$movieoffset_seconds;
    180                     }
    181                     else { $movieoffset_display = "00:".sprintf("%02s", $movieoffset); }
    182 
    183                     $thumbnaildisplaycode = $thumbnaildisplaycode.'<div style="text-align:center; display:inline-block; margin:2px;"><label for="kgflashmedia-thumb'.$i.'"><img src="'.$thumbnailurl.'?'.rand().'" width="200" height="'.$thumbnailheight.'"></label><br /><input type="radio" name="kgflashmedia-thumb" id="kgflashmedia-thumb'.$i.'" value="'.str_replace('/thumb_tmp/', '/', $thumbnailurl).'" onchange="getElementById(\'attachments['. $postID .'][kgflashmediaplayer-poster]\').value = this.value; getElementById(\'attachments['. $postID .'][thumbtime]\').value = \''. $movieoffset_display .'\'; getElementById(\'attachments_'. $postID .'_numberofthumbs\').value =\'1\';"></div>';
    184 
    185                     $increaser++;
    186                     $i++;
    187                 } //end thumbnail loop
    188 
    189                 //$thumbnaildisplaycode = $thumbnaildisplaycode.'<p><input type="button" id="attachments['. $postID .'][confirmbutton]" class="button-secondary" value="Confirm" name="confirmbutton" onclick="kg_generate_thumb('. $postID .', \'confirm\');"/></p>';
    190 
    191                 $arr = array ( "thumbnaildisplaycode"=>$thumbnaildisplaycode, "movie_width"=>$movie_width, "movie_height"=>$movie_height );
     161                $movieoffset = round(($movie_duration_seconds * $iincreaser) / ($numberofthumbs * 2));
     162
     163                if ($generate_button == "random") { //adjust offset random amount
     164                    $movieoffset = $movieoffset - rand(0, round($movie_duration_seconds / $numberofthumbs));
     165                    if ($movieoffset < 0) { $movieoffset = "0"; }
     166                }
     167
     168                if ($thumbtimecode) { //if a specific thumbnail timecode is set
     169                    if ($thumbtimecode == "firstframe") { $thumbtimecode = "0"; }
     170                    $timecode_array = explode(":", $thumbtimecode);
     171                    $timecode_array = array_reverse($timecode_array);
     172                    $thumbtimecode = $timecode_array[0] + ($timecode_array[1] * 60) + ($timecode_array[2] * 3600);
     173                    $movieoffset = $thumbtimecode;
     174                    $i = $numberofthumbs + 1;
     175                }
     176
     177                if ($dofirstframe == "true" && $i == 1) {
     178                    $movieoffset = "0";
     179                }
     180
     181                $thumbnailfilename[$i] = $jpgpath.$moviefilebasename."_thumb".$i.".jpg";
     182                $thumbnailfilename[$i] = str_replace(" ", "_", $thumbnailfilename[$i]);
     183                $ffmpeg_options = '-y -ss '.$movieoffset.' -i "'.$moviefilepath.'" '.$movie_rotate.' -vframes 1 "'.$thumbnailfilename[$i].'"';
     184                $thumbnailurl = $thumbnailfilebase."_thumb".$i.'.jpg';
     185                $thumbnailurl = str_replace(" ", "_", $thumbnailurl);
     186
     187                exec($ffmpegPath." ".$ffmpeg_options);
     188
     189                if (floatval($movieoffset) > 60) {
     190                    $movieoffset_minutes = sprintf("%02s", intval(intval($movieoffset) / 60) );
     191                    $movieoffset_seconds = sprintf("%02s", round(fmod( floatval($movieoffset), 60), 2) );
     192                    $movieoffset_display = $movieoffset_minutes.":".$movieoffset_seconds;
     193                }
     194                else { $movieoffset_display = "00:".sprintf("%02s", $movieoffset); }
     195
     196                $thumbnaildisplaycode = '<div class="kg_thumbnail_select" name="attachments_'.$postID.'_thumb'.$i.'" id="attachments_'.$postID.'_thumb'.$i.'"><label for="kgflashmedia-thumb'.$i.'"><img src="'.$thumbnailurl.'?'.rand().'" width="200" height="'.$thumbnailheight.'" class="kg_thumbnail"></label><br /><input type="radio" name="kgflashmedia-thumb" id="kgflashmedia-thumb'.$i.'" value="'.str_replace('/thumb_tmp/', '/', $thumbnailurl).'" onchange="getElementById(\'attachments['. $postID .'][kgflashmediaplayer-poster]\').value = this.value; getElementById(\'attachments['. $postID .'][thumbtime]\').value = \''. $movieoffset_display .'\'; getElementById(\'attachments_'. $postID .'_numberofthumbs\').value =\'1\';"></div>';
     197
     198                switch ($movie_info['rotate']) {
     199                    case "90";
     200                    case "270": $movie_width ^= $movie_height ^= $movie_width ^= $movie_height; break; //swap height & width
     201                }
     202
     203                $i++;
     204
     205                $arr = array ( "thumbnaildisplaycode"=>$thumbnaildisplaycode, "movie_width"=>$movie_width, "movie_height"=>$movie_height, "lastthumbnumber"=>$i, "movieoffset"=>$movieoffset );
    192206
    193207                echo json_encode($arr);
    194208            }//if generate
    195209
    196             if ($action == encode) {
     210            if ($action == "encode") {
    197211
    198212                //preferred encode path is the directory of the original file (likely in the wp_upload dir)
    199213                $encodepath = "";
    200                 $url_parts = parse_url($uploads['url']);
    201                 if ( strpos($moviefilepath, $url_parts['host']) != "" ) { //if we're on the same server
    202                     $home_path = substr(strrev(strstr(strrev($uploads['basedir']), strrev("public_html"))), 0, -strlen("public_html")); //home path of the current server
    203                     $moviefiledirectory = dirname(parse_url($moviefilepath, PHP_URL_PATH)); //gets file's directory
    204                     $encodepath = $home_path."public_html".$moviefiledirectory."/";
    205                 }
    206                 if ( !is_writable($encodepath) ) { //if the original directory is not writable use a directory in base wp_upload
    207                     $encodepath = $uploads['basedir']."/html5encodes/";
    208                     if ( !file_exists($encodepath) ) { mkdir($encodepath); }
    209                 }
    210 
    211                 $ipodfilepath = $encodepath.$moviefilebasename."-ipod.m4v";
    212                 $ogvfilepath = $encodepath.$moviefilebasename.".ogv";
    213                 $webmfilepath = $encodepath.$moviefilebasename.".webm";
     214                $embed_display = "";
     215                $ffmpeg_ipod_options = "";
     216                $ffmpeg_ogv_options = "";
     217                $ffmpeg_webm_options = "";
     218                $logfile = "";
     219                $processPID = "";
     220                $serverOS = "";
     221                               
     222                $encode_anything = "false";
     223
     224                $encodevideo_info = kg_encodevideo_info($movieurl, $postID);
    214225
    215226                if ($encodemobile == "true") {
    216                 if ( ! file_exists($ipodfilepath) || filesize($webmfilepath) < 24576 ) {
    217                     $ipod_movie_height = strval(round(floatval($movie_height) / floatval($movie_width) * 640));
    218                     if ($ipod_movie_height % 2 != 0) { $ipod_movie_height++; }
    219                     if ( strpos($movie_info['configuration'], 'enable-libfaac') &&  strpos($movie_info['configuration'], 'enable-libx264') ) {
    220                         $ffmpeg_ipod_options = ' -acodec libfaac -ab 128k -s 640x'.$ipod_movie_height.' -vcodec libx264 -vpre slow -vpre ipod640 -b 800k -bt 800k -threads 1 -f ipod "'.$ipodfilepath.'"';
    221                         $embed_display .= "<strong> Encoding Mobile M4V... </strong>";
     227                if ( ! $encodevideo_info['mobile_exists'] || ($encodevideo_info['sameserver'] && filesize($encodevideo_info['mobilefilepath']) < 24576) ) {
     228
     229                    switch($mobile_res) {
     230                        case "480": $ipod_movie_max_width = 640; break;
     231                        case "720": $ipod_movie_max_width = 1280; break;
     232                        case "1080": $ipod_movie_max_width = 1920; break;
     233                        default: $ipod_movie_max_width = 640;
     234                    }
     235
     236                    if ( floatval($movie_width)  > $ipod_movie_max_width ) { $ipod_movie_width = strval($ipod_movie_max_width); }
     237                    else { $ipod_movie_width = $movie_width; }
     238                    $ipod_movie_height = strval(round(floatval($movie_height) / floatval($movie_width) * $ipod_movie_width));
     239                    if ($ipod_movie_height % 2 != 0) { $ipod_movie_height++; } //make sure it's an even number
     240
     241                    if ( strpos($movie_info['configuration'], 'enable-libfaac') || strpos($movie_info['configuration'], 'enable-libvo-aacenc') &&  strpos($movie_info['configuration'], 'enable-libx264') ) {
     242
     243                        if ( strpos($movie_info['configuration'], 'enable-libfaac') ) { $aaclib = "libfaac"; }
     244                        else { $aaclib = "libvo_aacenc"; }
     245
     246                        $ipodbitrate = $movie_height * 3;
     247
     248                        $ffmpeg_ipod_options = ' -acodec '.$aaclib.' -ab 128k -s '.$ipod_movie_width.'x'.$ipod_movie_height.' -vcodec libx264 -threads 1 '.$movie_rotate.' -b:v '.$ipodbitrate.'k -bt 800k -f ipod "'.$encodevideo_info['mobilefilepath'].'"';
     249                        $encode_anything = "true";
     250                        $embed_display .= "<strong> Encoding Mobile M4V. </strong>";
    222251                    }//if the proper FFMPEG libraries are enabled
    223                     else { $embed_display .= "<strong>FFMPEG missing library 'libfaac' or 'libx264' required for iPod encoding. </strong>"; }
    224                 }//if iPod file doesn't already exist
     252                    else { $embed_display .= "<strong>FFMPEG missing library 'libfaac' 'libvo-aacenc' or 'libx264' required for Mobile M4V encoding. </strong>"; }
     253                }//if mobile file doesn't already exist
    225254                else { $embed_display .= "<strong>Mobile M4V Already Encoded! </strong>"; }
    226255                }//if mobile is checked
    227256
    228257                if ($encodewebm == "true") {
    229                 if ( ! file_exists($webmfilepath) || filesize($webmfilepath) < 24576 ) {
     258                if ( ! $encodevideo_info['webm_exists'] || ($encodevideo_info['sameserver'] && filesize($encodevideo_info['webmfilepath']) < 24576) ) {
    230259                    if ( strpos($movie_info['configuration'], 'enable-libvorbis') &&  strpos($movie_info['configuration'], 'enable-libvpx') ) {
    231260                        $webmbitrate = $movie_height * 3;
    232                         $ffmpeg_webm_options = ' -ab 128k -b '.$webmbitrate.'k -threads 1 "'.$webmfilepath.'"';
    233                         $embed_display .= "<strong> Encoding WEBM... </strong>";
     261                        $ffmpeg_webm_options = ' -ab 128k -b:v '.$webmbitrate.'k '.$movie_rotate.' -threads 1 "'.$encodevideo_info['webmfilepath'].'"';
     262                        $encode_anything = "true";
     263                        $embed_display .= "<strong> Encoding WEBM. </strong>";
    234264                    }//if the proper FFMPEG libraries are enabled
    235265                    else { $embed_display .= "<strong>FFMPEG missing library 'libvorbis' or 'libvpx' required for WEBM encoding. </strong>"; }
     
    239269
    240270                if ($encodeogg == "true") {
    241                 if ( ! file_exists($ogvfilepath) || filesize($webmfilepath) < 24576 ) {
     271                if ( ! $encodevideo_info['ogg_exists'] || ($encodevideo_info['sameserver'] && filesize($encodevideo_info['oggfilepath']) < 24576) ) {
    242272
    243273                    if ( strpos($movie_info['configuration'], 'enable-libvorbis') &&  strpos($movie_info['configuration'], 'enable-libtheora') ) {
    244274                        $ogvbitrate = $movie_height * 3;
    245                         $ffmpeg_ogv_options = ' -acodec libvorbis -ab 128k -vcodec libtheora -b '.$ogvbitrate.'k -threads 1 "'.$ogvfilepath.'"';
    246                         $embed_display .= "<strong> Encoding OGV... </strong>";
     275                        $ffmpeg_ogv_options = ' -acodec libvorbis -ab 128k -vcodec libtheora -b:v '.$ogvbitrate.'k '.$movie_rotate.' -threads 1 "'.$encodevideo_info['oggfilepath'].'"';
     276                        $encode_anything = "true";
     277                        $embed_display .= "<strong> Encoding OGV. </strong>";
    247278                    }//if the proper FFMPEG libraries are enabled
    248279                    else { $embed_display .= "<strong>FFMPEG missing library 'libvorbis' or 'libtheora' required for OGV encoding. </strong>"; }
     
    252283
    253284
    254                 if ( ! file_exists($ogvfilepath) || ! file_exists($ipodfilepath) || ! file_exists($webmfilepath) ) {
    255                     $ffmpeg_options = '-y -i "'.$moviefilepath.'"'.$ffmpeg_ipod_options.$ffmpeg_ogv_options.$ffmpeg_webm_options;
    256 
    257                     $process = new Process($ffmpegPath." ".$ffmpeg_options);
     285                if ( $encode_anything == "true" ) {
     286
     287                    if ( ! file_exists($encodevideo_info['encodepath']) ) { mkdir($encodevideo_info['encodepath']); }           
     288
     289                    $ffmpeg_options = '-y -i "'.$moviefilepath.'" '.$ffmpeg_ipod_options.$ffmpeg_ogv_options.$ffmpeg_webm_options;
     290                    $logfile = $encodevideo_info['encodepath'].str_replace(" ", "_", $moviefilebasename)."_".sprintf("%04s",mt_rand(1, 1000))."_encode.txt";
     291                    $cmd = escapeshellcmd($ffmpegPath." ".$ffmpeg_options);
     292                    $cmd = $cmd." > ".$logfile." 2>&1 & echo $!";
     293                   
     294                    $process = new Process($cmd);
     295
     296                    sleep(1);
     297
     298                    $processPID = $process->getPid();
     299                    $serverOS = $process->OS;
     300                    $encodevideo_info = kg_encodevideo_info($movieurl, $postID); //update after encoding starts
     301
     302                    $embed_display .= " <em><small>(continues if window is closed)</small></em>";
     303
     304                    //$output_map = array_map(create_function('$key, $value', 'return $key.":".$value." # ";'), array_keys($process->output), array_values($process->output));
     305                    //$output_implode = implode($output_map);
     306                   
     307                    //$embed_display .= "Command: ".$cmd." Status: ".$process->status()." Output: ".$output_implode;
    258308
    259309                }//if any HTML5 videos don't already exist
    260310
    261                 $arr = array ( "embed_display"=>$embed_display );
    262 
     311                $replaceoptions = "";
     312                if ( $encodevideo_info['mobile_exists'] ) { $replaceoptions .= '<option value="'.$encodevideo_info['mobileurl'].'">Mobile/H.264</option>'; }
     313                if ( $encodevideo_info['webm_exists'] ) { $replaceoptions .= '<option value="'.$encodevideo_info['webmurl'].'">WEBM</option>'; }
     314                if ( $encodevideo_info['ogg_exists'] ) { $replaceoptions .= '<option value="'.$encodevideo_info['oggurl'].'">OGV</option>'; }
     315
     316                $altembedselect = '<span class="kg_embedselect">Embed <select name="attachments['.$postID.'][kgflashmediaplayer-altembed]" id="attachments['.$postID.'][kgflashmediaplayer-altembed]"><option value="'.$movieurl.'">original</option>'.$replaceoptions.'</select></span>';
     317
     318                //$encodevideo_info_map = array_map(create_function('$key, $value', 'return $key.":".$value." # ";'), array_keys($encodevideo_info), array_values($encodevideo_info));
     319                //$encodevideo_info_implode = implode($encodevideo_info_map);
     320
     321                $arr = array ( "embed_display"=>$embed_display, "pid"=>$processPID, "logfile"=>$logfile, "movie_duration"=>$movie_duration_seconds, "encode_anything"=>$encode_anything, "altembedselect"=>$altembedselect, "serverOS"=>$serverOS );
    263322                echo json_encode($arr);
    264 
     323               
    265324            }//if encode
    266325
    267326        }//if ffmpeg can open movie
    268327
    269         else { $thumbnaildisplaycode = '<strong>Can\'t open movie file.</strong>' ;
    270             $arr = array ( "thumbnaildisplaycode"=>$thumbnaildisplaycode );
     328        else { $thumbnaildisplaycode = '<strong>Can\'t open movie file.</strong><br />'.$movie_info['output'];
     329            $arr = array ( "thumbnaildisplaycode"=>$thumbnaildisplaycode, "embed_display"=>$thumbnaildisplaycode, "lastthumbnumber"=>"break" );
    271330            echo json_encode($arr);
    272331        } //can't open movie
     
    275334
    276335    else { $thumbnaildisplaycode = '<strong>Error: FFMPEG not found. Verify that FFMPEG is installed and check the <a href="options-general.php?page=video-embed-thumbnail-generator.php">path to FFMPEG plugin setting</a>.</strong>' ;
    277         $arr = array ( "thumbnaildisplaycode"=>$thumbnaildisplaycode );
     336        $arr = array ( "thumbnaildisplaycode"=>$thumbnaildisplaycode, "embed_display"=>$thumbnaildisplaycode, "lastthumbnumber"=>"break" );
    278337        echo json_encode($arr);
    279338    } //no ffmpeg
     
    282341}// if encoding or generating
    283342
    284 if ($action == delete) {
     343if ($action == "delete") {
    285344
    286345    if ($poster) {
     
    297356
    298357
    299 if ($action == submit) {
     358if ($action == "submit") {
    300359
    301360        $posterfile = pathinfo($poster, PATHINFO_BASENAME);
     
    309368                }
    310369            }
    311             if ( is_dir($uploads['path'].'/thumb_tmp') && ($files = @scandir($uploads['path'].'/thumb_tmp') && (count($files) < 2)) ) { rmdir($uploads['path'].'/thumb_tmp'); }
     370
     371            if ( is_empty_dir($uploads["path"].'/thumb_tmp') ) { rrmdir($uploads["path"].'/thumb_tmp'); }
    312372        }
    313373
  • video-embed-thumbnail-generator/trunk/kg_video_plugin.js

    r486697 r507924  
    1414
    1515function kg_set_aspect(postID, checked) {
    16 if (checked) { document.getElementById('attachments['+postID+'][kgflashmediaplayer-aspect]').value = document.getElementById('attachments_'+postID+'_kgflashmediaplayer-height').value / document.getElementById('attachments_'+postID+'_kgflashmediaplayer-width').value; }
     16    if (checked) { document.getElementById('attachments['+postID+'][kgflashmediaplayer-aspect]').value = document.getElementById('attachments_'+postID+'_kgflashmediaplayer-height').value / document.getElementById('attachments_'+postID+'_kgflashmediaplayer-width').value;
     17    }
    1718}
    1819
    1920function kg_generate_thumb(postID, buttonPushed) {
    2021
    21     var kg_ffmpeg_path = document.getElementById('attachments['+postID+'][kgflashmediaplayer-ffmpeg_path]').value;
     22    var kgflashmediaplayersecurity = document.getElementById('attachments['+postID+'][kgflashmediaplayer-security]').value;
    2223    var kg_encodemobile = document.getElementById('attachments['+postID+'][kgflashmediaplayer-encodemobile]').value;
    2324    var kg_encodeogg = document.getElementById('attachments['+postID+'][kgflashmediaplayer-encodeogg]').value;
    2425    var kg_encodewebm = document.getElementById('attachments['+postID+'][kgflashmediaplayer-encodewebm]').value;
    25     var kg_plugin_dir = document.getElementById('attachments['+postID+'][kgflashmediaplayer-plugin_dir]').value;
    26     var kg_upload_dir_url = document.getElementById('attachments['+postID+'][kgflashmediaplayer-upload_url]').value;
    27     var kg_upload_dir_path = document.getElementById('attachments['+postID+'][kgflashmediaplayer-upload_path]').value;
    28     var kg_upload_dir_basedir = document.getElementById('attachments['+postID+'][kgflashmediaplayer-upload_basedir]').value;
    2926    var attachmentURL = document.getElementById('attachments['+postID+'][kgflashmediaplayer-url]').value;
    3027    var howmanythumbs = document.getElementById('attachments_'+postID+'_numberofthumbs').value;
     
    3532    var thumbnailplaceholderid = "#attachments_"+postID+"_thumbnailplaceholder";
    3633    var encodeplaceholderid = "#attachments_"+postID+"_encodeplaceholder";
     34    var encodeprogressplaceholderid = "#attachments_"+postID+"_encodeprogressplaceholder";
     35    var altembedselectid = "#attachments_"+postID+"_altembedselect";
     36    var thumbnailboxID = "#attachments_"+postID+"_kgflashmediaplayer-thumbnailbox";
     37    var thumbnailboxoverlayID = "#attachments_"+postID+"_kgflashmediaplayer-thumbnailboxoverlay";
    3738    var widthID = 'attachments_'+postID+'_kgflashmediaplayer-width';
    3839    var heightID = 'attachments_'+postID+'_kgflashmediaplayer-height';
     
    4243    var maxheightID = 'attachments['+postID+'][kgflashmediaplayer-maxheight]';
    4344
    44 
    45     if (buttonPushed == "generate" || buttonPushed == "random" ) { actionName = "generate"; }
    46     else { actionName = buttonPushed; }
    47 
    48     if (buttonPushed == "delete") {
    49         document.getElementById('attachments['+postID+'][kgflashmediaplayer-poster]').value = "";
    50         document.getElementById('attachments['+postID+'][thumbtime]').value = "";
     45    if (buttonPushed == "generate" || buttonPushed == "random" ) {
     46        actionName = "generate";
     47        if (specifictimecode != 0 ) { howmanythumbs = 1; }
     48    }
     49    else {
     50        actionName = buttonPushed;
     51        howmanythumbs = 1;
    5152    }
    5253
    5354    if (buttonPushed != "encode") {
    5455        jQuery(thumbnailplaceholderid).empty();
    55         jQuery(thumbnailplaceholderid).append('<strong>Loading...</strong>');
     56        jQuery(thumbnailplaceholderid).append('<p><strong>Choose Thumbnail:</strong></p><div id="attachments_'+postID+'_kgflashmediaplayer-thumbnailboxoverlay" name="attachments_'+postID+'_kgflashmediaplayer-thumbnailboxoverlay" class="kg_thumbnail_overlay"><div id="attachments_'+postID+'_kgflashmediaplayer-ajaxloading" name="attachments_'+postID+'_kgflashmediaplayer-ajaxloading" class="kg_ajax_loading"></div><div name="attachments_'+postID+'_kgflashmediaplayer-thumbnailbox" id="attachments_'+postID+'_kgflashmediaplayer-thumbnailbox" class="kg_thumbnail_box"></div></div>');
    5657    }
    5758
    5859    if (buttonPushed == "encode") {
    5960        jQuery(encodeplaceholderid).empty();
    60     }
    61 
    62     jQuery.post(kg_plugin_dir + '/kg_callffmpeg.php', { movieurl: attachmentURL, numberofthumbs: howmanythumbs, action: actionName, ffmpeg: kg_ffmpeg_path, encodemobile: kg_encodemobile, encodeogg: kg_encodeogg, encodewebm: kg_encodewebm, uploads_path: kg_upload_dir_path, uploads_url: kg_upload_dir_url, uploads_basedir: kg_upload_dir_basedir, attachmentID: postID, generate_button: buttonPushed, thumbtimecode: specifictimecode, dofirstframe: firstframethumb, poster: posterurl }, function(data) {
    63 
    64         if (buttonPushed != "encode") {
    65             jQuery(thumbnailplaceholderid).empty();
    66             jQuery(thumbnailplaceholderid).append(data.thumbnaildisplaycode);
    67         }
    68 
    69         if (actionName == "generate") {
    70             kg_aspect = data.movie_height/data.movie_width;
    71             document.getElementById('attachments['+postID+'][kgflashmediaplayer-aspect]').value = kg_aspect;
    72             if (parseInt(data.movie_width) < parseInt(document.getElementById(maxwidthID).value) ) { document.getElementById(widthID).value = data.movie_width; }
    73             else { document.getElementById(widthID).value = document.getElementById(maxwidthID).value; }
    74             if (parseInt(data.movie_width) > parseInt(document.getElementById(maxwidthID).value) ) { document.getElementById(heightID).value = Math.round(kg_aspect*parseInt(document.getElementById(maxwidthID).value)); }
    75             else { document.getElementById(heightID).value = data.movie_height; }
    76             if(postID != "singleurl") {
    77                 document.getElementById(widthsaveID).value = document.getElementById(widthID).value;
    78                 document.getElementById(heightsaveID).value = document.getElementById(heightID).value;
     61        jQuery(encodeprogressplaceholderid).empty();
     62        jQuery(encodeplaceholderid).append('<strong>Encoding...</strong>');
     63    }
     64
     65
     66    var i=1;
     67    var increaser = 0;
     68    var iincreaser = 0;
     69
     70    //for (i=1; i<=howmanythumbs; i++) { //loop until thumbnails are generated
     71
     72    function kg_do_post() {
     73
     74        iincreaser = i + increaser;
     75
     76        jQuery.post(ajaxurl, { action:"kg_callffmpeg", security: kgflashmediaplayersecurity, movieurl: attachmentURL, numberofthumbs: howmanythumbs, thumbnumber:i, thumbnumberplusincreaser:iincreaser, ffmpeg_action: actionName, encodemobile: kg_encodemobile, encodeogg: kg_encodeogg, encodewebm: kg_encodewebm, attachmentID: postID, generate_button: buttonPushed, thumbtimecode: specifictimecode, dofirstframe: firstframethumb, poster: posterurl }, function(data) {
     77   
     78            if (buttonPushed != "encode") {
     79                jQuery(thumbnailboxID).append(data.thumbnaildisplaycode);
     80                var thumbnailselectID = "#attachments_"+postID+"_thumb"+i;
     81                jQuery(thumbnailselectID).css({display:"none"});
     82                //jQuery(thumbnailselectID).fadeIn(1000);
     83                jQuery(thumbnailselectID).animate({opacity: 'toggle', height: 'toggle', width: 'toggle'}, 1000);
     84                //jQuery(thumbnailselectID).animate({display:"inline-block"}, 2000);
     85                if (data.lastthumbnumber != "break") { i = parseInt(data.lastthumbnumber); }
     86                else { i = howmanythumbs + 1; }
     87                increaser++;
     88                if ( i <= howmanythumbs ) { setTimeout(function(){kg_do_post()}, 1000); }
     89                else { jQuery(thumbnailboxoverlayID).fadeTo(2000, 1); }
     90
     91                kg_aspect = data.movie_height/data.movie_width;
     92                document.getElementById('attachments['+postID+'][kgflashmediaplayer-aspect]').value = kg_aspect;
     93                if (parseInt(data.movie_width) < parseInt(document.getElementById(maxwidthID).value) ) { document.getElementById(widthID).value = data.movie_width; }
     94                else { document.getElementById(widthID).value = document.getElementById(maxwidthID).value; }
     95                if (parseInt(data.movie_width) > parseInt(document.getElementById(maxwidthID).value) ) { document.getElementById(heightID).value = Math.round(kg_aspect*parseInt(document.getElementById(maxwidthID).value)); }
     96                else { document.getElementById(heightID).value = data.movie_height; }
     97                if(postID != "singleurl") {
     98                    document.getElementById(widthsaveID).value = document.getElementById(widthID).value;
     99                    document.getElementById(heightsaveID).value = document.getElementById(heightID).value;
     100                }
     101                jQuery.post( ajaxurl ,  { action:"kg_schedule_cleanup_generated_files", security:kgflashmediaplayersecurity, thumbs:"true" } );
    79102            }
    80         }
    81 
    82         if (buttonPushed == "encode") {
    83             jQuery(encodeplaceholderid).append(data.embed_display);
    84         }
    85 
    86     }, "json");
    87 
    88 jQuery.post( ajaxurl ,  { action:"kg_schedule_cleanup_generated_files" } );
    89 
     103   
     104            if (buttonPushed == "encode") {
     105                jQuery(encodeplaceholderid).empty();
     106                jQuery(encodeprogressplaceholderid).empty();
     107                jQuery(encodeplaceholderid).append(data.embed_display);
     108                jQuery(altembedselectid).empty();
     109                jQuery(altembedselectid).append(data.altembedselect);
     110                if ( data.encode_anything == "true" ) {
     111                    var kg_start_time = new Date().getTime();
     112                    jQuery.post( ajaxurl ,  { action:"kg_schedule_cleanup_generated_files", security:kgflashmediaplayersecurity, logfile:data.logfile } );
     113                    if (data.serverOS != "windows" ) {
     114                        jQuery(encodeprogressplaceholderid).append('<div class="meter"><span style="width:0%;"></span></div>');
     115                        setTimeout(function(){kg_check_encode_progress(postID, data.pid, data.logfile, data.movie_duration, data.altembedselect, kg_start_time)}, 1000);
     116                    }
     117                    else { //if it's Windows skip the progress bar
     118                        jQuery(encodeprogressplaceholderid).append('<div class="meter_finished"><span style="width:100%;">100%</span></div>');
     119                        jQuery(encodeplaceholderid).empty();
     120                        jQuery(encodeplaceholderid).append('<strong>Encoding Complete</strong>');
     121                    }
     122                }
     123            }
     124        }, "json");
     125
     126    }// end kg_do_post function
     127
     128    kg_do_post(); //actually call the loop
    90129}
    91130
    92131function kg_insert_shortcode() {
    93132
    94     jQuery.post(document.getElementById('attachments[singleurl][kgflashmediaplayer-plugin_dir]').value + '/kg_callffmpeg.php', {
    95         movieurl: document.getElementById('attachments[singleurl][kgflashmediaplayer-url]').value, action:'submit', poster: document.getElementById('attachments[singleurl][kgflashmediaplayer-poster]').value, uploads_path: document.getElementById('attachments[singleurl][kgflashmediaplayer-upload_path]').value }, function(data) {
     133    var kgflashmediaplayersecurity = document.getElementById('attachments[singleurl][kgflashmediaplayer-security]').value;
     134
     135    jQuery.post(ajaxurl, { action:'kg_callffmpeg', security: kgflashmediaplayersecurity, attachmentID: 'singleurl', movieurl: document.getElementById('attachments[singleurl][kgflashmediaplayer-url]').value, ffmpeg_action:'submit', poster: document.getElementById('attachments[singleurl][kgflashmediaplayer-poster]').value }, function(data) {
    96136        jQuery('attachments_singleurl_thumbnailplaceholder').empty();
    97137    }, "json" );
     
    109149    parent.send_to_editor(shortcode);
    110150}
     151
     152function kg_check_encode_progress(postID, kg_pid, kg_logfile, kg_movie_duration, kg_altembedselect, kg_start_time) {
     153    var encodeprogressplaceholderid = "#attachments_"+postID+"_encodeprogressplaceholder";
     154    var encodeplaceholderid = "#attachments_"+postID+"_encodeplaceholder";
     155    var altembedselectid = "#attachments_"+postID+"_altembedselect";
     156    var kgflashmediaplayersecurity = document.getElementById('attachments['+postID+'][kgflashmediaplayer-security]').value;
     157    var stopChecking = false;
     158
     159    jQuery.post(ajaxurl, { action:"kg_check_encode_progress", security: kgflashmediaplayersecurity, pid: kg_pid, logfile: kg_logfile, movie_duration: kg_movie_duration }, function(data) {
     160
     161        var display_percent = "";
     162        if ( data.percent_done > 7 ) { display_percent = data.percent_done+"%"; }
     163
     164        var kg_current_time = new Date().getTime();
     165        var kg_time_elapsed = Math.round( (kg_current_time - kg_start_time) / 1000 );
     166        if ( kg_time_elapsed >= 60 ) {
     167            kg_time_elapsed_minutes = Math.floor(kg_time_elapsed/60);
     168            kg_time_elapsed_seconds = kg_time_elapsed%60;
     169            kg_time_elapsed_seconds = (kg_time_elapsed_seconds < 10) ? ("0" + kg_time_elapsed_seconds) : kg_time_elapsed_seconds;
     170            kg_time_elapsed_display = kg_time_elapsed_minutes+':'+kg_time_elapsed_seconds;
     171        }
     172        else { kg_time_elapsed_display = kg_time_elapsed+' seconds'; }
     173
     174        if ( data.percent_done != "" && data.percent_done != "100" ) {
     175            var kg_time_remaining = Math.floor( (kg_time_elapsed / (data.percent_done/100) ) - kg_time_elapsed);
     176            if ( kg_time_remaining >= 60 ) {
     177                kg_time_remaining_minutes = Math.round(kg_time_remaining/60);
     178                kg_time_remaining_seconds = kg_time_remaining%60;
     179                kg_time_remaining_seconds = (kg_time_remaining_seconds < 10) ? ("0" + kg_time_remaining_seconds) : kg_time_remaining_seconds;
     180                kg_time_remaining_display = kg_time_remaining_minutes+':'+kg_time_remaining_seconds;
     181            }
     182            else { kg_time_remaining_display = kg_time_remaining+' seconds'; }
     183            jQuery(encodeprogressplaceholderid).empty();
     184            jQuery(encodeprogressplaceholderid).append('<div class="meter"><span style="width:'+data.percent_done+'%;">'+display_percent+'</span></div><div class="kg_cancel_button"><input type="button" id="attachments_'+postID+'_kgflashmediaplayer-cancelencode" class="button-secondary" value="Cancel" name="attachments_'+postID+'_cancelencode" onclick="kg_cancel_encode('+kg_pid+', \''+postID+'\');"></div><div style="display:block;"><small>Elapsed: '+kg_time_elapsed_display+'. Estimated Remaining: '+kg_time_remaining_display+'. FPS:'+data.fps+'</small></div>');
     185        }
     186
     187        if (data.other_message != "") {
     188            clearTimeout(percent_timeout);
     189            stopChecking = true;
     190            jQuery(encodeplaceholderid).empty();
     191            jQuery(encodeplaceholderid).append('<strong>Encoding Halted</strong>');
     192            jQuery(encodeprogressplaceholderid).empty();
     193            jQuery(encodeprogressplaceholderid).append('<strong><span style="color:red;">Message from FFMPEG: '+data.other_message+'</span></strong>');
     194        }
     195
     196        if ( data.percent_done == "100" ) {
     197            clearTimeout(percent_timeout);
     198            stopChecking = true;
     199            //delete window.kg_start_time_over;
     200            jQuery(encodeprogressplaceholderid).empty();
     201            jQuery(encodeprogressplaceholderid).append('<div class="meter_finished"><span style="width:100%;">100%</span></div><div style="display:block;"><small>Elapsed: '+kg_time_elapsed+' seconds. Estimated Remaining: 0 seconds.</small></div>');
     202            jQuery(encodeplaceholderid).empty();
     203            jQuery(encodeplaceholderid).append('<strong>Encoding Complete</strong>');
     204        }
     205        //jQuery(encodeplaceholderid).empty();
     206        //jQuery(encodeplaceholderid).append(data.embed_display);
     207
     208        if ( data.fps !== "" ) {
     209            var kg_timetowait = Math.round(30000/parseInt(data.fps));
     210            if (kg_timetowait < 1000) { kg_timetowait = 1000; }
     211        }
     212        else { var kg_timetowait = 2000; }
     213
     214        if ( stopChecking != true ) {
     215            percent_timeout = setTimeout(function(){kg_check_encode_progress(postID, kg_pid, kg_logfile, kg_movie_duration, kg_altembedselect, kg_start_time)}, kg_timetowait);
     216        }
     217
     218    }, "json" );
     219}
     220
     221function kg_cancel_encode(kg_pid, postID) {
     222
     223    var kgflashmediaplayersecurity = document.getElementById('attachments['+postID+'][kgflashmediaplayer-security]').value;
     224    var cancelbuttonID = 'attachments_'+postID+'_kgflashmediaplayer-cancelencode';
     225
     226    document.getElementById(cancelbuttonID).disabled = true;
     227    document.getElementById(cancelbuttonID).title = "Command sent. Be patient";
     228   
     229    jQuery.post(ajaxurl, { action:"kg_cancel_encode", security: kgflashmediaplayersecurity, kg_pid: kg_pid } );
     230
     231}
  • video-embed-thumbnail-generator/trunk/readme.txt

    r486730 r507924  
    1 === Plugin Name ===
     1=== Video Embed & Thumbnail Generator ===
    22Contributors: kylegilman
    3 Tags: video, html5, shortcode, thumbnail, ffmpeg
     3Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=kylegilman@gmail.com&item_name=Video%20Embed%20And%20Thumbnail%20Generator%20Plugin%20Donation/
     4Tags: video, html5, shortcode, thumbnail, ffmpeg, embed, mobile, webm, ogg, h.264
    45Requires at least: 3.0
    56Tested up to: 3.3.1
    6 Stable tag: 1.1
     7Stable tag: 2.0
    78
    89Generates thumbnails, HTML5-compliant videos, and embed codes for locally hosted videos. Requires FFMPEG for thumbnails and encodes.
     
    1617The embedded player will default to a Flash video player if you're using a Flash-compatible file (flv, f4v, mp4, mov, or m4v). Otherwise it will use an HTML5 video element. I highly recommend H.264 video and AAC audio in an MP4 container. If you're encoding with Apple's Compressor, the "Streaming" setting should be "Fast Start" (NOT Fast Start - Compressed Header). I've written up my recommended video encode settings in <a href="http://www.kylegilman.net/2011/02/25/making-mp4-h-264-videos-in-apple-compressor/">a post on my website</a>.
    1718
    18 The plugin uses FFMPEG to generate thumbnails and encode HTML5/mobile videos. By default the plugin looks for FFMPEG in `/usr/local/bin` but if FFMPEG is installed in a different place on your server, you can point it to the correct place in the plugin settings.
     19The plugin uses FFMPEG to generate thumbnails and encode HTML5/mobile videos. By default the plugin looks for FFMPEG in `/usr/local/bin` but if FFMPEG is installed in a different place on your server, you can point it to the correct place in the plugin settings. Users running WordPress on Windows servers should try using Linux-style paths (with forward slashes instead of backslashes and a forward slash instead of C:\)
    1920
    2021If FFMPEG is installed on your server, you can generate thumbnails using either the "Generate" or "Randomize" buttons. The "Generate" button will always generate thumbnails from the same frames of your video, evenly spaced. If you don't like them you can randomize the results with the "Randomize" button. If you want to see the first frame of the video, check the "Force 1st Frame Thumbnail" button. If you want really fine control you can enter timecode in the "Thumbnail Timecode" field. Use mm:ss format. If you want even more control you can use decimals to approximate frames. For example, `23.5` will generate a thumbnail halfway between the 23rd and 24th seconds in the video. `02:23.25` would be one quarter of the way between the 143rd and 144th seconds. You can generate as many or as few as you need (up to 9 at a time). The unused thumbnails will be deleted once you click "Insert into Post" or "Save Changes."
     
    2223In the plugin settings you can set the default maximum width based on the width of your particular template and those values will be filled in when you open the window. If you generate thumbnails, the video display dimensions will be automatically adjusted to match the size and aspect ratio of the video file. You can make further adjustments if you want.
    2324
    24 The "Encode" button is still a bit experimental. If you have FFMPEG on your server, clicking the button will start encoding an iPod/iPad/Android compliant H.264 video (which will also work in Safari and IE 9), or a Firefox/Chrome-compatible WEBM or OGV video in the same directory as your original file. Anyone using a modern browser who doesn't have a Flash plugin will see these files instead of the original. The files will encode in the background and will take several minutes to complete, depending on your server setup and the length and size of your video. Currently, if something goes wrong after the encode starts, the plugin will not tell you. It also won't tell you when the files are done. You just have to wait.
     25The "Encode" button is still a bit experimental. If you have FFMPEG on your server, clicking the button will start encoding an iPod/iPad/Android compliant H.264 video (which will also work in Safari and IE 9), or a Firefox/Chrome-compatible WEBM or OGV video in the same directory as your original file. Anyone using a modern browser who doesn't have a Flash plugin will see these files instead of the original. The files will encode in the background and will take several minutes to complete, depending on your server setup and the length and size of your video. New in version 2.0, you will see the encoding progress, you will have the option to cancel an encoding job, and you should get an error message if something goes wrong. Closing the window will not cancel encoding, but once the window is closed the progress bar won't come back. Users on Windows servers will not get any feedback while the files are encoding.
     26
     27Also new in this version is the option to encode an HD Mobile/H.264 file. Since there are more devices that can handle HD H.264 videos available now, you can choose to increase the resolution to 720p or 1080p. Keep in mind, very few mobile devices can currently play 1080p video.
    2528
    2629The plugin is currently favoring Flash instead of HTML5 because Flash is a better user experience in most cases. I'm particularly not a fan of some browsers' tendencies to auto-download HTML5 video elements. I may eventually include the option to favor HTML5. However, if you embed a non-Flash compatible file (like an ogv or webm file) then you will only get the HTML5 video element. If you want to make ogv, webm, or H.264 files available and can't use the FFMPEG encode button, you can upload your own files to the same directory as the original and the plugin will automatically find them. For example, if your main file is awesomevid.mp4, the plugin will look for awesomevid.webm and awesomevid.ogv as well. If you want to embed a high-res H.264 video but also make a mobile-compatible version available, add -ipod.m4v to the end of the filename (awesomevid-ipod.m4v) and it will be served up to most smartphones and tablets instead of the original.
    2730
    2831Android viewers who don't use Flash will see a play button superimposed on the thumbnail to make it a little clearer that it's an embedded video.
     32
     33If you have Mobile, WEBM, or OGV files encoded, you will have the option to embed one of those files instead of the original. This is for a small group of users who need to upload a file format that can't be embedded and want to replace that file with a newly encoded file. No matter which option you choose, any other encoded files will still be automatically swapped in on the appropriate devices and browsers.
    2934
    3035If you want to make it easier for people to save the video to their computers, you can choose to include a link by checking the "Generate Download Link Below Video" button.
     
    3742width="720" height="404"]http://www.kylegilman.net/wp-content/uploads/2011/10/Reel-11-10-10-web.mp4[/FMP]`
    3843
    39 Once you save the post, the thumbnail file will be registered in the Wordpress Media Library and added to the post's attachments. Thumbnails are saved in the current Wordpress uploads directory. HTML5 videos are not yet registered with the media library.
     44After you save the post, the thumbnail file will be registered in the Wordpress Media Library and added to the post's attachments. Thumbnails are saved in the current Wordpress uploads directory. Encoded videos are not yet registered with the media library.
    4045
    4146= If you want to further modify the way the Flash video player works, you can add the following options inside the [FMP] tag. These will override anything you’ve set in the plugin settings. =
     
    8489Some of it will work without FFMPEG. You can generate embed codes for your videos on any host because that part of the plugin is JavaScript running in your browser. But without FFMPEG you won't be able to generate thumbnails or generate HTML5 videos. There is no way around this. A program has to read the video files in order to generate the thumbnails, and FFMPEG is the best one I've found to do that.
    8590
     91= Why doesn't the encoding progress bar work on Windows? =
     92
     93Because I can't figure out how to do it. Windows works a little differently from Linux, and I don't understand it enough to get it to work.
     94
    8695== Screenshots ==
    8796
    88971. Thumbnail & Embed Options in the Media Library/Insert Video page.
    89 2. "Embed from Url" tab.
    90 3. Shortcode inserted into the post content by the plugin.
     982. Encoding in progress.
     993. "Embed from Url" tab.
     1004. Shortcode inserted into the post content by the plugin.
    91101
    92102== Changelog ==
     103
     104= 2.0 - February 20, 2012=
     105* Large rewrite to fix several security issues. Full server paths are no longer exposed in the Media Upload form, all AJAX calls are handled through wp_ajax, and nonces are checked.
     106* Video encoding shows progress bar on Linux servers.
     107* Ability to cancel encoding added.
     108* Option to encode 720p or 1080p H.264 videos.
     109* Videos recorded on phones in portrait mode (tall and skinny) will not end up sideways if FFMPEG version .10 or later is installed.
     110* Thumbnail generation process uses fancy jQuery animation.
     111* Better check for FFMPEG. Should actually work in Windows now.
    93112
    94113= 1.1 - January 8, 2012 =
     
    128147= 0.2 - January 18, 2011 =
    129148* First Release
     149
     150== Upgrade Notice ==
     151
     152= 2.0 = Fixes several security issues.
  • video-embed-thumbnail-generator/trunk/video-embed-thumbnail-generator.php

    r486697 r507924  
    33Plugin Name: Video Embed & Thumbnail Generator
    44Plugin URI: http://www.kylegilman.net/2011/01/18/video-embed-thumbnail-generator-wordpress-plugin/
    5 Description: Generate video thumbnails, HTML5-compliant videos, and video embed shortcodes. Some functions require FFMPEG.
    6 Version: 1.1   
     5Description: Generates thumbnails, HTML5-compliant videos, and embed codes for locally hosted videos. Requires FFMPEG for thumbnails and encodes. <a href="options-general.php?page=video-embed-thumbnail-generator.php">Settings</a> | <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=kylegilman@gmail.com&item_name=Video%20Embed%20And%20Thumbnail%20Generator%20Plugin%20Donation/">Donate</a>
     6Version: 2.0   
    77Author: Kyle Gilman
    88Author URI: http://www.kylegilman.net/
     
    5858}
    5959
     60function is_empty_dir($dir)
     61{
     62    if ($dh = @opendir($dir))
     63    {
     64        while ($file = readdir($dh))
     65        {
     66            if ($file != '.' && $file != '..') {
     67                closedir($dh);
     68                return false;
     69            }
     70        }
     71        closedir($dh);
     72        return true;
     73    }
     74    else return false; // whatever the reason is : no such dir, not a dir, not readable
     75}
     76
     77function kg_explodeX($delimiters,$string)
     78{
     79    $return_array = Array($string); // The array to return
     80    $d_count = 0;
     81    while (isset($delimiters[$d_count])) // Loop to loop through all delimiters
     82    {
     83        $new_return_array = Array();
     84        foreach($return_array as $el_to_split) // Explode all returned elements by the next delimiter
     85        {
     86            $put_in_new_return_array = explode($delimiters[$d_count],$el_to_split);
     87            foreach($put_in_new_return_array as $substr) // Put all the exploded elements in array to return
     88            {
     89                $new_return_array[] = $substr;
     90            }
     91        }
     92        $return_array = $new_return_array; // Replace the previous return array by the next version
     93        $d_count++;
     94    }
     95    return $return_array; // Return the exploded elements
     96}
    6097
    6198function rrmdir($dir) {
     
    72109}
    73110
     111function kg_check_ffmpeg_exists() {
     112
     113        $exec_enabled = false;
     114        $ffmpeg_exists = false;
     115        $output = array();
     116
     117        if(function_exists('exec')) {
     118            exec(get_option('wp_FMP_ffmpeg').'/ffmpeg 2>&1', $output, $returnvalue);
     119            $exec_enabled = true;
     120        } //attempt to execute FFMPEG
     121
     122        if ( $exec_enabled == true && strpos(end($output), 'even better') != false ) { //if FFMPEG executed
     123            update_option('wp_FMP_ffmpeg_exists', "true");
     124            $ffmpeg_exists = true;
     125        }
     126        else {  update_option('wp_FMP_ffmpeg_exists', "notinstalled"); }
     127
     128        $output_output = implode("/n", $output);
     129
     130        $arr = array ("exec_enabled"=>$exec_enabled, "ffmpeg_exists"=>$ffmpeg_exists, "return_value"=>$returnvalue, "output"=>$output_output);
     131
     132        return $arr;
     133}
     134
     135function kg_encodevideo_info($movieurl, $postID) {
     136
     137    $uploads = wp_upload_dir();
     138    $movie_extension = pathinfo(parse_url($movieurl, PHP_URL_PATH), PATHINFO_EXTENSION);
     139    $encodevideo_info['moviefilebasename'] = basename($movieurl,'.'.$movie_extension);
     140    $moviefilepath = str_replace(" ", "%20", $movieurl);
     141
     142    if ($postID != "singleurl") { //if it's an attachment, not from URL
     143        $moviefile = get_attached_file($postID);
     144        $path_parts = pathinfo($moviefile);
     145        $encodevideo_info['encodepath'] = $path_parts['dirname']."/";
     146        $encodevideo_info['sameserver'] = true;
     147    }
     148    else {
     149        $url_parts = parse_url($uploads['url']);
     150        if ( strpos($moviefilepath, $url_parts['host']) != "" ) { //if we're on the same server
     151            $encodevideo_info['sameserver'] = true;
     152            $filename = urldecode($moviefilepath);
     153            $parsed_url= parse_url($filename);
     154            $fileinfo = pathinfo($filename);
     155            $parsed_url['extension'] = $fileinfo['extension'];
     156            $parsed_url['filename'] = $fileinfo['basename'];
     157            $parsed_url['localpath'] = $_SERVER['DOCUMENT_ROOT'].$parsed_url['path'];
     158            // just in case there is a double slash created when joining document_root and path
     159            $parsed_url['localpath'] = preg_replace('/\/\//', '/', $parsed_url['localpath']);
     160
     161            $encodevideo_info['encodepath'] = rtrim($parsed_url['localpath'], $parsed_url['filename']);
     162        }
     163        else {
     164            $encodevideo_info['sameserver'] = false;
     165            $encodevideo_info['encodepath'] = $uploads['basedir']."/html5encodes/";
     166        }
     167    }
     168
     169    $movieurl_noextension = preg_replace("/\\.[^.\\s]{3,4}$/", "", $movieurl);
     170    $encodevideo_info['mobileurl'] = $movieurl_noextension."-ipod.m4v";
     171    $encodevideo_info['oggurl'] = $movieurl_noextension.".ogv";
     172    $encodevideo_info['webmurl'] = $movieurl_noextension.".webm";
     173
     174    if ( !is_writable($encodevideo_info['encodepath']) ) { //if the original directory is not writable use a directory in base wp_upload
     175        $encodevideo_info['encodepath'] = $uploads['basedir']."/html5encodes/";
     176        $encodevideo_info['html5encodes'] = true;
     177        $encodevideo_info['mobileurl'] = $uploads['baseurl']."/html5encodes/".$encodevideo_info['moviefilebasename']."-ipod.m4v";
     178        $encodevideo_info['oggurl'] = $uploads['baseurl']."/html5encodes/".$encodevideo_info['moviefilebasename'].".ogv";
     179        $encodevideo_info['webmurl'] = $uploads['baseurl']."/html5encodes/".$encodevideo_info['moviefilebasename'].".webm";
     180    }
     181
     182    $encodevideo_info['mobilefilepath'] = $encodevideo_info['encodepath'].$encodevideo_info['moviefilebasename']."-ipod.m4v";
     183    $encodevideo_info['oggfilepath'] = $encodevideo_info['encodepath'].$encodevideo_info['moviefilebasename'].".ogv";
     184    $encodevideo_info['webmfilepath'] = $encodevideo_info['encodepath'].$encodevideo_info['moviefilebasename'].".webm";
     185
     186    $encodevideo_info['mobilefilepath_html5encodes'] = $uploads['basedir']."/html5encodes/".$encodevideo_info['moviefilebasename']."-ipod.m4v";
     187    $encodevideo_info['oggfilepath_html5encodes'] = $uploads['basedir']."/html5encodes/".$encodevideo_info['moviefilebasename'].".ogv";
     188    $encodevideo_info['webmfilepath_html5encodes'] = $uploads['basedir']."/html5encodes/".$encodevideo_info['moviefilebasename'].".webm";
     189
     190    if ( file_exists($encodevideo_info['mobilefilepath']) ) { $encodevideo_info['mobile_exists'] = true; }
     191    else {
     192        if ( file_exists($encodevideo_info['mobilefilepath_html5encodes']) ) {
     193            $encodevideo_info['mobilefilepath'] = $encodevideo_info['mobilefilepath_html5encodes'];
     194            $encodevideo_info['mobile_exists'] = true;
     195        }
     196        else { $encodevideo_info['mobile_exists'] = false; }
     197    }
     198    if ( file_exists($encodevideo_info['oggfilepath']) ) { $encodevideo_info['ogg_exists'] = true; }
     199    else {
     200        if ( file_exists($encodevideo_info['oggfilepath_html5encodes']) ) {
     201            $encodevideo_info['oggfilepath'] = $encodevideo_info['oggfilepath_html5encodes'];
     202            $encodevideo_info['ogg_exists'] = true;
     203        }
     204        else { $encodevideo_info['ogg_exists'] = false; }
     205    }
     206    if ( file_exists($encodevideo_info['webmfilepath']) ) { $encodevideo_info['webm_exists'] = true; }
     207    else {
     208        if ( file_exists($encodevideo_info['webmfilepath_html5encodes']) ) {
     209            $encodevideo_info['webmfilepath'] = $encodevideo_info['webmfilepath_html5encodes'];
     210            $encodevideo_info['webm_exists'] = true;
     211        }
     212        else { $encodevideo_info['webm_exists'] = false; }
     213    }
     214
     215    if ( !$encodevideo_info['sameserver'] ) { //last resort if it's not on the same server, check url_exists
     216        if ( !file_exists($encodevideo_info['mobilefilepath']) ) {
     217            if ( url_exists($movieurl_noextension."-ipod.m4v") ) {
     218                $encodevideo_info['mobile_exists'] = true;
     219                $encodevideo_info['mobileurl'] = $movieurl_noextension."-ipod.m4v"; ;
     220            }
     221            else { $encodevideo_info['mobile_exists'] = false; }
     222        }
     223        if ( !file_exists($encodevideo_info['oggfilepath']) ) {
     224            if ( url_exists($movieurl_noextension.".ogv") ) {
     225                $encodevideo_info['ogg_exists'] = true;
     226                $encodevideo_info['oggurl'] = $movieurl_noextension.".ogv"; ;
     227            }
     228            else { $encodevideo_info['ogg_exists'] = false; }
     229        }
     230        if ( !file_exists($encodevideo_info['webmfilepath']) ) {
     231            if ( url_exists($movieurl_noextension.".webm") ) {
     232                $encodevideo_info['webm_exists'] = true;
     233                $encodevideo_info['webmurl'] = $movieurl_noextension.".webm"; ;
     234            }
     235        }
     236    }
     237
     238    return $encodevideo_info;
     239}
    74240
    75241function video_embed_thumbnail_generator_activate() {
     
    94260   define("wp_FMP_default_ffmpeg_exists", "notchecked", true);
    95261   define("wp_FMP_default_encodemobile", "true", true);
     262   define("wp_FMP_default_mobile_res", "480", true);
    96263   define("wp_FMP_default_encodeogg", "false", true);
    97264   define("wp_FMP_default_encodewebm", "true", true);
     
    115282   add_option('wp_FMP_ffmpeg', wp_FMP_default_ffmpeg);
    116283   add_option('wp_FMP_ffmpeg_exists', wp_FMP_default_ffmpeg_exists);
     284   add_option('wp_FMP_mobile_res', wp_FMP_default_mobile_res);
    117285   add_option('wp_FMP_encodemobile', wp_FMP_default_encodemobile);
    118286   add_option('wp_FMP_encodeogg', wp_FMP_default_encodeogg);
    119287   add_option('wp_FMP_encodewebm', wp_FMP_default_encodewebm);
    120288
    121     exec(get_option('wp_FMP_ffmpeg').'/ffmpeg /dev/null 2>&1', $output, $returnvalue); //attempt to execute FFMPEG
    122     if ($returnvalue < 126 ) { //if FFMPEG executed
    123         update_option('wp_FMP_ffmpeg_exists', "true");
    124     }
    125     else { update_option('wp_FMP_ffmpeg_exists', "notinstalled"); }
     289   kg_check_ffmpeg_exists();
     290
    126291}
    127292
     
    212377            $h264compatible = array("mp4", "mov", "m4v");
    213378
    214             //look for encoded files in the same directory as the movie, or in the encodes folder
    215             $originalurl = dirname(trim($content))."/".$moviefilebasename;
    216             $uploads = wp_upload_dir();
    217             $url_parts = parse_url($uploads['baseurl']);
    218             $moviefiledirectory = dirname(parse_url(trim($content), PHP_URL_PATH));
    219             $home_path = substr(strrev(strstr(strrev($uploads['basedir']), strrev("public_html"))), 0, -strlen("public_html"));
    220             if ( strpos( dirname(trim($content)), $url_parts['host']) != "" ) { //if it's on the current server
    221                 $originalpath = $home_path."public_html".$moviefiledirectory."/".$moviefilebasename;
    222             }
    223             $encodeurl = $uploads['baseurl']."/html5encodes/".$moviefilebasename;
    224             $encodepath = $uploads['basedir']."/html5encodes/".$moviefilebasename;
    225 
    226             $html5type = array("-ipod.m4v", ".ogv", ".webm");
    227 
    228             foreach ($html5type as $extension) {
    229                 $existing_url = "";
    230                 if ( ".".$moviefiletype == $extension ) { $existing_url = $content; }
    231                 if ($existing_url == "") { //search on the server for matching filename
    232                     if ( file_exists($originalpath.$extension) ) { $existing_url = $originalurl.$extension; }
    233                 }
    234                 if ($existing_url == "") { //search in the wp_upload html5encodes directory
    235                     if ( file_exists($encodepath.$extension) ) { $existing_url = $encodeurl.$extension; }
    236                 }
    237                 if ($existing_url == "" && $originalpath == "") { //if the file's not on the server, search wherever it is
    238                     if ( url_exists($originalurl.$extension) ) { $existing_url = $originalurl.$extension; }
    239                 }
    240                 $html5file[$extension] = $existing_url;
    241             }
     379            $encodevideo_info = kg_encodevideo_info(trim($content), 'singleurl');
    242380
    243381            $code = "<div id=\"flashcontent".$div_suffix."\">";
     
    245383            if ($query_atts["loop"] == 'true') { $code .= "loop='loop' " ;}
    246384            if ($query_atts["autoplay"] == 'true') { $code .= "autoplay='autoplay' " ;}
    247             if ($query_atts["controls"] != 'none') { $code .= "controls='controls' " ;}
     385            if ($query_atts["controlbar"] != 'none') { $code .= "controls='controls' " ;}
    248386            if ($isAndroid) { $code .= "onclick='this.play();' "; }
    249387            $code .= "preload='metadata' ";
     
    258396
    259397            if ( in_array($moviefiletype, $h264compatible) ) {
    260                 if ( $html5file["-ipod.m4v"] !="" && $isTierIphone ) {
    261                     $code .= "<source src='".$html5file['-ipod.m4v']."'";
     398                if ( $encodevideo_info["mobile_exists"] && $isTierIphone ) {
     399                    $code .= "<source src='".$encodevideo_info["mobileurl"]."'";
    262400                }
    263                 else { $code .= "<source src='".$content."'"; }
     401                else { $code .= "<source src='".trim($content)."'"; }
    264402                if (!$isAndroid) { $code.= " type='video/mp4'"; }
    265403                $code .=">\n";
    266404            }
    267             else { if ($html5file["-ipod.m4v"] != "") {
    268                 $code .= "<source src='".$html5file['-ipod.m4v']."'";
     405            else { if ( $encodevideo_info["mobile_exists"] ) {
     406                $code .= "<source src='".$encodevideo_info["mobileurl"]."'";
    269407                if (!$isAndroid) { $code.= " type='video/mp4'"; }
    270408                $code .=">\n";
    271409            } }
    272             if ($html5file[".webm"] != "") { $code .= "<source src='".$html5file['.webm']."' type='video/webm'>\n"; }
    273             if ($html5file[".ogv"] != "") { $code .= "<source src='".$html5file['.ogv']."' type='video/ogg'>\n"; }
     410            if ( $encodevideo_info["webm_exists"] ) { $code .= "<source src='".$encodevideo_info["webmurl"]."' type='video/webm'>\n"; }
     411            if ( $encodevideo_info["ogg_exists"] ) { $code .= "<source src='".$encodevideo_info["oggurl"]."' type='video/ogg'>\n"; }
    274412            $code .= "</video>\n";
    275413            $code .= "</div>\n\n";
     
    311449   define("wp_FMP_default_skin", plugins_url("", __FILE__)."/flash/skin/kg_skin.xml", true);
    312450   define("wp_FMP_default_ffmpeg", "/usr/local/bin", true);
     451   define("wp_FMP_default_mobile_res", "480", true);
    313452   define("wp_FMP_default_encodemobile", "true", true);
    314453   define("wp_FMP_default_encodeogg", "false", true);
     
    333472            update_option('wp_FMP_skin', wp_FMP_default_skin); 
    334473            update_option('wp_FMP_ffmpeg', wp_FMP_default_ffmpeg);
     474            update_option('wp_FMP_mobile_res', wp_FMP_default_mobile_res);
    335475            update_option('wp_FMP_encodemobile', wp_FMP_default_encodemobile);
    336476            update_option('wp_FMP_encodeogg', wp_FMP_default_encodeogg);   
     
    339479            echo "<div class='updated'><p><strong>Video Embed & Thumbnail Generator plugin reset to default settings</strong></p></div>";
    340480
    341             exec(get_option('wp_FMP_ffmpeg').'/ffmpeg /dev/null 2>&1', $output, $returnvalue); //attempt to execute FFMPEG
    342             if ($returnvalue < 126 ) { //if FFMPEG executed
    343                 update_option('wp_FMP_ffmpeg_exists', "true");
    344             }
    345             else {
     481            $ffmpeg_info = kg_check_ffmpeg_exists();
     482
     483            if ( $ffmpeg_info['exec_enabled'] == false ) {
     484                echo "<div class='error'><p><strong>EXEC function is disabled in PHP settings. Embed codes will work, but video thumbnail generation and Mobile/HTML5 encoding will not. Contact your System Administrator to find out if you can enable EXEC</strong></p></div>";
     485            }
     486            elseif ( $ffmpeg_info['ffmpeg_exists'] == false ) {
    346487                echo "<div class='error'><p><strong>FFMPEG not found at ".get_option('wp_FMP_ffmpeg').". Embed codes will work, but video thumbnail generation and Mobile/HTML5 encoding will not.</strong></p></div>";
    347                 update_option('wp_FMP_ffmpeg_exists', "notinstalled");
    348488            }
    349489   
     
    416556                update_option(wp_FMP_encodewebm, "false");
    417557            }       
    418            
     558
     559            update_option('wp_FMP_mobile_res', $_POST[wp_FMP_mobile_res]);         
    419560            update_option('wp_FMP_width', $_POST[wp_FMP_width]);
    420561            update_option('wp_FMP_height', $_POST[wp_FMP_height]);
     
    431572            echo "<div class='updated'><p><strong>Video Embed & Thumbnail Generator plugin settings updated</strong></p></div>";
    432573
    433             exec(get_option('wp_FMP_ffmpeg').'/ffmpeg /dev/null 2>&1', $output, $returnvalue); //attempt to execute FFMPEG
    434             if ($returnvalue < 126 ) { //if FFMPEG executed
    435                 update_option('wp_FMP_ffmpeg_exists', "true");
    436             }
    437             else {
     574
     575            $ffmpeg_info = kg_check_ffmpeg_exists();
     576
     577            if ( $ffmpeg_info['exec_enabled'] == false ) {
     578                echo "<div class='error'><p><strong>EXEC function is disabled in PHP settings. Embed codes will work, but video thumbnail generation and Mobile/HTML5 encoding will not. Contact your System Administrator to find out if you can enable EXEC</strong></p></div>";
     579            }
     580            elseif ( $ffmpeg_info['ffmpeg_exists'] == false ) {
    438581                echo "<div class='error'><p><strong>FFMPEG not found at ".get_option('wp_FMP_ffmpeg').". Embed codes will work, but video thumbnail generation and Mobile/HTML5 encoding will not.</strong></p></div>";
    439                 update_option('wp_FMP_ffmpeg_exists', "false");
    440582            }
    441583        }
     
    481623                                echo " />\n";
    482624                            ?>
    483                             Uncheck if you don't want HTML5 video fallback.
     625                            Uncheck if you don't want HTML5 video fallback when Flash isn't installed.
    484626                        </td>
    485627                    </tr>
     
    516658                            <em>Requires FFMPEG.</em>
    517659                        </td>
     660                    </tr>
     661                    <tr>
     662                        <th scope="row" valign="top" align="left">
     663                            <label>Maximum H.264/Mobile Encode Resolution:</label>
     664                        </th>
     665                        <td width="10"></td>
     666                        <td>
     667                            <select name="wp_FMP_mobile_res" id="wp_FMP_mobile_res">
     668                                <?php
     669                                    $res_480 = "";
     670                                    $res_720 = "";
     671                                    $res_1080 = "";
     672                                    if(get_option('wp_FMP_mobile_res') == "480") {
     673                                        $res_480 = " selected=\"selected\"";
     674                                    }
     675                                    if(get_option('wp_FMP_mobile_res') == "720") {
     676                                        $res_720 = " selected=\"selected\"";
     677                                    }
     678                                    if(get_option('wp_FMP_mobile_res') == "1080") {
     679                                        $res_1080 = " selected=\"selected\"";
     680                                    }
     681                                ?>
     682                                <option value="480"<?php echo $res_480 ?>>480p</option>
     683                                <option value="720"<?php echo $res_720 ?>>720p</option>
     684                                <option value="1080"<?php echo $res_1080 ?>>1080p</option>
     685                            </select>
     686                            <em>Newer mobile devices can display HD video (iPhone 4/iPad 1/some Android play 720p, iPhone 4s/iPad 2 play 1080p) but many older devices (iPhone 3Gs/older Android) can't play higher than 480p. Increase at your own risk.</em>
     687                        </td>   
    518688                    </tr>
    519689                    <tr>
     
    8481018      if( substr($post->post_mime_type, 0, 5) == 'video' ){
    8491019
     1020        $form_fields["kgflashmediaplayer-security"]["input"] = "hidden";
     1021        $form_fields["kgflashmediaplayer-security"]["value"] = wp_create_nonce('video-embed-thumbnail-generator-nonce');
     1022
     1023        $movieurl = wp_get_attachment_url($post->ID);
    8501024        $form_fields["kgflashmediaplayer-url"]["input"] = "hidden";
    851         $form_fields["kgflashmediaplayer-url"]["value"] = wp_get_attachment_url($post->ID);
    852 
    853         $form_fields["kgflashmediaplayer-ffmpeg_path"]["input"] = "hidden";
    854         $form_fields["kgflashmediaplayer-ffmpeg_path"]["value"] = get_option('wp_FMP_ffmpeg');
     1025        $form_fields["kgflashmediaplayer-url"]["value"] = $movieurl;
    8551026
    8561027        $encodemobileset = get_post_meta($post->ID, "_kgflashmediaplayer-encodemobile", true);
     
    8691040        $form_fields["kgflashmediaplayer-encodewebm"]["value"] = $encodewebmset;
    8701041
    871         $form_fields["kgflashmediaplayer-plugin_dir"]["input"] = "hidden";
    872         $form_fields["kgflashmediaplayer-plugin_dir"]["value"] = plugins_url("", __FILE__);
    873 
    874         $uploads = wp_upload_dir();
    875         $form_fields["kgflashmediaplayer-upload_url"]["input"] = "hidden";
    876         $form_fields["kgflashmediaplayer-upload_url"]["value"] = $uploads['url'];
    877 
    878         $form_fields["kgflashmediaplayer-upload_path"]["input"] = "hidden";
    879         $form_fields["kgflashmediaplayer-upload_path"]["value"] = $uploads['path'];
    880 
    881         $form_fields["kgflashmediaplayer-upload_basedir"]["input"] = "hidden";
    882         $form_fields["kgflashmediaplayer-upload_basedir"]["value"] = $uploads['basedir'];
     1042        $encoded = get_post_meta($post->ID, "_kgflashmediaplayer-encoded", true);
     1043        $form_fields["kgflashmediaplayer-encoded"]["input"] = "hidden";
     1044        $form_fields["kgflashmediaplayer-encoded"]["value"] = $encoded;
    8831045
    8841046        $maxwidth = get_option('wp_FMP_width');
     
    9161078        $thumbnail_url = get_post_meta($post->ID, "_kgflashmediaplayer-poster", true);
    9171079
     1080        $uploads = wp_upload_dir();
    9181081        $url_parts = parse_url($uploads['baseurl']);
    9191082        $moviefiledirectory = dirname(parse_url(trim($thumbnail_url), PHP_URL_PATH));
     
    9341097    else { $numberofthumbs_value = "4"; }
    9351098
    936     if ( get_option('wp_FMP_ffmpeg_exists') == false ) { //make sure the new ffmpeg_exists option exists
    937         exec(get_option('wp_FMP_ffmpeg').'/ffmpeg /dev/null 2>&1', $output, $returnvalue); //attempt to execute FFMPEG
    938         if ($returnvalue < 126 ) { //if FFMPEG executed
    939             add_option('wp_FMP_ffmpeg_exists', "true");
    940         }
    941         else { add_option('wp_FMP_ffmpeg_exists', "notinstalled"); }
    942     }
     1099    if ( get_option('wp_FMP_ffmpeg_exists') == false ) { kg_check_ffmpeg_exists(); } //make sure the new ffmpeg_exists option exists
    9431100
    9441101    if ( get_option('wp_FMP_ffmpeg_exists') == "notinstalled" ) { $ffmpeg_disabled_text = 'disabled="disabled" title="FFMPEG not found at '.get_option('wp_FMP_ffmpeg').'"'; }
     1102    else { $ffmpeg_disabled_text = ""; }
    9451103
    9461104    $form_fields["generator"]["label"] = __("Thumbnails");
     
    9751133        if ($encodewebmset == "false") { $webmchecked = ""; }
    9761134        else { $webmchecked = "checked"; }
     1135
     1136        $replaceoptions = "";
     1137
     1138    $altembedset = get_post_meta($post->ID, "_kgflashmediaplayer-altembed", true);
     1139    $encodevideo_info = kg_encodevideo_info($movieurl, $post->ID);
     1140
     1141    $altembedselect = "";
     1142        $selected = ' selected="selected" ';
     1143        $mobileselected = "";
     1144        $oggselected = "";
     1145        $webmselected = "";
     1146        if ($altembedset == $encodevideo_info['mobileurl']) { $mobileselected = $selected; }
     1147        if ($altembedset == $encodevideo_info['oggurl']) { $oggselected = $selected; }
     1148        if ($altembedset == $encodevideo_info['webmurl']) { $webmselected = $selected; }
     1149
     1150        if ( $encodevideo_info['mobile_exists'] ) { $replaceoptions .= '<option '.$mobileselected.' value="'.$encodevideo_info['mobileurl'].'">Mobile/H.264</option>'; }
     1151        if ( $encodevideo_info['webm_exists'] ) { $replaceoptions .= '<option '.$webmselected.' value="'.$encodevideo_info['webmurl'].'">WEBM</option>'; }
     1152        if ( $encodevideo_info['ogg_exists'] ) { $replaceoptions .= '<option '.$oggselected.' value="'.$encodevideo_info['oggurl'].'">OGV</option>'; }
     1153        if ( $encodevideo_info['mobile_exists'] || $encodevideo_info['webm_exists'] || $encodevideo_info['ogg_exists'] ) { $altembedselect ='<span class="kg_embedselect">Embed <select name="attachments['.$post->ID.'][kgflashmediaplayer-altembed]" id="attachments['.$post->ID.'][kgflashmediaplayer-altembed]"><option value="'.$movieurl.'">original</option>'.$replaceoptions.'</select></span>'; }
     1154
    9771155        $form_fields["kgflashmediaplayer-encode"]["label"] = __("HTML5 & Mobile");
    9781156        $form_fields["kgflashmediaplayer-encode"]["input"] = "html";
     
    9881166    <label for="attachments['. $post->ID .'][kgflashmediaplayer-encodeoggcheck]">OGV</label>
    9891167
    990     <div style="display:inline-block;" id="attachments_'. $post->ID .'_encodeplaceholder"></div><br /><small><em>(Experimental) Generates video files compatible with most mobile & HTML5-compatible browsers.</em></small>';
     1168    <div style="display:inline;" id="attachments_'. $post->ID .'_altembedselect">'.$altembedselect.'</div>
     1169    <div style="display:block;" id="attachments_'. $post->ID .'_encodeplaceholder"></div>
     1170    <div style="display:block;" id="attachments_'. $post->ID .'_encodeprogressplaceholder"></div>
     1171
     1172<small><em>(Experimental) Generates video files compatible with most mobile & HTML5-compatible browsers.</em></small>';
    9911173
    9921174        $showtitlechecked = get_post_meta($post->ID, "_kgflashmediaplayer-showtitle", true);
     
    9971179        $form_fields["kgflashmediaplayer-options"]["label"] = __("Video Embed Options");
    9981180        $form_fields["kgflashmediaplayer-options"]["input"] = "html";
    999         $form_fields["kgflashmediaplayer-options"]["html"] = '<input type="checkbox" name="attachments[{$post->ID}][kgflashmediaplayer-showtitle]" id="attachments[{$post->ID}][kgflashmediaplayer-showtitle]" value="checked" onclick="if(this.checked) { document.getElementById(\'attachments['.$post->ID.'][kgflashmediaplayer-showtitlesave]\').value = \'checked\'; } else { document.getElementById(\'attachments['.$post->ID.'][kgflashmediaplayer-showtitlesave]\').value = \'unchecked\'; }"" '.$showtitlechecked.'>
    1000     <label for="attachments[{$post->ID}][kgflashmediaplayer-showtitle]">Include Title Above Video</label><br />
    1001 
    1002     <input type="checkbox" name="attachments[{$post->ID}][kgflashmediaplayer-downloadlink]" id="attachments[{$post->ID}][kgflashmediaplayer-downloadlink]" value="checked" onclick="if(this.checked) { document.getElementById(\'attachments['.$post->ID.'][kgflashmediaplayer-downloadsave]\').value = \'checked\'; } else { document.getElementById(\'attachments['.$post->ID.'][kgflashmediaplayer-downloadsave]\').value = \'unchecked\'; }" '.$downloadlinkchecked.'>
    1003     <label for="attachments[{$post->ID}][kgflashmediaplayer-downloadlink]">Generate Download Link Below Video<em><small>(Makes it easier for users to download video file)</em></small></label><br />
    1004 
    1005     <input type="checkbox" name="attachments[{$post->ID}][kgflashmediaplayer-embed]" id="attachments[{$post->ID}][kgflashmediaplayer-embed]" value="checked" onclick="if(this.checked) { document.getElementById(\'attachments['.$post->ID.'][kgflashmediaplayer-embedsave]\').value = \'checked\'; } else { document.getElementById(\'attachments['.$post->ID.'][kgflashmediaplayer-embedsave]\').value = \'unchecked\'; }" '.$embedchecked.'>
    1006     <label for="attachments[{$post->ID}][kgflashmediaplayer-embed]">Generate Embed Shortcode <em><small>(Turn off checkbox to use default WordPress video embedding)</small></em></label>';
     1181        $form_fields["kgflashmediaplayer-options"]["html"] = '<input type="checkbox" name="attachments['.$post->ID.'][kgflashmediaplayer-showtitle]" id="attachments['.$post->ID.'][kgflashmediaplayer-showtitle]" value="checked" onclick="if(this.checked) { document.getElementById(\'attachments['.$post->ID.'][kgflashmediaplayer-showtitlesave]\').value = \'checked\'; } else { document.getElementById(\'attachments['.$post->ID.'][kgflashmediaplayer-showtitlesave]\').value = \'unchecked\'; }"" '.$showtitlechecked.'>
     1182    <label for="attachments['.$post->ID.'][kgflashmediaplayer-showtitle]">Include Title Above Video</label><br />
     1183
     1184    <input type="checkbox" name="attachments['.$post->ID.'][kgflashmediaplayer-downloadlink]" id="attachments['.$post->ID.'][kgflashmediaplayer-downloadlink]" value="checked" onclick="if(this.checked) { document.getElementById(\'attachments['.$post->ID.'][kgflashmediaplayer-downloadsave]\').value = \'checked\'; } else { document.getElementById(\'attachments['.$post->ID.'][kgflashmediaplayer-downloadsave]\').value = \'unchecked\'; }" '.$downloadlinkchecked.'>
     1185    <label for="attachments['.$post->ID.'][kgflashmediaplayer-downloadlink]">Generate Download Link Below Video<em><small>(Makes it easier for users to download video file)</em></small></label><br />
     1186
     1187    <input type="checkbox" name="attachments['.$post->ID.'][kgflashmediaplayer-embed]" id="attachments['.$post->ID.'][kgflashmediaplayer-embed]" value="checked" onclick="if(this.checked) { document.getElementById(\'attachments['.$post->ID.'][kgflashmediaplayer-embedsave]\').value = \'checked\'; } else { document.getElementById(\'attachments['.$post->ID.'][kgflashmediaplayer-embedsave]\').value = \'unchecked\'; }" '.$embedchecked.'>
     1188    <label for="attachments['.$post->ID.'][kgflashmediaplayer-embed]">Generate Embed Shortcode <em><small>(Turn off checkbox to use default WordPress video embedding)</small></em></label>';
    10071189
    10081190        //$form_fields["kgflashmediaplayer-attachment"]["label"] = __("All Meta");
     
    10361218                }
    10371219            }
    1038             if ( is_dir($uploads['path'].'/thumb_tmp') && ($files = @scandir($uploads['path'].'/thumb_tmp') && (count($files) < 2)) ) { rmdir($uploads['path'].'/thumb_tmp'); }
     1220            if ( is_empty_dir($uploads["path"].'/thumb_tmp') ) { rrmdir($uploads["path"].'/thumb_tmp'); }
    10391221        }
    10401222        update_post_meta($post['ID'], '_kgflashmediaplayer-poster', $attachment['kgflashmediaplayer-poster']);
     
    10501232        if( isset($attachment['kgflashmediaplayer-downloadsave']) ) { update_post_meta($post['ID'], '_kgflashmediaplayer-download', $attachment['kgflashmediaplayer-downloadsave']); }
    10511233        if( isset($attachment['kgflashmediaplayer-showtitlesave']) ) { update_post_meta($post['ID'], '_kgflashmediaplayer-showtitle', $attachment['kgflashmediaplayer-showtitlesave']); }
    1052 
     1234        if( isset($attachment['kgflashmediaplayer-altembed']) ) { update_post_meta($post['ID'], '_kgflashmediaplayer-altembed', $attachment['kgflashmediaplayer-altembed']); }
     1235       /* if( isset($attachment['kgflashmediaplayer-encoded']) ) { update_post_meta($post['ID'], '_kgflashmediaplayer-encoded', $attachment['kgflashmediaplayer-encoded']); } */
    10531236
    10541237        //$attachment_printr = print_r($attachment, true);
     
    10741257    if ($attachment['embed'] == "checked" || $attachment_id == "singleurl" ) {
    10751258        $output = "";
    1076         $attachment['url'] = wp_get_attachment_url($attachment_id);
     1259        $attachment['altembed'] = get_post_meta($attachment_id, "_kgflashmediaplayer-altembed", true);
     1260        if ( $attachment['altembed'] != "" ) { $attachment['url'] = $attachment['altembed']; }
     1261        else { $attachment['url'] = wp_get_attachment_url($attachment_id); }
    10771262        $attachment['title'] = get_the_title($attachment_id);
    10781263        $attachment['poster'] = get_post_meta($attachment_id, "_kgflashmediaplayer-poster", true);
     
    11111296function media_embedurl_process() {
    11121297
    1113 if ( get_option('wp_FMP_ffmpeg_exists') == false ) { //make sure the new ffmpeg_exists option exists
    1114     exec(get_option('wp_FMP_ffmpeg').'/ffmpeg /dev/null 2>&1', $output, $returnvalue); //attempt to execute FFMPEG
    1115     if ($returnvalue < 126 ) { //if FFMPEG executed
    1116         add_option('wp_FMP_ffmpeg_exists', "true");
    1117     }
    1118     else { add_option('wp_FMP_ffmpeg_exists', "notinstalled"); }
    1119 }
     1298if ( get_option('wp_FMP_ffmpeg_exists') == false ) { kg_check_ffmpeg_exists(); } //make sure the new ffmpeg_exists option exists
    11201299
    11211300if ( get_option('wp_FMP_ffmpeg_exists') == "notinstalled" ) { $ffmpeg_disabled_text = 'disabled="disabled" title="FFMPEG not found at '.get_option('wp_FMP_ffmpeg').'"'; }
     1301else { $ffmpeg_disabled_text = ""; }
    11221302
    11231303if ( get_option('wp_FMP_encodemobile') == "true" ) { $mobilechecked = "checked";  }
     1304else { $mobilechecked = ""; }
    11241305if ( get_option('wp_FMP_encodeogg') == "true" ) { $oggchecked = "checked";  }
     1306else { $oggchecked = ""; }
    11251307if ( get_option('wp_FMP_encodewebm') == "true" ) { $webmchecked = "checked";  }
     1308else { $webmchecked = ""; }
    11261309
    11271310media_upload_header();
     
    11791362    <label for="attachments[singleurl][kgflashmediaplayer-encodeoggcheck]">OGV</label>
    11801363
    1181 <div id="attachments_singleurl_encodeplaceholder" name="attachments_singleurl_encodeplaceholder" style="display:inline-block;"></div><br />
    1182                 <small><em>(Experimental) Generates video files compatible with most mobile & HTML5-compatible browsers.</em></small></td>
     1364    <div style="display:inline;" id="attachments_singleurl_altembedselect"></div>
     1365    <div style="display:block;" id="attachments_singleurl_encodeplaceholder"></div>
     1366    <div style="display:block;" id="attachments_singleurl_encodeprogressplaceholder"></div>
     1367
     1368    <small><em>(Experimental) Generates video files compatible with most mobile & HTML5-compatible browsers.</em></small></td>
    11831369            </tr>
    11841370            <tr>
     
    12021388?>
    12031389
    1204 <input type='hidden' name='attachments[singleurl][kgflashmediaplayer-ffmpeg_path]' id='attachments[singleurl][kgflashmediaplayer-ffmpeg_path]' value='<?php echo get_option('wp_FMP_ffmpeg'); ?>' />
     1390<input type='hidden' name='attachments[singleurl][kgflashmediaplayer-security]' id='attachments[singleurl][kgflashmediaplayer-security]' value='<?php echo wp_create_nonce('video-embed-thumbnail-generator-nonce'); ?>' />
    12051391<input type='hidden' name='attachments[singleurl][kgflashmediaplayer-encodemobile]' id='attachments[singleurl][kgflashmediaplayer-encodemobile]' value='<?php echo get_option('wp_FMP_encodemobile'); ?>' />
    12061392<input type='hidden' name='attachments[singleurl][kgflashmediaplayer-encodeogg]' id='attachments[singleurl][kgflashmediaplayer-encodeogg]' value='<?php echo get_option('wp_FMP_encodeogg'); ?>' />
    12071393<input type='hidden' name='attachments[singleurl][kgflashmediaplayer-encodewebm]' id='attachments[singleurl][kgflashmediaplayer-encodewebm]' value='<?php echo get_option('wp_FMP_encodewebm'); ?>' />
    1208 <input type='hidden' name='attachments[singleurl][kgflashmediaplayer-plugin_dir]' id='attachments[singleurl][kgflashmediaplayer-plugin_dir]' value='<?php echo plugins_url("", __FILE__); ?>' />
    1209 <input type='hidden' name='attachments[singleurl][kgflashmediaplayer-upload_url]' id='attachments[singleurl][kgflashmediaplayer-upload_url]' value='<?php echo $uploads['url']; ?>' />
    1210 <input type='hidden' name='attachments[singleurl][kgflashmediaplayer-upload_path]' id='attachments[singleurl][kgflashmediaplayer-upload_path]' value='<?php echo $uploads['path']; ?>' />
    1211 <input type='hidden' name='attachments[singleurl][kgflashmediaplayer-upload_basedir]' id='attachments[singleurl][kgflashmediaplayer-upload_basedir]' value='<?php echo $uploads['basedir']; ?>' />
    12121394<input type='hidden' name='attachments[singleurl][kgflashmediaplayer-maxheight]' id='attachments[singleurl][kgflashmediaplayer-maxheight]' value='<?php echo($maxheight); ?>' />
    12131395<input type='hidden' name='attachments[singleurl][kgflashmediaplayer-maxwidth]' id='attachments[singleurl][kgflashmediaplayer-maxwidth]' value='<?php echo($maxwidth); ?>' />
     
    12231405add_action('media_upload_embedurl', 'kg_embedurl_handle');
    12241406
    1225 
    1226 
    1227 
    1228 function kg_cleanup_generated_thumbnails_handler($posterurl) {
     1407function kg_cleanup_generated_logfiles_handler($logfile) {
     1408    $lastmodified = "";
     1409    if ( file_exists($logfile) ) { $lastmodified = filemtime($logfile); }
     1410        if ( $lastmodified != false ) {
     1411            if ( time() - $lastmodified > 120 ) { unlink($logfile); }
     1412            else {
     1413                $timestamp = wp_next_scheduled( 'kg_cleanup_generated_logfiles' );
     1414                wp_unschedule_event($timestamp, 'kg_cleanup_generated_logfiles' );
     1415                $args = array('logfile'=>$logfile);
     1416                wp_schedule_single_event(time()+600, 'kg_cleanup_generated_logfiles', $args);
     1417            }
     1418        }
     1419}
     1420add_action('kg_cleanup_generated_logfiles','kg_cleanup_generated_logfiles_handler');
     1421
     1422function kg_cleanup_generated_thumbnails_handler() {
    12291423    $uploads = wp_upload_dir();
    12301424    rrmdir($uploads['path'].'/thumb_tmp'); //remove the whole tmp file directory
     
    12321426add_action('kg_cleanup_generated_thumbnails','kg_cleanup_generated_thumbnails_handler');
    12331427
    1234 function kg_schedule_cleanup_generated_files() { //schedules deleting all tmp thumbnails if no thumbnails are generated in an hour
    1235     $timestamp = wp_next_scheduled( 'kg_cleanup_generated_thumbnails' );
    1236     wp_unschedule_event($timestamp, 'kg_cleanup_generated_thumbnails' );
    1237     wp_schedule_single_event(time()+3600, 'kg_cleanup_generated_thumbnails');
     1428function kg_schedule_cleanup_generated_files() { //schedules deleting all tmp thumbnails or logfiles if no files are generated in an hour   
     1429
     1430    check_ajax_referer( 'video-embed-thumbnail-generator-nonce', 'security' );
     1431
     1432    if (isset($_POST['thumbs'])) {
     1433        $timestamp = wp_next_scheduled( 'kg_cleanup_generated_thumbnails' );
     1434        wp_unschedule_event($timestamp, 'kg_cleanup_generated_thumbnails' );
     1435        wp_schedule_single_event(time()+3600, 'kg_cleanup_generated_thumbnails');
     1436    }
     1437
     1438    if (isset($_POST['logfile'])) {
     1439        $timestamp = wp_next_scheduled( 'kg_cleanup_generated_logfiles' );
     1440        wp_unschedule_event($timestamp, 'kg_cleanup_generated_logfiles' );
     1441        $args = array('logfile'=>$_POST['logfile']);
     1442        wp_schedule_single_event(time()+600, 'kg_cleanup_generated_logfiles', $args);
     1443    }
    12381444    die(); // this is required to return a proper result
    12391445}
    12401446add_action('wp_ajax_kg_schedule_cleanup_generated_files', 'kg_schedule_cleanup_generated_files');
     1447
     1448function kg_callffmpeg() {
     1449
     1450    check_ajax_referer( 'video-embed-thumbnail-generator-nonce', 'security' );
     1451    global $wpdb;
     1452    include_once dirname( __FILE__ ) .'/kg_callffmpeg.php';
     1453    die(); // this is required to return a proper result
     1454}
     1455
     1456add_action('wp_ajax_kg_callffmpeg', 'kg_callffmpeg');
     1457
     1458function kg_check_encode_progress() {
     1459
     1460    check_ajax_referer( 'video-embed-thumbnail-generator-nonce', 'security' );
     1461    global $wpdb;
     1462    $pid = $_POST['pid'];
     1463    $logfile = $_POST['logfile'];
     1464    $movie_duration = $_POST['movie_duration'];
     1465    $embed_display = "";
     1466    $percent_done = "";
     1467    $other_message = "";
     1468    $logfilecontents = "";
     1469    $lastline = "";
     1470
     1471    if ( is_file($logfile) ) {
     1472
     1473        $logfilecontents = file_get_contents($logfile);
     1474        $fp = fopen($logfile, 'w');
     1475        fclose($fp);
     1476        $lastlines = kg_explodeX(array("\r","\n"), $logfilecontents);
     1477        $lastlines_output = print_r($lastlines, true);
     1478        $lastline = end($lastlines);
     1479        if ( $lastline == "" ) { $lastline = prev($lastlines); }
     1480   
     1481        $last_match = "";
     1482        $time_matches = "";
     1483        $video_matches = "";
     1484        $libx264_matches = "";
     1485        $fps_matches = "";
     1486        $fps_match = "";
     1487        $basename = "";
     1488   
     1489        preg_match('/time=(.*?) /', $lastline, $time_matches);
     1490   
     1491        if ( array_key_exists(1, $time_matches) != true ) {
     1492            preg_match('/video:(.*?) /', $lastline, $video_matches);
     1493            preg_match('/libx264 (.*?) /', $lastline, $libx264_matches);
     1494        }
     1495   
     1496        if ( array_key_exists(1, $time_matches) == true ) {
     1497            $current_hours = intval(substr($time_matches[1], -11, 2));
     1498            $current_minutes = intval(substr($time_matches[1], -8, 2));
     1499            $current_seconds = intval(substr($time_matches[1], -5, 2));
     1500            $current_seconds = ($current_hours * 60 * 60) + ($current_minutes * 60) + $current_seconds;
     1501            $percent_done = round(intval($current_seconds)/intval($movie_duration)*100);
     1502   
     1503            preg_match('/fps=\s+(.*?) /', $lastline, $fps_matches);
     1504            if ( array_key_exists(1, $fps_matches) == true ) { $fps_match = $fps_matches[1]; }
     1505            else {  $fps_match = "10"; }
     1506        }
     1507        elseif ( array_key_exists(1, $video_matches) == true || array_key_exists(1, $libx264_matches) == true ) {
     1508            $percent_done = 100;
     1509        }
     1510        else {
     1511            $other_message = $lastline;
     1512            $basename = substr($logfile, 0, -16);
     1513            if ( is_file($basename."-ipod.m4v") ) {
     1514                if ( (time() - filemtime($basename."-ipod.m4v")) < 30 ) { unlink($basename."-ipod.m4v"); }
     1515            }
     1516            if ( is_file($basename.".ogv") ) {
     1517                if ( (time() - filemtime($basename.".ogv")) < 30 ) { unlink($basename.".ogv"); }
     1518            }
     1519            if ( is_file($basename.".webm") ) {
     1520                if ( (time() - filemtime($basename.".webm")) < 30 ) { //unlink($basename.".webm");
     1521}
     1522            }
     1523        }
     1524   
     1525        if ( $percent_done == "100" || $other_message != "" ) { if ( file_exists($logfile) ) { unlink($logfile); } }
     1526   
     1527        $embed_display .= $lastline;
     1528        $arr = array ( "embed_display"=>$embed_display, "percent_done"=>$percent_done, "other_message"=>$other_message, "fps"=>$fps_match );
     1529    }
     1530    else { $arr = array ( "other_message"=>"Encoding Failed" ); }
     1531
     1532    echo json_encode($arr);
     1533
     1534    die(); // this is required to return a proper result
     1535}
     1536add_action('wp_ajax_kg_check_encode_progress', 'kg_check_encode_progress');
     1537
     1538function kg_cancel_encode() {
     1539
     1540    check_ajax_referer( 'video-embed-thumbnail-generator-nonce', 'security' );
     1541
     1542    if (isset($_POST['kg_pid'])) {
     1543        $kg_pid = $_POST['kg_pid'];
     1544        if ( intval($kg_pid) > 0 ) {
     1545            //$command = escapeshellcmd('kill '.$kg_pid);
     1546            //exec($command);
     1547            posix_kill($kg_pid, 15);
     1548        }
     1549    }
     1550
     1551    die(); // this is required to return a proper result
     1552}
     1553add_action('wp_ajax_kg_cancel_encode', 'kg_cancel_encode');
    12411554
    12421555function enqueue_kg_script() { //loads plugin-related javascripts
     
    12451558add_action('admin_enqueue_scripts', 'enqueue_kg_script');
    12461559
     1560function enqueue_kg_style() { //loads plugin-related CSS
     1561    $myStyleUrl = plugins_url('video-embed-thumbnail-generator.css', __FILE__);
     1562    wp_enqueue_style('kg_progressbar_style', $myStyleUrl);
     1563}
     1564add_action('admin_print_styles', 'enqueue_kg_style');
     1565
    12471566add_action('wp_head', 'addSWFObject');
    12481567add_action('admin_menu', 'addFMPOptionsPage');
Note: See TracChangeset for help on using the changeset viewer.