<?php include_once './includes/bootstrap.php'; try { $video = new \PHPVideoToolkit\Video('media/BigBuckBunny_320x180.mp4', $config); $process = $video->getProcess(); // $process->setProcessTimelimit(1); $output = $video->extractSegment(new \PHPVideoToolkit\Timecode(10), new \PHPVideoToolkit\Timecode(20))->save('./output/big_buck_bunny_' . time() . '.mp3', new \PHPVideoToolkit\AudioFormat_Mp3('output', '/opt/local/bin/ffmpeg', './tmp')); echo '<h1>Executed Command</h1>'; \PHPVideoToolkit\Trace::vars($process->getExecutedCommand()); echo '<hr /><h1>FFmpeg Process Messages</h1>'; \PHPVideoToolkit\Trace::vars($process->getMessages()); echo '<hr /><h1>Buffer Output</h1>'; \PHPVideoToolkit\Trace::vars($process->getBuffer(true)); } catch (\PHPVideoToolkit\FfmpegProcessOutputException $e) { echo '<h1>Error</h1>'; \PHPVideoToolkit\Trace::vars($e); $process = $video->getProcess(); if ($process->isCompleted()) { echo '<hr /><h2>Executed Command</h2>'; \PHPVideoToolkit\Trace::vars($process->getExecutedCommand()); echo '<hr /><h2>FFmpeg Process Messages</h2>'; \PHPVideoToolkit\Trace::vars($process->getMessages()); echo '<hr /><h2>Buffer Output</h2>'; \PHPVideoToolkit\Trace::vars($process->getBuffer(true)); } } catch (\PHPVideoToolkit\Exception $e) { echo '<h1>Error</h1>'; \PHPVideoToolkit\Trace::vars($e); }
<?php include_once './includes/bootstrap.php'; try { $video = new \PHPVideoToolkit\Video($example_video_path, $config); $result = $video->extractFrame(new \PHPVideoToolkit\Timecode('00:00:50.00'))->save('./output/extract-frame.example2.jpg'); // $result is an \PHPVideoToolkit\Image object on success } catch (\PHPVideoToolkit\Exception $e) { \PHPVideoToolkit\Trace::vars($video->getProcess()->getExecutedCommand()); \PHPVideoToolkit\Trace::vars($video->getProcess()->getBuffer()); \PHPVideoToolkit\Trace::vars($video->getProcess()->getLastSplit()); \PHPVideoToolkit\Trace::vars($e); }
/** * See contract for documentation */ public function loadMedia($media) { // Set up the basics $return_files = array('full' => '', 'chunks' => array()); $source_media_path = $media->media_path; // Extract relevant pieces of the specified media path $parsed_url = parse_url($source_media_path); $media_scheme = $parsed_url['scheme']; $media_host = $parsed_url['host']; $media_user = array_key_exists('user', $parsed_url) ? $parsed_url['user'] : ""; $media_path = $parsed_url['path']; $parsed_path = pathinfo($media_path); $file_type = array_key_exists('extension', $parsed_path) ? $parsed_path['extension'] : "mp3"; // Set up the pieces of the destination file names $destination_file_base = $this->getFileBase($media); $destination_directory = env('FPRINT_STORE') . 'media_cache/'; $temp_media_file = $destination_file_base . "." . $file_type; $temp_media_path = $destination_directory . $temp_media_file; // If the file doesn't exist, download it if (file_exists($temp_media_path)) { $return_files['full'] = $temp_media_file; } else { $temp_media_file = $this->loadFile($source_media_path, $destination_directory, $destination_file_base, $file_type); if ($temp_media_file == "") { throw new \Exception("Could not download the media: " . $source_media_path); } // Save the media path $return_files['full'] = $temp_media_file; // Set up PHPVideoToolkit (for use in the next steps) $config = new \PHPVideoToolkit\Config(array('temp_directory' => '/tmp', 'ffmpeg' => env('FFMPEG_BINARY_PATH'), 'ffprobe' => env('FFPROBE_BINARY_PATH'), 'yamdi' => '', 'qtfaststart' => ''), true); // Slice down the new media file if it has a listed start / duration if ($media->duration > 0) { // Extract the section we care about $start = new \PHPVideoToolkit\Timecode($media->start); $end = new \PHPVideoToolkit\Timecode($media->start + $media->duration); // Process differently based on the file type switch ($file_type) { case 'mp3': case 'wav': $audio = new \PHPVideoToolkit\Audio($temp_media_path, null, null, false); $command = $audio->extractSegment($start, $end); break; case 'mp4': $video = new \PHPVideoToolkit\Video($temp_media_path, null, null, false); $command = $video->extractSegment($start, $end); break; } // We need to save as a separate file then overwrite $trimmed_media_path = $temp_media_path . "trimmed." . $file_type; $process = $command->save($trimmed_media_path, null, true); rename($trimmed_media_path, $temp_media_path); } } // Check if the file parts already exist $chunk_glob_path = $destination_directory . $destination_file_base . "_*." . $file_type; $chunk_paths = glob($chunk_glob_path); // If the chunks already exist use them, otherwise make them. if (sizeof($chunk_paths) > 0) { foreach ($chunk_paths as $chunk_path) { $return_files['chunks'][] = basename($chunk_path); } } else { // Calculate the number of chunks needed $parser = new \PHPVideoToolkit\MediaParser(); $media_data = $parser->getFileInformation($temp_media_path); $slice_duration = env('FPRINT_CHUNK_LENGTH'); $duration = $media_data['duration']->total_seconds; // Perform the actual slicing // TODO: there is an issue where slices that are too small might cause errors. // We will need to add logic to detect those and merge them into the previous slice if ($duration > env('FPRINT_CHUNK_LENGTH') + 60) { switch ($file_type) { case 'mp3': case 'wav': $audio = new \PHPVideoToolkit\Audio($temp_media_path, null, null, false); $slices = $audio->split(env('FPRINT_CHUNK_LENGTH')); break; case 'mp4': $video = new \PHPVideoToolkit\Video($temp_media_path, null, null, false); $slices = $video->split(env('FPRINT_CHUNK_LENGTH')); break; } $process = $slices->save($destination_directory . $destination_file_base . "_%index." . $file_type); $output = $process->getOutput(); // Get the filenames foreach ($output as $chunk) { $return_files['chunks'][] = basename($chunk->getMediaPath()); } } else { $copy_path = str_replace("." . $file_type, "_0." . $file_type, $temp_media_path); copy($temp_media_path, $copy_path); $return_files['chunks'][] = basename($copy_path); } } return $return_files; }
<?php include_once './includes/bootstrap.php'; try { $video = new \PHPVideoToolkit\Video('media/BigBuckBunny_320x180.mp4', $config); $process = $video->getProcess(); // $process->setProcessTimelimit(1); $output = $video->extractSegment(new \PHPVideoToolkit\Timecode(10), new \PHPVideoToolkit\Timecode(20))->save('./output/big_buck_bunny.3gp'); echo '<h1>Executed Command</h1>'; \PHPVideoToolkit\Trace::vars($process->getExecutedCommand()); echo '<hr /><h1>FFmpeg Process Messages</h1>'; \PHPVideoToolkit\Trace::vars($process->getMessages()); echo '<hr /><h1>Buffer Output</h1>'; \PHPVideoToolkit\Trace::vars($process->getBuffer(true)); } catch (\PHPVideoToolkit\FfmpegProcessOutputException $e) { echo '<h1>Error</h1>'; \PHPVideoToolkit\Trace::vars($e); $process = $video->getProcess(); if ($process->isCompleted()) { echo '<hr /><h2>Executed Command</h2>'; \PHPVideoToolkit\Trace::vars($process->getExecutedCommand()); echo '<hr /><h2>FFmpeg Process Messages</h2>'; \PHPVideoToolkit\Trace::vars($process->getMessages()); echo '<hr /><h2>Buffer Output</h2>'; \PHPVideoToolkit\Trace::vars($process->getBuffer(true)); } } catch (\PHPVideoToolkit\Exception $e) { echo '<h1>Error</h1>'; \PHPVideoToolkit\Trace::vars($e); }
/** * Uploads a new image * @global type $CFG * @param type $recordID * @param type $userID * @param type $file * @param type $label * @param type $tags * @param type $db * @return type */ public function upload_media_video($ffmpeg, $recordID, $file, $label, $tags = '') { global $CFG; //$myFile = "logfile.txt"; $maxsize = 100000000; $filesize = 0; if (is_uploaded_file($file['tmp_name'])) { // check the file is less than the maximum file size if ($file['size'] < $maxsize) { // $filesize = $file['size']; $extArr = explode(".", strtolower($file['name'])); $filetype = end($extArr); // database connection try { $conn = new PDO("mysql:host={$CFG->db};dbname={$CFG->schema}", $CFG->dbuser, $CFG->dbuserpass); } catch (PDOException $e) { die('<data><error>failed connecting to database</error><detail>' . $e->getMessage() . '</detail></data>'); } // move the file to a new place, using a hash. Check that this file hasn't been already uploaded- if so, simply refer to that instead $contenthash = md5(file_get_contents($file['tmp_name'])); $raw_file = $CFG->site_root . "media/" . $contenthash; if (!file_exists($raw_file)) { if (!move_uploaded_file($file['tmp_name'], $raw_file)) { return "<data><error>problem moving file</error><detail/></data>"; } } // if the move is successful, make a screenshot $video = new PHPVideoToolkit\Video($raw_file); $process = $video->extractFrame(new \PHPVideoToolkit\Timecode(10))->save($CFG->site_root . "media/vidthumbs/" . $contenthash . ".jpg", null, \PHPVideoToolkit\Media::OVERWRITE_EXISTING); // make the screenshot smaller $img1 = imagecreatefromjpeg($CFG->site_root . "media/vidthumbs/" . $contenthash . ".jpg"); $width = imagesx($img1); $height = imagesy($img1); $new_height = 75; $new_width = floor($width * ($new_height / $height)); $thumb = imagecreatetruecolor($new_width, $new_height); imagecopyresized($thumb, $img1, 0, 0, 0, 0, $new_width, $new_height, $width, $height); // get an overlay $img2 = imagecreatefrompng($CFG->site_root . "icons/video.png"); // combine them imagecopyresampled($thumb, $img2, 0, 0, 0, 0, 48, 48, 48, 48); // write back to file imagejpeg($thumb, $CFG->site_root . "media/vidthumbs/" . $contenthash . ".jpg"); // our sql query $sql = "INSERT INTO `media` (`recordID`, `type`, `size`, `label`, `name`, `file_path`, `thumb_path`) VALUES (:recordID, :filetype, :filesize, :label, :filename, :raw_file, :thumb_path)"; $stmt = $conn->prepare($sql); $stmt->bindValue(':recordID', $recordID, PDO::PARAM_INT); $stmt->bindValue(':filetype', $filetype, PDO::PARAM_STR); $stmt->bindValue(':filesize', $file['size'], PDO::PARAM_STR); $stmt->bindValue(':label', $label, PDO::PARAM_STR); $stmt->bindValue(':filename', $file['name'], PDO::PARAM_STR); $stmt->bindValue(':raw_file', $raw_file, PDO::PARAM_STR); $stmt->bindValue(':thumb_path', $CFG->site_root . "media/vidthumbs/" . $contenthash . ".jpg", PDO::PARAM_STR); if (!$stmt->execute()) { return '<data><error>file entry into database failed</error><detail>' . var_dump($stmt->errorInfo()) . '</detail></data>'; } } else { return '<data><error>file too big</error><detail></detail></data>'; } } else { return '<data><error>moving file to temp failed</error><detail></detail></data>'; } return '<data><result>ok</result></data>'; }
<?php include_once './includes/bootstrap.php'; try { $video = new \PHPVideoToolkit\Video('media/BigBuckBunny_320x180.mp4', $config); $process = $video->getProcess(); // $process->setProcessTimelimit(1); $output = $video->extractSegment(new \PHPVideoToolkit\Timecode(10), new \PHPVideoToolkit\Timecode(20))->save('./output/big_buck_bunny.flv', null, \PHPVideoToolkit\Media::OVERWRITE_EXISTING); echo '<h1>Executed Command</h1>'; \PHPVideoToolkit\Trace::vars($process->getExecutedCommand()); echo '<hr /><h1>FFmpeg Process Messages</h1>'; \PHPVideoToolkit\Trace::vars($process->getMessages()); echo '<hr /><h1>Buffer Output</h1>'; \PHPVideoToolkit\Trace::vars($process->getBuffer(true)); } catch (\PHPVideoToolkit\FfmpegProcessOutputException $e) { echo '<h1>Error</h1>'; \PHPVideoToolkit\Trace::vars($e); $process = $video->getProcess(); if ($process->isCompleted()) { echo '<hr /><h2>Executed Command</h2>'; \PHPVideoToolkit\Trace::vars($process->getExecutedCommand()); echo '<hr /><h2>FFmpeg Process Messages</h2>'; \PHPVideoToolkit\Trace::vars($process->getMessages()); echo '<hr /><h2>Buffer Output</h2>'; \PHPVideoToolkit\Trace::vars($process->getBuffer(true)); } } catch (\PHPVideoToolkit\Exception $e) { echo '<h1>Error</h1>'; \PHPVideoToolkit\Trace::vars($e); }
/** * Converts source media to configured media formats and references them * * @param \WIRO\Html5mediaelements\Domain\Model\Media $media media record * @param array $config conversion configuration for media formats * @return void */ protected function convertMedia(Media $media, array $config) { // Create a local file for processing $originalFile = $media->getSourceFile()->getOriginalResource()->getOriginalFile(); $localFile = $originalFile->getForLocalProcessing(FALSE); // Prepare for conversion if ($media->isAudio()) { $source = new \PHPVideoToolkit\Audio($localFile); } else { $source = new \PHPVideoToolkit\Video($localFile); } $multiOutput = new \PHPVideoToolkit\MultiOutput(); $outputContext = array(); foreach ($config as $formatName => $formatConfig) { // Skip files without audio and video if ($media->isAudio() && !$formatConfig['audio']['enabled'] || $media->isVideo() && !$formatConfig['audio']['enabled'] && !$formatConfig['video']['enabled']) { continue; } // Generate video file name $fileName = $this->generateFilename($originalFile, $formatConfig['filename']); $filePath = $this->tempPathFiles . $fileName; // Store information about conversion input $outputContext[] = array('format' => $formatName, 'path' => $filePath, 'name' => $fileName); // Configure output format $fallbackFormat = $media->isAudio() ? 'AudioFormat' : 'VideoFormat'; $className = '\\PHPVideoToolkit\\' . $fallbackFormat . '_' . ucfirst($formatConfig['format']); if ($formatConfig['format'] && class_exists($className)) { $format = new $className(); } else { $format = \PHPVideoToolkit\Format::getFormatFor($filePath, null, $fallbackFormat); } // Set format options from configuration if ($formatConfig['audio']['enabled']) { if ($formatConfig['audio']['codec']) { $format->setAudioCodec($formatConfig['audio']['codec']); } if ($formatConfig['audio']['bitrate']) { $format->setAudioBitrate((double) $formatConfig['audio']['bitrate']); } if ($formatConfig['audio']['quality']) { $format->setAudioQuality((double) $formatConfig['audio']['quality']); } if ($formatConfig['audio']['sampleFrequency']) { $format->setAudioSampleFrequency((int) $formatConfig['audio']['sampleFrequency']); } if ($formatConfig['audio']['channels']) { $format->setAudioChannels((int) $formatConfig['audio']['channels']); } if ($formatConfig['audio']['volume']) { $format->setVolume((int) $formatConfig['audio']['volume']); } } else { $format->disableAudio(); } if ($media->isVideo()) { if ($formatConfig['video']['enabled']) { if ($formatConfig['video']['codec']) { $format->setVideoCodec($formatConfig['video']['codec']); } if ($formatConfig['video']['width'] && $formatConfig['video']['height']) { $format->setVideoDimensions($formatConfig['video']['width'], $formatConfig['video']['height'], true); } if ($formatConfig['video']['aspectRatio']) { $format->setVideoAspectRatio($formatConfig['video']['aspectRatio'], true); } if ($formatConfig['video']['frameRate']) { $format->setVideoFrameRate((double) $formatConfig['video']['frameRate']); } if ($formatConfig['video']['maxFrames']) { $format->setVideoMaxFrames($formatConfig['video']['maxFrames']); } if ($formatConfig['video']['bitrate']) { $format->setVideoBitrate($formatConfig['video']['bitrate']); } if ($formatConfig['video']['pixelFormat']) { $format->setVideoPixelFormat($formatConfig['video']['pixelFormat']); } if ($formatConfig['video']['quality']) { $format->setVideoQuality((double) $formatConfig['video']['quality']); } if ($formatConfig['video']['h264']['preset']) { $format->setH264Preset($formatConfig['video']['h264']['preset']); } if ($formatConfig['video']['h264']['tune']) { $format->setH264Tune($formatConfig['video']['h264']['tune']); } if ($formatConfig['video']['h264']['profile']) { $format->setH264Profile($formatConfig['video']['h264']['profile']); } } else { $format->disableVideo(); } } // Add to conversion command $multiOutput->addOutput($filePath, $format); } if (empty($outputContext)) { return; } // TODO make asynchronous $process = $source->save($multiOutput, null, \PHPVideoToolkit\Media::OVERWRITE_UNIQUE); /* // Start conversion $progressHandler = new \PHPVideoToolkit\ProgressHandlerNative(null); $process = $source->saveNonBlocking($multiOutput, null, \PHPVideoToolkit\Media::OVERWRITE_UNIQUE, $progressHandler); \TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($progressHandler, 'SP'); return; // Wait for files being converted $lastStatus = null; while ($progressHandler->completed !== true) { $probe = $progressHandler->probe(true); if ($probe['status'] !== $lastStatus) { //echo $probe['status'] . PHP_EOL; $lastStatus = $probe['status']; } sleep(0.5); } */ // Get converted files $outputFiles = $process->getAllOutput(); foreach ($outputContext as $i => $fileOptions) { // Add converted file to FAL $file = $originalFile->getParentFolder()->addFile($outputFiles[$i], $fileOptions['name'], 'changeName'); // TODO check for permission of user (_cli_scheduler) // Set dimension metadata of converted file $this->setFileMetadata($file); // Create new optimized media record $mediaOptimized = $this->objectManager->get('WIRO\\Html5mediaelements\\Domain\\Model\\MediaOptimized'); $mediaOptimized->setPid($media->getPid()); $mediaOptimized->setType($media->isAudio() ? MediaOptimized::TYPE_AUDIO : MediaOptimized::TYPE_VIDEO); $mediaOptimized->setFormat($fileOptions['format']); // Add reference to media record $media->addOptimizedMedium($mediaOptimized); $this->mediaRepository->update($media); $this->persistenceManager->persistAll(); // Add reference to converted file $this->addFileReference('tx_html5mediaelements_domain_model_mediaoptimized', 'optimized_file', $mediaOptimized, $file); } // Set converted flag in media record $media->setIsConverted(true); $this->mediaRepository->update($media); }
<?php include_once './includes/bootstrap.php'; try { $video = new \PHPVideoToolkit\Video($example_video_path, $config); $output = $video->extractFrames(new \PHPVideoToolkit\Timecode(40), new \PHPVideoToolkit\Timecode(50))->save('./output/big_buck_bunny_frame_%timecode.jpg'); // $output is an array of \PHPVideoToolkit\Image objects upon success. } catch (\PHPVideoToolkit\Exception $e) { if ($video->getProcess()->isCompleted()) { \PHPVideoToolkit\Trace::vars($video->getProcess()->getExecutedCommand()); \PHPVideoToolkit\Trace::vars($video->getProcess()->getBuffer()); } \PHPVideoToolkit\Trace::vars($e); }
$transcoders = array('php', 'convert', 'gifsicle-with-gd', 'gifsicle-with-convert'); foreach ($transcoders as $gif_transcoder) { $start = microtime_float(); $output_path = './output/big_buck_bunny.' . $gif_transcoder . '.gif'; if ($gif_transcoder === 'gifsicle-with-gd') { $config->convert = null; $config->gif_transcoder = 'gifsicle'; } else { if ($gif_transcoder === 'gifsicle-with-convert') { $config->convert = $convert; $config->gif_transcoder = 'gifsicle'; } } $output_format = \PHPVideoToolkit\Format::getFormatFor($output_path, $config, 'ImageFormat'); $output_format->setVideoFrameRate(12); $video = new \PHPVideoToolkit\Video('media/BigBuckBunny_320x180.mp4', $config); $output = $video->extractSegment(new \PHPVideoToolkit\Timecode(10), new \PHPVideoToolkit\Timecode(70))->save($output_path, $output_format); $length = microtime_float() - $start; echo '<h1>' . str_replace('-', ' ', $gif_transcoder) . '</h1>'; echo 'File = ' . $output_path . '<br />'; echo 'Time to encode = ' . $length . '<br />'; echo 'File size = ' . filesize($output_path) / 1024 / 1024 . ' MB<br />'; } } catch (\PHPVideoToolkit\FfmpegProcessOutputException $e) { echo '<h1>Error</h1>'; \PHPVideoToolkit\Trace::vars($e); $process = $video->getProcess(); if ($process->isCompleted()) { echo '<hr /><h2>Executed Command</h2>'; \PHPVideoToolkit\Trace::vars($process->getExecutedCommand()); echo '<hr /><h2>FFmpeg Process Messages</h2>';