コード例 #1
1
 public function register(Application $app)
 {
     $app['ffmpeg.configuration'] = array();
     $app['ffmpeg.default.configuration'] = array('ffmpeg.threads' => 4, 'ffmpeg.timeout' => 300, 'ffmpeg.binaries' => array('avconv', 'ffmpeg'), 'ffprobe.timeout' => 30, 'ffprobe.binaries' => array('avprobe', 'ffprobe'));
     $app['ffmpeg.logger'] = null;
     $app['ffmpeg.configuration.build'] = $app->share(function (Application $app) {
         return array_replace($app['ffmpeg.default.configuration'], $app['ffmpeg.configuration']);
     });
     $app['ffmpeg'] = $app['ffmpeg.ffmpeg'] = $app->share(function (Application $app) {
         $configuration = $app['ffmpeg.configuration.build'];
         if (isset($configuration['ffmpeg.timeout'])) {
             $configuration['timeout'] = $configuration['ffmpeg.timeout'];
         }
         return FFMpeg::create($configuration, $app['ffmpeg.logger'], $app['ffmpeg.ffprobe']);
     });
     $app['ffprobe.cache'] = $app->share(function () {
         return new ArrayCache();
     });
     $app['ffmpeg.ffprobe'] = $app->share(function (Application $app) {
         $configuration = $app['ffmpeg.configuration.build'];
         if (isset($configuration['ffmpeg.timeout'])) {
             $configuration['timeout'] = $configuration['ffprobe.timeout'];
         }
         return FFProbe::create($configuration, $app['ffmpeg.logger'], $app['ffprobe.cache']);
     });
 }
コード例 #2
1
 /**
  * The event handler function for callback function.
  * Convert audion file
  * @param AMQPMessage $msg
  */
 public function execute(AMQPMessage $msg)
 {
     $session = (int) unserialize($msg->body)['session'];
     $job = $this->container->getRepository('masterofcodeBundle:Job')->find($session);
     if (!$job) {
         throw new NotFoundHttpException("System error: cannot use given session id");
     }
     $this->setStatus($job, 1);
     try {
         $format = new Flac();
         $format->setAudioChannels(2)->setAudioKiloBitrate(128);
         $audio = FFMpeg::create()->open($job->getPath());
         $audio->save($format, $job->getDownloadPath());
     } catch (Exception $e) {
         $this->setStatus($job, 3);
         throw new NotFoundHttpException("System error: cannot convert file.");
     }
     $this->setStatus($job, 2);
     echo 'File ' . $job->getPath() . ' has been converted! Session #' . $job->getId() . "\n";
 }
コード例 #3
0
 public function __construct(VideoRepository $videos, Application $app, Adapter $adapter)
 {
     $this->videos = $videos;
     $this->app = $app;
     $this->adapter = $adapter;
     $this->ffmpeg = FFMpeg::create(['ffmpeg.binaries' => config('vidible.ffmpeg'), 'ffprobe.binaries' => config('vidible.ffprobe')]);
 }
コード例 #4
0
 public function __construct(EntityManager $em, $session, $mediaManager)
 {
     $this->em = $em;
     $this->session = $session;
     $this->mediaManager = $mediaManager;
     $this->ffmpeg = \FFMpeg\FFMpeg::create();
 }
コード例 #5
0
 /**
  * ConvertVideo run function.
  * This function is executed, when a worker is executing a task.
  * The return parameter will determine, if the task will be marked completed, or be requeued.
  *
  * @param array $data The array passed to QueuedTask->createJob()
  * @param int $id The id of the QueuedTask
  * @return bool Success
  */
 public function run($data, $id = null)
 {
     /**	@var \FFMpeg\FFMpeg $ffmpeg */
     $ffmpeg = \FFMpeg\FFMpeg::create(array('ffmpeg.binaries' => Configure::read('ffmpeg_path'), 'ffprobe.binaries' => Configure::read('ffprobe_path'), 'timeout' => 0, 'ffmpeg.threads' => 12));
     //For debug
     $ffmpeg->getFFMpegDriver()->listen(new \Alchemy\BinaryDriver\Listeners\DebugListener());
     $ffmpeg->getFFMpegDriver()->on('debug', function ($message) {
         echo $message . "\n";
     });
     $filepath = $data['filepath'];
     $filename = $data['filename'];
     $ext = $data['ext'];
     $width = $data['width'];
     $height = $data['height'];
     $video = $ffmpeg->open($filepath . $filename . $ext);
     $video->filters()->resize(new FFMpeg\Coordinate\Dimension($width, $height), \FFMpeg\Filters\Video\ResizeFilter::RESIZEMODE_INSET)->synchronize();
     $webm = new FFMpeg\Format\Video\WebM();
     $webm->setKiloBitrate(800);
     $video->save($webm, $filepath . $filename . '_360p.webm');
     $this->loadModel('Media');
     $file = $this->Media->findById($data['media_id']);
     $converted = $file['Media']['converted'] + 1;
     $this->Media->updateAll(array('converted' => $converted), array('id' => $file['Media']['id']));
     return true;
 }
