├── TODO.md ├── data ├── logs │ └── .gitkeep └── tmp │ └── .gitkeep ├── examples ├── data │ ├── logs │ │ └── .gitkeep │ └── tmp │ │ └── .gitkeep ├── source │ ├── arial.ttf │ ├── bg_red.jpg │ ├── static.gif │ ├── static.png │ ├── animated.gif │ ├── bg_black.jpg │ ├── bg_blue.png │ ├── bg_white.jpg │ ├── calibri.ttf │ ├── bg_green.jpeg │ ├── overlay_1.jpg │ ├── overlay_2.jpg │ ├── bg_forest_yellow.jpg │ ├── intro_720p_muted.mp4 │ ├── animated-spinner.apng │ ├── demo_video_720p_HD.mp4 │ ├── alpha-intro.mov │ └── spokesperson-alpha.mov ├── init.php ├── alphakey-strict-duration.php ├── concatenate.php ├── alphakey-spokesperson.php ├── draw-overlay-image.php ├── draw-animated-gif.php ├── alphakey-with-drawtext.php ├── draw-texts-and-boxes.php ├── draw-texts-and-boxes-ts.php └── audio.php ├── .github └── FUNDING.yml ├── .gitattributes ├── .gitignore ├── src └── php-ffmpeg-extensions │ ├── Media │ ├── CollectionInterface.php │ ├── MediaTypeTrait.php │ ├── VideoCollection.php │ ├── Audio.php │ └── Video.php │ ├── Filters │ ├── Audio │ │ ├── MergeFilterOptions │ │ │ ├── OptionInterface.php │ │ │ ├── OptionsCollection.php │ │ │ └── OptionAudioFile.php │ │ ├── AudioFilterInterface.php │ │ ├── AudioFilters.php │ │ └── MergeFilter.php │ ├── Video │ │ ├── FilterComplexOptions │ │ │ ├── OptionInterface.php │ │ │ ├── TimeLineTrait.php │ │ │ ├── OptionColorkey.php │ │ │ ├── ZindexTrait.php │ │ │ ├── CoordinatesTrait.php │ │ │ ├── OptionAlphakey.php │ │ │ ├── DimensionsTrait.php │ │ │ ├── FadeInOutTrait.php │ │ │ ├── OptionChromakey.php │ │ │ ├── OptionDrawBox.php │ │ │ ├── OptionsCollection.php │ │ │ ├── OptionOverlay.php │ │ │ └── OptionDrawText.php │ │ ├── VideoFilterInterface.php │ │ ├── VideoFilters.php │ │ └── ComplexFilter.php │ ├── ExtraInputStreamInterface.php │ └── ExtraInputStreamTrait.php │ ├── Input │ ├── FileInterface.php │ └── File.php │ ├── Format │ ├── VideoInterface.php │ └── Video │ │ └── X264.php │ ├── FFProbe │ └── DataMapping │ │ └── Stream.php │ ├── FFProbe.php │ ├── Coordinate │ ├── Duration.php │ ├── Point.php │ ├── Dimension.php │ └── TimeLine.php │ └── FFMpeg.php ├── composer.json ├── README.md └── LICENSE /TODO.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data/logs/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data/tmp/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/data/logs/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/data/tmp/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | custom: https://paypal.me/alexandersharapov 2 | -------------------------------------------------------------------------------- /examples/source/arial.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sharapov-outsource/php-ffmpeg-extensions/HEAD/examples/source/arial.ttf -------------------------------------------------------------------------------- /examples/source/bg_red.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sharapov-outsource/php-ffmpeg-extensions/HEAD/examples/source/bg_red.jpg -------------------------------------------------------------------------------- /examples/source/static.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sharapov-outsource/php-ffmpeg-extensions/HEAD/examples/source/static.gif -------------------------------------------------------------------------------- /examples/source/static.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sharapov-outsource/php-ffmpeg-extensions/HEAD/examples/source/static.png -------------------------------------------------------------------------------- /examples/source/animated.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sharapov-outsource/php-ffmpeg-extensions/HEAD/examples/source/animated.gif -------------------------------------------------------------------------------- /examples/source/bg_black.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sharapov-outsource/php-ffmpeg-extensions/HEAD/examples/source/bg_black.jpg -------------------------------------------------------------------------------- /examples/source/bg_blue.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sharapov-outsource/php-ffmpeg-extensions/HEAD/examples/source/bg_blue.png -------------------------------------------------------------------------------- /examples/source/bg_white.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sharapov-outsource/php-ffmpeg-extensions/HEAD/examples/source/bg_white.jpg -------------------------------------------------------------------------------- /examples/source/calibri.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sharapov-outsource/php-ffmpeg-extensions/HEAD/examples/source/calibri.ttf -------------------------------------------------------------------------------- /examples/source/bg_green.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sharapov-outsource/php-ffmpeg-extensions/HEAD/examples/source/bg_green.jpeg -------------------------------------------------------------------------------- /examples/source/overlay_1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sharapov-outsource/php-ffmpeg-extensions/HEAD/examples/source/overlay_1.jpg -------------------------------------------------------------------------------- /examples/source/overlay_2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sharapov-outsource/php-ffmpeg-extensions/HEAD/examples/source/overlay_2.jpg -------------------------------------------------------------------------------- /examples/source/bg_forest_yellow.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sharapov-outsource/php-ffmpeg-extensions/HEAD/examples/source/bg_forest_yellow.jpg -------------------------------------------------------------------------------- /examples/source/intro_720p_muted.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sharapov-outsource/php-ffmpeg-extensions/HEAD/examples/source/intro_720p_muted.mp4 -------------------------------------------------------------------------------- /examples/source/animated-spinner.apng: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sharapov-outsource/php-ffmpeg-extensions/HEAD/examples/source/animated-spinner.apng -------------------------------------------------------------------------------- /examples/source/demo_video_720p_HD.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sharapov-outsource/php-ffmpeg-extensions/HEAD/examples/source/demo_video_720p_HD.mp4 -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | examples/source/alpha-intro.mov filter=lfs diff=lfs merge=lfs -text 2 | examples/source/spokesperson-alpha.mov filter=lfs diff=lfs merge=lfs -text 3 | -------------------------------------------------------------------------------- /examples/source/alpha-intro.mov: -------------------------------------------------------------------------------- 1 | version https://git-lfs.github.com/spec/v1 2 | oid sha256:080419296d5c8a622a864612ee1a22d353924df2e1b925b6d6a3bbd46a0af6f7 3 | size 261758400 4 | -------------------------------------------------------------------------------- /examples/source/spokesperson-alpha.mov: -------------------------------------------------------------------------------- 1 | version https://git-lfs.github.com/spec/v1 2 | oid sha256:815d0fe7037b919fc7a6152394a1c88ef19e668cef416c12cc8047ea7a27cbd5 3 | size 64325806 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | vendor 3 | composer.lock 4 | data/tmp/* 5 | data/logs/* 6 | !data/logs/.gitkeep 7 | !data/tmp/.gitkeep 8 | examples/output 9 | examples/tests/* 10 | examples/data/logs/* 11 | examples/ffmpeg-20170915-6743351-win64-static 12 | !examples/data/logs/.gitkeep 13 | !examples/output/.gitkeep -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Media/CollectionInterface.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Media; 9 | 10 | interface CollectionInterface { 11 | public function all(); 12 | 13 | public function count(); 14 | } -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Filters/Audio/MergeFilterOptions/OptionInterface.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Filters\Audio\MergeFilterOptions; 9 | 10 | interface OptionInterface { 11 | public function getCommand(); 12 | 13 | public function __toString(); 14 | } 15 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Input/FileInterface.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Input; 9 | 10 | /** 11 | * Interface FileInterface 12 | * @package Sharapov\FFMpegExtensions\Stream 13 | */ 14 | interface FileInterface { 15 | public function setPath($file); 16 | 17 | public function getPath(); 18 | } 19 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Filters/Video/FilterComplexOptions/OptionInterface.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions; 9 | 10 | interface OptionInterface { 11 | public function getCommand(); 12 | 13 | public function getZIndex(); 14 | 15 | public function __toString(); 16 | } 17 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Format/VideoInterface.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Format; 9 | 10 | interface VideoInterface extends \FFMpeg\Format\VideoInterface 11 | { 12 | /** 13 | * Returns the Constant Rate Factor 14 | * 15 | * @return array 16 | */ 17 | public function getConstantRateFactor(); 18 | } 19 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Filters/ExtraInputStreamInterface.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Filters; 9 | 10 | use Sharapov\FFMpegExtensions\Input\FileInterface; 11 | 12 | interface ExtraInputStreamInterface { 13 | public function setExtraInputStream(FileInterface $file); 14 | 15 | public function getExtraInputStream(); 16 | } 17 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/FFProbe/DataMapping/Stream.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\FFProbe\DataMapping; 9 | 10 | use FFMpeg\Exception\LogicException; 11 | use FFMpeg\Exception\RuntimeException; 12 | use FFMpeg\Coordinate\Dimension; 13 | use FFMpeg\FFProbe\DataMapping\AbstractData; 14 | 15 | class Stream extends AbstractData { 16 | public function setMetadataTitle() { 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Filters/Video/VideoFilterInterface.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Filters\Video; 9 | 10 | use FFMpeg\Filters\FilterInterface; 11 | use FFMpeg\Format\VideoInterface; 12 | use Sharapov\FFMpegExtensions\Input\FileInterface; 13 | use Sharapov\FFMpegExtensions\Media\Video; 14 | 15 | interface VideoFilterInterface extends FilterInterface { 16 | public function getExtraInputs(); 17 | 18 | public function setExtraInput(FileInterface $input); 19 | 20 | public function apply(Video $video, VideoInterface $format); 21 | } 22 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/FFProbe.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions; 9 | 10 | use Doctrine\Common\Cache\Cache; 11 | use FFMpeg\Driver\FFProbeDriver; 12 | 13 | class FFProbe extends \FFMpeg\FFProbe { 14 | private static $_instance; 15 | 16 | public function __construct(FFProbeDriver $ffprobe, Cache $cache) { 17 | parent::__construct($ffprobe, $cache); 18 | self::$_instance = $this; 19 | } 20 | 21 | /** 22 | * @return \Sharapov\FFMpegExtensions\FFProbe 23 | */ 24 | public static function getInstance() { 25 | return self::$_instance; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Filters/Audio/AudioFilterInterface.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Filters\Audio; 9 | 10 | use FFMpeg\Filters\FilterInterface; 11 | use FFMpeg\Format\AudioInterface; 12 | use Sharapov\FFMpegExtensions\Media\Audio; 13 | 14 | interface AudioFilterInterface extends FilterInterface { 15 | /** 16 | * Applies the filter on the the Audio media given an format. 17 | * 18 | * @param Audio $audio 19 | * @param AudioInterface $format 20 | * 21 | * @return array An array of arguments 22 | */ 23 | public function apply(Audio $audio, AudioInterface $format); 24 | } 25 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Media/MediaTypeTrait.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Media; 9 | 10 | use FFMpeg\Driver\FFMpegDriver; 11 | use Sharapov\FFMpegExtensions\FFProbe; 12 | use Sharapov\FFMpegExtensions\Input\FileInterface; 13 | 14 | trait MediaTypeTrait { 15 | 16 | private $_file; 17 | 18 | public function __construct(FileInterface $file, FFMpegDriver $driver, FFProbe $ffprobe) { 19 | $this->_file = $file; 20 | parent::__construct($file->getPath(), $driver, $ffprobe); 21 | } 22 | 23 | public function getFile() { 24 | return $this->_file; 25 | } 26 | 27 | public function setFile(FileInterface $file) { 28 | $this->_file = $file; 29 | } 30 | } -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Filters/Video/FilterComplexOptions/TimeLineTrait.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions; 9 | 10 | use Sharapov\FFMpegExtensions\Coordinate\TimeLine; 11 | 12 | trait TimeLineTrait { 13 | 14 | protected $_timeLine; 15 | 16 | /** 17 | * Returns timeline object 18 | * @return null|TimeLine 19 | */ 20 | public function getTimeLine() { 21 | return $this->_timeLine; 22 | } 23 | 24 | /** 25 | * Set timeline object. 26 | * 27 | * @param TimeLine $timeLine 28 | * 29 | * @return $this 30 | */ 31 | public function setTimeLine(TimeLine $timeLine) { 32 | $this->_timeLine = $timeLine; 33 | 34 | return $this; 35 | } 36 | } -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Filters/Video/VideoFilters.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Filters\Video; 9 | 10 | use Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions\OptionsCollection; 11 | use Sharapov\FFMpegExtensions\Media\Video; 12 | 13 | class VideoFilters extends \FFMpeg\Filters\Video\VideoFilters { 14 | public function __construct(Video $media) { 15 | parent::__construct($media); 16 | } 17 | 18 | /** 19 | * Resizes a video to a given dimension. 20 | * 21 | * @param OptionsCollection $optionsCollection 22 | * 23 | * @return VideoFilters 24 | */ 25 | public function complex(OptionsCollection $optionsCollection) { 26 | $this->media->addFilter(new ComplexFilter($optionsCollection)); 27 | 28 | return $this; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Filters/Video/FilterComplexOptions/OptionColorkey.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions; 9 | 10 | use Sharapov\FFMpegExtensions\Filters\ExtraInputStreamInterface; 11 | 12 | /** 13 | * Colorkey filter option. Actually it's the same as OptionChromakey 14 | * @package Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions 15 | */ 16 | class OptionColorkey extends OptionChromakey 17 | implements 18 | OptionInterface, 19 | ExtraInputStreamInterface { 20 | /** 21 | * Returns command string. 22 | * @return string 23 | */ 24 | public function getCommand() { 25 | return sprintf("[%s]colorkey=%s[clrky];[%s]scale=%s[bg],[bg][clrky]overlay[%s]", ':s1', $this->getColor(), ':s2', (string)$this->getDimensions(), ':s3'); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Format/Video/X264.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Format\Video; 9 | 10 | use Sharapov\FFMpegExtensions\Format\VideoInterface; 11 | 12 | /** 13 | * The X264 video format 14 | * Uses aac audio codec by default. libfaac is is considered non-free 15 | * and most of unix systems doesn't provide ffmpeg with it. 16 | * Also that's a crappy encoder, there are better alternatives. 17 | */ 18 | class X264 extends \FFMpeg\Format\Video\X264 implements VideoInterface { 19 | 20 | /** @var int */ 21 | private $crf; 22 | 23 | public function __construct($audioCodec = 'aac', $videoCodec = 'libx264') { 24 | parent::__construct($audioCodec, $videoCodec); 25 | } 26 | 27 | /** 28 | * @param $cbr 29 | * 30 | * @return $this 31 | */ 32 | public function setConstantRateFactor($crf) { 33 | $this->crf = $crf; 34 | 35 | return $this; 36 | } 37 | 38 | /** 39 | * {@inheritDoc} 40 | */ 41 | public function getConstantRateFactor() 42 | { 43 | return $this->crf; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /examples/init.php: -------------------------------------------------------------------------------- 1 | 4 | * @link http://www.sharapov.biz/ 5 | * @license https://www.gnu.org/licenses/gpl-3.0.en.html GNU General Public License 6 | */ 7 | 8 | use \Monolog\Logger as MonologLogger; 9 | use \Monolog\Handler\StreamHandler; 10 | 11 | require_once dirname(__FILE__) . '/../vendor/autoload.php'; 12 | 13 | error_reporting(E_ALL); 14 | ini_set('display_errors', 1); 15 | date_default_timezone_set('UTC'); 16 | 17 | chdir(dirname(__FILE__)); 18 | 19 | try { 20 | $logger = new MonologLogger('debug'); 21 | $logger->pushHandler(new StreamHandler('../data/logs/render.log', MonologLogger::ERROR)); 22 | $logger->pushHandler(new StreamHandler('../data/logs/info.log', MonologLogger::INFO)); 23 | } catch (\Exception $e) { 24 | die($e->getMessage()); 25 | } 26 | 27 | $config = [ 28 | 'ffmpeg.binaries' => './ffmpeg33', 29 | 'ffprobe.binaries' => './ffprobe', 30 | 'timeout' => 3600, // The timeout for the underlying process 31 | 'ffmpeg.threads' => 12, // The number of threads that FFMpeg should use 32 | ]; 33 | 34 | // Init ffmpeg library 35 | $ffmpeg = \Sharapov\FFMpegExtensions\FFMpeg::create($config, $logger); 36 | 37 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Coordinate/Duration.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Coordinate; 9 | 10 | use FFMpeg\Exception\InvalidArgumentException; 11 | 12 | class Duration { 13 | protected $duration; 14 | 15 | /** 16 | * @param integer $duration 17 | * 18 | * @throws InvalidArgumentException when one of the parameters is invalid 19 | */ 20 | public function __construct($duration) { 21 | if(!is_numeric($duration) || $duration < 0) { 22 | throw new InvalidArgumentException('Duration time should be positive integer or float value. ' . $duration . ' given.'); 23 | } 24 | 25 | $this->duration = preg_replace('/,/', '.', $duration); 26 | } 27 | 28 | /** 29 | * @return string 30 | */ 31 | public function __toString() { 32 | return $this->getCommand(); 33 | } 34 | 35 | public function getCommand() { 36 | return implode(" ", ['-t', $this->getDuration()]); 37 | } 38 | 39 | /** 40 | * @return integer 41 | */ 42 | public function getDuration() { 43 | return $this->duration; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Filters/Video/FilterComplexOptions/ZindexTrait.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions; 9 | 10 | use FFMpeg\Exception\InvalidArgumentException; 11 | 12 | trait ZindexTrait { 13 | protected $_zIndex = null; 14 | 15 | /** 16 | * Returns Z-Index coordinate. 17 | * @return mixed 18 | */ 19 | public function getZIndex() { 20 | return $this->_zIndex; 21 | } 22 | 23 | /** 24 | * Set Z-Index coordinate. 25 | * The z-index property specifies the stack order of an element. 26 | * An element with greater stack order is always in front of an element with a lower stack order. 27 | * Should be positive integer more than 100. 28 | * 29 | * @param int $z 30 | * 31 | * @return $this 32 | */ 33 | public function setZIndex($z) { 34 | if(!is_int($z) or $z < 100) { 35 | throw new InvalidArgumentException('Z-Index should be positive integer more than or equal 100. ' . $z . ' given.'); 36 | } 37 | 38 | $this->_zIndex = $z; 39 | 40 | return $this; 41 | } 42 | } -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "sharapov/php-ffmpeg-extensions", 3 | "description": "An extensions library for the PHP FFMpeg (https://github.com/PHP-FFMpeg/PHP-FFMpeg)", 4 | "license": "GPL-3.0", 5 | "type": "library", 6 | "keywords": [ 7 | "ffmpeg", 8 | "php-ffmpeg", 9 | "ffmpeg overlay", 10 | "chromakey", 11 | "colorkey", 12 | "alpha layer", 13 | "mov", 14 | "video processing", 15 | "video", 16 | "audio processing", 17 | "audio", 18 | "avconv", 19 | "avprobe", 20 | "ffprobe" 21 | ], 22 | "homepage": "https://github.com/sharapovweb/php-ffmpeg-extensions", 23 | "authors": [ 24 | { 25 | "name": "Alexander Sharapov", 26 | "email": "alexander@sharapov.biz", 27 | "homepage": "http://sharapov.biz", 28 | "role": "Developer" 29 | } 30 | ], 31 | "require": { 32 | "php": ">=5.4 || ^7.0", 33 | "php-ffmpeg/php-ffmpeg": "^v0.18.0" 34 | }, 35 | "require-dev": { 36 | "monolog/monolog": "^2.0" 37 | }, 38 | "suggest": { 39 | "php-ffmpeg/extras": "A compilation of common audio & video drivers for PHP-FFMpeg" 40 | }, 41 | "autoload": { 42 | "psr-4": { 43 | "Sharapov\\FFMpegExtensions\\": "src/php-ffmpeg-extensions/" 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Filters/Video/FilterComplexOptions/CoordinatesTrait.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions; 9 | 10 | use Sharapov\FFMpegExtensions\Coordinate\Point; 11 | use FFMpeg\Exception\InvalidArgumentException; 12 | 13 | trait CoordinatesTrait { 14 | protected $_coordinates; 15 | 16 | /** 17 | * Returns coordinates object. 18 | * 19 | * @param bool $returnDefault 20 | * 21 | * @return \Sharapov\FFMpegExtensions\Coordinate\Point|string 22 | */ 23 | public function getCoordinates($returnDefault = false) { 24 | return ($this->_coordinates instanceof Point) ? $this->_coordinates : (($returnDefault) ? : $this->getDefaultCoordinates()); 25 | } 26 | 27 | /** 28 | * Set coordinates object. 29 | * 30 | * @param Point $point 31 | * 32 | * @return $this 33 | */ 34 | public function setCoordinates(Point $point) { 35 | $this->_coordinates = $point; 36 | 37 | return $this; 38 | } 39 | 40 | /** 41 | * Gets default coordinates 42 | * @return string 43 | */ 44 | public function getDefaultCoordinates() { 45 | return '0:0'; 46 | } 47 | } -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Coordinate/Point.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Coordinate; 9 | 10 | use FFMpeg\Exception\InvalidArgumentException; 11 | 12 | class Point { 13 | const AUTO_VERTICAL = '(h-th)/2'; 14 | const AUTO_HORIZONTAL = '(w-tw)/2'; 15 | 16 | protected $x; 17 | protected $y; 18 | 19 | /** 20 | * Point constructor. 21 | * 22 | * @param mixed $x 23 | * @param mixed $y 24 | */ 25 | public function __construct($x = self::AUTO_HORIZONTAL, $y = self::AUTO_VERTICAL) { 26 | if($x != self::AUTO_HORIZONTAL and !is_int($x)) { 27 | throw new InvalidArgumentException('X should be positive integer or "' . self::AUTO_HORIZONTAL . '". ' . $x . ' given.'); 28 | } 29 | if($y != self::AUTO_VERTICAL and !is_int($y)) { 30 | throw new InvalidArgumentException('Y should be positive integer or "' . self::AUTO_VERTICAL . '". ' . $y . ' given.'); 31 | } 32 | 33 | $this->x = $x; 34 | $this->y = $y; 35 | } 36 | 37 | /** 38 | * @return string 39 | */ 40 | public function __toString() { 41 | return sprintf("%s:%s", $this->getX(), $this->getY()); 42 | } 43 | 44 | /** 45 | * @return integer 46 | */ 47 | public function getX() { 48 | return $this->x; 49 | } 50 | 51 | /** 52 | * @return integer 53 | */ 54 | public function getY() { 55 | return $this->y; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Media/VideoCollection.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Media; 9 | 10 | /** 11 | * Video collection 12 | * @package Sharapov\FFMpegExtensions\Media 13 | */ 14 | class VideoCollection implements CollectionInterface, \Countable, \IteratorAggregate { 15 | private $_streams; 16 | 17 | public function __construct(array $options = []) { 18 | $this->_streams = array_values($options); 19 | } 20 | 21 | /** 22 | * Returns the first video stream of the collection, null if the collection is 23 | * empty. 24 | * @return null|Video 25 | */ 26 | public function first() { 27 | $option = reset($this->_streams); 28 | 29 | return $option ? : null; 30 | } 31 | 32 | /** 33 | * Adds a video stream to the collection. 34 | * 35 | * @param Video $stream 36 | * 37 | * @return VideoCollection 38 | */ 39 | public function add(Video $stream) { 40 | $this->_streams[] = $stream; 41 | 42 | return $this; 43 | } 44 | 45 | /** 46 | * {@inheritdoc} 47 | */ 48 | public function count() { 49 | return count($this->_streams); 50 | } 51 | 52 | /** 53 | * Returns the array of contained options. 54 | * @return array 55 | */ 56 | public function all() { 57 | return $this->_streams; 58 | } 59 | 60 | /** 61 | * {@inheritdoc} 62 | */ 63 | public function getIterator() { 64 | return new \ArrayIterator($this->_streams); 65 | } 66 | } -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Filters/ExtraInputStreamTrait.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Filters; 9 | 10 | use FFMpeg\Exception\InvalidArgumentException; 11 | use FFMpeg\FFProbe\DataMapping\StreamCollection; 12 | use Sharapov\FFMpegExtensions\Input\FileInterface; 13 | use Sharapov\FFMpegExtensions\FFProbe; 14 | 15 | trait ExtraInputStreamTrait { 16 | 17 | /** 18 | * @var FileInterface 19 | */ 20 | protected $_extraInputStream; 21 | 22 | /** 23 | * Get probe data of extra input stream. 24 | * @return StreamCollection 25 | */ 26 | public function getProbeData() { 27 | return $this->getProbe()->streams($this->getExtraInputStream()->getPath()); 28 | } 29 | 30 | /** 31 | * @return FFProbe 32 | */ 33 | public function getProbe() { 34 | return FFProbe::getInstance(); 35 | } 36 | 37 | /** 38 | * @return FileInterface 39 | * @throws InvalidArgumentException 40 | */ 41 | public function getExtraInputStream() { 42 | if(!$this->_extraInputStream instanceof FileInterface) { 43 | throw new InvalidArgumentException(sprintf('Extra input stream for %s is not defined.', __CLASS__)); 44 | } 45 | 46 | return $this->_extraInputStream; 47 | } 48 | 49 | /** 50 | * @param FileInterface $file 51 | * 52 | * @return $this 53 | */ 54 | public function setExtraInputStream(FileInterface $file) { 55 | $this->_extraInputStream = $file; 56 | 57 | return $this; 58 | } 59 | } -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Coordinate/Dimension.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Coordinate; 9 | 10 | use FFMpeg\Exception\InvalidArgumentException; 11 | 12 | /** 13 | * Dimension object, used for manipulating width and height couples 14 | */ 15 | class Dimension { 16 | const WIDTH_MAX = 'iw'; 17 | const HEIGHT_MAX = 'ih'; 18 | 19 | protected $width; 20 | protected $height; 21 | 22 | /** 23 | * @param integer $width 24 | * @param integer $height 25 | * 26 | * @throws InvalidArgumentException when one of the parameteres is invalid 27 | */ 28 | public function __construct($width, $height) { 29 | if((!is_int($width) and $width != self::WIDTH_MAX) || (!is_int($height) and $width != self::HEIGHT_MAX)) { 30 | throw new InvalidArgumentException('Width and height should be positive integer or "' . self::WIDTH_MAX . '", "' . self::HEIGHT_MAX . '". ' . $width . ', ' . $height . ' given.'); 31 | } 32 | 33 | $this->width = $width; 34 | $this->height = $height; 35 | } 36 | 37 | /** 38 | * @return string 39 | */ 40 | public function __toString() { 41 | return sprintf("%s:%s", $this->getWidth(), $this->getHeight()); 42 | } 43 | 44 | /** 45 | * Returns width. 46 | * @return integer 47 | */ 48 | public function getWidth() { 49 | return $this->width; 50 | } 51 | 52 | /** 53 | * Returns height. 54 | * @return integer 55 | */ 56 | public function getHeight() { 57 | return $this->height; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Input/File.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Input; 9 | 10 | use FFMpeg\Exception\InvalidArgumentException; 11 | use Sharapov\FFMpegExtensions\FFMpeg; 12 | 13 | /** 14 | * Class File 15 | * @package Sharapov\FFMpegExtensions\Stream 16 | */ 17 | class File implements FileInterface { 18 | protected $_filePath; 19 | protected $_mimes; 20 | 21 | /** 22 | * File constructor. 23 | * 24 | * @param null $file 25 | */ 26 | public function __construct($file = null) { 27 | $this->_mimes = FFMpeg::getSupportedMimes(); 28 | if(!is_null($file)) { 29 | $this->setPath($file); 30 | } 31 | } 32 | 33 | /** 34 | * Sets a file 35 | * 36 | * @param $file 37 | * 38 | * @return $this 39 | * @throws InvalidArgumentException 40 | */ 41 | public function setPath($file) { 42 | if(!file_exists($file) or !is_file($file)) { 43 | throw new InvalidArgumentException(sprintf('Incorrect file specified. %s given.', $file)); 44 | } 45 | 46 | if(!$mime = mime_content_type($file) or !in_array($mime, $this->_mimes)) { 47 | throw new InvalidArgumentException(sprintf('File type is not supported. %s given. Run FFMpeg::getSupportedMimes() to find the list of supported mimes.', $mime)); 48 | } 49 | 50 | $this->_filePath = $file; 51 | 52 | return $this; 53 | } 54 | 55 | /** 56 | * Gets a file path 57 | * @return mixed 58 | */ 59 | public function getPath() { 60 | return $this->_filePath; 61 | } 62 | } -------------------------------------------------------------------------------- /examples/alphakey-strict-duration.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | use \Sharapov\FFMpegExtensions\Input\File as InputFile; 9 | use \Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions; 10 | use \Sharapov\FFMpegExtensions\Coordinate; 11 | use \Alchemy\BinaryDriver\Exception\ExecutionFailureException; 12 | 13 | require_once 'init.php'; 14 | 15 | // Open source video 16 | $video = $ffmpeg->open(new InputFile('source/Todd-version1-no-text-centered-am2.mov')); 17 | 18 | // Initiate complex filter options collection 19 | $options = new FilterComplexOptions\OptionsCollection(); 20 | 21 | // Create alphakey option 22 | $alphaKey = new FilterComplexOptions\OptionAlphakey(); 23 | $alphaKey 24 | // Set input stream for alphakey 25 | ->setExtraInputStream(new InputFile('source/Coast - 1270.mp4')) 26 | ->setDimensions(new Coordinate\Dimension(1280, 720)) 27 | // Set video alphakey background duration to meet the main video duration 28 | ->setDuration(new Coordinate\Duration($video->getStreamDuration())); 29 | 30 | $options 31 | ->add($alphaKey); 32 | 33 | // Apply filter options to video 34 | $video 35 | ->filters() 36 | ->complex($options); 37 | 38 | // Run render 39 | $format = new Sharapov\FFMpegExtensions\Format\Video\X264('libmp3lame'); 40 | $format->on('progress', function($video, $format, $percentage) { 41 | echo "$percentage% transcoded\n"; 42 | }); 43 | 44 | try { 45 | $video 46 | ->save($format, 'output/output.mp4'); 47 | print 'Done!'; 48 | } catch (ExecutionFailureException $e) { 49 | print $e->getMessage(); 50 | } 51 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Filters/Video/FilterComplexOptions/OptionAlphakey.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions; 9 | 10 | use Sharapov\FFMpegExtensions\Coordinate\Duration; 11 | use Sharapov\FFMpegExtensions\Filters\ExtraInputStreamInterface; 12 | use Sharapov\FFMpegExtensions\Filters\ExtraInputStreamTrait; 13 | 14 | /** 15 | * Alpha layer filter option 16 | * @package Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions 17 | */ 18 | class OptionAlphakey 19 | implements 20 | OptionInterface, 21 | ExtraInputStreamInterface { 22 | use DimensionsTrait; 23 | use ExtraInputStreamTrait; 24 | use ZindexTrait; 25 | 26 | protected $_duration; 27 | 28 | /** 29 | * Returns duration object 30 | * @return mixed 31 | */ 32 | public function getDuration() { 33 | return $this->_duration; 34 | } 35 | 36 | /** 37 | * Set duration object. 38 | * 39 | * @param Duration $duration 40 | * 41 | * @return $this 42 | */ 43 | public function setDuration(Duration $duration) { 44 | $this->_duration = $duration; 45 | 46 | return $this; 47 | } 48 | 49 | /** 50 | * Returns a command string. 51 | * @return string 52 | */ 53 | public function __toString() { 54 | return $this->getCommand(); 55 | } 56 | 57 | /** 58 | * Returns command string. 59 | * @return string 60 | */ 61 | public function getCommand() { 62 | return sprintf("[%s]scale=%s[abg],[%s][abg]overlay[%s]", ':s1', (string)$this->getDimensions(), ':s2', ':s3'); 63 | } 64 | } -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Filters/Video/FilterComplexOptions/DimensionsTrait.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions; 9 | 10 | use Sharapov\FFMpegExtensions\Coordinate\Dimension; 11 | use FFMpeg\Exception\InvalidArgumentException; 12 | 13 | trait DimensionsTrait { 14 | 15 | protected $_dimensions; 16 | 17 | /** 18 | * Returns dimensions object. 19 | * 20 | * @param bool $returnDefault 21 | * 22 | * @return \Sharapov\FFMpegExtensions\Coordinate\Dimension|string 23 | */ 24 | public function getDimensions($returnDefault = false) { 25 | return ($this->_dimensions instanceof Dimension) ? $this->_dimensions : (($returnDefault) ? : $this->getDefaultDimensions()); 26 | } 27 | 28 | /** 29 | * Returns coordinates object. 30 | * 31 | * @param Dimension $dimension 32 | * 33 | * @return mixed 34 | */ 35 | public function setDimensions(Dimension $dimension) { 36 | $this->_dimensions = $dimension; 37 | 38 | return $this; 39 | } 40 | 41 | /** 42 | * Gets default dimensions 43 | * @return string 44 | */ 45 | public function getDefaultDimensions() { 46 | if($this->isImage()) { 47 | $dimensions = @getimagesize($this->getExtraInputStream()->getPath()); 48 | if($dimensions) { 49 | return sprintf('%s:%s', $dimensions[0], $dimensions[1]); 50 | } 51 | } else { 52 | throw new InvalidArgumentException('Due to performance issues we cannot automatically detect non-image overlay dimensions. Please set them before encoding.'); 53 | } 54 | 55 | return '0:0'; 56 | } 57 | } -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Filters/Video/FilterComplexOptions/FadeInOutTrait.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions; 9 | 10 | use FFMpeg\Exception\InvalidArgumentException; 11 | 12 | trait FadeInOutTrait { 13 | 14 | protected $_fadeInSeconds; 15 | 16 | protected $_fadeOutSeconds; 17 | 18 | /** 19 | * Returns fade-in time in seconds. 20 | * @return mixed 21 | */ 22 | public function getFadeIn() { 23 | return $this->_fadeInSeconds; 24 | } 25 | 26 | /** 27 | * Set fade-in time in seconds. 28 | * 29 | * @param mixed $seconds 30 | * 31 | * @return $this 32 | */ 33 | public function setFadeIn($seconds) { 34 | if(!is_numeric($seconds) || $seconds < 0) { 35 | throw new InvalidArgumentException('Fade-in time should be positive integer or float value. ' . $seconds . ' given.'); 36 | } 37 | 38 | $this->_fadeInSeconds = preg_replace('/,/', '.', $seconds); 39 | 40 | return $this; 41 | } 42 | 43 | /** 44 | * Returns fade-out time in seconds. 45 | * @return mixed 46 | */ 47 | public function getFadeOut() { 48 | return $this->_fadeOutSeconds; 49 | } 50 | 51 | /** 52 | * Set fade-out time in seconds. 53 | * 54 | * @param mixed $seconds 55 | * 56 | * @return $this 57 | * @throws InvalidArgumentException 58 | */ 59 | public function setFadeOut($seconds) { 60 | if(!is_numeric($seconds) || $seconds < 0) { 61 | throw new InvalidArgumentException('Fade-out time should be positive integer or float value. ' . $seconds . ' given.'); 62 | } 63 | 64 | $this->_fadeOutSeconds = preg_replace('/,/', '.', $seconds); 65 | 66 | return $this; 67 | } 68 | } -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Coordinate/TimeLine.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Coordinate; 9 | 10 | use FFMpeg\Exception\InvalidArgumentException; 11 | 12 | class TimeLine { 13 | protected $start; 14 | protected $end; 15 | 16 | /** 17 | * @param integer $start Starting timestamp in seconds 18 | * @param integer $end Ending timestamp in seconds 19 | * 20 | * @throws InvalidArgumentException when one of the parameters is invalid 21 | */ 22 | public function __construct($start, $end) { 23 | if(!is_numeric($start) || !is_numeric($end) || $start < 0 || $end < 0) { 24 | throw new InvalidArgumentException('Start and end time should be positive integer or float value. ' . $start . ', ' . $end . ' given.'); 25 | } 26 | 27 | if($end <= $start) { 28 | throw new InvalidArgumentException('End time should not be less or equal to start. ' . $start . ', ' . $end . ' given.'); 29 | } 30 | 31 | $this->start = preg_replace('/,/', '.', $start); 32 | $this->end = preg_replace('/,/', '.', $end); 33 | } 34 | 35 | /** 36 | * @return integer 37 | */ 38 | public function getDuration() { 39 | return $this->end - $this->start; 40 | } 41 | 42 | /** 43 | * @return string 44 | */ 45 | public function __toString() { 46 | return $this->getCommand(); 47 | } 48 | 49 | public function getCommand() { 50 | return sprintf("enable='between(%s)'", implode(",", ['t', $this->getStartTime(), $this->getEndTime()])); 51 | } 52 | 53 | /** 54 | * @return integer 55 | */ 56 | public function getStartTime() { 57 | return $this->start; 58 | } 59 | 60 | /** 61 | * @return integer 62 | */ 63 | public function getEndTime() { 64 | return $this->end; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Filters/Audio/AudioFilters.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Filters\Audio; 9 | 10 | use Sharapov\FFMpegExtensions\Filters\Audio\MergeFilterOptions\OptionAudioFile; 11 | use Sharapov\FFMpegExtensions\Filters\Audio\MergeFilterOptions\OptionsCollection; 12 | use Sharapov\FFMpegExtensions\Input\FileInterface; 13 | use Sharapov\FFMpegExtensions\Media\Audio; 14 | 15 | class AudioFilters extends \FFMpeg\Filters\Audio\AudioFilters { 16 | public function __construct(Audio $media) { 17 | parent::__construct($media); 18 | } 19 | 20 | /** 21 | * Converts stereo to mono. 22 | * @return $this 23 | */ 24 | public function stereo2mono() { 25 | $this->media->addFilter(new MergeFilter(null, MergeFilter::STEREO_2_MONO)); 26 | 27 | return $this; 28 | } 29 | 30 | /** 31 | * Converts mono audio to stereo. The audio file will be mixed as the right channel. 32 | * 33 | * @param \Sharapov\FFMpegExtensions\Input\FileInterface $file 34 | * 35 | * @return $this 36 | */ 37 | public function mono2stereo(FileInterface $file) { 38 | $this->media->addFilter(new MergeFilter(new OptionsCollection([new OptionAudioFile($file)]), MergeFilter::MONO_2_STEREO)); 39 | 40 | return $this; 41 | } 42 | 43 | /** 44 | * Converts multiple streams to stereo. 45 | * @return $this 46 | */ 47 | public function all2stereo() { 48 | $this->media->addFilter(new MergeFilter(null, MergeFilter::ALL_2_STEREO)); 49 | 50 | return $this; 51 | } 52 | 53 | /** 54 | * Combine two or more stereo inputs into one stereo output. 55 | * 56 | * @param \Sharapov\FFMpegExtensions\Filters\Audio\MergeFilterOptions\OptionsCollection $optionsCollection 57 | * 58 | * @return $this 59 | */ 60 | public function combineStereos(OptionsCollection $optionsCollection) { 61 | $this->media->addFilter(new MergeFilter($optionsCollection, MergeFilter::MUX_STEREO)); 62 | 63 | return $this; 64 | } 65 | 66 | public function replace() { 67 | return $this; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /examples/concatenate.php: -------------------------------------------------------------------------------- 1 | 6 | * http://sharapov.biz/ 7 | * 8 | */ 9 | 10 | use \Sharapov\FFMpegExtensions\Input\File as InputFile; 11 | use \Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions; 12 | use \Sharapov\FFMpegExtensions\Coordinate; 13 | use \Alchemy\BinaryDriver\Exception\ExecutionFailureException; 14 | 15 | require_once 'init.php'; 16 | 17 | $collection = new \Sharapov\FFMpegExtensions\Media\VideoCollection(); 18 | // Open source video 19 | $video = $ffmpeg->open( new InputFile( 'source/demo_video_720p_HD.mp4' ) ); 20 | 21 | // Initiate complex filter options collection 22 | $options = new FilterComplexOptions\OptionsCollection(); 23 | 24 | // Pass option to the options collection 25 | $options 26 | ->add( ( ( new FilterComplexOptions\OptionDrawText() ) 27 | // Set z-index property. Greater value is always in front 28 | ->setZIndex( 160 ) 29 | // You can use fade-in and fade-out effects. Set time in seconds 30 | ->setFadeIn( 2 ) 31 | ->setFadeOut( 2 ) 32 | // Set font path 33 | ->setFontFile( new InputFile( 'source/arial.ttf' ) ) 34 | // Set font color. Accepts transparency value as the second argument. Float value between 0 and 1. 35 | ->setFontColor( 'ffffff' ) 36 | // Set font size in pixels 37 | ->setFontSize( 33 ) 38 | // Set text string 39 | ->setText( 'Concatenation videos' ) 40 | // Coordinates where the text should be rendered. Accepts positive integer or 41 | // constants "(w-tw)/2", "(h-th)/2" to handle auto-horizontal, auto-vertical values 42 | ->setCoordinates( new Coordinate\Point( Coordinate\Point::AUTO_HORIZONTAL, 50 ) ) 43 | // Set timings (start, stop) in seconds. Accepts float values as well 44 | ->setTimeLine( new Coordinate\TimeLine( 2, 8 ) ) ) ); 45 | 46 | // Apply filter options to video 47 | $video 48 | ->filters() 49 | ->complex( $options ); 50 | 51 | 52 | // Adding clips to the collection 53 | $collection 54 | ->add( $video ) 55 | ->add( $ffmpeg->open( new InputFile( 'source/Coast - 1270.mp4' ) ) ); 56 | 57 | // And do concatenation 58 | $format = new \Sharapov\FFMpegExtensions\Format\Video\X264(); 59 | $format->on( 'progress', function ( $video, $format, $percentage ) { 60 | echo "$percentage% transcoded\n"; 61 | } ); 62 | 63 | try { 64 | $ffmpeg->concatenate( $format, $collection, 'output/merged.mp4' ); 65 | print 'Done!'; 66 | } catch ( ExecutionFailureException $e ) { 67 | print $e->getMessage(); 68 | } -------------------------------------------------------------------------------- /examples/alphakey-spokesperson.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | use \Sharapov\FFMpegExtensions\Input\File as InputFile; 9 | use \Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions; 10 | use \Sharapov\FFMpegExtensions\Coordinate; 11 | use \Alchemy\BinaryDriver\Exception\ExecutionFailureException; 12 | 13 | require_once 'init.php'; 14 | 15 | // Open source video 16 | $video = $ffmpeg->open(new InputFile('source/spokesperson-alpha.mov')); 17 | 18 | // Initiate complex filter options collection 19 | $options = new FilterComplexOptions\OptionsCollection(); 20 | 21 | // Create alphakey option 22 | $alphaKey = new FilterComplexOptions\OptionAlphakey(); 23 | $alphaKey 24 | // Set input stream for alphakey 25 | ->setExtraInputStream(new InputFile('source/demo_video_720p_HD.mp4')) 26 | ->setDimensions(new Coordinate\Dimension(1280, 720)) 27 | // Set video alphakey background duration to meet the main video duration 28 | ->setDuration(new Coordinate\Duration($video->getStreamDuration())); 29 | 30 | $options 31 | ->add($alphaKey); 32 | 33 | // Pass option to the options collection 34 | $options 35 | ->add(((new FilterComplexOptions\OptionDrawText()) 36 | // Set z-index property. Greater value is always in front 37 | ->setZIndex(160) 38 | // You can use fade-in and fade-out effects. Set time in seconds 39 | ->setFadeIn(1) 40 | ->setFadeOut(1) 41 | // Set font path 42 | ->setFontFile(new InputFile('source/arial.ttf')) 43 | // Set font color. Accepts transparency value as the second argument. Float value between 0 and 1. 44 | ->setFontColor('ffffff') 45 | // Set font size in pixels 46 | ->setFontSize(33) 47 | // Set text string 48 | ->setText('Spokesperson chromakey demonstration') 49 | // Coordinates where the text should be rendered. Accepts positive integer or 50 | // constants "(w-tw)/2", "(h-th)/2" to handle auto-horizontal, auto-vertical values 51 | ->setCoordinates(new Coordinate\Point(Coordinate\Point::AUTO_HORIZONTAL, 50)) 52 | // Set timings (start, stop) in seconds. Accepts float values as well 53 | ->setTimeLine(new Coordinate\TimeLine(1, 6)) 54 | // Set bounding box 55 | ->setBoundingBox('000000', 10, 0.5))); 56 | 57 | // Apply filter options to video 58 | $video 59 | ->filters() 60 | ->complex($options); 61 | 62 | // Run render 63 | $format = new Sharapov\FFMpegExtensions\Format\Video\X264('libmp3lame'); 64 | $format->on('progress', function($video, $format, $percentage) { 65 | echo "$percentage% transcoded\n"; 66 | }); 67 | 68 | try { 69 | $video 70 | ->save($format, 'output/output.mp4'); 71 | print 'Done!'; 72 | } catch (ExecutionFailureException $e) { 73 | print $e->getMessage(); 74 | } 75 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Filters/Audio/MergeFilterOptions/OptionsCollection.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Filters\Audio\MergeFilterOptions; 9 | 10 | use FFMpeg\Exception\InvalidArgumentException; 11 | use Sharapov\FFMpegExtensions\Filters\ExtraInputStreamInterface; 12 | 13 | class OptionsCollection implements \Countable, \IteratorAggregate { 14 | const TYPE_AUDIOFILE = 'AudioFile'; 15 | 16 | private $_options; 17 | 18 | public function __construct(array $options = []) { 19 | $this->_options = array_values($options); 20 | } 21 | 22 | /** 23 | * Returns the first stream of the collection, null if the collection is 24 | * empty. 25 | * @return null|OptionInterface 26 | */ 27 | public function first() { 28 | $option = reset($this->_options); 29 | 30 | return $option ? : null; 31 | } 32 | 33 | /** 34 | * Adds an option to the collection. 35 | * 36 | * @param OptionInterface $option 37 | * 38 | * @return OptionsCollection 39 | */ 40 | public function add(OptionInterface $option) { 41 | $this->_options[] = $option; 42 | 43 | return $this; 44 | } 45 | 46 | /** 47 | * {@inheritdoc} 48 | */ 49 | public function count() { 50 | return count($this->_options); 51 | } 52 | 53 | /** 54 | * Returns the array of contained options. 55 | * @return array 56 | */ 57 | public function all() { 58 | return $this->_options; 59 | } 60 | 61 | /** 62 | * Returns options that has an extra input streams. 63 | * @return \ArrayIterator|\Traversable 64 | */ 65 | public function filterHasExtraInputs() { 66 | return new OptionsCollection(array_filter((array)$this->getIterator(), function(OptionInterface $option) { 67 | if($option instanceof ExtraInputStreamInterface) { 68 | return true; 69 | } 70 | })); 71 | } 72 | 73 | /** 74 | * {@inheritdoc} 75 | */ 76 | public function getIterator() { 77 | return new \ArrayIterator($this->_options); 78 | } 79 | 80 | /** 81 | * Returns options filtered by type. 82 | * 83 | * @param string $typeName 84 | * 85 | * @return \ArrayIterator|\Traversable 86 | */ 87 | public function filter($typeName) { 88 | switch($typeName) { 89 | case self::TYPE_AUDIOFILE: 90 | return new OptionsCollection(array_filter((array)$this->getIterator(), [$this, '_filter' . ucfirst($typeName)])); 91 | default : 92 | throw new InvalidArgumentException('Invalid option type requested.'); 93 | } 94 | } 95 | 96 | /** 97 | * {@inheritdoc} 98 | */ 99 | private function _filterAudioFile(OptionInterface $option) { 100 | return (bool)$option instanceof OptionAudioFile; 101 | } 102 | } -------------------------------------------------------------------------------- /examples/draw-overlay-image.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | use \Sharapov\FFMpegExtensions\Input\File as InputFile; 9 | use \Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions; 10 | use \Sharapov\FFMpegExtensions\Coordinate; 11 | use \Alchemy\BinaryDriver\Exception\ExecutionFailureException; 12 | 13 | require_once 'init.php'; 14 | 15 | // Open source video 16 | $video = $ffmpeg->open(new InputFile('source/demo_video_720p_HD.mp4')); 17 | 18 | // Create complex filter collection 19 | $options = new FilterComplexOptions\OptionsCollection(); 20 | 21 | // Create overlay option 1 22 | $overlay1 = new FilterComplexOptions\OptionOverlay(); 23 | $overlay1 24 | // Set z-index property. Greater value is always in front 25 | ->setZIndex(160) 26 | // You can use fade-in and fade-out effects. Set time in seconds 27 | ->setFadeIn(2) 28 | ->setFadeOut(2) 29 | // Set image path 30 | ->setExtraInputStream(new InputFile('source/demo_video_720p_HD.mp4')) 31 | // Coordinates where the text should be rendered. Accepts positive integer or 32 | // constants "(w-tw)/2", "(h-th)/2" to handle auto-horizontal, auto-vertical values 33 | ->setCoordinates(new Coordinate\Point(23, 50)) 34 | // Set image dimensions 35 | ->setDimensions(new Coordinate\Dimension(450, 200)) 36 | // Set timings (start, stop) in seconds. Accepts float values as well 37 | ->setTimeLine(new Coordinate\TimeLine(1, 10)); 38 | 39 | // Pass option to the options collection 40 | $options 41 | ->add($overlay1); 42 | 43 | // Create overlay option 1 44 | $overlay2 = new FilterComplexOptions\OptionOverlay(); 45 | $overlay2 46 | // Set z-index property. Greater value is always in front 47 | ->setZIndex(260) 48 | // You can use fade-in and fade-out effects. Set time in seconds 49 | ->setFadeIn(4) 50 | ->setFadeOut(4) 51 | // Set image path 52 | ->setExtraInputStream(new InputFile('source/bg_red.jpg')) 53 | // Coordinates where the text should be rendered. Accepts positive integer or 54 | // constants "(w-tw)/2", "(h-th)/2" to handle auto-horizontal, auto-vertical values 55 | ->setCoordinates(new Coordinate\Point(430, 400)) 56 | // Set image dimensions 57 | ->setDimensions(new Coordinate\Dimension(450, 200)) 58 | // Set timings (start, stop) in seconds. Accepts float values as well 59 | ->setTimeLine(new Coordinate\TimeLine(3, 13)); 60 | 61 | // Pass option to the options collection 62 | $options 63 | ->add($overlay2); 64 | 65 | // Apply filter options to video 66 | $video 67 | ->filters() 68 | ->complex($options); 69 | 70 | // Run render 71 | $format = new Sharapov\FFMpegExtensions\Format\Video\X264('libmp3lame'); 72 | $format->on('progress', function($video, $format, $percentage) { 73 | echo "$percentage% transcoded\n"; 74 | }); 75 | 76 | try { 77 | $video 78 | ->save($format, 'output/output.mp4'); 79 | print 'Done!'; 80 | } catch (ExecutionFailureException $e) { 81 | print $e->getMessage(); 82 | } 83 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Filters/Video/FilterComplexOptions/OptionChromakey.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions; 9 | 10 | use Sharapov\FFMpegExtensions\Filters\ExtraInputStreamInterface; 11 | use Sharapov\FFMpegExtensions\Filters\ExtraInputStreamTrait; 12 | use FFMpeg\Exception\InvalidArgumentException; 13 | 14 | /** 15 | * Chromakey filter option 16 | * @package Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions 17 | */ 18 | class OptionChromakey 19 | implements 20 | OptionInterface, 21 | ExtraInputStreamInterface { 22 | use TimeLineTrait; 23 | use DimensionsTrait; 24 | use ExtraInputStreamTrait; 25 | 26 | protected $_color = '0x3BBD1E:0.6:0.3'; 27 | 28 | /** 29 | * Returns a command string. 30 | * @return string 31 | */ 32 | public function __toString() { 33 | return $this->getCommand(); 34 | } 35 | 36 | /** 37 | * Returns command string. 38 | * @return string 39 | */ 40 | public function getCommand() { 41 | return sprintf("[%s]chromakey=%s[chromky];[%s]scale=%s[bg],[bg][chromky]overlay[%s]", ':s1', $this->getColor(), ':s2', (string)$this->getDimensions(), ':s3'); 42 | } 43 | 44 | /** 45 | * Get RGB colorspace. 46 | * @return string 47 | */ 48 | public function getColor() { 49 | return $this->_color; 50 | } 51 | 52 | /** 53 | * RGB colorspace color keying. 54 | * Accepts the following options: 55 | * $color - The color which will be replaced with transparency. 56 | * $similarity - Similarity percentage with the key color. 57 | * 0.01 matches only the exact key color, while 1.0 matches everything. 58 | * $blend - Blend percentage. 59 | * 0.0 makes pixels either fully transparent, or not transparent at all. 60 | * Higher values result in semi-transparent pixels, with a higher transparency the more similar 61 | * the pixels color is to the key color. 62 | * 63 | * @param $color 64 | * @param float $similarity 65 | * @param float $blend 66 | * 67 | * @return $this 68 | */ 69 | public function setColor($color, $similarity = 0.6, $blend = 0.3) { 70 | if(!is_numeric($similarity) || $similarity < 0 || $similarity > 1) { 71 | throw new InvalidArgumentException('Similarity should be integer or float value from 0 to 1. ' . $similarity . ' given.'); 72 | } 73 | 74 | if(!is_numeric($blend) || $blend < 0 || $blend > 1) { 75 | throw new InvalidArgumentException('Blend should be integer or float value from 0 to 1. ' . $blend . ' given.'); 76 | } 77 | 78 | $color = ltrim($color, '#'); 79 | $color = str_pad($color, 6, 0, STR_PAD_RIGHT); 80 | if(!preg_match('/^[a-f0-9]{6}$/i', $color)) { 81 | throw new InvalidArgumentException('Invalid value of color. Should be hex color string.'); 82 | } 83 | 84 | $this->_color = '0x' . $color . ':' . $similarity . ':' . $blend; 85 | 86 | return $this; 87 | } 88 | 89 | /** 90 | * Z-Index of chromakey option is always 0. 91 | * @return int 92 | */ 93 | public function getZIndex() { 94 | return 0; 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /examples/draw-animated-gif.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | use \Sharapov\FFMpegExtensions\Input\File as InputFile; 9 | use \Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions; 10 | use \Sharapov\FFMpegExtensions\Coordinate; 11 | use \Alchemy\BinaryDriver\Exception\ExecutionFailureException; 12 | 13 | require_once 'init.php'; 14 | 15 | // Open source video 16 | $video = $ffmpeg->open(new InputFile('source/demo_video_720p_HD.mp4')); 17 | 18 | // Apply filter options to video 19 | $video 20 | ->filters() 21 | ->complex( 22 | new FilterComplexOptions\OptionsCollection([ 23 | ((new FilterComplexOptions\OptionOverlay()) 24 | // Set z-index property. Greater value is always in front 25 | ->setZIndex(260) 26 | // You can use fade-in and fade-out effects. Set time in seconds 27 | ->setFadeIn(2) 28 | ->setFadeOut(2) 29 | // Set image path 30 | ->setExtraInputStream(new InputFile('source/animated.gif')) 31 | // Coordinates where the text should be rendered. Accepts positive integer or 32 | // constants "(w-tw)/2", "(h-th)/2" to handle auto-horizontal, auto-vertical values 33 | ->setCoordinates(new Coordinate\Point(230, 200)) 34 | // Set image dimensions 35 | //->setDimensions(new Coordinate\Dimension(450, 200)) 36 | // Set timings (start, stop) in seconds. Accepts float values as well 37 | ->setTimeLine(new Coordinate\TimeLine(3, 13))) 38 | ])); 39 | 40 | // Run render 41 | $format = new Sharapov\FFMpegExtensions\Format\Video\X264('libmp3lame'); 42 | $format->on('progress', function($video, $format, $percentage) { 43 | echo "$percentage% transcoded\n"; 44 | }); 45 | 46 | try { 47 | $video 48 | ->save($format, 'output/output.mp4'); 49 | print 'Done!'; 50 | } catch (ExecutionFailureException $e) { 51 | print $e->getMessage(); 52 | } 53 | 54 | /* 55 | * -loop 1 56 | "ffmpeg-20170915-6743351-win64-static/bin/ffmpeg.exe" -y -i "source/demo_video_720p_HD.mp4" -ignore_loop 0 -i "source/animated.gif" -filter_complex "[1:v]format=yuva420p,scale=450:200,fade=t=in:st=0:d=4:alpha='1',fade=t=out:st=9:d=4:alpha='1'[t1],[0:v][t1]overlay=230:200:shortest='1':enable='between(t,3,13)'" -threads 12 -vcodec libx264 -acodec libmp3lame -b:v 1000k -refs 6 -coder 1 -sc_threshold 40 -flags +loop -me_range 16 -subq 7 -i_qfactor 0.71 -qcomp 0.6 -qdiff 4 -trellis 1 -b:a 128k "output/output.mp4" 57 | */ 58 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Filters/Audio/MergeFilterOptions/OptionAudioFile.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Filters\Audio\MergeFilterOptions; 9 | 10 | use Sharapov\FFMpegExtensions\Filters\ExtraInputStreamInterface; 11 | use Sharapov\FFMpegExtensions\Filters\ExtraInputStreamTrait; 12 | use Sharapov\FFMpegExtensions\Input\FileInterface; 13 | use FFMpeg\Exception\InvalidArgumentException; 14 | 15 | /** 16 | * Audiofile filter option 17 | * @package Sharapov\FFMpegExtensions\Filters\Audio\MergeFilterOptions 18 | */ 19 | class OptionAudioFile 20 | implements 21 | OptionInterface, 22 | ExtraInputStreamInterface { 23 | use ExtraInputStreamTrait; 24 | 25 | protected $_volumeLevel; 26 | 27 | public function __construct(FileInterface $file) { 28 | $this->setExtraInputStream($file); 29 | } 30 | 31 | /** 32 | * Get volume level. 33 | * @return string 34 | */ 35 | public function getVolumeLevel() { 36 | return $this->_volumeLevel; 37 | } 38 | 39 | /** 40 | * Set volume level. 41 | * @return $this 42 | */ 43 | public function setVolumeLevel($level) { 44 | if(!is_numeric($level) || $level < 0 || $level > 1) { 45 | throw new InvalidArgumentException('Volume level should be integer or float value from 0 to 1. ' . $level . ' given.'); 46 | } 47 | 48 | $this->_volumeLevel = $level; 49 | 50 | return $this; 51 | } 52 | 53 | /** 54 | * Returns command string. 55 | * @return string 56 | */ 57 | public function getCommandMono2Stereo() { 58 | return sprintf("[%s][%s]amerge=inputs=2[%s]", ':s1', ':s2', ':s3'); 59 | } 60 | 61 | /** 62 | * Returns command string. 63 | * @return string 64 | */ 65 | public function getCommandMuxStereo() { 66 | // [1:a]volume=1[a2][0:a][a2]amerge=inputs=2,pan=stereo|c0_volumeLevel != null) { 74 | $volume = sprintf('aformat=sample_fmts=fltp:sample_rates=44100:channel_layouts=stereo,volume=%s[av];[av][%s]', $this->_volumeLevel, ':s2'); 75 | } else { 76 | $volume = '[:s2]'; 77 | } 78 | 79 | return sprintf("[%s]%samerge=inputs=2,pan=stereo|c0getCommand(); 88 | } 89 | 90 | public function getCommand() { 91 | return ''; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /examples/alphakey-with-drawtext.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | use \Sharapov\FFMpegExtensions\Input\File as InputFile; 9 | use \Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions; 10 | use \Sharapov\FFMpegExtensions\Coordinate; 11 | use \Alchemy\BinaryDriver\Exception\ExecutionFailureException; 12 | 13 | require_once 'init.php'; 14 | 15 | // Open source video 16 | $video = $ffmpeg->open(new InputFile('source/alpha-intro.mov')); 17 | 18 | // Initiate complex filter options collection 19 | $options = new FilterComplexOptions\OptionsCollection(); 20 | 21 | // Create alphakey option 22 | $alphaKey = new FilterComplexOptions\OptionAlphakey(); 23 | $alphaKey 24 | // Set input stream for alphakey 25 | ->setExtraInputStream(new InputFile('source/Coast - 1270.mp4')) 26 | ->setDimensions(new Coordinate\Dimension(1280, 720)); 27 | 28 | $options 29 | ->add($alphaKey); 30 | 31 | // Pass option to the options collection 32 | $options 33 | ->add(((new FilterComplexOptions\OptionDrawText()) 34 | // Set z-index property. Greater value is always in front 35 | ->setZIndex(160) 36 | // You can use fade-in and fade-out effects. Set time in seconds 37 | ->setFadeIn(3) 38 | ->setFadeOut(2) 39 | // Set font path 40 | ->setFontFile(new InputFile('source/arial.ttf')) 41 | // Set font color. Accepts transparency value as the second argument. Float value between 0 and 1. 42 | ->setFontColor('ffffff') 43 | // Set font size in pixels 44 | ->setFontSize(33) 45 | // Set text string 46 | ->setText('Welcome to php-ffmpeg-extensions alphakey demonstration') 47 | // Coordinates where the text should be rendered. Accepts positive integer or 48 | // constants "(w-tw)/2", "(h-th)/2" to handle auto-horizontal, auto-vertical values 49 | ->setCoordinates(new Coordinate\Point(Coordinate\Point::AUTO_HORIZONTAL, 50)) 50 | // Set timings (start, stop) in seconds. Accepts float values as well 51 | ->setTimeLine(new Coordinate\TimeLine(4, 8)))); 52 | 53 | $options 54 | ->add(((new FilterComplexOptions\OptionDrawText()) 55 | // Set z-index property. Greater value is always in front 56 | ->setZIndex(160) 57 | // You can use fade-in and fade-out effects. Set time in seconds 58 | ->setFadeIn(3) 59 | ->setFadeOut(4) 60 | // Set font path 61 | ->setFontFile(new InputFile('source/arial.ttf')) 62 | // Set font color. Accepts transparency value as the second argument. Float value between 0 and 1. 63 | ->setFontColor('ffffff') 64 | // Set font size in pixels 65 | ->setFontSize(33) 66 | // Set text string 67 | ->setText('Example fading text with bounding box') 68 | // Coordinates where the text should be rendered. Accepts positive integer or 69 | // constants "(w-tw)/2", "(h-th)/2" to handle auto-horizontal, auto-vertical values 70 | ->setCoordinates(new Coordinate\Point(Coordinate\Point::AUTO_HORIZONTAL, 600)) 71 | // Set timings (start, stop) in seconds. Accepts float values as well 72 | ->setTimeLine(new Coordinate\TimeLine(10, 18)) 73 | // Set bounding box 74 | ->setBoundingBox('000000', 10, 0.5))); 75 | 76 | // Apply filter options to video 77 | $video 78 | ->filters() 79 | ->complex($options); 80 | 81 | // Run render 82 | $format = new Sharapov\FFMpegExtensions\Format\Video\X264('libmp3lame'); 83 | $format->on('progress', function($video, $format, $percentage) { 84 | echo "$percentage% transcoded\n"; 85 | }); 86 | 87 | try { 88 | $video 89 | ->save($format, 'output/output.mp4'); 90 | print 'Done!'; 91 | } catch (ExecutionFailureException $e) { 92 | print $e->getMessage(); 93 | } 94 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Filters/Video/FilterComplexOptions/OptionDrawBox.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions; 9 | 10 | use FFMpeg\Exception\InvalidArgumentException; 11 | use Sharapov\FFMpegExtensions\Coordinate\TimeLine; 12 | use Sharapov\FFMpegExtensions\Media\Video; 13 | 14 | /** 15 | * DrawText filter option 16 | * @package Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions 17 | */ 18 | class OptionDrawBox implements OptionInterface { 19 | use TimeLineTrait; 20 | use CoordinatesTrait; 21 | use DimensionsTrait; 22 | use ZindexTrait; 23 | 24 | protected $_color = '000000@0.4:t=max'; 25 | 26 | /** 27 | * @var Video 28 | */ 29 | protected $_video; 30 | 31 | /** 32 | * Constructor. Set box color. 33 | * 34 | * @param $color 35 | * @param float $transparency 36 | * @param string $thickness 37 | */ 38 | public function __construct($color = '000000', $transparency = 0.4, $thickness = 'max') { 39 | $this->setColor($color, $transparency, $thickness); 40 | } 41 | 42 | /** 43 | * Set video stream 44 | * 45 | * @param Video $video 46 | * 47 | * @return $this 48 | */ 49 | public function setVideoStream(Video $video) { 50 | $this->_video = $video; 51 | 52 | return $this; 53 | } 54 | 55 | /** 56 | * Returns a command string. 57 | * @return string 58 | */ 59 | public function __toString() { 60 | return $this->getCommand(); 61 | } 62 | 63 | /** 64 | * Returns command string. 65 | * @return string 66 | */ 67 | public function getCommand() { 68 | // If specific timeline is not provided for the drawtext, we must apply drawtext for the whole video 69 | if(!$this->_timeLine instanceof TimeLine) { 70 | $this->setTimeLine(new TimeLine(0, $this->getVideoStream()->getStreamDuration())); 71 | } 72 | 73 | return sprintf("[%s]drawbox=%s[%s]", ':s1', implode(":", [ 74 | "x=" . $this->getCoordinates()->getX(), 75 | "y=" . $this->getCoordinates()->getY(), 76 | "w=" . $this->getDimensions()->getWidth(), 77 | "h=" . $this->getDimensions()->getHeight(), 78 | "color='" . $this->getColor() . "'", 79 | $this->getTimeLine()->getCommand() 80 | ]), ':s2'); 81 | } 82 | 83 | /** 84 | * @return Video 85 | */ 86 | public function getVideoStream() { 87 | return $this->_video; 88 | } 89 | 90 | /** 91 | * Get box color. 92 | * @return string 93 | */ 94 | public function getColor() { 95 | return $this->_color; 96 | } 97 | 98 | /** 99 | * Set box color. 100 | * 101 | * @param $color 102 | * @param float $transparency 103 | * @param string $thickness 104 | * 105 | * @return $this 106 | */ 107 | public function setColor($color, $transparency = 0.4, $thickness = 'max') { 108 | if(!is_numeric($transparency) || $transparency < 0 || $transparency > 1) { 109 | throw new InvalidArgumentException('Transparency should be integer or float value from 0 to 1. ' . $transparency . ' given.'); 110 | } 111 | 112 | if($thickness != 'max' and !is_int($thickness)) { 113 | throw new InvalidArgumentException('Thickness should be positive integer or "max". ' . $thickness . ' given.'); 114 | } 115 | 116 | $color = ltrim($color, '#'); 117 | $color = str_pad($color, 6, 0, STR_PAD_RIGHT); 118 | if(!preg_match('/^[a-f0-9]{6}$/i', $color)) { 119 | throw new InvalidArgumentException('Color should be HEX string. ' . $color . ' given.'); 120 | } 121 | 122 | $this->_color = $color . '@' . $transparency . ":t=" . $thickness; 123 | 124 | return $this; 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Media/Audio.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Media; 9 | 10 | use Alchemy\BinaryDriver\Exception\ExecutionFailureException; 11 | 12 | use FFMpeg\Format\FormatInterface; 13 | use FFMpeg\Filters\Audio\SimpleFilter; 14 | use FFMpeg\Exception\RuntimeException; 15 | use FFMpeg\Exception\InvalidArgumentException; 16 | use FFMpeg\Filters\FilterInterface; 17 | use FFMpeg\Format\ProgressableInterface; 18 | use Sharapov\FFMpegExtensions\Filters\Audio\AudioFilterInterface; 19 | use Sharapov\FFMpegExtensions\Filters\Audio\AudioFilters; 20 | 21 | class Audio extends \FFMpeg\Media\Audio { 22 | use MediaTypeTrait; 23 | 24 | /** 25 | * {@inheritdoc} 26 | * @return AudioFilters 27 | */ 28 | public function filters() { 29 | return new AudioFilters($this); 30 | } 31 | 32 | /** 33 | * {@inheritdoc} 34 | * @return Audio 35 | */ 36 | public function addFilter(FilterInterface $filter) { 37 | if(!$filter instanceof AudioFilterInterface) { 38 | throw new InvalidArgumentException('Audio only accepts AudioFilterInterface filters'); 39 | } 40 | 41 | $this->filters->add($filter); 42 | 43 | return $this; 44 | } 45 | 46 | /** 47 | * Exports the audio in the desired format, applies registered filters. 48 | * 49 | * @param FormatInterface $format 50 | * @param string $outputPathFile 51 | * 52 | * @return Audio 53 | * @throws RuntimeException 54 | */ 55 | public function save(FormatInterface $format, $outputPathFile) { 56 | $commands = ['-y', '-i', $this->pathfile]; 57 | 58 | $filters = clone $this->filters; 59 | $extraFilters = []; 60 | 61 | foreach($filters as $filter) { 62 | // Video filter options must be attached after all the extra input streams 63 | if($filter instanceof \Sharapov\FFMpegExtensions\Filters\Audio\AudioFilterInterface) { 64 | /** @var \FFMpeg\Format\AudioInterface $format */ 65 | $extraFilters = array_merge($extraFilters, $filter->apply($this, $format)); 66 | } 67 | // If filter has extra input streams, we need to attach them into the command 68 | if(count($filter->getExtraInputs()) > 0) { 69 | $commands = array_merge($commands, $filter->getExtraInputs()); 70 | } 71 | } 72 | 73 | $commands = array_merge($commands, $extraFilters); 74 | 75 | $filters->add(new SimpleFilter($format->getExtraParams(), 10)); 76 | 77 | if($this->driver->getConfiguration()->has('ffmpeg.threads')) { 78 | $filters->add(new SimpleFilter(['-threads', $this->driver->getConfiguration()->get('ffmpeg.threads')])); 79 | } 80 | if(null !== $format->getAudioCodec()) { 81 | $filters->add(new SimpleFilter(['-acodec', $format->getAudioCodec()])); 82 | } 83 | 84 | foreach($filters as $filter) { 85 | if(!$filter instanceof \Sharapov\FFMpegExtensions\Filters\Audio\AudioFilterInterface) { 86 | $commands = array_merge($commands, $filter->apply($this, $format)); 87 | } 88 | } 89 | 90 | if(null !== $format->getAudioKiloBitrate()) { 91 | $commands[] = '-b:a'; 92 | $commands[] = $format->getAudioKiloBitrate() . 'k'; 93 | } 94 | if(null !== $format->getAudioChannels()) { 95 | $commands[] = '-ac'; 96 | $commands[] = $format->getAudioChannels(); 97 | } 98 | $commands[] = $outputPathFile; 99 | 100 | try { 101 | $listeners = null; 102 | 103 | if($format instanceof ProgressableInterface) { 104 | $listeners = $format->createProgressListener($this, $this->ffprobe, 1, 1); 105 | } 106 | 107 | $this->driver->command($commands, false, $listeners); 108 | } catch (ExecutionFailureException $e) { 109 | $this->cleanupTemporaryFile($outputPathFile); 110 | throw new RuntimeException('Encoding failed', $e->getCode(), $e); 111 | } 112 | 113 | return $this; 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Filters/Video/FilterComplexOptions/OptionsCollection.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions; 9 | 10 | use FFMpeg\Exception\InvalidArgumentException; 11 | use Sharapov\FFMpegExtensions\Filters\ExtraInputStreamInterface; 12 | 13 | /** 14 | * Options collection 15 | * @package Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions 16 | */ 17 | class OptionsCollection implements \Countable, \IteratorAggregate { 18 | const TYPE_OVERLAY = 'Overlay'; 19 | const TYPE_DRAWTEXT = 'DrawText'; 20 | const TYPE_DRAWBOX = 'DrawBox'; 21 | const TYPE_CHROMAKEY = 'Chromakey'; 22 | const TYPE_ALPHAKEY = 'Alphakey'; 23 | 24 | private $_options; 25 | 26 | public function __construct(array $options = []) { 27 | $this->_options = array_values($options); 28 | } 29 | 30 | /** 31 | * Returns the first stream of the collection, null if the collection is 32 | * empty. 33 | * @return null|OptionInterface 34 | */ 35 | public function first() { 36 | $option = reset($this->_options); 37 | 38 | return $option ? : null; 39 | } 40 | 41 | /** 42 | * Adds an option to the collection. 43 | * 44 | * @param OptionInterface $option 45 | * 46 | * @return OptionsCollection 47 | */ 48 | public function add(OptionInterface $option) { 49 | $this->_options[] = $option; 50 | 51 | return $this; 52 | } 53 | 54 | /** 55 | * {@inheritdoc} 56 | */ 57 | public function count() { 58 | return count($this->_options); 59 | } 60 | 61 | /** 62 | * Returns the array of contained options. 63 | * @return array 64 | */ 65 | public function all() { 66 | return $this->_options; 67 | } 68 | 69 | /** 70 | * Returns options that has an extra input streams. 71 | * @return null|\ArrayIterator|\Traversable 72 | */ 73 | public function filterHasExtraInputs() { 74 | return new OptionsCollection(array_filter((array)$this->getIterator(), function(OptionInterface $option) { 75 | if($option instanceof ExtraInputStreamInterface) { 76 | return true; 77 | } 78 | })); 79 | } 80 | 81 | /** 82 | * {@inheritdoc} 83 | */ 84 | public function getIterator() { 85 | return new \ArrayIterator($this->_options); 86 | } 87 | 88 | /** 89 | * Returns options filtered by type. 90 | * 91 | * @param string $typeName 92 | * 93 | * @return \ArrayIterator|\Traversable 94 | */ 95 | public function filter($typeName) { 96 | switch($typeName) { 97 | case self::TYPE_DRAWBOX: 98 | case self::TYPE_DRAWTEXT: 99 | case self::TYPE_OVERLAY: 100 | case self::TYPE_CHROMAKEY: 101 | case self::TYPE_ALPHAKEY: 102 | return new OptionsCollection(array_filter((array)$this->getIterator(), [ 103 | $this, 104 | '_filter' . ucfirst($typeName) 105 | ])); 106 | default : 107 | throw new InvalidArgumentException('Invalid option type requested.'); 108 | } 109 | } 110 | 111 | /** 112 | * Returns options sorted by z-index. 113 | * @return \ArrayIterator|\Traversable 114 | */ 115 | public function sortByZindex() { 116 | $optionsIterator = $this->getIterator(); 117 | $optionsIterator->uasort(function($a, $b) { 118 | /** @var OptionInterface $a */ 119 | /** @var OptionInterface $b */ 120 | return strnatcmp($a->getZIndex(), $b->getZIndex()); 121 | }); 122 | 123 | return $optionsIterator; 124 | } 125 | 126 | /** 127 | * {@inheritdoc} 128 | */ 129 | protected function _filterOverlay(OptionInterface $option) { 130 | if($option instanceof OptionOverlay) { 131 | return true; 132 | } 133 | } 134 | 135 | /** 136 | * {@inheritdoc} 137 | */ 138 | protected function _filterDrawText(OptionInterface $option) { 139 | if($option instanceof OptionDrawText) { 140 | return true; 141 | } 142 | } 143 | 144 | /** 145 | * {@inheritdoc} 146 | */ 147 | protected function _filterDrawBox(OptionInterface $option) { 148 | if($option instanceof OptionDrawBox) { 149 | return true; 150 | } 151 | } 152 | 153 | /** 154 | * {@inheritdoc} 155 | */ 156 | protected function _filterChromakey(OptionInterface $option) { 157 | if($option instanceof OptionChromakey) { 158 | return true; 159 | } 160 | } 161 | 162 | /** 163 | * {@inheritdoc} 164 | */ 165 | protected function _filterAlphakey(OptionInterface $option) { 166 | if($option instanceof OptionAlphakey) { 167 | return true; 168 | } 169 | } 170 | } -------------------------------------------------------------------------------- /examples/draw-texts-and-boxes.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | use \Sharapov\FFMpegExtensions\Input\File as InputFile; 9 | use \Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions; 10 | use \Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions\OptionsCollection; 11 | use \Sharapov\FFMpegExtensions\Coordinate; 12 | use \Alchemy\BinaryDriver\Exception\ExecutionFailureException; 13 | 14 | require_once 'init.php'; 15 | 16 | // Open source video 17 | $video = $ffmpeg->open(new InputFile('source/demo_video_720p_HD.mp4')); 18 | 19 | // Apply filter options to video 20 | $video 21 | ->filters() 22 | ->complex(new OptionsCollection([ 23 | ((new FilterComplexOptions\OptionDrawText()) 24 | // Set z-index property. Greater value is always in front 25 | ->setZIndex(160) 26 | // You can use fade-in and fade-out effects. Set time in seconds 27 | ->setFadeIn(1) 28 | ->setFadeOut(2) 29 | // Set font path 30 | ->setFontFile(new InputFile('source/arial.ttf')) 31 | // Set font color. Accepts transparency value as the second argument. Float value between 0 and 1. 32 | ->setFontColor('#ffffff') 33 | // Set font size in pixels 34 | ->setFontSize(33) 35 | // Set text string 36 | ->setText('php-ffmpeg-extensions library') 37 | // Coordinates where the text should be rendered. Accepts positive integer or 38 | // constants "(w-tw)/2", "(h-th)/2" to handle auto-horizontal, auto-vertical values 39 | ->setCoordinates(new Coordinate\Point(Coordinate\Point::AUTO_HORIZONTAL, 50)) 40 | // Set timings (start, stop) in seconds. Accepts float values as well 41 | ->setTimeLine(new Coordinate\TimeLine(1, 20))), 42 | 43 | ((new FilterComplexOptions\OptionDrawText()) 44 | ->setZIndex(160) 45 | ->setFadeIn(1) 46 | ->setFadeOut(2) 47 | ->setFontFile(new InputFile('source/arial.ttf')) 48 | ->setFontColor('#ffffff') 49 | ->setFontSize(28) 50 | ->setText('Sharapov A. (www.sharapov.biz)') 51 | ->setCoordinates(new Coordinate\Point(15, 600)) 52 | ->setTimeLine(new Coordinate\TimeLine(2, 20))), 53 | 54 | ((new FilterComplexOptions\OptionDrawBox()) 55 | ->setZIndex(130) 56 | ->setColor('000000', 0.6) 57 | ->setDimensions(new Coordinate\Dimension(Coordinate\Dimension::WIDTH_MAX, 60)) 58 | ->setCoordinates(new Coordinate\Point(0, 580))), 59 | 60 | ((new FilterComplexOptions\OptionDrawText()) 61 | ->setZIndex(160) 62 | ->setFadeIn(1) 63 | ->setFadeOut(2) 64 | ->setFontFile(new InputFile('source/arial.ttf')) 65 | ->setFontColor('#ffffff') 66 | ->setFontSize(28) 67 | ->setText('v2.0') 68 | ->setCoordinates(new Coordinate\Point(1200, 600)) 69 | ->setTimeLine(new Coordinate\TimeLine(3, 20))) 70 | ])); 71 | 72 | // Run render 73 | $format = new Sharapov\FFMpegExtensions\Format\Video\X264('libmp3lame'); 74 | $format->on('progress', function($video, $format, $percentage) { 75 | echo "$percentage% transcoded\n"; 76 | }); 77 | 78 | try { 79 | $video 80 | ->save($format, 'output/output.mp4'); 81 | print 'Done!'; 82 | } catch (ExecutionFailureException $e) { 83 | print $e->getMessage(); 84 | } 85 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Filters/Video/FilterComplexOptions/OptionOverlay.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions; 9 | 10 | use Sharapov\FFMpegExtensions\Coordinate\Dimension; 11 | use Sharapov\FFMpegExtensions\Coordinate\Point; 12 | use Sharapov\FFMpegExtensions\Coordinate\TimeLine; 13 | use Sharapov\FFMpegExtensions\Filters\ExtraInputStreamInterface; 14 | use Sharapov\FFMpegExtensions\Filters\ExtraInputStreamTrait; 15 | 16 | /** 17 | * Overlay filter option 18 | * @package Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions 19 | */ 20 | class OptionOverlay 21 | implements 22 | OptionInterface, 23 | ExtraInputStreamInterface { 24 | use TimeLineTrait; 25 | use FadeInOutTrait; 26 | use CoordinatesTrait; 27 | use DimensionsTrait; 28 | use ExtraInputStreamTrait; 29 | use ZindexTrait; 30 | 31 | /** 32 | * Get input streams collection. 33 | * @return \FFMpeg\FFProbe\DataMapping\StreamCollection 34 | */ 35 | public function getProbeData() { 36 | return $this->getProbe()->streams($this->getExtraInputStream()->getPath()); 37 | } 38 | 39 | /** 40 | * Get input stream format. 41 | * @return \FFMpeg\FFProbe\DataMapping\Format 42 | */ 43 | public function getFormat() { 44 | return $this->getProbe()->format($this->getExtraInputStream()->getPath()); 45 | } 46 | 47 | /** 48 | * Returns a command string. 49 | * @return string 50 | */ 51 | public function __toString() { 52 | return $this->getCommand(); 53 | } 54 | 55 | /** 56 | * Returns command string. 57 | * @return string 58 | */ 59 | public function getCommand() { 60 | if($this->getTimeLine() instanceof TimeLine) { 61 | $timeLine = sprintf(":%s", (string)$this->getTimeLine()); 62 | } else { 63 | $timeLine = ''; 64 | } 65 | 66 | if($this->_fadeInSeconds or $this->_fadeOutSeconds) { 67 | $fadeTime = []; 68 | if($this->_fadeInSeconds) { 69 | $fadeTime[] = sprintf("fade=t=in:st=0:d=%s:alpha='1'", $this->_fadeInSeconds); 70 | } 71 | if($this->_fadeOutSeconds) { 72 | if($this->getTimeLine() instanceof TimeLine) { 73 | // We have to calculate the starting point of fade out if we have the TimeLine object 74 | $fadeTime[] = sprintf("fade=t=out:st=%s:d=%s:alpha='1'", ($this->getTimeLine()->getEndTime() - $this->_fadeOutSeconds), $this->_fadeOutSeconds); 75 | } else { 76 | // Otherwise we add {VIDEO_LENGTH} tag to calculate the starting point on the next step 77 | $fadeTime[] = sprintf("fade=t=out:st={VIDEO_LENGTH}:d=%s:alpha='1'", $this->_fadeOutSeconds); 78 | } 79 | } 80 | $fadeTime = sprintf(",%s", implode(",", $fadeTime)); 81 | } else { 82 | $fadeTime = ''; 83 | } 84 | 85 | // We have to add shortest=1 for images to stop the overlay when the main video ends 86 | if($this->isStaticImage() or $this->isAnimatedGif() or $this->isAnimatedPng()) { 87 | $shortest = ":shortest='1'"; 88 | } else { 89 | $shortest = ''; 90 | } 91 | 92 | return sprintf("[%s]format=yuva420p,scale=%s%s[%s],[%s][%s]overlay=%s%s%s[%s]", ':s1', (string)$this->getDimensions(), $fadeTime, ':s2', ':s3', ':s4', (string)$this->getCoordinates(), $shortest, $timeLine, ':s5'); 93 | } 94 | 95 | /** 96 | * Checks if overlay is static image (not animated gif or png). 97 | * @return bool 98 | */ 99 | public function isStaticImage() { 100 | return true === $this->isImage() and false === $this->isAnimatedGif() and false === $this->isAnimatedPng(); 101 | } 102 | 103 | /** 104 | * Detect animated gif 105 | * @return bool 106 | */ 107 | public function isAnimatedGif() { 108 | return (bool)preg_match('#(\x00\x21\xF9\x04.{4}\x00\x2C.*){2,}#s', @file_get_contents($this->getExtraInputStream()->getPath())); 109 | } 110 | 111 | /** 112 | * Identifies APNGs 113 | * Written by Coda, functionified by Foone/Popcorn Mariachi#!9i78bPeIxI 114 | * This code is in the public domain 115 | * Returns: true if the file is an APNG, false if it is any other sort of file (it is not checked for PNG validity) 116 | * takes on argument, a filename. 117 | * @return bool 118 | */ 119 | public function isAnimatedPng() { 120 | $img_bytes = @file_get_contents($this->getExtraInputStream()->getPath()); 121 | if($img_bytes) { 122 | if(strpos(substr($img_bytes, 0, strpos($img_bytes, 'IDAT')), 123 | 'acTL') !== false) { 124 | return true; 125 | } 126 | } 127 | 128 | return false; 129 | } 130 | 131 | /** 132 | * Checks if overlay is image (both static or animated) 133 | * @return bool 134 | */ 135 | public function isImage() { 136 | return false !== @imagecreatefromstring(@file_get_contents($this->getExtraInputStream()->getPath())); 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /examples/draw-texts-and-boxes-ts.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | use \Sharapov\FFMpegExtensions\Input\File as InputFile; 9 | use \Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions; 10 | use \Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions\OptionsCollection; 11 | use \Sharapov\FFMpegExtensions\Coordinate; 12 | use \Alchemy\BinaryDriver\Exception\ExecutionFailureException; 13 | 14 | require_once 'init.php'; 15 | 16 | /** @var \Sharapov\FFMpegExtensions\FFMpeg $ffmpeg */ 17 | 18 | // Set extra mime type 19 | $ffmpeg::setMime('application/octet-stream'); 20 | 21 | // Open source video 22 | $video = $ffmpeg->open(new InputFile('source/360p_010.ts')); 23 | 24 | // Apply filter options to video 25 | $video 26 | ->filters() 27 | ->complex(new OptionsCollection([ 28 | ((new FilterComplexOptions\OptionDrawText()) 29 | // Set z-index property. Greater value is always in front 30 | ->setZIndex(160) 31 | // You can use fade-in and fade-out effects. Set time in seconds 32 | ->setFadeIn(1) 33 | ->setFadeOut(2) 34 | // Set font path 35 | ->setFontFile(new InputFile('source/arial.ttf')) 36 | // Set font color. Accepts transparency value as the second argument. Float value between 0 and 1. 37 | ->setFontColor('#ffffff') 38 | // Set font size in pixels 39 | ->setFontSize(33) 40 | // Set text string 41 | ->setText('php-ffmpeg-extensions library') 42 | // Coordinates where the text should be rendered. Accepts positive integer or 43 | // constants "(w-tw)/2", "(h-th)/2" to handle auto-horizontal, auto-vertical values 44 | ->setCoordinates(new Coordinate\Point(Coordinate\Point::AUTO_HORIZONTAL, 50)) 45 | // Set timings (start, stop) in seconds. Accepts float values as well 46 | ->setTimeLine(new Coordinate\TimeLine(1, 20))), 47 | 48 | ((new FilterComplexOptions\OptionDrawText()) 49 | ->setZIndex(160) 50 | ->setFadeIn(1) 51 | ->setFadeOut(2) 52 | ->setFontFile(new InputFile('source/arial.ttf')) 53 | ->setFontColor('#ffffff') 54 | ->setFontSize(28) 55 | ->setText('Sharapov A. (www.sharapov.biz)') 56 | ->setCoordinates(new Coordinate\Point(15, 600)) 57 | ->setTimeLine(new Coordinate\TimeLine(2, 20))), 58 | 59 | ((new FilterComplexOptions\OptionDrawBox()) 60 | ->setZIndex(130) 61 | ->setColor('000000', 0.6) 62 | ->setDimensions(new Coordinate\Dimension(Coordinate\Dimension::WIDTH_MAX, 60)) 63 | ->setCoordinates(new Coordinate\Point(0, 580))), 64 | 65 | ((new FilterComplexOptions\OptionDrawText()) 66 | ->setZIndex(160) 67 | ->setFadeIn(1) 68 | ->setFadeOut(2) 69 | ->setFontFile(new InputFile('source/arial.ttf')) 70 | ->setFontColor('#ffffff') 71 | ->setFontSize(28) 72 | ->setText('v2.0') 73 | ->setCoordinates(new Coordinate\Point(1200, 600)) 74 | ->setTimeLine(new Coordinate\TimeLine(3, 20))) 75 | ])); 76 | 77 | $video->setMuxdelay(0); 78 | $video->setPreset('ultrafast'); 79 | 80 | // Run render 81 | $format = new Sharapov\FFMpegExtensions\Format\Video\X264('copy'); 82 | $format->setPasses(1); 83 | $format->setConstantRateFactor(22); 84 | $format->on('progress', function($video, $format, $percentage) { 85 | echo "$percentage% transcoded\n"; 86 | }); 87 | 88 | try { 89 | $video 90 | ->save($format, 'output/output-ts1.mp4'); 91 | print 'Done!'; 92 | } catch (ExecutionFailureException $e) { 93 | print $e->getMessage(); 94 | } 95 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # php-ffmpeg-extensions 2 | An extensions library for the PHP FFMpeg (https://github.com/PHP-FFMpeg/PHP-FFMpeg) 3 | 4 | Installation (via Composer): 5 | ============================ 6 | 7 | For composer installation, add: 8 | 9 | ```json 10 | "require": { 11 | "sharapov/php-ffmpeg-extensions": "^0.2" 12 | }, 13 | ``` 14 | 15 | to your composer.json file and update your dependencies. Or you can run: 16 | 17 | ```sh 18 | $ composer require sharapov/php-ffmpeg-extensions 19 | ``` 20 | 21 | Notes: 22 | ====== 23 | 24 | Tested with ffmpeg 3+, not tested with ffmpeg 4+ 25 | 26 | 27 | Usage: 28 | ====== 29 | 30 | Now you can autoload or use the class via its namespace. Below are examples of how to use the library. 31 | 32 | Draw texts and boxes 33 | -------------------------- 34 | 35 | ```php 36 | 37 | // Init FFMpeg library 38 | $ffmpeg = \Sharapov\FFMpegExtensions\FFMpeg::create(array( 39 | 'ffmpeg.binaries' => '/path/to/ffmpeg', // Path to FFMpeg 40 | 'ffprobe.binaries' => '/path/to/ffprobe', // Path to FFProbe 41 | 'timeout' => 3600, // The timeout for the underlying process 42 | 'ffmpeg.threads' => 12, // The number of threads that FFMpeg should use 43 | )); 44 | 45 | // Open source video 46 | $video = $ffmpeg->open( new InputFile( 'source/Coast - 1270.mp4' ) ); 47 | 48 | // Apply filter options to video 49 | $video 50 | ->filters() 51 | ->complex( new OptionsCollection( [ 52 | ( ( new FilterComplexOptions\OptionDrawText() ) 53 | // Set z-index property. Greater value is always in front 54 | ->setZIndex( 160 ) 55 | // You can use fade-in and fade-out effects. Set time in seconds 56 | ->setFadeIn( 1 ) 57 | ->setFadeOut( 2 ) 58 | // Set font path 59 | ->setFontFile( new InputFile( 'source/arial.ttf' ) ) 60 | // Set font color. Accepts transparency value as the second argument. Float value between 0 and 1. 61 | ->setFontColor( '#ffffff' ) 62 | // Set font size in pixels 63 | ->setFontSize( 33 ) 64 | // Set text string 65 | ->setText( 'php-ffmpeg-extensions library' ) 66 | // Coordinates where the text should be rendered. Accepts positive integer or 67 | // constants "(w-tw)/2", "(h-th)/2" to handle auto-horizontal, auto-vertical values 68 | ->setCoordinates( new Coordinate\Point( Coordinate\Point::AUTO_HORIZONTAL, 50 ) ) 69 | // Set timings (start, stop) in seconds. Accepts float values as well 70 | ->setTimeLine( new Coordinate\TimeLine( 1, 20 ) ) ), 71 | 72 | ( ( new FilterComplexOptions\OptionDrawText() ) 73 | ->setZIndex( 160 ) 74 | ->setFadeIn( 1 ) 75 | ->setFadeOut( 2 ) 76 | ->setFontFile( new InputFile( 'source/arial.ttf' ) ) 77 | ->setFontColor( '#ffffff' ) 78 | ->setFontSize( 28 ) 79 | ->setText( 'Sharapov A. (www.sharapov.biz)' ) 80 | ->setCoordinates( new Coordinate\Point( 15, 600 ) ) 81 | ->setTimeLine( new Coordinate\TimeLine( 2, 20 ) ) ), 82 | 83 | ( ( new FilterComplexOptions\OptionDrawBox() ) 84 | ->setZIndex( 130 ) 85 | ->setColor( '000000', 0.6 ) 86 | ->setDimensions( new Coordinate\Dimension( Coordinate\Dimension::WIDTH_MAX, 60 ) ) 87 | ->setCoordinates( new Coordinate\Point( 0, 580 ) ) ), 88 | 89 | ( ( new FilterComplexOptions\OptionDrawText() ) 90 | ->setZIndex( 160 ) 91 | ->setFadeIn( 1 ) 92 | ->setFadeOut( 2 ) 93 | ->setFontFile( new InputFile( 'source/arial.ttf' ) ) 94 | ->setFontColor( '#ffffff' ) 95 | ->setFontSize( 28 ) 96 | ->setText( 'v2.0' ) 97 | ->setCoordinates( new Coordinate\Point( 1200, 600 ) ) 98 | ->setTimeLine( new Coordinate\TimeLine( 3, 20 ) ) ) 99 | ] ) ); 100 | 101 | // Run render 102 | $format = new \FFMpeg\Format\Video\X264( 'libmp3lame' ); 103 | $format->on( 'progress', function ( $video, $format, $percentage ) { 104 | echo "$percentage% transcoded\n"; 105 | } ); 106 | 107 | try { 108 | $video 109 | ->save( $format, 'output/output.mp4' ); 110 | print 'Done!'; 111 | } catch ( ExecutionFailureException $e ) { 112 | print $e->getMessage(); 113 | } 114 | ``` 115 | 116 | You will find other examples in "/examples" folder. 117 | 118 | Changelog 119 | ========= 120 | 121 | 122 | Links 123 | ===== 124 | [PHP FFMpeg Homepage](https://github.com/PHP-FFMpeg/PHP-FFMpeg) 125 | 126 | [Composer](https://getcomposer.org/) 127 | 128 | [GitHub](https://github.com/sharapov-outsource/php-ffmpeg-extensions) 129 | 130 | [Packagist](https://packagist.org/packages/sharapov/php-ffmpeg-extensions) 131 | -------------------------------------------------------------------------------- /examples/audio.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | ini_set('display_errors', 1); 9 | date_default_timezone_set('UTC'); 10 | require_once dirname(__FILE__) . '/../vendor/autoload.php'; 11 | 12 | $logger = new \Monolog\Logger('debug'); 13 | $logger->pushHandler(new \Monolog\Handler\StreamHandler('render.log', \Monolog\Logger::ERROR)); 14 | $logger->pushHandler(new \Monolog\Handler\StreamHandler('info.log', \Monolog\Logger::INFO)); 15 | 16 | if($_SERVER['SERVER_NAME'] == 'ffmpeg.local') { 17 | 18 | $ffmpeg = \Sharapov\FFMpegExtensions\FFMpeg::create([ 19 | 'ffmpeg.binaries' => 'D:\Projects\videomachine2\ffmpeg\bin\ffmpeg.exe', // Path to FFMpeg 20 | 'ffprobe.binaries' => 'D:\Projects\videomachine2\ffmpeg\bin\ffprobe.exe', // Path to FFProbe 21 | 'timeout' => 3600, // The timeout for the underlying process 22 | 'ffmpeg.threads' => 12, // The number of threads that FFMpeg should use 23 | ], $logger); 24 | 25 | 26 | } else { 27 | 28 | $ffmpeg = \Sharapov\FFMpegExtensions\FFMpeg::create([ 29 | //'ffmpeg.binaries' => 'D:\Projects\videomachine2\ffmpeg\bin\ffmpeg.exe', // Path to FFMpeg 30 | //'ffprobe.binaries' => 'D:\Projects\videomachine2\ffmpeg\bin\ffprobe.exe', // Path to FFProbe 31 | 'ffmpeg.binaries' => '/home/ezmembersarea/videoapp/app/module/RenderEngine/FFmpegStatic/ffmpeg', 32 | 'ffprobe.binaries' => '/home/ezmembersarea/videoapp/app/module/RenderEngine/FFmpegStatic/ffprobe', 33 | 'timeout' => 3600, // The timeout for the underlying process 34 | 'ffmpeg.threads' => 12, // The number of threads that FFMpeg should use 35 | ], $logger); 36 | } 37 | $audio = $ffmpeg->open(new \Sharapov\FFMpegExtensions\Input\File(dirname(__FILE__) . '/source/LastResort.mp3')); 38 | 39 | $options = new \Sharapov\FFMpegExtensions\Filters\Audio\MergeFilterOptions\OptionsCollection(); 40 | $file1 = new \Sharapov\FFMpegExtensions\Filters\Audio\MergeFilterOptions\OptionAudioFile(new \Sharapov\FFMpegExtensions\Input\File(dirname(__FILE__) . '/source/LastStand.mp3')); 41 | $file1 42 | ->setVolumeLevel(0.2); 43 | $options 44 | ->add($file1); 45 | 46 | $audio 47 | ->filters() 48 | ->combineStereos($options); 49 | //->stereo2mono(); 50 | //->mono2stereo(new \Sharapov\FFMpegExtensions\Input\File(dirname(__FILE__) . '/source/mono2.mp3')); 51 | //->merge($filterOptions); 52 | 53 | //print '
';
54 | //print_r($video);
55 | //print '
'; 56 | 57 | $format = new \FFMpeg\Format\Audio\Mp3(); 58 | $format->on('progress', function($video, $format, $percentage) { 59 | print $percentage . "\n"; 60 | }); 61 | 62 | $audio->save($format, dirname(__FILE__) . '/output/output.mp3'); 63 | die("\n
1"); 64 | 65 | 66 | /* 67 | * 68 | '/home/ezmembersarea/videoapp/app/module/RenderEngine/FFmpegStatic/ffmpeg' '-y' '-i' '/home/ezmembersarea/public_html/app/ffmpeg-ext/examples/source/demo_video_720p_HD.mp4' '-i' '/home/ezmembersarea/public_html/app/ffmpeg-ext/examples/source/intro_720p_muted.mp4' '-i' '/home/ezmembersarea/public_html/app/ffmpeg-ext/examples/source/bg_green.jpeg' '-filter_complex' '[1:v]scale=120:60[t1],[0:v][t1]overlay=130:180' '-b:v' '1000k' '-refs' '6' '-coder' '1' '-sc_threshold' '40' '-flags' '+loop' '-me_range' '16' '-subq' '7' '-i_qfactor' '0.71' '-qcomp' '0.6' '-qdiff' '4' '-trellis' '1' '-b:a' '128k' '/home/ezmembersarea/public_html/app/ffmpeg-ext/examples/output/output.mp4' 69 | * 70 | * 71 | * 72 | * 73 | * 74 | * 75 | '/home/ezmembersarea/videoapp/app/module/RenderEngine/FFmpegStatic/ffmpeg' '-y' '-i' '/home/ezmembersarea/public_html/app/ffmpeg-ext/examples/source/demo_video_720p_HD.mp4' '-i' '/home/ezmembersarea/public_html/app/ffmpeg-ext/examples/source/bg_green.jpeg' '-i' '/home/ezmembersarea/public_html/app/ffmpeg-ext/examples/source/intro_720p_muted.mp4' '-filter_complex' '[1:v]scale=120:60[s2],[0:v][s2]overlay=130:150[s3],[2:v]scale=120:60[s4],[s3][s4]overlay=130:180[s5],[s5]drawtext=fontfile=/home/ezmembersarea/public_html/app/ffmpeg-ext/examples/source/OpenSansRegular.ttf:text='\''Layer2'\'':fontcolor='\''#ffffff@1'\'':fontsize=20:x=130:y=160:box=1:boxcolor='\''000000'\''@1:boxborderw=10,drawtext=fontfile=/home/ezmembersarea/public_html/app/ffmpeg-ext/examples/source/OpenSansRegular.ttf:text='\''Layer1'\'':fontcolor='\''#ffffff@1'\'':fontsize=20:x=130:y=150:box=1:boxcolor='\''red'\''@1:boxborderw=10' '-b:v' '1000k' '-refs' '6' '-coder' '1' '-sc_threshold' '40' '-flags' '+loop' '-me_range' '16' '-subq' '7' '-i_qfactor' '0.71' '-qcomp' '0.6' '-qdiff' '4' '-trellis' '1' '-b:a' '128k' '/home/ezmembersarea/public_html/app/ffmpeg-ext/examples/output/output.mp4' 76 | * 77 | * 78 | '/home/ezmembersarea/videoapp/app/module/RenderEngine/FFmpegStatic/ffmpeg' '-y' '-i' '/home/ezmembersarea/public_html/app/ffmpeg-ext/examples/source/demo_video_720p_HD.mp4' '-i' '/home/ezmembersarea/public_html/app/ffmpeg-ext/examples/source/intro_720p_muted.mp4' '-i' '/home/ezmembersarea/public_html/app/ffmpeg-ext/examples/source/bg_green.jpeg' '-filter_complex' '[2:v]scale=120:60[s4],[0:v][s4]overlay=130:180[s6],[1:v]scale=120:60[s2],[s2][s2]overlay=130:150[s3],[s3]drawtext=fontfile=/home/ezmembersarea/public_html/app/ffmpeg-ext/examples/source/OpenSansRegular.ttf:text='\''Layer2'\'':fontcolor='\''#ffffff@1'\'':fontsize=20:x=130:y=160:box=1:boxcolor='\''000000'\''@1:boxborderw=10,drawtext=fontfile=/home/ezmembersarea/public_html/app/ffmpeg-ext/examples/source/OpenSansRegular.ttf:text='\''Layer1'\'':fontcolor='\''#ffffff@1'\'':fontsize=20:x=130:y=150:box=1:boxcolor='\''red'\''@1:boxborderw=10' '-b:v' '1000k' '-refs' '6' '-coder' '1' '-sc_threshold' '40' '-flags' '+loop' '-me_range' '16' '-subq' '7' '-i_qfactor' '0.71' '-qcomp' '0.6' '-qdiff' '4' '-trellis' '1' '-b:a' '128k' '/home/ezmembersarea/public_html/app/ffmpeg-ext/examples/output/output.mp4' 79 | * 80 | */ 81 | 82 | $video2 = $ffmpeg->open(new \Sharapov\FFMpegExtensions\Input\File(dirname(__FILE__) . '/source/EZSCtest1a.mov')); 83 | 84 | $audio = $ffmpeg->open(new \Sharapov\FFMpegExtensions\Input\File(dirname(__FILE__) . '/source/demo-sound.mp3')); 85 | 86 | 87 | print '
';
88 | print_r($video);
89 | print '
'; 90 | 91 | print '
';
92 | print_r($video2);
93 | print '
'; 94 | 95 | print '
';
96 | print_r($audio);
97 | print '
'; -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Filters/Audio/MergeFilter.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Filters\Audio; 9 | 10 | use FFMpeg\Exception\InvalidArgumentException; 11 | use FFMpeg\Format\AudioInterface; 12 | use Sharapov\FFMpegExtensions\Filters\Audio\MergeFilterOptions\OptionsCollection; 13 | use Sharapov\FFMpegExtensions\Input\FileInterface; 14 | use Sharapov\FFMpegExtensions\Media\Audio; 15 | 16 | class MergeFilter implements AudioFilterInterface { 17 | const STEREO_2_MONO = 10; 18 | const MONO_2_STEREO = 20; 19 | const ALL_2_STEREO = 30; 20 | const MUX_STEREO = 40; 21 | 22 | /** 23 | * @var \Sharapov\FFMpegExtensions\Filters\Audio\MergeFilterOptions\OptionsCollection 24 | */ 25 | private $_optionsCollection; 26 | 27 | private $_optionsPrepared; 28 | 29 | private $_extraInputs = []; 30 | 31 | private $_action; 32 | 33 | /** @var integer */ 34 | private $priority; 35 | 36 | /** 37 | * MergeFilter constructor. 38 | * 39 | * @param \Sharapov\FFMpegExtensions\Filters\Audio\MergeFilterOptions\OptionsCollection|null $optionsCollection 40 | * @param int $action 41 | */ 42 | public function __construct(OptionsCollection $optionsCollection = null, $action = self::STEREO_2_MONO) { 43 | if($optionsCollection instanceof OptionsCollection) { 44 | $this->setOptionsCollection($optionsCollection); 45 | } 46 | 47 | $this->setAction($action); 48 | } 49 | 50 | /** 51 | * @return mixed 52 | */ 53 | public function getAction() { 54 | return $this->_action; 55 | } 56 | 57 | /** 58 | * @param $action 59 | * 60 | * @return $this 61 | */ 62 | public function setAction($action) { 63 | switch($action) { 64 | case self::STEREO_2_MONO: 65 | $this->_action = $action; 66 | break; 67 | case self::MONO_2_STEREO: 68 | $this->_action = $action; 69 | break; 70 | case self::ALL_2_STEREO: 71 | $this->_action = $action; 72 | break; 73 | case self::MUX_STEREO: 74 | $this->_action = $action; 75 | break; 76 | default : 77 | throw new InvalidArgumentException('Invalid action type requested.'); 78 | } 79 | 80 | return $this; 81 | } 82 | 83 | /** 84 | * @return array 85 | */ 86 | public function getExtraInputs() { 87 | return $this->_extraInputs; 88 | } 89 | 90 | /** 91 | * @return int 92 | */ 93 | public function getPriority() { 94 | return $this->priority; 95 | } 96 | 97 | /** 98 | * @param \Sharapov\FFMpegExtensions\Media\Audio $audio 99 | * @param \FFMpeg\Format\AudioInterface $format 100 | * 101 | * @return array 102 | */ 103 | public function apply(Audio $audio, AudioInterface $format) { 104 | $commands = $inputsMapping = $inputs = []; 105 | $lastStreamId = null; 106 | 107 | if($this->getOptionsCollection()) { 108 | $firstStreamId = '0:a'; 109 | $lastStreamId = $firstStreamId; 110 | 111 | // Detect all additional inputs numbers 112 | for( 113 | $i = 0; $i <= $this 114 | ->getOptionsCollection() 115 | ->filterHasExtraInputs() 116 | ->count(); $i++ 117 | ) { 118 | $inputsMapping[] = sprintf('%s:a', $i); 119 | } 120 | } 121 | 122 | switch($this->_action) { 123 | case self::STEREO_2_MONO: 124 | $commands[] = '-ac'; 125 | $commands[] = '1'; 126 | break; 127 | case self::MONO_2_STEREO: 128 | $imn = 1; 129 | $stm = 1; 130 | if($this->getOptionsCollection()) { 131 | foreach($this->getOptionsCollection() as $option) { 132 | /** @var \Sharapov\FFMpegExtensions\Filters\Audio\MergeFilterOptions\OptionAudioFile $option */ 133 | $this->_optionsPrepared[] = 134 | str_replace([ 135 | ':s1', 136 | ':s2', 137 | ':s3' 138 | ], [ 139 | $lastStreamId, 140 | $inputsMapping[$imn], 141 | 's' . $stm, 142 | ], $option->getCommandMono2Stereo()); 143 | 144 | $lastStreamId = 's' . $stm; 145 | $stm++; 146 | 147 | // Pass input paths to the separate array 148 | $this->setExtraInput($option->getExtraInputStream()); 149 | } 150 | } 151 | break; 152 | case self::ALL_2_STEREO: 153 | $commands[] = '-ac'; 154 | $commands[] = '2'; 155 | break; 156 | case self::MUX_STEREO: 157 | $imn = 1; 158 | $stm = 1; 159 | if($this->getOptionsCollection()) { 160 | foreach($this->getOptionsCollection() as $option) { 161 | /** @var \Sharapov\FFMpegExtensions\Filters\Audio\MergeFilterOptions\OptionAudioFile $option */ 162 | $this->_optionsPrepared[] = 163 | str_replace([ 164 | ':s1', 165 | ':s2', 166 | ':s3' 167 | ], [ 168 | $inputsMapping[$imn], 169 | $lastStreamId, 170 | 's' . $stm, 171 | ], $option->getCommandMuxStereo()); 172 | 173 | $lastStreamId = 's' . $stm; 174 | $stm++; 175 | 176 | // Pass input paths to the separate array 177 | $this->setExtraInput($option->getExtraInputStream()); 178 | } 179 | } 180 | break; 181 | default : 182 | } 183 | 184 | if(count($this->_optionsPrepared) > 0) { 185 | $commands = array_merge($inputs, [ 186 | '-filter_complex', 187 | rtrim(implode(',', $this->_optionsPrepared), '[' . $lastStreamId . ']') 188 | ]); 189 | } 190 | 191 | print_r($commands); 192 | 193 | return $commands; 194 | } 195 | 196 | /** 197 | * @return mixed 198 | */ 199 | public function getOptionsCollection() { 200 | return $this->_optionsCollection; 201 | } 202 | 203 | /** 204 | * @param \Sharapov\FFMpegExtensions\Filters\Audio\MergeFilterOptions\OptionsCollection $optionsCollection 205 | * 206 | * @return $this 207 | */ 208 | public function setOptionsCollection(OptionsCollection $optionsCollection) { 209 | $this->_optionsCollection = $optionsCollection; 210 | 211 | return $this; 212 | } 213 | 214 | /** 215 | * @param \Sharapov\FFMpegExtensions\Input\FileInterface $file 216 | * 217 | * @return $this 218 | */ 219 | public function setExtraInput(FileInterface $file) { 220 | $this->_extraInputs[] = '-i'; 221 | $this->_extraInputs[] = $file->getPath(); 222 | 223 | return $this; 224 | } 225 | } -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/FFMpeg.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions; 9 | 10 | use Alchemy\BinaryDriver\ConfigurationInterface; 11 | use Alchemy\BinaryDriver\Exception\ExecutionFailureException; 12 | use FFMpeg\Exception\InvalidArgumentException; 13 | use FFMpeg\Exception\RuntimeException; 14 | use FFMpeg\Driver\FFMpegDriver; 15 | use FFMpeg\Format\FormatInterface; 16 | use Psr\Log\LoggerInterface; 17 | use Sharapov\FFMpegExtensions\Input\FileInterface; 18 | use Sharapov\FFMpegExtensions\Media\Audio; 19 | use Sharapov\FFMpegExtensions\Media\CollectionInterface; 20 | use Sharapov\FFMpegExtensions\Media\Video; 21 | 22 | class FFMpeg { 23 | /** @var array */ 24 | private static $_mimes = [ 25 | 'video/quicktime', 26 | 'video/mpeg', 27 | 'video/mp4', 28 | 'audio/mpeg3', 29 | 'audio/x-mpeg-3', 30 | 'audio/mpeg', 31 | 'audio/wav', 32 | 'audio/x-wav', 33 | 'image/gif', 34 | 'image/png', 35 | 'image/bmp', 36 | 'image/x-windows-bmp', 37 | 'image/jpeg', 38 | 'image/pjpeg', 39 | 'application/x-font-ttf', 40 | 'application/font-sfnt', 41 | 'application/octet-stream', 42 | 'font/sfnt' 43 | ]; 44 | /** @var FFMpegDriver */ 45 | private $_driver; 46 | /** @var FFProbe */ 47 | private $_ffprobe; 48 | /** @var string */ 49 | private $_tmpDir; 50 | 51 | /** 52 | * FFMpeg constructor 53 | * 54 | * @param FFMpegDriver $ffmpeg 55 | * @param FFProbe $ffprobe 56 | */ 57 | public function __construct(FFMpegDriver $ffmpeg, FFProbe $ffprobe) { 58 | $this->_driver = $ffmpeg; 59 | $this->_ffprobe = $ffprobe; 60 | $this->setTempDirectory(getcwd() . '/data/tmp/'); 61 | } 62 | 63 | /** 64 | * Sets temporary directory 65 | * 66 | * @param $path 67 | */ 68 | public function setTempDirectory($path) { 69 | $this->_tmpDir = $path; 70 | 71 | if(!is_dir($this->_tmpDir)) { 72 | @mkdir($this->_tmpDir, 0755, true); 73 | } 74 | 75 | if(!is_dir($this->_tmpDir)) { 76 | throw new ExecutionFailureException('Cannot create a temporary directory.'); 77 | } 78 | } 79 | 80 | /** 81 | * Creates a new FFMpeg instance 82 | * 83 | * @param array|ConfigurationInterface $configuration 84 | * @param LoggerInterface $logger 85 | * @param FFProbe $probe 86 | * 87 | * @return FFMpeg 88 | */ 89 | public static function create($configuration = [], LoggerInterface $logger = null, FFProbe $probe = null) { 90 | if(null === $probe) { 91 | $probe = FFProbe::create($configuration, $logger, null); 92 | } 93 | 94 | return new static(FFMpegDriver::create($logger, $configuration), $probe); 95 | } 96 | 97 | /** 98 | * Set extra mime type 99 | * 100 | * @param $mime 101 | */ 102 | public static function setMime($mime) { 103 | self::$_mimes[] = $mime; 104 | } 105 | 106 | /** 107 | * Returns the list of supported mime types 108 | * @return array 109 | */ 110 | public static function getSupportedMimes() { 111 | return self::$_mimes; 112 | } 113 | 114 | /** 115 | * Sets FFMpeg driver 116 | * 117 | * @param FFMpegDriver $ffmpeg 118 | * 119 | * @return $this 120 | */ 121 | public function setFFMpegDriver(FFMpegDriver $ffmpeg) { 122 | $this->_driver = $ffmpeg; 123 | 124 | return $this; 125 | } 126 | 127 | /** 128 | * Opens a file in order to be processed. 129 | * 130 | * @param $file 131 | * 132 | * @return Audio|Video 133 | * @throws InvalidArgumentException 134 | * @throws RuntimeException 135 | */ 136 | public function open($file) { 137 | if(!$file instanceof FileInterface) { 138 | throw new InvalidArgumentException('Input object must implement FileInterface'); 139 | } 140 | 141 | if(null === $streams = $this->getFFProbe()->streams($file->getPath())) { 142 | throw new RuntimeException(sprintf('Unable to probe "%s".', $file->getPath())); 143 | } 144 | 145 | if(0 < count($streams->videos())) { 146 | return new Video($file, $this->getFFMpegDriver(), $this->getFFProbe()); 147 | } elseif(0 < count($streams->audios())) { 148 | return new Audio($file, $this->getFFMpegDriver(), $this->getFFProbe()); 149 | } 150 | 151 | throw new InvalidArgumentException('Unable to detect file format, only audio and video supported'); 152 | } 153 | 154 | /** 155 | * Gets FFProbe 156 | * @return FFProbe 157 | */ 158 | public function getFFProbe() { 159 | return $this->_ffprobe; 160 | } 161 | 162 | /** 163 | * Sets FFProbe 164 | * 165 | * @param FFProbe $ffprobe 166 | * 167 | * @return FFMpeg 168 | */ 169 | public function setFFProbe(FFProbe $ffprobe) { 170 | $this->_ffprobe = $ffprobe; 171 | 172 | return $this; 173 | } 174 | 175 | /** 176 | * Gets the ffmpeg driver. 177 | * @return FFMpegDriver 178 | */ 179 | public function getFFMpegDriver() { 180 | return $this->_driver; 181 | } 182 | 183 | /** 184 | * Concatenate two or more streams 185 | * 186 | * @param \Sharapov\FFMpegExtensions\Media\CollectionInterface $collection 187 | * @param string $outputPathFile 188 | * @param FormatInterface $format 189 | * 190 | * @return string 191 | */ 192 | public function concatenate(FormatInterface $format, CollectionInterface $collection, $outputPathFile) { 193 | if($collection->count() == 0) { 194 | throw new InvalidArgumentException('Collection is empty'); 195 | } 196 | 197 | /** 198 | * @see https://ffmpeg.org/ffmpeg-formats.html#concat 199 | * @see https://trac.ffmpeg.org/wiki/Concatenate 200 | */ 201 | $sourcesFile = $this->_tmpDir . uniqid('ffmpeg-concat-'); 202 | // Set the content of this file 203 | $fileStream = @fopen($sourcesFile, 'w'); 204 | 205 | if($fileStream === false) { 206 | throw new ExecutionFailureException('Cannot open a temporary file.'); 207 | } 208 | 209 | $sources = []; 210 | // Pre-encode each clip in collection 211 | foreach($collection as $i => $item) { 212 | if($item instanceof Video) { 213 | $tmpFile = 'ffmpeg-' . uniqid(md5(time()) . '-') . '.mp4'; 214 | $item 215 | ->save($format, $this->_tmpDir . $tmpFile); 216 | $sources[] = $this->_tmpDir . $tmpFile; 217 | fwrite($fileStream, "file " . $tmpFile . "\n"); 218 | } 219 | } 220 | fclose($fileStream); 221 | 222 | // Execute the command 223 | try { 224 | $this->_driver->command([ 225 | '-y', 226 | '-f', 227 | 'concat', 228 | '-safe', 229 | '0', 230 | '-i', 231 | $sourcesFile, 232 | '-c', 233 | 'copy', 234 | $outputPathFile 235 | ]); 236 | } catch (ExecutionFailureException $e) { 237 | $this->_cleanupTemporaryFile($outputPathFile); 238 | $this->_cleanupTemporaryFile($sourcesFile); 239 | $this->_cleanupTemporaryFile($sources); 240 | throw new RuntimeException('Unable to save concatenated video', $e->getCode(), $e); 241 | } 242 | 243 | $this->_cleanupTemporaryFile($sources); 244 | $this->_cleanupTemporaryFile($sourcesFile); 245 | 246 | return $outputPathFile; 247 | } 248 | 249 | /** 250 | * Cleanup temporary files 251 | * 252 | * @param $filename 253 | * 254 | * @return $this 255 | */ 256 | private function _cleanupTemporaryFile($filename) { 257 | if(is_array($filename)) { 258 | foreach($filename as $file) { 259 | $this->_cleanupTemporaryFile($file); 260 | } 261 | } else { 262 | if(file_exists($filename) && is_writable($filename)) { 263 | unlink($filename); 264 | } 265 | } 266 | 267 | return $this; 268 | } 269 | } 270 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Media/Video.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Media; 9 | 10 | use Alchemy\BinaryDriver\Exception\ExecutionFailureException; 11 | use FFMpeg\Exception\InvalidArgumentException; 12 | use FFMpeg\Exception\RuntimeException; 13 | use FFMpeg\Filters\Audio\SimpleFilter; 14 | use FFMpeg\Format\AudioInterface; 15 | use FFMpeg\Format\FormatInterface; 16 | use FFMpeg\Format\ProgressableInterface; 17 | use Sharapov\FFMpegExtensions\Format\VideoInterface; 18 | use Neutron\TemporaryFilesystem\Manager as FsManager; 19 | use Sharapov\FFMpegExtensions\Filters\Video\VideoFilters; 20 | 21 | class Video extends \FFMpeg\Media\Video { 22 | use MediaTypeTrait; 23 | 24 | /** @var array */ 25 | private $options = [ 26 | 'preset' => null, 27 | 'muxdelay' => null 28 | ]; 29 | 30 | /** @var array */ 31 | private $supportedPresets = [ 32 | 'ultrafast', 33 | 'superfast', 34 | 'veryfast', 35 | 'faster', 36 | 'fast', 37 | 'medium', 38 | 'slow', 39 | 'slower', 40 | 'veryslow' 41 | ]; 42 | 43 | /** 44 | * {@inheritdoc} 45 | * @return VideoFilters 46 | */ 47 | public function filters() { 48 | return new VideoFilters($this); 49 | } 50 | 51 | /** 52 | * Exports the video in the desired format, applies registered filters. 53 | * 54 | * @param FormatInterface $format 55 | * @param string $outputPathFile 56 | * 57 | * @return Video 58 | * @throws RuntimeException 59 | */ 60 | public function save(FormatInterface $format, $outputPathFile) { 61 | $commands = ['-y', '-i', $this->pathfile]; 62 | 63 | $filters = clone $this->filters; 64 | $extraFilters = []; 65 | 66 | foreach($filters as $filter) { 67 | // Video filter options must be attached after all the extra input streams 68 | if($filter instanceof \Sharapov\FFMpegExtensions\Filters\Video\VideoFilterInterface) { 69 | /** @var VideoInterface $format */ 70 | $extraFilters = array_merge($extraFilters, $filter->apply($this, $format)); 71 | } 72 | // If filter has extra input streams, we need to attach them into the command 73 | if(count($filter->getExtraInputs()) > 0) { 74 | $commands = array_merge($commands, $filter->getExtraInputs()); 75 | } 76 | } 77 | 78 | $commands = array_merge($commands, $extraFilters); 79 | 80 | $filters->add(new SimpleFilter($format->getExtraParams(), 10)); 81 | 82 | if($this->driver->getConfiguration()->has('ffmpeg.threads')) { 83 | $filters->add(new SimpleFilter(['-threads', $this->driver->getConfiguration()->get('ffmpeg.threads')])); 84 | } 85 | if($format instanceof VideoInterface) { 86 | if(null !== $format->getVideoCodec()) { 87 | $filters->add(new SimpleFilter(['-vcodec', $format->getVideoCodec()])); 88 | } 89 | } 90 | if($format instanceof AudioInterface) { 91 | if(null !== $format->getAudioCodec()) { 92 | $filters->add(new SimpleFilter(['-acodec', $format->getAudioCodec()])); 93 | } 94 | } 95 | 96 | foreach($filters as $filter) { 97 | if(!$filter instanceof \Sharapov\FFMpegExtensions\Filters\Video\VideoFilterInterface) { 98 | $commands = array_merge($commands, $filter->apply($this, $format)); 99 | } 100 | } 101 | 102 | if($format instanceof VideoInterface) { 103 | if($this->getPreset() !== null) { 104 | $commands[] = '-preset'; 105 | $commands[] = $this->getPreset(); 106 | } else { 107 | $commands[] = '-b:v'; 108 | $commands[] = $format->getKiloBitrate() . 'k'; 109 | $commands[] = '-refs'; 110 | $commands[] = '6'; 111 | $commands[] = '-coder'; 112 | $commands[] = '1'; 113 | $commands[] = '-sc_threshold'; 114 | $commands[] = '40'; 115 | $commands[] = '-flags'; 116 | $commands[] = '+loop'; 117 | $commands[] = '-me_range'; 118 | $commands[] = '16'; 119 | $commands[] = '-subq'; 120 | $commands[] = '7'; 121 | $commands[] = '-i_qfactor'; 122 | $commands[] = '0.71'; 123 | $commands[] = '-qcomp'; 124 | $commands[] = '0.6'; 125 | $commands[] = '-qdiff'; 126 | $commands[] = '4'; 127 | $commands[] = '-trellis'; 128 | $commands[] = '1'; 129 | } 130 | 131 | if($this->getMuxdelay() !== null) { 132 | $commands[] = '-muxdelay'; 133 | $commands[] = $this->getMuxdelay(); 134 | } 135 | 136 | if($format->getConstantRateFactor() !== null) { 137 | $commands[] = '-crf'; 138 | $commands[] = $format->getConstantRateFactor(); 139 | } 140 | } 141 | 142 | if($format instanceof AudioInterface && $format->getAudioCodec() != 'copy') { 143 | if(null !== $format->getAudioKiloBitrate()) { 144 | $commands[] = '-b:a'; 145 | $commands[] = $format->getAudioKiloBitrate() . 'k'; 146 | } 147 | if(null !== $format->getAudioChannels()) { 148 | $commands[] = '-ac'; 149 | $commands[] = $format->getAudioChannels(); 150 | } 151 | } 152 | 153 | $fs = FsManager::create(); 154 | $fsId = uniqid('ffmpeg-passes'); 155 | $passPrefix = $fs->createTemporaryDirectory(0777, 50, $fsId) . '/' . uniqid('pass-'); 156 | $passes = []; 157 | $totalPasses = $format->getPasses(); 158 | 159 | if(1 > $totalPasses) { 160 | throw new InvalidArgumentException('Pass number should be a positive value.'); 161 | } 162 | 163 | for($i = 1; $i <= $totalPasses; $i++) { 164 | $pass = $commands; 165 | 166 | if($totalPasses > 1) { 167 | $pass[] = '-pass'; 168 | $pass[] = $i; 169 | $pass[] = '-passlogfile'; 170 | $pass[] = $passPrefix; 171 | } 172 | 173 | $pass[] = $outputPathFile; 174 | 175 | $passes[] = $pass; 176 | } 177 | 178 | $failure = null; 179 | 180 | foreach($passes as $pass => $passCommands) { 181 | try { 182 | /** add listeners here */ 183 | $listeners = null; 184 | 185 | if($format instanceof ProgressableInterface) { 186 | $listeners = $format->createProgressListener($this, $this->ffprobe, $pass + 1, $totalPasses); 187 | } 188 | 189 | $this->driver->command($passCommands, false, $listeners); 190 | } catch (ExecutionFailureException $e) { 191 | $failure = $e; 192 | break; 193 | } 194 | } 195 | 196 | $fs->clean($fsId); 197 | 198 | if(null !== $failure) { 199 | throw new RuntimeException('Encoding failed', $failure->getCode(), $failure); 200 | } 201 | 202 | return $this; 203 | } 204 | 205 | /** 206 | * @return mixed 207 | */ 208 | public function getStreamDuration() { 209 | return $this->getStreams()->videos()->first()->get('duration'); 210 | } 211 | 212 | /** 213 | * TODO: need refactor and moving to separate options class 214 | * @param $preset 215 | */ 216 | public function setPreset($preset) { 217 | if(!in_array($preset, $this->supportedPresets)) { 218 | throw new InvalidArgumentException('Preset type doesn\'t supported. Supported types: ' . implode(', ', $this->supportedPresets) . '.'); 219 | } 220 | 221 | $this->options['preset'] = $preset; 222 | } 223 | 224 | /** 225 | * TODO: need refactor and moving to separate options class 226 | * @return mixed 227 | */ 228 | public function getPreset() { 229 | return ($this->options['preset'] !== null) ? $this->options['preset'] : null; 230 | } 231 | 232 | /** 233 | * TODO: need refactor and moving to separate options class 234 | * @param $delay 235 | */ 236 | public function setMuxdelay($delay) { 237 | if(!is_numeric($delay) || $delay < 0) { 238 | throw new InvalidArgumentException('Muxdelay should be integer or float value. ' . $delay . ' given.'); 239 | } 240 | 241 | $this->options['muxdelay'] = $delay; 242 | } 243 | 244 | /** 245 | * TODO: need refactor and moving to separate options class 246 | * @return mixed 247 | */ 248 | public function getMuxdelay() { 249 | return ($this->options['muxdelay'] !== null) ? $this->options['muxdelay'] : null; 250 | } 251 | } 252 | -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Filters/Video/ComplexFilter.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Filters\Video; 9 | 10 | use FFMpeg\Format\VideoInterface; 11 | use Sharapov\FFMpegExtensions\Coordinate\Duration; 12 | use Sharapov\FFMpegExtensions\Coordinate\TimeLine; 13 | use Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions\OptionAlphakey; 14 | use Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions\OptionChromakey; 15 | use Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions\OptionDrawText; 16 | use Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions\OptionDrawBox; 17 | use Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions\OptionOverlay; 18 | use Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions\OptionsCollection; 19 | use Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions\OptionInterface; 20 | use Sharapov\FFMpegExtensions\Input\FileInterface; 21 | use Sharapov\FFMpegExtensions\Media\Video; 22 | 23 | class ComplexFilter implements VideoFilterInterface { 24 | /** 25 | * @var OptionsCollection 26 | */ 27 | private $_optionsCollection; 28 | 29 | private $_optionsPrepared; 30 | 31 | private $_extraInputs = []; 32 | 33 | /** 34 | * @var integer 35 | */ 36 | private $priority; 37 | 38 | /** 39 | * ComplexFilter constructor. 40 | * 41 | * @param OptionsCollection|null $optionsCollection 42 | */ 43 | public function __construct(OptionsCollection $optionsCollection = null) { 44 | if($optionsCollection instanceof OptionsCollection) { 45 | $this->setOptionsCollection($optionsCollection); 46 | } 47 | } 48 | 49 | /** 50 | * {@inheritdoc} 51 | */ 52 | public function getExtraInputs() { 53 | return $this->_extraInputs; 54 | } 55 | 56 | /** 57 | * {@inheritdoc} 58 | */ 59 | public function getPriority() { 60 | return $this->priority; 61 | } 62 | 63 | /** 64 | * {@inheritdoc} 65 | */ 66 | public function apply(Video $video, VideoInterface $format) { 67 | $firstStreamId = '0:v'; 68 | $lastStreamId = $firstStreamId; 69 | $inputsMapping = $inputs = []; 70 | // Detect all additional inputs numbers 71 | for( 72 | $i = 0; $i <= $this 73 | ->getOptionsCollection() 74 | ->filterHasExtraInputs() 75 | ->count(); $i++ 76 | ) { 77 | $inputsMapping[] = sprintf('%s:v', $i); 78 | } 79 | 80 | // Prepare overlay inputs 81 | $optionsOverlay = $this->getOptionsCollection()->sortByZindex(); 82 | $imn = 1; 83 | $stm = 1; 84 | if($optionsOverlay->count() > 0) { 85 | foreach($optionsOverlay as $option) { 86 | if($option instanceof OptionDrawText) { 87 | $option 88 | ->setVideoStream($video); 89 | $this->_optionsPrepared[] = 90 | str_replace([ 91 | ':s1', 92 | ':s2' 93 | ], [ 94 | $lastStreamId, 95 | 's' . $stm 96 | ], $option->getCommand()); 97 | 98 | $lastStreamId = 's' . $stm; 99 | 100 | } elseif($option instanceof OptionDrawBox) { 101 | $option 102 | ->setVideoStream($video); 103 | $this->_optionsPrepared[] = 104 | str_replace([ 105 | ':s1', 106 | ':s2' 107 | ], [ 108 | $lastStreamId, 109 | 's' . $stm 110 | ], $option->getCommand()); 111 | 112 | $lastStreamId = 's' . $stm; 113 | 114 | } elseif($option instanceof OptionOverlay) { 115 | 116 | $this->_optionsPrepared[] = 117 | str_replace([ 118 | ':s1', 119 | ':s2', 120 | ':s3', 121 | ':s4', 122 | ':s5', 123 | '{VIDEO_LENGTH}' 124 | ], [ 125 | $inputsMapping[$imn], 126 | 't' . ($imn), 127 | $lastStreamId, 128 | 't' . $imn, 129 | 's' . $stm, 130 | ($video->getStreamDuration() - $option->getFadeOut()) 131 | ], $option->getCommand()); 132 | // We need to save last stream id to apply next options in the correct order 133 | $lastStreamId = 's' . $stm; 134 | // For image overlay we have to add -loop 1 before input 135 | if($option->isStaticImage()) { 136 | $this->_extraInputs[] = '-loop'; 137 | $this->_extraInputs[] = '1'; 138 | } 139 | 140 | if($option->isAnimatedGif() or $option->isAnimatedPng()) { 141 | $this->_extraInputs[] = '-ignore_loop'; 142 | $this->_extraInputs[] = '0'; 143 | } 144 | 145 | // Pass input paths to the separate array 146 | $this->setExtraInput($option->getExtraInputStream()); 147 | $imn++; 148 | 149 | } elseif($option instanceof OptionChromakey) { 150 | 151 | $this->_optionsPrepared[] = 152 | str_replace([ 153 | ':s1', 154 | ':s2', 155 | ':s3' 156 | ], [ 157 | $lastStreamId, 158 | $inputsMapping[$imn], 159 | 's' . $stm 160 | ], $option->getCommand()); 161 | // We need to get a last stream id to apply next options in the correct order 162 | $lastStreamId = 's' . $stm; 163 | // Pass input paths to the separate array 164 | $this->setExtraInput($option->getExtraInputStream()); 165 | $imn++; 166 | 167 | } elseif($option instanceof OptionAlphakey) { 168 | 169 | $this->_optionsPrepared[] = 170 | str_replace([ 171 | ':s1', 172 | ':s2', 173 | ':s3' 174 | ], [ 175 | $lastStreamId, 176 | $inputsMapping[$imn], 177 | 's' . $stm 178 | ], $option->getCommand()); 179 | // We need to get a last stream id to apply next options in the correct order 180 | $lastStreamId = 's' . $stm; 181 | 182 | if($option->getDuration() instanceof Duration) { 183 | $duration = explode(" ", $option->getDuration()); 184 | } else { 185 | $duration = null; 186 | } 187 | 188 | // Pass input paths to the separate array 189 | $this->setExtraInput($option->getExtraInputStream(), $duration); 190 | $imn++; 191 | 192 | } else { 193 | } 194 | $stm++; 195 | } 196 | } 197 | 198 | if(count($this->_optionsPrepared) > 0) { 199 | $commands = array_merge($inputs, [ 200 | '-filter_complex', 201 | //rtrim(implode(',', $this->_optionsPrepared), '[' . $lastStreamId . ']') 202 | str_replace('[' . $lastStreamId . ']', '', implode(',', $this->_optionsPrepared)) 203 | ]); 204 | } else { 205 | $commands = []; 206 | } 207 | 208 | return $commands; 209 | } 210 | 211 | /** 212 | * @return OptionsCollection 213 | */ 214 | public function getOptionsCollection() { 215 | return $this->_optionsCollection; 216 | } 217 | 218 | /** 219 | * {@inheritdoc} 220 | */ 221 | public function setOptionsCollection(OptionsCollection $optionsCollection) { 222 | $this->_optionsCollection = $optionsCollection; 223 | } 224 | 225 | /** 226 | * {@inheritdoc} 227 | */ 228 | public function setExtraInput(FileInterface $file, array $options = null) { 229 | if($options) { 230 | foreach($options as $option) { 231 | $this->_extraInputs[] = $option; 232 | } 233 | } 234 | $this->_extraInputs[] = '-i'; 235 | $this->_extraInputs[] = $file->getPath(); 236 | } 237 | } -------------------------------------------------------------------------------- /src/php-ffmpeg-extensions/Filters/Video/FilterComplexOptions/OptionDrawText.php: -------------------------------------------------------------------------------- 1 | 5 | * http://sharapov.biz/ 6 | */ 7 | 8 | namespace Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions; 9 | 10 | use FFMpeg\Exception\InvalidArgumentException; 11 | use Sharapov\FFMpegExtensions\Coordinate\TimeLine; 12 | use Sharapov\FFMpegExtensions\Input\FileInterface; 13 | use Sharapov\FFMpegExtensions\Media\Video; 14 | 15 | /** 16 | * DrawText filter option 17 | * @package Sharapov\FFMpegExtensions\Filters\Video\FilterComplexOptions 18 | */ 19 | class OptionDrawText implements OptionInterface { 20 | use TimeLineTrait; 21 | use FadeInOutTrait; 22 | use CoordinatesTrait; 23 | use ZindexTrait; 24 | 25 | protected $_fontFile; 26 | 27 | protected $_fontSize = 20; 28 | 29 | protected $_fontColor = '#000000'; 30 | 31 | protected $_text = 'Default text'; 32 | 33 | protected $_boundingBox; 34 | 35 | protected $_textShadow; 36 | 37 | protected $_textBorder; 38 | 39 | protected $_escapeSymbols = [ 40 | ':' => '\:' 41 | ]; 42 | 43 | /** 44 | * @var Video 45 | */ 46 | protected $_video; 47 | 48 | /** 49 | * Set video stream 50 | * 51 | * @param Video $video 52 | * 53 | * @return $this 54 | */ 55 | public function setVideoStream(Video $video) { 56 | $this->_video = $video; 57 | 58 | return $this; 59 | } 60 | 61 | /** 62 | * Get pairs to escape. 63 | * @return array 64 | */ 65 | public function getEscapeSymbols() { 66 | return $this->_escapeSymbols; 67 | } 68 | 69 | /** 70 | * Set pairs to escape. 71 | * 72 | * @param array $pairs 73 | * 74 | * @return $this 75 | */ 76 | public function setEscapeSymbols(array $pairs) { 77 | $this->_escapeSymbols = $pairs; 78 | 79 | return $this; 80 | } 81 | 82 | /** 83 | * Returns text shadow value. 84 | * @return mixed 85 | */ 86 | public function getTextShadow() { 87 | return $this->_textShadow; 88 | } 89 | 90 | /** 91 | * The color to be used for drawing a shadow behind the drawn text. 92 | * The x and y offsets for the text shadow position with respect to the position of the text. They can be either 93 | * positive or negative values. 94 | * 95 | * @param $color 96 | * @param int $x 97 | * @param int $y 98 | * @param int $transparency 99 | * 100 | * @return $this 101 | */ 102 | public function setTextShadow($color, $x = 0, $y = 0, $transparency = 1) { 103 | if(!is_numeric($transparency) || $transparency < 0 || $transparency > 1) { 104 | throw new InvalidArgumentException('Transparency should be integer or float value from 0 to 1. ' . $transparency . ' given.'); 105 | } 106 | 107 | if(!is_numeric($x) or !is_numeric($y)) { 108 | throw new InvalidArgumentException('Shadow X and Y should be either positive or negative values. ' . $x . ', ' . $y . ' given.'); 109 | } 110 | 111 | $this->_textShadow = [ 112 | "shadowcolor='" . $color . "'@" . $transparency, 113 | "shadowx=" . $x, 114 | "shadowy=" . $y 115 | ]; 116 | 117 | return $this; 118 | } 119 | 120 | /** 121 | * Returns text border value. 122 | * @return mixed 123 | */ 124 | public function getTextBorder() { 125 | return $this->_textBorder; 126 | } 127 | 128 | /** 129 | * Set the color to be used for drawing border around text. 130 | * 131 | * @param $color 132 | * @param int $border 133 | * @param int $transparency 134 | * 135 | * @return $this 136 | */ 137 | public function setTextBorder($color, $border = 2, $transparency = 1) { 138 | if(!is_numeric($transparency) || $transparency < 0 || $transparency > 1) { 139 | throw new InvalidArgumentException('Transparency should be integer or float value from 0 to 1. ' . $transparency . ' given.'); 140 | } 141 | 142 | if(!is_integer($border)) { 143 | throw new InvalidArgumentException('Border should be positive integer. ' . $border . ' given.'); 144 | } 145 | 146 | $this->_textBorder = [ 147 | "bordercolor='" . $color . "'@" . $transparency, 148 | "borderw=" . $border 149 | ]; 150 | 151 | return $this; 152 | } 153 | 154 | /** 155 | * Returns box color value. 156 | * @return mixed 157 | */ 158 | public function getBoundingBox() { 159 | return $this->_boundingBox; 160 | } 161 | 162 | /** 163 | * The color to be used for drawing box around text. 164 | * 165 | * @param $color 166 | * @param int $border 167 | * @param int $transparency 168 | * 169 | * @return $this 170 | */ 171 | public function setBoundingBox($color, $border = 10, $transparency = 1) { 172 | if(!is_numeric($transparency) || $transparency < 0 || $transparency > 1) { 173 | throw new InvalidArgumentException('Transparency should be integer or float value from 0 to 1. ' . $transparency . ' given.'); 174 | } 175 | 176 | if(!is_integer($border)) { 177 | throw new InvalidArgumentException('Border should be positive integer. ' . $border . ' given.'); 178 | } 179 | 180 | $color = ltrim($color, '#'); 181 | $color = str_pad($color, 6, 0, STR_PAD_RIGHT); 182 | if(!preg_match('/^[a-f0-9]{6}$/i', $color)) { 183 | throw new InvalidArgumentException('Color should be HEX string. ' . $color . ' given.'); 184 | } 185 | 186 | $this->_boundingBox = [ 187 | "boxcolor='" . $color . "'@" . $transparency, 188 | "boxborderw=" . $border 189 | ]; 190 | 191 | return $this; 192 | } 193 | 194 | /** 195 | * Returns a command string. 196 | * @return string 197 | */ 198 | public function __toString() { 199 | return $this->getCommand(); 200 | } 201 | 202 | /** 203 | * Returns command string. 204 | * @return string 205 | */ 206 | public function getCommand() { 207 | $options = [ 208 | "fontfile=" . $this->getFontFile()->getPath(), 209 | "text='" . $this->_escapeSymbols() . "'", 210 | "fontcolor='" . $this->getFontColor() . "'", 211 | "fontsize=" . $this->getFontSize(), 212 | "x=" . $this->getCoordinates()->getX(), 213 | "y=" . $this->getCoordinates()->getY() 214 | ]; 215 | 216 | if($this->_fadeInSeconds == null) { 217 | $this->_fadeInSeconds = 0; 218 | } 219 | 220 | if($this->_fadeOutSeconds == null) { 221 | $this->_fadeOutSeconds = 0; 222 | } 223 | 224 | // If specific timeline is not provided for the drawtext, we must apply drawtext for the whole video 225 | if(!$this->_timeLine instanceof TimeLine) { 226 | $this->setTimeLine(new TimeLine(0, $this->getVideoStream()->getStreamDuration())); 227 | } 228 | 229 | /** 230 | * FadeIn and Out 231 | * t1 - fade in start time (in seconds) 232 | * t2 - fade in length (in seconds) 233 | * t3 - time to keep fully opaque (in seconds) 234 | * t4 - fade out length (in seconds) 235 | * More manuals 236 | * @link http://ffmpeg.shanewhite.co/ 237 | * @link http://noizeramp.com/2016/10/19/ffmpeg-fade-in-out-expressions/ 238 | */ 239 | $fadeTime = sprintf(":alpha='if(lt(t,%s),0,if(lt(t,%s),(t-%s)/%s,if(lt(t,%s),1,if(lt(t,%s),(%s-(t-%s))/%s,0))))'", $this->getTimeLine()->getStartTime(), ($this->getTimeLine()->getStartTime() + $this->_fadeInSeconds), $this->getTimeLine()->getStartTime(), $this->_fadeInSeconds, ($this->getTimeLine()->getStartTime() + $this->_fadeInSeconds + $this->getTimeLine()->getEndTime()), ($this->getTimeLine()->getStartTime() + $this->_fadeInSeconds + $this->getTimeLine()->getEndTime() + $this->_fadeOutSeconds), $this->_fadeOutSeconds, ($this->getTimeLine()->getStartTime() + $this->_fadeInSeconds + $this->getTimeLine()->getEndTime()), $this->_fadeOutSeconds); 240 | 241 | // Bounding box 242 | if($this->_boundingBox != null) { 243 | $options[] = "box=1:" . implode(":", $this->_boundingBox); 244 | } 245 | 246 | // Text shadow 247 | if($this->_textShadow != null) { 248 | $options[] = implode(":", $this->_textShadow); 249 | } 250 | 251 | // Text border 252 | if($this->_textBorder != null) { 253 | $options[] = implode(":", $this->_textBorder); 254 | } 255 | 256 | return sprintf("[%s]drawtext=%s%s[%s]", ':s1', implode(":", $options), $fadeTime, ':s2'); 257 | } 258 | 259 | /** 260 | * Get path. 261 | * @return mixed 262 | */ 263 | public function getFontFile() { 264 | if(!$this->_fontFile instanceof FileInterface) { 265 | throw new InvalidArgumentException('Font is undefined.'); 266 | } 267 | 268 | return $this->_fontFile; 269 | } 270 | 271 | /** 272 | * Set path to font file. 273 | * 274 | * @param $file 275 | * 276 | * @return $this 277 | */ 278 | public function setFontFile(FileInterface $file) { 279 | $this->_fontFile = $file; 280 | 281 | return $this; 282 | } 283 | 284 | /** 285 | * Replaces special symbols. 286 | * @return string 287 | */ 288 | private function _escapeSymbols() { 289 | return strtr($this->getText(), $this->_escapeSymbols); 290 | } 291 | 292 | /** 293 | * Get text. 294 | * @return string 295 | */ 296 | public function getText() { 297 | return $this->_text; 298 | } 299 | 300 | /** 301 | * Set text to be overlapped. 302 | * 303 | * @param $text 304 | * 305 | * @return $this 306 | */ 307 | public function setText($text) { 308 | $this->_text = $text; 309 | 310 | return $this; 311 | } 312 | 313 | /** 314 | * Get font color. 315 | * @return string 316 | */ 317 | public function getFontColor() { 318 | return $this->_fontColor; 319 | } 320 | 321 | /** 322 | * Set font color. 323 | * 324 | * @param $color 325 | * @param int $transparency 326 | * 327 | * @return $this 328 | */ 329 | public function setFontColor($color, $transparency = 1) { 330 | if(!is_numeric($transparency) || $transparency < 0 || $transparency > 1) { 331 | throw new InvalidArgumentException('Transparency should be integer or float value from 0 to 1. ' . $transparency . ' given.'); 332 | } 333 | 334 | $color = ltrim($color, '#'); 335 | $color = str_pad($color, 6, 0, STR_PAD_RIGHT); 336 | if(!preg_match('/^[a-f0-9]{6}$/i', $color)) { 337 | throw new InvalidArgumentException('Color should be HEX string. ' . $color . ' given.'); 338 | } 339 | 340 | $this->_fontColor = $color . '@' . $transparency; 341 | 342 | return $this; 343 | } 344 | 345 | /** 346 | * Get font size. 347 | * @return int 348 | */ 349 | public function getFontSize() { 350 | return $this->_fontSize; 351 | } 352 | 353 | /** 354 | * Set font size. 355 | * 356 | * @param $size 357 | * 358 | * @return $this 359 | */ 360 | public function setFontSize($size) { 361 | $this->_fontSize = (int)$size; 362 | 363 | return $this; 364 | } 365 | 366 | /** 367 | * @return Video 368 | */ 369 | public function getVideoStream() { 370 | return $this->_video; 371 | } 372 | } 373 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------