public function getFrame($frame_number = false, $frame_rate = false) { try { $toolkit = new PHPVideoToolkit(PHPVIDEOTOOLKIT_TEMP_DIRECTORY); $tmp_name = $toolkit->unique() . '-%index.jpg'; // extract the frame $toolkit->extractFrame($frame_number, $frame_rate, '%ft'); $toolkit->setOutput(PHPVIDEOTOOLKIT_TEMP_DIRECTORY, $tmp_name, PHPVideoToolkit::OVERWRITE_EXISTING); $result = $this->_toolkit->execute(false, true); // check the image has been outputted if ($result !== PHPVideoToolkit::RESULT_OK) { return false; } $temp_output = array_shift(array_flip($toolkit->getLastOutput())); print_r($temp_output); $gd_img = imagecreatefromjpeg($temp_output); $ffmpeg_frame_time = $toolkit->formatTimecode($frame_number, '%ft', '%hh:%mm:%ss.%ms', $frame_rate); } catch (Exception $e) { echo $e; } return new ffmpeg_frame($gd_img, $ffmpeg_frame_time); }
echo '<strong>This example shows you how to extract frames from a movie.</strong><br />'; // load the examples configuration require_once 'example-config.php'; // require the library require_once '../phpvideotoolkit.' . $use_version . '.php'; echo '<strong>Note; </strong>This example should work correctly, however it\'s not. I don\'t currently understand why it\'s not producing the expected thumbnails. I\'m currently looking into it and the xample will be updated when this process is fixed.<br /><br />'; // temp directory $tmp_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'tmp/'; // input movie files $files_to_process = array(PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/MOV00007.3gp', PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/Video000.3gp', PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/cat.mpeg'); // output files dirname has to exist $thumbnail_output_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'processed/thumbnails/'; // log dir $log_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'logs/'; // start PHPVideoToolkit class $toolkit = new PHPVideoToolkit($tmp_dir); // set PHPVideoToolkit class to run silently $toolkit->on_error_die = FALSE; // the number of frames to extract per second $extraction_frame_rate = 5; // start the timer collection $total_process_time = 0; // loop through the files to process foreach ($files_to_process as $key => $file) { // get the filename parts $filename = basename($file); $filename_minus_ext = substr($filename, 0, strrpos($filename, '.')); echo '<strong>Extracting ' . $filename . '</strong><br />'; // set the input file $ok = $toolkit->setInputFile($file, $extraction_frame_rate); // check the return value in-case of error
/** * Returns the available pixel formats. * * @return * array An array of pixel formats available to ffmpeg. */ public function getAvailablePixelFormats() { $info = $this->getFFmpegInfo(TRUE); if (!isset($info['pixelformats'])) { PHPVideoToolkit::$ffmpeg_info = FALSE; $info = $this->getFFmpegInfo(FALSE); if (!isset($info['pixelformats'])) { return array(); } } return array_keys($info['pixelformats']); }
public static function gif($file, $options=array(), $target_extension='gif') { // merge the options with the defaults $options = array_merge(array( 'temp_dir' => '/tmp', 'width' => 320, 'height' => 240, 'ratio' => false, //PHPVideoToolkit::RATIO_STANDARD, 'frame_rate' => 1, 'loop_output' => 0, // 0 will loop endlessly 'output_dir' => null, // this doesn't have to be set it can be automatically retreived from 'output_file' 'output_file' => '#filename.#ext', // you can use #filename to automagically hold the filename and #ext to automagically hold the target format extension 'output_title' => '#filename', // you can use #filename to automagically hold the filename and #ext to automagically hold the target format extension 'use_multipass' => false, 'generate_log' => true, 'log_directory' => null, 'die_on_error' => false, 'overwrite_mode' => PHPVideoToolkit::OVERWRITE_FAIL ), $options); // start PHPVideoToolkit class require_once dirname(dirname(__FILE__)).DS.'phpvideotoolkit.php5.php'; $toolkit = new PHPVideoToolkit($options['temp_dir']); $toolkit->on_error_die = $options['die_on_error']; // get the output directory if($options['output_dir']) { $output_dir = $options['output_dir']; } else { $output_dir = dirname($options['output_file']); $output_dir = $output_dir == '.' ? dirname($file) : $output_dir; } // get the filename parts $filename = basename($file); $filename_minus_ext = substr($filename, 0, strrpos($filename, '.')); // get the output filename $output_filename = str_replace(array('#filename', '#ext'), array($filename_minus_ext, $target_extension), basename($options['output_file'])); // set the input file $ok = $toolkit->setInputFile($file); // check the return value in-case of error if(!$ok) { $toolkit->reset(); array_push(self::$_error_messages, $toolkit->getLastError()); return false; } $toolkit->setFormat(PHPVideoToolkit::FORMAT_GIF); $toolkit->disableAudio(); if($options['ratio'] !== false) { $toolkit->setVideoAspectRatio($options['ratio']); } $toolkit->setVideoOutputDimensions($options['width'], $options['height']); $toolkit->setVideoFrameRate($options['frame_rate']); $toolkit->addCommand('-loop_output', $options['loop_output']); // set the output details and overwrite if nessecary $ok = $toolkit->setOutput($output_dir, $output_filename, $options['overwrite_mode']); // check the return value in-case of error if(!$ok) { $toolkit->reset(); array_push(self::$_error_messages, $toolkit->getLastError()); return false; } // execute the ffmpeg command using multiple passes and log the calls and PHPVideoToolkit results $result = $toolkit->execute($options['use_multipass'], $options['generate_log']); array_push(self::$_commands, $toolkit->getLastCommand()); // check the return value in-case of error if($result !== PHPVideoToolkit::RESULT_OK) { // move the log file to the log directory as something has gone wrong if($options['generate_log']) { $log_dir = $options['log_directory'] ? $options['log_directory'] : $output_dir; $toolkit->moveLog($log_dir.$filename_minus_ext.'.log'); array_push(self::$_log_files, $log_dir.$filename_minus_ext.'.log'); } $toolkit->reset(); array_push(self::$_error_messages, $toolkit->getLastError()); return $result; } array_push(self::$_outputs, $toolkit->getLastOutput()); // reset $toolkit->reset(); return $result; }
echo '<strong>This example shows how to simply create an FLV stream script.</strong><br />'; echo '<span style="font-size:12px;">• The flash media player used below is Jeroen Wijering\'s excellent <a href="http://www.jeroenwijering.com/?item=JW_FLV_Media_Player">Flash Media Player</a>. Although bundled with this package the Flash Media Player has a <a href="http://creativecommons.org/licenses/by-nc-sa/2.0/">Creative Commons Attribution-Noncommercial-Share Alike 2.0 Generic</a> license.</span><br />'; echo '<span style="font-size:12px;">• The media is embedded using <a href="http://sourceforge.net/projects/pluginobject/">PluginObject</a> to embed the examples. It is distributed under a BSD License.</span><br /><br />'; } // load the examples configuration $ignore_config_output = true; require_once 'example-config.php'; // set the flv file $flv = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/rickroll.flv'; if (isset($_GET['file'])) { // require the library require_once '../phpvideotoolkit.' . $use_version . '.php'; // temp directory $tmp_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'tmp/'; // start ffmpeg class $toolkit = new PHPVideoToolkit($tmp_dir); // set the flv input $toolkit->setInputFile($flv); // get the incoming stream position $stream_pos = isset($_GET['pos']) ? $_GET['pos'] : 0; // in this example we will enable bandwidth limiting at the extreme and is not really practicle for live purposes // it will only release 100 bytes of the file every second, thus it should take roughly 5 minutes to release a 29Mb file // it will also prevent the browser cache from retaining the file. $toolkit->flvStreamSeek($stream_pos, array('active' => true, 'packet_size' => $packet_size, 'packet_interval' => $packet_interval), false); exit; //<- exits } $size = filesize($flv); echo '<strong>Bandwidth Restrictions and Download Rate.</strong><br />'; echo 'The flv media is ' . $size . ' bytes, using the bandwidth speed limit of ' . $packet_interval . ' kb/s media should be completely loaded in roughly ' . round($size / ($packet_interval * 1024 * $packet_size), 1) . ' seconds.<br />'; echo 'This may not appear to be the case in the player as the player will buffer the contents, You should notice that after a while the player will re-buffer the file. This is because the file was not loaded directly but through this script which buffered the release of the flv.<br />';
/** * Commits all the commands and executes the ffmpeg procedure. This will also attempt to validate any outputted files in order to provide * some level of stop and check system. * * @access public * @param $multi_pass_encode boolean Determines if multi (2) pass encoding should be used. * @param $log boolean Determines if a log file of the results should be generated. * @return mixed * - false On error encountered. * - PHPVIDEOTOOLKIT_RESULT_OK (bool true) If the file has successfully been processed and moved ok to the output address * - PHPVIDEOTOOLKIT_RESULT_OK_BUT_UNWRITABLE (int -1) If the file has successfully been processed but was not able to be moved correctly to the output address * If this is the case you will manually need to move the processed file from the temp directory. You can * get around this by settings the third argument from PHPVideoToolkit::setOutput(), $overwrite to true. * - n (int) A positive integer is only returned when outputting a series of frame grabs from a movie. It dictates * the total number of frames grabbed from the input video. You should also not however, that if a conflict exists * with one of the filenames then this return value will not be returned, but PHPVIDEOTOOLKIT_RESULT_OK_BUT_UNWRITABLE * will be returned instead. * Because of the mixed return value you should always go a strict evaluation of the returned value. ie * * $result = $toolkit->excecute(); * if($result === false) * { * // error * } * else if($result === PHPVIDEOTOOLKIT_RESULT_OK_BUT_UNWRITABLE) * { * // ok but a manual move is required. The file to move can be it can be retrieved by $toolkit->getLastOutput(); * } * else if($result === PHPVIDEOTOOLKIT_RESULT_OK) * { * // everything is ok. * } */ function execute($multi_pass_encode=false, $log=false) { // check for inut and output params $has_placeholder = preg_match('/\%([0-9]+)index/', $this->_process_address) || (strpos($this->_process_address, '%index') === false && strpos($this->_process_address, '%timecode') === false); if($this->_input_file === null && !$has_placeholder) { return $this->_raiseError('execute_input_404'); //<- exits } // check to see if the output address has been set if($this->_process_address === null) { return $this->_raiseError('execute_output_not_set'); //<- exits } // check if temp dir is required and is writable if(($multi_pass_encode || $log) && !is_writable($this->_tmp_directory)) { return $this->_raiseError('execute_temp_unwritable'); //<- exits } if(($this->_overwrite_mode == PHPVIDEOTOOLKIT_OVERWRITE_PRESERVE || $this->_overwrite_mode == PHPVIDEOTOOLKIT_OVERWRITE_FAIL) && is_file($this->_process_address)) { return $this->_raiseError('execute_overwrite_process'); //<- exits } // carry out some overwrite checks if required $overwrite = ''; switch($this->_overwrite_mode) { case PHPVIDEOTOOLKIT_OVERWRITE_UNIQUE : // insert a unique id into the output address (the process address already has one) $unique = $this->unique(); $last_index = strrpos($this->_output_address, DS); $this->_output_address = substr($this->_output_address, 0, $last_index+1).$unique.'-'.substr($this->_output_address, $last_index+1); break; case PHPVIDEOTOOLKIT_OVERWRITE_EXISTING : // add an overwrite command to ffmpeg execution call $overwrite = '-y '; break; case PHPVIDEOTOOLKIT_OVERWRITE_PRESERVE : // do nothing as the preservation comes later break; case PHPVIDEOTOOLKIT_OVERWRITE_FAIL : default : // if the file should fail if(!$has_placeholder && is_file($this->_output_address)) { return $this->_raiseError('execute_overwrite_fail'); //<- exits } break; } $this->_timer_start = PHPVideoToolkit::microtimeFloat(); // we have multiple inputs that require joining so convert them to a joinable format and join if(is_array($this->_input_file)) { $this->_joinInput($log); } // add the input file command to the mix $this->addCommand('-i', $this->_input_file); // if multi pass encoding is enabled add the commands and logfile if($multi_pass_encode) { $multi_pass_file = $this->_tmp_directory.$this->unique().'-multipass'; $this->addCommand('-pass', 1); $this->addCommand('-passlogfile', $multi_pass_file); } // check to see if the format has been set and if it hasn't been set and the extension is a gif // we need to add an extra argument to set the pix format. $format = $this->hasCommand('-f'); if($format === false) { $extension = strtolower(array_pop(explode('.', $this->_input_file))); if($extension === 'gif') { $this->addCommand('-pix_fmt', 'rgb24'); } } else if($format === PHPVIDEOTOOLKIT_FORMAT_GIF) { $this->addCommand('-pix_fmt', 'rgb24'); } // check to see if an aspect ratio is set, if it is correct the width and heights to reflect that aspect ratio. // This isn't strictly needed it is purely for informational purposes that this is done, because if the width is not // inline with what is should be according to the aspect ratio ffmpeg will report the wrong final width and height // when using it to lookup information about the file. $ratio = $this->hasCommand('-aspect'); if($ratio !== false) { $size = $this->hasCommand('-s'); if($size === false) { $info = $this->getFileInfo(); if(isset($info['video']) && isset($info['video']['dimensions'])) { $size = $info['video']['dimensions']['width'].'x'.$info['video']['dimensions']['height']; } } if($size !== false) { $dim = explode('x', substr($size, 1, -1)); if(($boundry = strpos($ratio, ':')) !== false) { $ratio = substr($ratio, 1, $boundry-1)/substr($ratio, $boundry+1, -1); $new_width = round($dim[1]*$ratio); // make sure new width is an even number $ceiled = ceil($new_width); $new_width = $ceiled % 2 !== 0 ? floor($new_width) : $ceiled; if($new_width != $dim[0]) { $this->setVideoDimensions($new_width, $dim[1]); } } else if(strpos($ratio, '.') !== false) { $ratio = floatval($ratio); $new_width = $dim[1]*$ratio; // make sure new width is an even number $ceiled = ceil($new_width); $new_width = $ceiled % 2 !== 0 ? floor($new_width) : $ceiled; if($new_width != $dim[0]) { $this->setVideoDimensions($new_width, $dim[1]); } } } } // combine all the output commands $command_string = $this->_combineCommands(); // prepare the command suitable for exec // the input and overwrite commands have specific places to be set so they have to be added outside of the combineCommands function $exec_string = $this->_prepareCommand(PHPVIDEOTOOLKIT_FFMPEG_BINARY, $command_string, $overwrite.escapeshellcmd($this->_process_address)); // $exec_string = $this->_prepareCommand(PHPVIDEOTOOLKIT_FFMPEG_BINARY, '-i '.$this->_commands['-i'].' '.$command_string, $overwrite.escapeshellcmd($this->_process_address)); if($log) { $this->_log_file = $this->_tmp_directory.$this->unique().'.info'; array_push($this->_unlink_files, $this->_log_file); $exec_string = $exec_string.' &> '.$this->_log_file; } // execute the command exec($exec_string); // track the processed command by adding it to the class array_unshift($this->_processed, $exec_string); // create the multiple pass encode if($multi_pass_encode) { $pass2_exc_string = str_replace('-pass '.escapeshellarg(1), '-pass '.escapeshellarg(2), $exec_string); exec($pass2_exc_string); $this->_processed[0] = array($this->_processed[0], $pass2_exc_string); // remove the multipass log file unlink($multi_pass_file.'-0.log'); } // keep track of the time taken $execution_time = PHPVideoToolkit::microtimeFloat() - $this->_timer_start; array_unshift($this->_timers, $execution_time); // add the exec string to the log file if($log) { $lines = $this->_processed[0]; if(!is_array($lines)) { $lines = array($lines); } array_unshift($lines, $this->_getMessage('ffmpeg_log_separator'), $this->_getMessage('ffmpeg_log_ffmpeg_command'), $this->_getMessage('ffmpeg_log_separator')); array_unshift($lines, $this->_getMessage('ffmpeg_log_separator'), $this->_getMessage('ffmpeg_log_ffmpeg_gunk'), $this->_getMessage('ffmpeg_log_separator')); $this->_addToLog($lines, 'r+'); } // exit // must validate a series of outputed items // detect if the output address is a sequence output if(preg_match('/\%([0-9]+)d/', $this->_process_address, $d_matches) || strpos($this->_process_address, '%d') !== false) { // get the path details $process_info = pathinfo($this->_process_address); $output_info = pathinfo($this->_output_address); $pad_amount = intval($d_matches[1]); // print_r(array($process_info, $output_info)); // get the %index padd amounts $has_preg_index = preg_match('/\%([0-9]+)index/', $output_info['basename'], $index_matches); $output_index_pad_amount = isset($index_matches[1]) ? intval($index_matches[1], 1) : 0; // var_dump($index_matches); // init the iteration values $num = 1; $files = array(); $produced = array(); $error = false; $name_conflict = false; $file_exists = false; // get the first files name $filename = $process_info['dirname'].DS.str_replace($d_matches[0], str_pad($num, $pad_amount, '0', STR_PAD_LEFT), $process_info['basename']); $use_timecode = strpos($output_info['basename'], '%timecode') !== false; $use_index = $has_preg_index || strpos($output_info['basename'], '%index') !== false; // if(!$use_timecode && $use_index) // { // if($log) // { // $this->_logResult('execute_overwrite_fail'); // } // return $this->_raiseError('execute_overwrite_fail'); // } // start the timecode pattern replacement values if($use_timecode) { $secs_start = $this->formatTimecode($this->_image_output_timecode_start, '%hh:%mm:%ss.%ms', '%mt', $this->_image_output_timecode_fps); $fps_inc = 1/$this->_image_output_timecode_fps; $fps_current_sec = 0; $fps_current_frame = 0; } // loop checking for file existence while(@is_file($filename)) { // check for empty file $size = filesize($filename); if($size == 0) { $error = true; } array_push($produced, $filename); // create the substitution arrays $searches = array(); $replacements = array(); if($use_index) { array_push($searches, isset($index_matches[0]) ? $index_matches[0] : '%index'); array_push($replacements, str_pad($num, $output_index_pad_amount, '0', STR_PAD_LEFT)); } // check if timecode is in the output name, no need to use it if not if($use_timecode) { $fps_current_sec += $fps_inc; $fps_current_frame += 1; if($fps_current_sec >= 1) { $fps_current_sec = $fps_inc; $secs_start += 1; $fps_current_frame = 1; } $timecode = $this->formatSeconds($secs_start, $this->image_output_timecode_format, $this->_image_output_timecode_fps); $timecode = str_replace(array(':', '.'), $this->timecode_seperator_output, $timecode); // add to the substitution array array_push($searches, '%timecode'); array_push($replacements, $timecode); } // check if the file exists already and if it does check that it can be overriden $old_filename = $filename; // print_r(array($searches, $replacements, $output_info['basename'])); $new_file = str_replace($searches, $replacements, $output_info['basename']); $new_filename = $output_info['dirname'].DS.$new_file; // var_dump($filename, $new_filename); if(!is_file($new_filename) || $this->_overwrite_mode == PHPVIDEOTOOLKIT_OVERWRITE_EXISTING) { rename($filename, $new_filename); $filename = $new_filename; } // the file exists and is not allowed to be overriden so just rename in the temp directory using the timecode else if($this->_overwrite_mode == PHPVIDEOTOOLKIT_OVERWRITE_PRESERVE) { $new_filename = $process_info['dirname'].DS.'tbm-'.$this->unique().'-'.$new_file; rename($filename, $new_filename); $filename = $new_filename; // add the error to the log file if($log) { $this->_logResult('execute_image_file_exists', array('file'=>$new_filename)); } // flag the conflict $file_exists = true; } // the file exists so the process must fail else { // add the error to the log file if($log) { $this->_logResult('execute_overwrite_fail'); } // tidy up the produced files array_merge($this->_unlink_files, $produced); return $this->_raiseError('execute_overwrite_fail'); } // process the name change if the %d is to be replaced with the timecode $num += 1; $files[$filename] = $size > 0 ? basename($filename) : false; // print_r("\r\n\r\n".is_file($old_filename)." - ".$old_filename.' => '.$new_filename); // print_r($files); // get the next incremented filename to check for existance $filename = $process_info['dirname'].DS.str_replace($d_matches[0], str_pad($num, $pad_amount, '0', STR_PAD_LEFT), $process_info['basename']); } // de-increment the last num as it wasn't found $num -= 1; // if the file was detected but were empty then display a different error if($error === true) { // add the error to the log file if($log) { $this->_logResult('execute_partial_error', array('input'=>$this->_input_file)); } return $this->_raiseError('execute_partial_error', array('input'=>$this->_input_file)); //<- exits } // post process any files // print_r($files); $post_process_result = $this->_postProcess($log, $files); // print_r($files); if(is_array($post_process_result)) { // post process has occurred and everything is fine $num = count($files); } else if($post_process_result !== false) { // the file has encountered an error in the post processing of the files return $post_process_result; } // var_dump("\r\n\r\n", $files, __LINE__, __FILE__, "\r\n\r\n"); // exit; // if the result is false then no post process has taken place $this->_process_file_count = $num; // no files were generated in this sequence if($num == 0) { // add the error to the log file if($log) { $this->_logResult('execute_image_error', array('input'=>$this->_input_file)); } return $this->_raiseError('execute_image_error', array('input'=>$this->_input_file)); //<- exits } // add the files the the class a record of what has been generated array_unshift($this->_files, $files); array_push($lines, $this->_getMessage('ffmpeg_log_separator'), $this->_getMessage('ffmpeg_log_ffmpeg_output'), $this->_getMessage('ffmpeg_log_separator'), implode("\n", $files)); $this->_addToLog($lines, 'r+'); return $file_exists ? PHPVIDEOTOOLKIT_RESULT_OK_BUT_UNWRITABLE : PHPVIDEOTOOLKIT_RESULT_OK; } // must validate one file else { // check that it is a file if(!is_file($this->_process_address)) { // add the error to the log file if($log) { $this->_logResult('execute_output_404', array('input'=>$this->_input_file)); } return $this->_raiseError('execute_output_404', array('input'=>$this->_input_file)); //<- exits } // the file does exist but is it empty? if(filesize($this->_process_address) == 0) { // add the error to the log file if($log) { $this->_logResult('execute_output_empty', array('input'=>$this->_input_file)); } return $this->_raiseError('execute_output_empty', array('input'=>$this->_input_file)); //<- exits } // the file is ok so move to output address if(!is_file($this->_output_address) || $this->_overwrite_mode == PHPVIDEOTOOLKIT_OVERWRITE_EXISTING) { // post process any files $post_process_result = $this->_postProcess($log, array($this->_process_address)); if(is_array($post_process_result) || $post_process_result === true) { // post process has occurred and everything is fine } else if($post_process_result !== false) { return $post_process_result; } // if the result is false then no post process has taken place // rename the file to the final destination and check it went ok if(rename($this->_process_address, $this->_output_address)) { array_push($lines, $this->_getMessage('ffmpeg_log_separator'), $this->_getMessage('ffmpeg_log_ffmpeg_output'), $this->_getMessage('ffmpeg_log_separator'), $this->_output_address); $this->_addToLog($lines, 'r+'); // the file has been renamed ok // add the error to the log file if($log) { $this->_logResult('execute_result_ok', array('output'=>$this->_output_address)); } $this->_process_file_count = 1; // add the file the the class a record of what has been generated array_unshift($this->_files, array($this->_output_address)); return PHPVIDEOTOOLKIT_RESULT_OK; } // renaming failed so return ok but erro else { // add the error to the log file if($log) { $this->_logResult('execute_result_ok_but_unwritable', array('process'=>$this->_process_address, 'output'=>$this->_output_address)); } // add the file the the class a record of what has been generated array_unshift($this->_files, array($this->_process_address)); array_push($lines, $this->_getMessage('ffmpeg_log_separator'), $this->_getMessage('ffmpeg_log_ffmpeg_output'), $this->_getMessage('ffmpeg_log_separator'), $this->_process_address); $this->_addToLog($lines, 'r+'); return PHPVIDEOTOOLKIT_RESULT_OK_BUT_UNWRITABLE; } } // if it is not we signal that it has been created but has not been moved. else if($this->_overwrite_mode == PHPVIDEOTOOLKIT_OVERWRITE_PRESERVE) { // add the error to the log file if($log) { $this->_logResult('execute_result_ok_but_unwritable', array('process'=>$this->_process_address, 'output'=>$this->_output_address)); } // add the file the the class a record of what has been generated array_unshift($this->_files, array($this->_process_address)); return PHPVIDEOTOOLKIT_RESULT_OK_BUT_UNWRITABLE; } // the file exists so the process must fail else { // add the error to the log file if($log) { $this->_logResult('execute_overwrite_fail'); } // tidy up the produced files array_push($this->_unlink_files, $this->_process_address); return $this->_raiseError('execute_overwrite_fail'); } } return null; }
// require the library require_once '../phpvideotoolkit.' . $use_version . '.php'; // please replace xxxxx with the full absolute path to the files and folders // also please make the $video_output_dir read and writeable by the webserver // temp directory $tmp_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'tmp/'; // input movie files $files_to_process = array(PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/MOV00007.3gp', PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/Video000.3gp', PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/cat.mpeg'); // output files dirname has to exist $video_output_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'processed/videos/'; // bit rate of audio (valid vaues are 16,32,64) $bitrate = 64; // sampling rate (valid values are 11025, 22050, 44100) $samprate = 44100; // start PHPVideoToolkit class $toolkit = new PHPVideoToolkit($tmp_dir); // set PHPVideoToolkit class to run silently $toolkit->on_error_die = FALSE; // loop through the files to process foreach ($files_to_process as $file) { echo '<strong>Information for : ' . $file . "</strong><br />\r\n"; // set the input file $ok = $toolkit->setInputFile($file); // check the return value in-case of error if (!$ok) { // if there was an error then get it echo $toolkit->getLastError() . "<br />\r\n"; $toolkit->reset(); continue; } $data = $toolkit->getFileInfo();
/** * Returns information about the specified file without having to use ffmpeg-php * as it consults the ffmpeg binary directly. This idea for this function has been borrowed from * a French ffmpeg class located: http://www.phpcs.com/codesource.aspx?ID=45279 * * @access public * @todo Change the search from string explode to a regex based search * @param string $file The absolute path of the file that is required to be manipulated. * @return mixed false on error encountered, true otherwise **/ public function getFileInfo($file = false, $tmp_directory = '/tmp/') { // check to see if this is a static call if ($file !== false && PHPVideoToolkit::$_static === true) { $toolkit = new PHPVideoToolkit($tmp_directory); return $toolkit->getFileInfo($file); } // if the file has not been specified check to see if an input file has been specified if ($file === false) { if (!$this->_input_file) { // input file not valid return $this->_raiseError('getFileInfo_no_input'); //<- exits } $file = $this->_input_file; } $file = escapeShellString($file); // die($file); // create a hash of the filename $hash = md5($file); // check to see if the info has already been generated if (isset(self::$_file_info[$hash])) { return self::$_file_info[$hash]; } // generate a random filename $info_file = $this->_tmp_directory . $this->unique($hash) . '.info'; // execute the ffmpeg lookup // exec(PHPVIDEOTOOLKIT_FFMPEG_BINARY.' -i '.$file.' &> '.$info_file); exec(PHPVIDEOTOOLKIT_FFMPEG_BINARY . ' -i ' . $file . ' 2>&1', $buffer); $buffer = implode("\r\n", $buffer); // $data = false; // try to open the file // $handle = fopen($info_file, 'r'); // if($handle) // { $data = array(); // $buffer = ''; // loop through the lines of data and collect the buffer // while (!feof($handle)) // { // $buffer .= fgets($handle, 4096); // } // die($buffer); // grab the duration and bitrate data preg_match_all('/Duration: (.*)/', $buffer, $matches); if (count($matches) > 0) { $parts = explode(', ', trim($matches[1][0])); $data['duration'] = array(); $timecode = $parts[0]; $data['duration']['seconds'] = $this->timecodeToSeconds($timecode); $data['bitrate'] = intval(ltrim($parts[2], 'bitrate: ')); $data['duration']['start'] = ltrim($parts[1], 'start: '); $data['duration']['timecode'] = array(); $data['duration']['timecode']['rounded'] = substr($timecode, 0, 8); $data['duration']['timecode']['seconds'] = array(); $data['duration']['timecode']['seconds']['exact'] = $timecode; $data['duration']['timecode']['seconds']['excess'] = intval(substr($timecode, 9)); } // match the video stream info preg_match('/Stream(.*): Video: (.*)/', $buffer, $matches); if (count($matches) > 0) { $data['video'] = array(); // get the dimension parts // print_r($matches); preg_match('/([0-9]{1,5})x([0-9]{1,5})/', $matches[2], $dimensions_matches); // print_r($dimensions_matches); $dimensions_value = $dimensions_matches[0]; $data['video']['dimensions'] = array('width' => floatval($dimensions_matches[1]), 'height' => floatval($dimensions_matches[2])); // get the framerate preg_match('/([0-9\\.]+) (fps|tb)\\(r\\)/', $matches[0], $fps_matches); $data['video']['frame_rate'] = floatval($fps_matches[1]); $fps_value = $fps_matches[0]; // get the ratios preg_match('/\\[PAR ([0-9\\:\\.]+) DAR ([0-9\\:\\.]+)\\]/', $matches[0], $ratio_matches); if (count($ratio_matches)) { $data['video']['pixel_aspect_ratio'] = $ratio_matches[1]; $data['video']['display_aspect_ratio'] = $ratio_matches[2]; } // work out the number of frames if (isset($data['duration']) && isset($data['video'])) { // set the total frame count for the video $data['video']['frame_count'] = ceil($data['duration']['seconds'] * $data['video']['frame_rate']); // set the framecode $frames = ceil($data['video']['frame_rate'] * ($data['duration']['timecode']['seconds']['excess'] / 10)); $data['duration']['timecode']['frames'] = array(); $data['duration']['timecode']['frames']['exact'] = $data['duration']['timecode']['rounded'] . '.' . $frames; $data['duration']['timecode']['frames']['excess'] = $frames; $data['duration']['timecode']['frames']['total'] = $data['video']['frame_count']; } // formats should be anything left over, let me know if anything else exists $parts = explode(',', $matches[2]); $other_parts = array($dimensions_value, $fps_value); $formats = array(); foreach ($parts as $key => $part) { $part = trim($part); if (!in_array($part, $other_parts)) { array_push($formats, $part); } } $data['video']['pixel_format'] = $formats[1]; $data['video']['codec'] = $formats[0]; } // match the audio stream info preg_match('/Stream(.*): Audio: (.*)/', $buffer, $matches); if (count($matches) > 0) { // setup audio values $data['audio'] = array('stereo' => -1, 'sample_rate' => -1, 'sample_rate' => -1); $other_parts = array(); // get the stereo value preg_match('/(stereo|mono)/i', $matches[0], $stereo_matches); if (count($stereo_matches)) { $data['audio']['stereo'] = $stereo_matches[0]; array_push($other_parts, $stereo_matches[0]); } // get the sample_rate preg_match('/([0-9]{3,6}) Hz/', $matches[0], $sample_matches); if (count($sample_matches)) { $data['audio']['sample_rate'] = count($sample_matches) ? floatval($sample_matches[1]) : -1; array_push($other_parts, $sample_matches[0]); } // get the bit rate preg_match('/([0-9]{1,3}) kb\\/s/', $matches[0], $bitrate_matches); if (count($bitrate_matches)) { $data['audio']['bitrate'] = count($bitrate_matches) ? floatval($bitrate_matches[1]) : -1; array_push($other_parts, $bitrate_matches[0]); } // formats should be anything left over, let me know if anything else exists $parts = explode(',', $matches[2]); $formats = array(); foreach ($parts as $key => $part) { $part = trim($part); if (!in_array($part, $other_parts)) { array_push($formats, $part); } } $data['audio']['codec'] = $formats[0]; } // check that some data has been obtained if (!count($data)) { $data = false; } else { $data['_raw_info'] = $buffer; } // fclose($handle); // } // if(is_file($info_file)) // { // if the info file exists remove it // unlink($info_file); // } // cache info and return return self::$_file_info[$hash] = $data; }
/** * extract frame * * @param string $file * @param string $time_frame * @return void * @author Andy Bennett */ public static function extract_frame($file = null, $time_frame = '00:00:00.1') { if (is_null($file)) { return null; } if (!defined('PHPVIDEOTOOLKIT_FFMPEG_BINARY')) { define('PHPVIDEOTOOLKIT_FFMPEG_BINARY', Kohana::config('ffmpeg.binaries_path')); } try { // require the library require_once 'phpvideotoolkit/phpvideotoolkit.php5.php'; // start the timer collection $total_process_time = 0; $tmp_dir = Kohana::config('ffmpeg.tmp_path'); // start PHPVideoToolkit class $toolkit = new PHPVideoToolkit($tmp_dir); // set PHPVideoToolkit class to run silently $toolkit->on_error_die = FALSE; // check the return value in-case of error if (!$toolkit->setInputFile($file)) { throw new Exception($toolkit->getLastError()); } // set the output dimensions $toolkit->setVideoOutputDimensions(PHPVideoToolkit::SIZE_SAS); // same as source // extract a thumbnail $toolkit->extractFrame($time_frame); // get the filename parts $path = dirname($file) . '/'; $filename = basename($file); $filename_minus_ext = substr($filename, 0, strrpos($filename, '.')); // set the output details $ok = $toolkit->setOutput($path, $filename_minus_ext . '.jpg', PHPVideoToolkit::OVERWRITE_EXISTING); // check the return value in-case of error if (!$ok) { throw new Exception($toolkit->getLastError()); } // execute the ffmpeg command $result = $toolkit->execute(false, true); // check the return value in-case of error if ($result !== PHPVideoToolkit::RESULT_OK) { throw new Exception($toolkit->getLastError()); } // reset $toolkit->reset(); return true; } catch (Exception $e) { // echo $toolkit->getLastCommand().'<br />'; echo $e->getMessage(); $toolkit->reset(); } }
$ignore_demo_files = true; // load the examples configuration require_once 'example-config.php'; // require the library require_once '../phpvideotoolkit.' . $use_version . '.php'; // temp directory $tmp_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'tmp/'; // set the frame rate for the timecodes $frame_rate = 25; // set the time to examine / format $timecode = '01:14:32.59'; $timecode_format = '%hh:%mm:%ss.%ms'; echo '<strong>Original Timecode</strong><br />'; echo $timecode . '<br /><br />'; // start ffmpeg class $toolkit = new PHPVideoToolkit($tmp_dir); echo '<strong>Timecode conversion to seconds</strong><br />'; echo 'Frame seconds (rounded) -> ' . $toolkit->formatTimecode($timecode, $timecode_format, '%st', $frame_rate) . '<br />'; echo 'Frame seconds (rounded down) -> ' . $toolkit->formatTimecode($timecode, $timecode_format, '%sf', $frame_rate) . '<br />'; echo 'Frame seconds (rounded up) -> ' . $toolkit->formatTimecode($timecode, $timecode_format, '%sc', $frame_rate) . '<br />'; echo 'Frame seconds -> ' . $toolkit->formatTimecode($timecode, $timecode_format, '%mt', $frame_rate) . '<br /><br />'; echo '<strong>Timecode conversion to frames</strong><br />'; echo 'Frame number (in current second) -> ' . $toolkit->formatTimecode($timecode, $timecode_format, '%fn', $frame_rate) . '<br />'; echo 'Frame number (in video) -> ' . $toolkit->formatTimecode($timecode, $timecode_format, '%ft', $frame_rate) . '<br /><br />'; echo '<strong>Timecode conversion to other timecodes</strong><br />'; echo 'hh:mm -> ' . $toolkit->formatTimecode($timecode, $timecode_format, '%hh:%mm', $frame_rate) . '<br />'; echo 'hh:mm:ss -> ' . $toolkit->formatTimecode($timecode, $timecode_format, '%hh:%mm:%ss', $frame_rate) . '<br />'; echo 'hh:mm:ss.fn -> ' . $toolkit->formatTimecode($timecode, $timecode_format, '%hh:%mm:%ss.%fn', $frame_rate) . '<br />'; echo 'hh:mm:ss.ms -> ' . $toolkit->formatTimecode($timecode, $timecode_format, '%hh:%mm:%ss.%ms', $frame_rate) . '<br />'; echo 'mm:ss (smart minutes) -> ' . $toolkit->formatTimecode($timecode, $timecode_format, '%mm:%ss', $frame_rate) . '<br />'; echo 'mm:ss.fn (smart minutes) -> ' . $toolkit->formatTimecode($timecode, $timecode_format, '%mm:%ss.%fn', $frame_rate) . '<br />';
// please replace xxxxx with the full absolute path to the files and folders // also please make the $thumbnail_output_dir read and writeable by the webserver // temp directory $tmp_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'tmp/'; // input movie files $video_to_process = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/cat.mpeg'; $watermark = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'watermark.png'; // $watermark = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH.'watermark.gif'; // output files dirname has to exist $video_output_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'processed/videos/'; // output files dirname has to exist $thumbnail_output_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'processed/thumbnails/'; // log dir $log_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'logs/'; // start PHPVideoToolkit class $toolkit = new PHPVideoToolkit($tmp_dir); $use_vhook = !isset($_GET['gd']) || $_GET['gd'] == '0'; if ($use_vhook) { // check to see if vhook support is enabled echo '<strong>Testing for vhook support...</strong><br />'; if (!$toolkit->hasVHookSupport() && !$_GET['dev']) { echo 'You FFmpeg binary has NOT been compiled with vhook support, you can not watermark video, you can however watermark image outputs.<br /><a href="?gd=1">Click here</a> to run the watermark demo on images only.<br />'; exit; //<- exits } echo 'You FFmpeg binary has been compiled with vhook support.<br /><br />'; } else { echo '<strong>GD watermarking only...</strong><br />'; echo 'Your FFmpeg binary has NOT been compiled with vhook support and we are only testing automated watermarking of images via GD now.<br /><a href="?gd=0">Click here</a> to go back to the vhook watermarking demo.<br /><br />'; } // set ffmpeg class to run silently
// require the library require_once '../phpvideotoolkit.' . $use_version . '.php'; // temp directory $tmp_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'tmp/'; // input movie files $files_to_process = array(PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/MOV02820.MPG', PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/MOV02832.MPG'); // output files dirname has to exist $video_output_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'processed/videos/'; // log dir $log_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'logs/'; // bit rate of audio (valid vaues are 16,32,64) $bitrate = 64; // sampling rate (valid values are 11025, 22050, 44100) $samprate = 44100; // start PHPVideoToolkit class $toolkit = new PHPVideoToolkit($tmp_dir); // set PHPVideoToolkit class to run silently $toolkit->on_error_die = FALSE; $input_file = array_pop($files_to_process); // get the filename parts $filename = basename($input_file); $filename_minus_ext = substr($filename, 0, strrpos($filename, '.')); // set the input file $ok = $toolkit->setInputFile($input_file); // check the return value in-case of error if (!$ok) { // if there was an error then get it echo $toolkit->getLastError() . "<br />\r\n"; $toolkit->reset(); exit; }
// require the library require_once '../phpvideotoolkit.' . $use_version . '.php'; // output files dirname has to exist $tmp_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'tmp/'; // input movie files $files_to_process = array(PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/mov02596-1.jpg', PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/mov02596-2.jpg', PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/mov02596-3.jpg', PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/mov02596-4.jpg', PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/mov02596-5.jpg', PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/mov02596-6.jpg', PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/mov02596-7.jpg', PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/mov02596-8.jpg', PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/mov02596-9.jpg', PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/mov02596-10.jpg', PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/mov02596-11.jpg', PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/mov02596-12.jpg', PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/mov02596-13.jpg', PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/mov02596-14.jpg'); $sound = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/Ballad of the Sneak.mp3'; // output files dirname has to exist $video_output_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'processed/videos/'; // log dir $log_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'logs/'; // output filename $output_filename = 'my-picture-movie.gif'; // $output_filename = 'my-picture-movie.mpeg'; // init PHPVideoToolkit class $toolkit = new PHPVideoToolkit($tmp_dir); // compile the image to the tmp dir with an input frame rate of 2 per second $ok = $toolkit->prepareImagesForConversionToVideo($files_to_process, 2); if (!$ok) { // if there was an error then get it echo $toolkit->getLastError() . "<br />\r\n"; exit; } // set a different output size (this will shrink the images to a video that is smaller, the images are 320x240) $toolkit->setVideoOutputDimensions(160, 120); // set endless looping $toolkit->setGifLoops(0); // $toolkit->addAudio($sound); // set the output parameters $ok = $toolkit->setOutput($video_output_dir, $output_filename, PHPVideoToolkit::OVERWRITE_EXISTING); if (!$ok) {
/** * Add a post */ public function iframe_add() { $this->setView('iframe_add.php'); @set_time_limit(0); $uploaded_files = array(); try { if (!isset(User_Model::$auth_data)) { throw new Exception(__('POST_ADD_ERROR_SESSION_EXPIRED')); } $is_student = isset(User_Model::$auth_data['student_number']); // Message $message = isset($_POST['message']) ? trim($_POST['message']) : ''; if ($message == '' || $message == __('PUBLISH_DEFAULT_MESSAGE')) { throw new Exception(__('POST_ADD_ERROR_NO_MESSAGE')); } $message = preg_replace('#\\n{2,}#', "\n\n", $message); // Category if (!isset($_POST['category']) || !ctype_digit($_POST['category'])) { throw new Exception(__('POST_ADD_ERROR_NO_CATEGORY')); } $category = (int) $_POST['category']; // Official post (in a group) $official = isset($_POST['official']); // Group $group = isset($_POST['group']) && ctype_digit($_POST['group']) ? (int) $_POST['group'] : 0; if ($group == 0) { $group = null; $official = false; } else { $groups_auth = Group_Model::getAuth(); if (isset($groups_auth[$group])) { if ($official && !$groups_auth[$group]['admin']) { throw new Exception(__('POST_ADD_ERROR_OFFICIAL')); } } else { throw new Exception(__('POST_ADD_ERROR_GROUP_NOT_FOUND')); } } // Private message $private = isset($_POST['private']); if ($private && !$is_student) { throw new Exception(__('POST_ADD_ERROR_PRIVATE')); } $attachments = array(); // Photos if (isset($_FILES['attachment_photo']) && is_array($_FILES['attachment_photo']['name'])) { foreach ($_FILES['attachment_photo']['size'] as $size) { if ($size > Config::UPLOAD_MAX_SIZE_PHOTO) { throw new Exception(__('POST_ADD_ERROR_PHOTO_SIZE', array('size' => File::humanReadableSize(Config::UPLOAD_MAX_SIZE_PHOTO)))); } } if ($filepaths = File::upload('attachment_photo')) { foreach ($filepaths as $filepath) { $uploaded_files[] = $filepath; } foreach ($filepaths as $i => $filepath) { $name = isset($_FILES['attachment_photo']['name'][$i]) ? $_FILES['attachment_photo']['name'][$i] : ''; try { $img = new Image(); $img->load($filepath); $type = $img->getType(); if ($type == IMAGETYPE_JPEG) { $ext = 'jpg'; } else { if ($type == IMAGETYPE_GIF) { $ext = 'gif'; } else { if ($type == IMAGETYPE_PNG) { $ext = 'png'; } else { throw new Exception(); } } } if ($img->getWidth() > 800) { $img->setWidth(800, true); } $img->save($filepath); // Thumb $thumbpath = $filepath . '.thumb'; $img->thumb(Config::$THUMBS_SIZES[0], Config::$THUMBS_SIZES[1]); $img->setType(IMAGETYPE_JPEG); $img->save($thumbpath); unset($img); $attachments[] = array($filepath, $name, $thumbpath); $uploaded_files[] = $thumbpath; } catch (Exception $e) { throw new Exception(__('POST_ADD_ERROR_PHOTO_FORMAT')); } } } } // Vidéos /* @uses PHPVideoToolkit : http://code.google.com/p/phpvideotoolkit/ * @requires ffmpeg, php5-ffmpeg */ if (isset($_FILES['attachment_video']) && is_array($_FILES['attachment_video']['name'])) { foreach ($_FILES['attachment_video']['size'] as $size) { if ($size > Config::UPLOAD_MAX_SIZE_VIDEO) { throw new Exception(__('POST_ADD_ERROR_VIDEO_SIZE', array('size' => File::humanReadableSize(Config::UPLOAD_MAX_SIZE_VIDEO)))); } } if ($filepaths = File::upload('attachment_video')) { foreach ($filepaths as $filepath) { $uploaded_files[] = $filepath; } foreach ($filepaths as $i => $filepath) { $name = isset($_FILES['attachment_video']['name'][$i]) ? $_FILES['attachment_video']['name'][$i] : ''; try { $video = new ffmpeg_movie($filepath, false); if (!$video->hasVideo()) { throw new Exception('No video stream found in the file'); } if (!$video->hasAudio()) { throw new Exception('No audio stream found in the file'); } } catch (Exception $e) { throw new Exception(__('POST_ADD_ERROR_VIDEO_FORMAT')); } // Video conversion try { $video_current_width = $video->getFrameWidth(); $video_width = min($video_current_width, Config::VIDEO_MAX_WIDTH); if ($video_width % 2 == 1) { // Even number required $video_width--; } $video_height = $video_width * $video->getFrameHeight() / $video_current_width; if ($video_height % 2 == 1) { // Even number required $video_height--; } // Extract thumb $video_thumb = $video->getFrame(round($video->getFrameCount() * 0.2)); unset($video); $video_thumb = $video_thumb->toGDImage(); $thumbpath = DATA_DIR . Config::DIR_DATA_TMP . File::getName($filepath) . '.thumb'; imagejpeg($video_thumb, $thumbpath, 95); unset($video_thumb); $img = new Image(); $img->load($thumbpath); $img->setWidth($video_width, true); $img->setType(IMAGETYPE_JPEG); $img->save($thumbpath); $uploaded_files[] = $thumbpath; unset($img); // Convert to FLV if (!preg_match('#\\.flv$#i', $filepath)) { $toolkit = new PHPVideoToolkit(); $toolkit->on_error_die = true; // Will throw exception on error $toolkit->setInputFile($filepath); $toolkit->setVideoOutputDimensions($video_width, $video_height); $toolkit->setFormatToFLV(Config::VIDEO_SAMPLING_RATE, Config::VIDEO_AUDIO_BIT_RATE); $toolkit->setOutput(DATA_DIR . Config::DIR_DATA_TMP, File::getName($filepath) . '.flv', PHPVideoToolkit::OVERWRITE_EXISTING); $toolkit->execute(false, false); // Multipass: false, Log: false File::delete($filepath); $filepath = $toolkit->getLastOutput(); $filepath = $filepath[0]; unset($toolkit); } $attachments[] = array($filepath, $name, $thumbpath); $uploaded_files[] = $filepath; } catch (Exception $e) { throw new Exception(__('POST_ADD_ERROR_VIDEO_CONVERT') . $e->getMessage()); } } } } // Audios if (isset($_FILES['attachment_audio']) && is_array($_FILES['attachment_audio']['name'])) { foreach ($_FILES['attachment_audio']['size'] as $size) { if ($size > Config::UPLOAD_MAX_SIZE_AUDIO) { throw new Exception(__('POST_ADD_ERROR_AUDIO_SIZE', array('size' => File::humanReadableSize(Config::UPLOAD_MAX_SIZE_AUDIO)))); } } if ($filepaths = File::upload('attachment_audio')) { foreach ($filepaths as $filepath) { $uploaded_files[] = $filepath; } foreach ($filepaths as $i => $filepath) { if (!preg_match('#\\.mp3$#', $filepath)) { throw new Exception(__('POST_ADD_ERROR_AUDIO_FORMAT')); } $name = isset($_FILES['attachment_audio']['name'][$i]) ? $_FILES['attachment_audio']['name'][$i] : ''; $attachments[] = array($filepath, $name); } } } // Files if (isset($_FILES['attachment_file']) && is_array($_FILES['attachment_file']['name'])) { foreach ($_FILES['attachment_file']['size'] as $size) { if ($size > Config::UPLOAD_MAX_SIZE_FILE) { throw new Exception(__('POST_ADD_ERROR_FILE_SIZE', array('size' => File::humanReadableSize(Config::UPLOAD_MAX_SIZE_FILE)))); } } if ($filepaths = File::upload('attachment_file')) { foreach ($filepaths as $filepath) { $uploaded_files[] = $filepath; } foreach ($filepaths as $i => $filepath) { if (!preg_match('#\\.[a-z0-9]{2,4}$#i', $filepath)) { throw new Exception(__('POST_ADD_ERROR_FILE_FORMAT')); } if (preg_match('#\\.(jpg|png|gif|mp3|flv)$#i', $filepath)) { throw new Exception(__('POST_ADD_ERROR_FILE_FORMAT2')); } $name = isset($_FILES['attachment_file']['name'][$i]) ? $_FILES['attachment_file']['name'][$i] : ''; $attachments[] = array($filepath, $name); } } } // Event if (isset($_POST['event_title']) && isset($_POST['event_start']) && isset($_POST['event_end'])) { // Title $event_title = trim($_POST['event_title']); if ($event_title == '') { throw new Exception(__('POST_ADD_ERROR_EVENT_NO_TITLE')); } // Dates if (!($event_start = strptime($_POST['event_start'], __('PUBLISH_EVENT_DATE_FORMAT')))) { throw new Exception(__('POST_ADD_ERROR_EVENT_DATE')); } if (!($event_end = strptime($_POST['event_end'], __('PUBLISH_EVENT_DATE_FORMAT')))) { throw new Exception(__('POST_ADD_ERROR_EVENT_DATE')); } $event_start = mktime($event_start['tm_hour'], $event_start['tm_min'], 0, $event_start['tm_mon'] + 1, $event_start['tm_mday'], $event_start['tm_year'] + 1900); $event_end = mktime($event_end['tm_hour'], $event_end['tm_min'], 0, $event_end['tm_mon'] + 1, $event_end['tm_mday'], $event_end['tm_year'] + 1900); if ($event_start > $event_end) { throw new Exception(__('POST_ADD_ERROR_EVENT_DATE_ORDER')); } $event = array($event_title, $event_start, $event_end); } else { $event = null; } // Survey if (isset($_POST['survey_question']) && isset($_POST['survey_end']) && isset($_POST['survey_answer']) && is_array($_POST['survey_answer'])) { // Question $survey_question = trim($_POST['survey_question']); if ($survey_question == '') { throw new Exception(__('POST_ADD_ERROR_SURVEY_NO_QUESTION')); } // Date if (!($survey_end = strptime($_POST['survey_end'], __('PUBLISH_EVENT_DATE_FORMAT')))) { throw new Exception(__('POST_ADD_ERROR_SURVEY_DATE')); } $survey_end = mktime($survey_end['tm_hour'], $survey_end['tm_min'], 0, $survey_end['tm_mon'] + 1, $survey_end['tm_mday'], $survey_end['tm_year'] + 1900); // Multiple answers $survey_multiple = isset($_POST['survey_multiple']); // Answers $survey_answers = array(); foreach ($_POST['survey_answer'] as $survey_answer) { $survey_answer = trim($survey_answer); if ($survey_answer != '') { $survey_answers[] = $survey_answer; } } if (count($survey_answers) < 2) { throw new Exception(__('POST_ADD_ERROR_SURVEY_ANSWERS')); } $survey = array($survey_question, $survey_end, $survey_multiple, $survey_answers); } else { $survey = null; } // Creation of the post $id = $this->model->addPost((int) User_Model::$auth_data['id'], $message, $category, $group, $official, $private); // Attach files foreach ($attachments as $attachment) { $this->model->attachFile($id, $attachment[0], $attachment[1], isset($attachment[2]) ? $attachment[2] : null); } // Event if (isset($event)) { $this->model->attachEvent($id, $event[0], $event[1], $event[2]); } // Survey if (isset($survey)) { $this->model->attachSurvey($id, $survey[0], $survey[1], $survey[2], $survey[3]); } $this->addJSCode(' parent.location = "' . Config::URL_ROOT . Routes::getPage('home') . '"; '); } catch (Exception $e) { // Delete all uploading files in tmp foreach ($uploaded_files as $uploaded_file) { File::delete($uploaded_file); } $this->addJSCode(' with(parent){ Post.errorForm(' . json_encode($e->getMessage()) . '); } '); } }
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ echo '<html><head></head><body>'; echo '<a style="font-size:12px;" href="index.php#examples">← Back to examples list</a><br /><br />'; echo '<strong>This example shows you how to access the information about your ffmpeg installation.</strong><br /><br />'; $ignore_demo_files = true; // load the examples configuration require_once 'example-config.php'; // require the library require_once '../phpvideotoolkit.' . $use_version . '.php'; // temp directory $tmp_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'tmp/'; // start ffmpeg class $toolkit = new PHPVideoToolkit($tmp_dir); // get the ffmpeg info $info = $toolkit->getFFmpegInfo(); // determine the type of support for ffmpeg-php echo '<strong>FFmpeg-PHP Support</strong><br />'; // determine if ffmpeg-php is supported $has_ffmpeg_php_support = $toolkit->hasFFmpegPHPSupport(); // you can also determine if it has ffmpeg php support with below // $has_ffmpeg_php_support = $info['ffmpeg-php-support']; switch ($has_ffmpeg_php_support) { case 'module': echo 'Congratulations you have the FFmpeg-PHP module installed.'; break; case 'emulated': echo 'You haven\'t got the FFmpeg-PHP module installed, however you can use the PHPVideoToolkit\'s adapter\'s to emulate FFmpeg-PHP.<br /><strong>Note:</strong> It is recommended that if you heavily use FFmpeg-PHP that you install the module.'; break;
/** * Returns the available codecs. * @access public * @param mixed $type The type of codec list to return, FALSE (to return all codecs), or either 'audio', 'video', or 'subtitle'. * @return array An array of codecs available to ffmpeg. */ public static function getAvailableCodecs($type = FALSE) { // check to see if this is a static call if (isset($this) === FALSE) { $toolkit = new PHPVideoToolkit(); $info = $toolkit->getFFmpegInfo(true); } else { $info = $this->getFFmpegInfo(true); } // are we checking for particluar method? $return_vals = array(); if ($type === FALSE) { $video_keys = array_keys($info['codecs']['video']); $audio_keys = array_keys($info['codecs']['audio']); $subtitle_keys = array_keys($info['codecs']['subtitle']); return array_merge($video_keys, $audio_keys, $subtitle_keys); } return isset($info['codecs'][$type]) === TRUE ? array_keys($info['codecs'][$type]) : FALSE; }
// require the library require_once '../phpvideotoolkit.' . $use_version . '.php'; // temp directory $tmp_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'tmp/'; // input movie files $files_to_process = array(PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/MOV00007.3gp', PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/cat.mpeg'); // output files dirname has to exist $audio_output_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'processed/audio/'; // log dir $log_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'logs/'; // bit rate of audio (valid vaues are 16,32,64) $bitrate = 64; // sampling rate (valid values are 11025, 22050, 44100) $samprate = 44100; // start PHPVideoToolkit class $toolkit = new PHPVideoToolkit($tmp_dir); // set PHPVideoToolkit class to run silently $toolkit->on_error_die = FALSE; // start the timer collection $total_process_time = 0; // loop through the files to process foreach ($files_to_process as $key => $file) { // get the filename parts $filename = basename($file); $filename_minus_ext = substr($filename, 0, strrpos($filename, '.')); echo '<strong>Processing ' . $filename . '</strong><br />'; // set the input file $ok = $toolkit->setInputFile($file); // check the return value in-case of error if (!$ok) { // if there was an error then get it
// load the examples configuration require_once 'example-config.php'; // require the library require_once '../phpvideotoolkit.' . $use_version . '.php'; // please replace xxxxx with the full absolute path to the files and folders // also please make the $thumbnail_output_dir read and writeable by the webserver // temp directory $tmp_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'tmp/'; // input movie files $files_to_process = array(PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/MOV00007.3gp', PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/Video000.3gp', PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/cat.mpeg'); // output files dirname has to exist $thumbnail_output_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'processed/thumbnails/'; // log dir $log_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'logs/'; // start phpvideotoolkit class $toolkit = new PHPVideoToolkit($tmp_dir); // set phpvideotoolkit class to run silently $toolkit->on_error_die = FALSE; // start the timer collection $total_process_time = 0; // loop through the files to process foreach ($files_to_process as $key => $file) { // get the filename parts $filename = basename($file); $filename_minus_ext = substr($filename, 0, strrpos($filename, '.')); // set the input file $ok = $toolkit->setInputFile($file); // check the return value in-case of error if (!$ok) { // if there was an error then get it echo '<b>' . $toolkit->getLastError() . "</b><br />\r\n";
// require the library require_once '../phpvideotoolkit.' . $use_version . '.php'; // temp directory $tmp_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'tmp/'; // input movie files $files_to_process = array(PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/MOV00007.3gp', PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/Video000.3gp', PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'to-be-processed/cat.mpeg'); // output files dirname has to exist $video_output_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'processed/videos/'; // log dir $log_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'logs/'; // bit rate of audio (valid vaues are 16,32,64) $bitrate = 64; // sampling rate (valid values are 11025, 22050, 44100) $samprate = 44100; // start PHPVideoToolkit class $toolkit = new PHPVideoToolkit($tmp_dir); // set PHPVideoToolkit class to run silently $toolkit->on_error_die = FALSE; // start the timer collection $total_process_time = 0; // loop through the files to process foreach ($files_to_process as $key => $file) { // get the filename parts $filename = basename($file); $filename_minus_ext = substr($filename, 0, strrpos($filename, '.')); echo '<strong>Processing ' . $filename . '</strong><br />'; // set the input file $ok = $toolkit->setInputFile($file); // check the return value in-case of error if (!$ok) { // if there was an error then get it