コード例 #6
0
ファイル: Convert.php プロジェクト: arall/video-converter
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $origin = $input->getArgument('origin');
     $destination = $input->getArgument('destination');
     $videos = glob($origin . '/*.{MP4}', GLOB_BRACE);
     foreach ($videos as $video) {
         // Check if video is already converted
         $basename = basename($video);
         if (!file_exists($destination . $basename)) {
             $progress = $this->getHelper('progress');
             $progress->start($output, 100);
             $output->writeln('<info>Converting ' . $basename . '</info>');
             // Convert
             $ffmpeg = \FFMpeg\FFMpeg::create(['timeout' => 0]);
             $ffmpegvideo = $ffmpeg->open($video);
             // Codec
             $format = new \FFMpeg\Format\Video\X264();
             // Progress
             $format->on('progress', function ($ffmpegvideo, $format, $percentage) use($progress, $output) {
                 // Progress
                 $progress->setCurrent($percentage);
             });
             // Format
             $format->setKiloBitrate(1200)->setAudioChannels(2)->setAudioKiloBitrate(128)->setAudioCodec('libmp3lame');
             // Resize
             $ffmpegvideo->filters()->resize(new \FFMpeg\Coordinate\Dimension(1280, 720))->synchronize();
             // Convert
             $ffmpegvideo->save($format, $destination . $basename);
             $progress->finish();
         } else {
             $output->writeln('<comment>' . $basename . ' already exists</comment>');
         }
     }
 }
コード例 #7
0
ファイル: Core.php プロジェクト: aequasi/screenshotr
 public function __construct($file, $screenshotDirectory = '/tmp')
 {
     $this->file = $file;
     $this->screenshotDirectory = $screenshotDirectory;
     $this->ffmpeg = FFMpeg::create();
     $this->ffprobe = FFProbe::create();
     $this->movie = $this->ffmpeg->open($file);
     $this->info = $this->ffprobe->format($file);
 }
コード例 #8
0
ファイル: Video.php プロジェクト: spatie/laravel-medialibrary
 public function convert(string $file, Conversion $conversion = null) : string
 {
     $imageFile = pathinfo($file, PATHINFO_DIRNAME) . '/' . pathinfo($file, PATHINFO_FILENAME) . '.jpg';
     $ffmpeg = FFMpeg::create(['ffmpeg.binaries' => config('laravel-medialibrary.ffmpeg_binaries'), 'ffprobe.binaries' => config('laravel-medialibrary.ffprobe_binaries')]);
     $video = $ffmpeg->open($file);
     $seconds = $conversion ? $conversion->getExtractVideoFrameAtSecond() : 0;
     $frame = $video->frame(TimeCode::fromSeconds($seconds));
     $frame->save($imageFile);
     return $imageFile;
 }
コード例 #9
0
ファイル: FFMpegTest.php プロジェクト: php-ffmpeg/php-ffmpeg
 public function testCreateWithLoggerAndProbe()
 {
     $logger = $this->getLoggerMock();
     $ffprobe = $this->getFFProbeMock();
     $ffmpeg = FFMpeg::create(array('timeout' => 42), $logger, $ffprobe);
     $this->assertInstanceOf('FFMpeg\\FFMpeg', $ffmpeg);
     $this->assertSame($logger, $ffmpeg->getFFMpegDriver()->getProcessRunner()->getLogger());
     $this->assertSame($ffprobe, $ffmpeg->getFFProbe());
     $this->assertSame(42, $ffmpeg->getFFMpegDriver()->getProcessBuilderFactory()->getTimeout());
 }
 /**
  * @param string $videoPath FULL path to the video
  * @return \FFMpeg\FFmpeg
  */
 protected function openVideo()
 {
     $videoPath = $this->getFile()->getFullPath();
     // FFMpeg information shall be pushed to the PHP system error_log
     $logger = new Logger('FFMpegErrorLogger');
     $logger->pushHandler(new ErrorHandler());
     // Create the FFMpeg instance and open the file
     $ffmpeg = \FFMpeg\FFMpeg::create(array(), $logger);
     return $ffmpeg->open($videoPath);
 }
コード例 #11
0
ファイル: Flac.php プロジェクト: flatbits/youstraw
 /**
  * Takes the downloaded mp4 file, convert it to an mp3 and delete the video file.
  * @param string $filePath
  */
 public function postDownload($filePath)
 {
     $ffmpeg = FFMpeg::create();
     $video = $ffmpeg->open($filePath);
     // Generate the mp3 filepath from the mp4 one
     $mp3FilePath = substr($filePath, 0, -3) . 'flac';
     // Do the conversion
     $video->save(new \FFMpeg\Format\Audio\Flac(), $mp3FilePath);
     // Delete the video file
     unlink($filePath);
 }
コード例 #12
0
ファイル: VideoUploader.php プロジェクト: poci-hu/testtask
 /**
  * Create screenshot from uploaded video
  * @param  \App\Models\Video $video The object we created
  * @return boolean	Always true
  */
 private function capture(\App\Models\Video $video)
 {
     //that's easier
     $video_path = public_path('/videos/' . $video->video);
     //find duration
     $ffprobe = \FFMpeg\FFProbe::create();
     $duration = $ffprobe->format($video_path)->get('duration');
     //take the shot
     $ffmpeg = \FFMpeg\FFMpeg::create();
     $capture = $ffmpeg->open($video_path);
     $capture->frame(\FFMpeg\Coordinate\TimeCode::fromSeconds($duration > 5 ? 5 : (int) ($duration / 2)))->save(public_path('/previews/' . $video->getKey() . '.jpg'));
     return true;
 }
コード例 #13
0
 public function start($params)
 {
     exec("pgrep ffmpeg", $pids);
     if (empty($pids)) {
         $query = "SELECT video.guid FROM video LEFT JOIN file ON video.video_guid=file.guid WHERE (video.processed != 'true' && video.processed != 'processing' && video.video_type = 'upload');";
         $results = Dbase::getResultsArray($query);
         foreach ($results as $result) {
             $video_guid = $result['guid'];
             $video = getEntity($video_guid, true);
             if (is_a($video, "SocialApparatus\\Video")) {
                 $file_guid = $video->video_guid;
                 if (!file_exists(SITEDATAPATH . "videos/{$file_guid}/video.mp4")) {
                     $file = getEntity($file_guid, true);
                     FileSystem::makePath(SITEDATAPATH . "videos/" . $file_guid, 0777);
                     $file_location = $file->file_location;
                     exec("pgrep ffmpeg", $pids);
                     if (empty($pids)) {
                         if (file_exists($file_location)) {
                             $target_dir = SITEDATAPATH . "videos/" . $file->guid . "/";
                             ini_set('max_execution_time', 3000);
                             $ffmpeg = \FFMpeg\FFMpeg::create(array('ffmpeg.binaries' => Setting::get("ffmpeg_ffmprobe_executable_path") . "/ffmpeg", 'ffprobe.binaries' => Setting::get("ffmpeg_ffmprobe_executable_path") . "/ffprobe", 'timeout' => 7200, 'ffmpeg.threads' => 6));
                             $oldmask = umask(0);
                             $video->proccessed = "processing";
                             $video->save();
                             $video_file = $ffmpeg->open($file_location);
                             $video_file->frame(\FFMpeg\Coordinate\TimeCode::fromSeconds(10))->save($target_dir . 'frame.jpg');
                             $video_file->filters()->resize(new \FFMpeg\Coordinate\Dimension(320, 240))->synchronize();
                             $video_file->save(new \FFMpeg\Format\Video\X264('libfdk_aac', 'libx264'), $target_dir . 'video.mp4')->save(new \FFMpeg\Format\Video\WebM(), $target_dir . 'video.webm')->save(new \FFMpeg\Format\Video\Ogg(), $target_dir . 'video.ogv');
                             $video = getEntity($video_guid);
                             $video->processed = "true";
                             $video->save();
                             umask($oldmask);
                             $user_guid = $video->owner_guid;
                             $message = "Your video has been processed.";
                             $link = $video->getURL();
                             notifyUser("video_processed", $video->guid, NULL, $user_guid);
                             continue;
                         } else {
                             $video->processed = "true";
                             $video->save();
                         }
                     }
                 } else {
                     $video->processed = "true";
                     $video->save();
                 }
             }
         }
     }
 }
コード例 #14
0
ファイル: VideoGif.php プロジェクト: antalaron/video-gif
 /**
  * Create.
  *
  * This method creates the thumbnail from the video.
  *
  * @param string   $videoFile     Video file to process
  * @param string   $thumbnailFile Output gif
  * @param int|null $count         Number of frames to use
  * @param int|null $interval      The interval beetween the frames of the gif
  * @param int|null $width         Width of the gif
  * @param int|null $height        Height of the gif
  * @param int|null $start         The start of the video part
  * @param int|null $end           The end of the video part
  *
  * @throws VideoException If error during procession or writing.
  */
 public function create($videoFile, $thumbnailFile, $count = null, $interval = null, $width = null, $height = null, $start = null, $end = null)
 {
     $count = $count ?: $this->defaults['count'];
     $interval = $interval ?: $this->defaults['interval'];
     $width = $width ?: $this->defaults['width'];
     $height = $height ?: $this->defaults['height'];
     try {
         $ffmpeg = FFMpeg::create();
         $ffprobe = FFProbe::create();
     } catch (\Exception $e) {
         throw new VideoException('Cannot start FFMpeg or FFProbe', 0, $e);
     }
     try {
         // Determine the duration of the video
         $duration = $ffprobe->format($videoFile)->get('duration');
     } catch (\Exception $e) {
         throw new VideoException(sprintf('Cannot determine the duration of %s', $videoFile), 0, $e);
     }
     // If invalid start or end time, assume it is the start and the end
     // of the video.
     $start = max(0, $start ?: 0);
     $end = min($duration, $end ?: $duration);
     $delay = (double) ($end - $start) / ($count + 1);
     $video = $ffmpeg->open($videoFile);
     $hashDir = $this->tmpDir . '/video-gif/' . md5($videoFile . time());
     if (!file_exists($hashDir)) {
         mkdir($hashDir, 0777, true);
     }
     $pos = $start;
     $frames = array();
     $durations = array();
     // Grab frames
     for ($i = 0; $i < $count; ++$i) {
         $pos += $delay;
         $video->frame(TimeCode::fromSeconds($pos))->save(sprintf($hashDir . '/tmp-frame%03d.jpg', $i));
         Image::open(sprintf($hashDir . '/tmp-frame%03d.jpg', $i))->cropResize($width, $height)->save(sprintf($hashDir . '/frame%03d.jpg', $i));
         $frames[] = sprintf($hashDir . '/frame%03d.jpg', $i);
         $durations[] = $interval;
     }
     $gc = new GifCreator();
     $gc->create($frames, $durations, 0);
     $this->removeDirectory($hashDir);
     if (false === @file_put_contents($thumbnailFile, $gc->getGif())) {
         throw new VideoException(sprintf('Cannot write %s', $thumbnailFile));
     }
 }
コード例 #15
0
ファイル: FfmpegHelper.php プロジェクト: VeerUP/rest-service
 /**
  * Encode video to custom video format
  *
  * @param $filePath
  * @param $outputFilePath
  * @param $format
  * @param array|ConfigurationInterface $ffmpegConfig
  * @return bool
  * @throws UnsupportedMediaTypeHttpException
  * @throws ErrorException
  */
 public static function convert($filePath, $outputFilePath, $format, $ffmpegConfig = [])
 {
     if (is_file($filePath)) {
         // define format interface for encoding
         $formatInterface = self::getFormatInterface($format);
         // init ffmpeg
         $ffmpeg = FFMpeg::create($ffmpegConfig);
         $video = $ffmpeg->open($filePath);
         // file encode
         try {
             // @todo здесь метод save() выбрасыват исключение при неудачном конвертировании, разобраться мб как то все-таки можно получить ошибку без исключения
             $video->save($formatInterface, $outputFilePath);
             return true;
         } catch (\Exception $error) {
             Yii::error($error, __METHOD__);
             return false;
         }
     }
     throw new ErrorException('Not found file: ' . $filePath);
 }
コード例 #16
0
ファイル: Thumbnail.php プロジェクト: lakshmajim/thumbnail
 /**
  * Create Thumbnail Image
  *
  * Create a new image from video source based on the specified parameters. 
  * This method will allows video to convert to image.
  * This method will add watermark to image
  *
  *  
  * @access public
  * @since  Method available since Release 1.0.0
  * @param  video_path      Video resource source path 
  * @param  storage_path    Image resource destination path
  * @param  thumbnail_name  Image name for output
  * @param  height                                                  [optional]
  * @param  width                                                   [optional]
  * @param  tts             Time to take screenshot                 [optional]
  * @param  water_mark      Thmbnail paly button image              [optional]
  * @param  wm              if true the only it inserts play button [optional]
  * @author lakshmajim <*****@*****.**>
  * @return boolean 
  */
 public function getThumbnail($video_path, $storage_path, $thumnail_name, $height = 320, $width = 240, $tts = 50, $water_mark = '', $wm = false)
 {
     try {
         $ffmpeg = FFMpeg::create();
         $video = $ffmpeg->open($video_path);
         $result_image = $storage_path . '/' . $thumnail_name;
         $video->filters()->resize(new Coordinate\Dimension($height, $width))->synchronize();
         //320, 240
         $video->frame(Coordinate\TimeCode::fromSeconds($tts))->save($result_image);
         if ($video) {
             if ($wm) {
                 $src = imagecreatefrompng($water_mark);
                 $got_image = imagecreatefromjpeg($result_image);
                 // Get dimensions of image screen shot
                 $width = imagesx($got_image);
                 $height = imagesy($got_image);
                 // final output image dimensions
                 $newwidth = env('THUMBNAIL_IMAGE_WIDTH');
                 $newheight = env('THUMBNAIL_IMAGE_HEIGHT');
                 $tmp = imagecreatetruecolor($newwidth, $newheight);
                 imagecopyresampled($tmp, $got_image, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
                 // Set the brush
                 imagesetbrush($tmp, $src);
                 // Draw a couple of brushes, each overlaying each
                 imageline($tmp, imagesx($tmp) / 2, imagesy($tmp) / 2, imagesx($tmp) / 2, imagesy($tmp) / 2, IMG_COLOR_BRUSHED);
                 imagejpeg($tmp, $result_image, 100);
             }
             return true;
         } else {
             return false;
         }
     } catch (Exception $thumbnailException) {
         // error processing request
         echo "Got Bad Cookie";
     }
 }
コード例 #17
0
 public function scaleImage($asset, $width, $height = null)
 {
     list($type, $subtype) = explode('/', $asset->mimeType());
     switch ($type) {
         case "video":
             $workdir = '/tmp/repose/';
             $ffmpeg = FFMpeg::create(array('ffmpeg.binaries' => '/usr/bin/ffmpeg', 'ffprobe.binaries' => '/usr/bin/ffprobe', 'timeout' => 3600, 'ffmpeg.threads' => 12));
             $video = $ffmpeg->open($this->real_root());
             $video->frame(TimeCode::fromSeconds(5))->save($workdir . DS . $asset->uuid() . '.jpg');
             $data = file_get_contents($workdir . DS . $asset->uuid() . '.jpg');
             $img = imagecreatefromstring($data);
             if (FALSE !== $img) {
                 return self::scaleJpeg($img, $width, $height);
             }
             break;
         case "image":
             if ($subtype === 'png') {
                 $img = imagecreatefromstring($this->content);
                 if (FALSE !== $img) {
                     return self::scalePng($img, $width, $height);
                 }
             } elseif ($subtype === 'jpeg') {
                 $img = imagecreatefromstring($this->content);
                 if (FALSE !== $img) {
                     return self::scaleJpeg($img, $width, $height);
                 }
             } elseif ($subtype === 'gif') {
                 $img = imagecreatefromstring($this->content);
                 if (FALSE !== $img) {
                     return self::scaleGif($img, $width, $height);
                 }
             }
     }
     var_dump('Failed to load image data: ' . $asset->filename);
     return FALSE;
 }
コード例 #18
0
ファイル: VideoController.php プロジェクト: nandeeshmp/app
 /**
  * @param StoreVideoRequest $request
  * @param $file_hash
  */
 private function extractVideoFrame(StoreVideoRequest $request, $file_hash)
 {
     $ffmpeg = FFMpeg::create();
     $video = $ffmpeg->open(base_path() . '/files/video/' . $file_hash . '.' . $request->file('video')->getClientOriginalExtension());
     $frame = $video->frame(TimeCode::fromSeconds(5));
     $frame->save(base_path() . '/files/video/' . $file_hash . '.jpg');
 }
コード例 #19
0
 public function __construct($file)
 {
     parent::__construct($file);
     $this->ffprobe = FFProbe::create(['ffmpeg.binaries' => env('FFMPEG'), 'ffprobe.binaries' => env('FFPROBE')]);
     $this->ffmpeg = FFMpeg::create(['ffmpeg.binaries' => env('FFMPEG'), 'ffprobe.binaries' => env('FFPROBE')]);
 }
コード例 #20
0
ファイル: document.lib.php プロジェクト: daffef/chamilo-lms
 /**
  * Converts wav to mp3 file.
  * Requires the ffmpeg lib. In ubuntu: sudo apt-get install ffmpeg
  * @param string $wavFile
  * @param bool $removeWavFileIfSuccess
  * @return bool
  */
 public static function convertWavToMp3($wavFile, $removeWavFileIfSuccess = false)
 {
     if (file_exists($wavFile)) {
         try {
             $ffmpeg = \FFMpeg\FFMpeg::create();
             $video = $ffmpeg->open($wavFile);
             $mp3File = str_replace('wav', 'mp3', $wavFile);
             $result = $video->save(new FFMpeg\Format\Audio\Mp3(), $mp3File);
             if ($result && $removeWavFileIfSuccess) {
                 unlink($wavFile);
             }
             if (file_exists($mp3File)) {
                 return $mp3File;
             }
         } catch (Exception $e) {
             error_log($e->getMessage());
             error_log($e->getPrevious()->getMessage());
         }
     }
     return false;
 }
コード例 #21
0
 /**
  * Handle the event.
  *
  * @param  VideoWasUploaded  $event
  * @return void
  */
 public function handle(VideoWasUploaded $event)
 {
     Log::info('Calling video conversion handler', ['infiles' => $event->infiles, 'outfile' => $event->outfile]);
     if (empty($event->outfile) || empty($event->infiles)) {
         throw new InvalidArgumentException('No video files given');
     } else {
         // get ffmpeg configuration
         $ffmpegBinary = config('rap-battle.ffmpeg_binary');
         $ffprobeBinary = config('rap-battle.ffprobe_binary');
         $timeout = config('rap-battle.ffmpeg_timeout', 3600);
         $ffmpegThreads = config('rap-battle.ffmpeg_threads', 12);
         $conf = array();
         if (!empty($ffmpegBinary)) {
             $conf['ffmpeg.binaries'] = $ffmpegBinary;
         }
         if (!empty($ffprobeBinary)) {
             $conf['ffprobe.binaries'] = $ffprobeBinary;
         }
         if (!empty($timeout)) {
             $conf['timeout'] = $timeout;
         }
         if (!empty($ffmpegThreads)) {
             $conf['ffmpeg.threads'] = $ffmpegThreads;
         }
         $ffmpeg = FFMpeg\FFMpeg::create($conf);
         // create video objects
         foreach ($event->infiles as $file) {
             $videos[] = $ffmpeg->open($file);
         }
         $width = config('rap-battle.video_width', 1920);
         $height = config('rap-battle.video_height', 1080);
         /**
          * The concatenation filter needs all videos to be the same size
          * therefore the resize filter will be added if only a single video
          * will be converted, otherwise the concatenation filter will be used
          */
         if (count($videos) == 1) {
             // only one input file
             // add resize filter
             // $resizefilter = new ResizeFilter(new Dimension($width, $height), ResizeFilter::RESIZEMODE_INSET);
             $resizefilter = new ResizeFilter(new Dimension($width, $height), ResizeFilter::RESIZEMODE_FIT);
             $videos[0]->addFilter($resizefilter);
             // apply setsar filter to correct pixel aspect ratio
             $setdar = new SimpleFilter(array('-vf', 'setdar=' . $height . '/' . $width));
             $videos[0]->addFilter($setdar);
         } else {
             // multiple input files: create concatenation filter
             // create concat filter
             $concatfilter = new ConcatFilter();
             $videos[0]->addFilter($concatfilter);
             // add videos
             for ($i = 1; $i < count($videos); $i++) {
                 $concatfilter->addVideo($videos[$i]);
             }
         }
         // create simple filter to add '-movflags faststart' parameter (to enable streaming)
         $movflags = new SimpleFilter(array('-movflags', 'faststart'));
         $videos[0]->addFilter($movflags);
         // set video format
         $format = new FFMpeg\Format\Video\X264();
         $videobitrate = config('rap-battle.video_bitrate', $format->getKiloBitrate());
         $format->setKiloBitrate($videobitrate);
         $audiobitrate = config('rap-battle.audio_bitrate', $format->getAudioKiloBitrate());
         $format->setAudioKiloBitrate($audiobitrate);
         //$audiocodec = config('rap-battle.audio_codec', $format->getAudioCodec());
         //$format->setAudioCodec($audiocodec);
         $format->setAudioCodec(null);
         // convert / concatenate video
         try {
             Log::info('Starting video conversion', ['infiles' => $event->infiles, 'outfiles' => $event->outfile]);
             $videos[0]->save($format, $event->outfile);
             Log::info('Video conversion successful', ['infiles' => $event->infiles, 'outfiles' => $event->outfile]);
         } catch (Exception $e) {
             // TODO: handle exception: video could not be converted / concatenated
             Log::error('Video conversion failed', ['exception' => $e->getMessage(), 'infiles' => $event->infiles, 'outfile' => $event->outfile]);
             return true;
             //throw $e;
         }
         // delete original video file(s) after successful conversion
         if ($event->deleteOnSuccess) {
             foreach ($event->infiles as $file) {
                 unlink($file);
             }
         }
         // fire following event
         if ($event->followingEvent != null) {
             \Event::fire($event->followingEvent);
         }
     }
 }
 /**
  * Set up the test
  */
 public function setUp()
 {
     parent::setUp();
     $this->manager = new FFmpegVideoManager(FFMpeg::create());
 }
コード例 #23
0
 public function __construct()
 {
     $this['logger.name'] = 'Media-Alchemyst drivers logger';
     $this['logger.level'] = function (Pimple $container) {
         return Logger::DEBUG;
     };
     $this['logger.handler'] = $this->share(function (Pimple $container) {
         return new NullHandler($container['logger.level']);
     });
     $bridge = class_exists('Symfony\\Bridge\\Monolog\\Logger');
     $this['logger.class'] = $bridge ? 'Symfony\\Bridge\\Monolog\\Logger' : 'Monolog\\Logger';
     $this['logger'] = $this->share(function (Pimple $container) {
         $logger = new $container['logger.class']($container['logger.name']);
         $logger->pushHandler($container['logger.handler']);
         return $logger;
     });
     $this['default.configuration'] = array('ffmpeg.threads' => 4, 'ffmpeg.ffmpeg.timeout' => 3600, 'ffmpeg.ffprobe.timeout' => 60, 'ffmpeg.ffmpeg.binaries' => null, 'ffmpeg.ffprobe.binaries' => null, 'imagine.driver' => null, 'gs.timeout' => 60, 'gs.binaries' => null, 'mp4box.timeout' => 60, 'mp4box.binaries' => null, 'swftools.timeout' => 60, 'swftools.pdf2swf.binaries' => null, 'swftools.swfrender.binaries' => null, 'swftools.swfextract.binaries' => null, 'unoconv.binaries' => null, 'unoconv.timeout' => 60);
     $this['configuration'] = array();
     $this['configuration.merged'] = $this->share(function (Pimple $container) {
         return array_replace($container['default.configuration'], $container['configuration']);
     });
     $this['ffmpeg.ffmpeg'] = $this->share(function (Pimple $container) {
         try {
             return FFMpeg::create(array_filter(array('ffmpeg.threads' => $container['configuration.merged']['ffmpeg.threads'], 'timeout' => $container['configuration.merged']['ffmpeg.ffmpeg.timeout'], 'ffmpeg.binaries' => $container['configuration.merged']['ffmpeg.ffmpeg.binaries'])), $container['logger'], $container['ffmpeg.ffprobe']);
         } catch (FFMpegExecutableNotFound $e) {
             throw new RuntimeException('Unable to create FFMpeg driver', $e->getCode(), $e);
         }
     });
     $this['ffmpeg.ffprobe.cache'] = $this->share(function (Pimple $container) {
         return new ArrayCache();
     });
     $this['ffmpeg.ffprobe'] = $this->share(function (Pimple $container) {
         try {
             return FFProbe::create(array_filter(array('timeout' => $container['configuration.merged']['ffmpeg.ffprobe.timeout'], 'ffprobe.binaries' => $container['configuration.merged']['ffmpeg.ffprobe.binaries'])), $container['logger'], $container['ffmpeg.ffprobe.cache']);
         } catch (FFMpegExecutableNotFound $e) {
             throw new RuntimeException('Unable to create FFProbe driver', $e->getCode(), $e);
         }
     });
     $this['imagine'] = $this->share(function (Pimple $container) {
         $driver = $container['configuration.merged']['imagine.driver'];
         switch (true) {
             case 'imagick' === strtolower($driver):
             case null === $driver && class_exists('Imagick'):
                 $driver = 'Imagine\\Imagick\\Imagine';
                 break;
             case 'gmagick' === strtolower($driver):
             case null === $driver && class_exists('Gmagick'):
                 $driver = 'Imagine\\Gmagick\\Imagine';
                 break;
             case 'gd' === strtolower($driver):
             case null === $driver && extension_loaded('gd'):
                 $driver = 'Imagine\\Gd\\Imagine';
                 break;
         }
         if (false === class_exists($driver) || false === in_array('Imagine\\Image\\ImagineInterface', class_implements($driver))) {
             throw new InvalidArgumentException(sprintf('Invalid Imagine driver %s', $driver));
         }
         return new $driver();
     });
     $this['swftools.driver-container'] = $this->share(function (Pimple $container) {
         return DriverContainer::create(array_filter(array('pdf2swf.binaries' => $container['configuration.merged']['swftools.pdf2swf.binaries'], 'swfrender.binaries' => $container['configuration.merged']['swftools.swfrender.binaries'], 'swfextract.binaries' => $container['configuration.merged']['swftools.swfextract.binaries'], 'timeout' => $container['configuration.merged']['swftools.timeout'])), $container['logger']);
     });
     $this['swftools.flash-file'] = $this->share(function (Pimple $container) {
         return new FlashFile($container['swftools.driver-container']);
     });
     $this['swftools.pdf-file'] = $this->share(function (Pimple $container) {
         return new PDFFile($container['swftools.driver-container']);
     });
     $this['unoconv'] = $this->share(function (Pimple $container) {
         try {
             return Unoconv::create(array_filter(array('unoconv.binaries' => $container['configuration.merged']['unoconv.binaries'], 'timeout' => $container['configuration.merged']['unoconv.timeout'])), $container['logger']);
         } catch (ExecutableNotFoundException $e) {
             throw new RuntimeException('Unable to create Unoconv driver', $e->getCode(), $e);
         }
     });
     $this['exiftool.exiftool'] = $this->share(function (Pimple $container) {
         return new Exiftool($container['logger']);
     });
     $this['exiftool.rdf-parser'] = $this->share(function (Pimple $container) {
         return new RDFParser();
     });
     $this['exiftool.reader'] = $this->share(function (Pimple $container) {
         return new Reader($container['exiftool.exiftool'], $container['exiftool.rdf-parser']);
     });
     $this['exiftool.writer'] = $this->share(function (Pimple $container) {
         return new Writer($container['exiftool.exiftool']);
     });
     $this['exiftool.preview-extractor'] = $this->share(function (Pimple $container) {
         return new PreviewExtractor($container['exiftool.exiftool']);
     });
     $this['ghostscript.transcoder'] = $this->share(function (Pimple $container) {
         try {
             return Transcoder::create(array_filter(array('gs.binaries' => $container['configuration.merged']['gs.binaries'], 'timeout' => $container['configuration.merged']['gs.timeout'])), $container['logger']);
         } catch (ExecutableNotFoundException $e) {
             throw new RuntimeException('Unable to create Unoconv driver', $e->getCode(), $e);
         }
     });
     $this['mp4box'] = $this->share(function (Pimple $container) {
         try {
             return MP4Box::create(array_filter(array('mp4box.binaries' => $container['configuration.merged']['mp4box.binaries'], 'timeout' => $container['configuration.merged']['mp4box.timeout'])));
         } catch (ExecutableNotFoundException $e) {
             throw new RuntimeException('Unable to create Unoconv driver', $e->getCode(), $e);
         }
     });
     $this['mediavorus'] = $this->share(function (Pimple $container) {
         $ffprobe = null;
         try {
             $ffprobe = $container['ffmpeg.ffprobe'];
         } catch (RuntimeException $e) {
         }
         return new MediaVorus($container['exiftool.reader'], $container['exiftool.writer'], $ffprobe);
     });
 }
コード例 #24
0
ファイル: document.lib.php プロジェクト: ragebat/chamilo-lms
 /**
  * Converts wav to mp3 file.
  * Requires the ffmpeg lib. In ubuntu: sudo apt-get install ffmpeg
  * @param string $wavFile
  * @param bool $removeWavFileIfSuccess
  * @return bool
  */
 public static function convertWavToMp3($wavFile, $removeWavFileIfSuccess = false)
 {
     require_once '../../../../vendor/autoload.php';
     if (file_exists($wavFile)) {
         try {
             $ffmpeg = \FFMpeg\FFMpeg::create();
             $video = $ffmpeg->open($wavFile);
             $mp3File = str_replace('wav', 'mp3', $wavFile);
             $result = $video->save(new FFMpeg\Format\Audio\Mp3(), $mp3File);
             if ($result && $removeWavFileIfSuccess) {
                 unlink($wavFile);
             }
             if (file_exists($mp3File)) {
                 return $mp3File;
             }
         } catch (Exception $e) {
         }
     }
     return false;
 }
コード例 #25
0
 /**
  * @return FFMpeg
  */
 public function getFFMpeg()
 {
     return FFMpeg::create(array('timeout' => 300));
 }
コード例 #26
0
ファイル: MediaService.php プロジェクト: CarsonF/WhatsApi
 /**
  * @param  string      $file
  * @param  int         $size
  * @return null|string
  */
 public function createVideoIcon($file, $size = 100)
 {
     if (!class_exists('FFMpeg\\FFMpeg')) {
         return null;
     }
     try {
         $preview = tempnam(sys_get_temp_dir(), 'preview-');
         $ffmpeg = FFMpeg::create();
         $video = $ffmpeg->open($file);
         $frame = $video->frame(TimeCode::fromString('0:0:0:0.0'));
         $frame->save($preview);
         $content = $this->createImageIcon($preview, $size);
         @unlink($preview);
         return $content;
     } catch (\Exception $e) {
         return null;
     }
 }
コード例 #27
0
 public function createAvatar($entity = false, $filename = false, $copy = false)
 {
     $target_dir = getDataPath() . "videos" . "/" . $this->video_guid . "/";
     $file_entity = getEntity($this->video_guid);
     makePath($target_dir, 0777);
     $ffmpeg = \FFMpeg\FFMpeg::create(array('ffmpeg.binaries' => Setting::get("ffmpeg_ffmprobe_executable_path") . "/ffmpeg", 'ffprobe.binaries' => Setting::get("ffmpeg_ffmprobe_executable_path") . "/ffprobe", 'timeout' => 7200, 'ffmpeg.threads' => 6));
     $file_location = $file_entity->file_location;
     $video = $ffmpeg->open($file_location);
     $video->frame(\FFMpeg\Coordinate\TimeCode::fromSeconds(2))->save($target_dir . 'frame.jpg');
 }
コード例 #28
0
ファイル: php_ffmpeg.php プロジェクト: yfix/yf
#!/usr/bin/php
<?php 
$config = ['require_services' => ['binary_driver', 'doctrine_cache', 'evenement', 'temporary_fs'], 'git_urls' => ['https://github.com/yfix/PHP-FFMpeg' => 'php-ffmpeg/'], 'autoload_config' => ['php-ffmpeg/src/FFMpeg/' => 'FFMpeg'], 'example' => function () {
    $ffmpeg = \FFMpeg\FFMpeg::create();
    var_dump($ffmpeg);
}];
if ($return_config) {
    return $config;
}
require_once __DIR__ . '/_yf_autoloader.php';
new yf_autoloader($config);
コード例 #29
0
 /**
  *  Get FFMpeg
  */
 private function getFFMpeg()
 {
     return $ffmpeg = \FFMpeg\FFMpeg::create($this->getFFMpegConfig());
 }
コード例 #30
-1
ファイル: Mp3.php プロジェクト: flatbits/youstraw
 /**
  * Takes the downloaded mp4 file, convert it to an mp3 and delete the video file.
  * @param string $filePath
  */
 public function postDownload($filePath)
 {
     $ffmpeg = FFMpeg::create();
     $video = $ffmpeg->open($filePath);
     // Generate the mp3 filepath from the mp4 one
     $mp3FilePath = substr($filePath, 0, -1) . '3';
     // Configure the format
     $audioFormat = new \FFMpeg\Format\Audio\Mp3();
     if ($this->getQuality() == self::QUALITY_HIGH) {
         $bitrate = 320;
     } else {
         $bitrate = 192;
     }
     $audioFormat->setAudioKiloBitrate($bitrate);
     // Do the conversion
     $video->save($audioFormat, $mp3FilePath);
     // Delete the video file
     unlink($filePath);
 }