scratch – Blame information for rev 115

Subversion Repositories:
Rev:
Rev Author Line No. Line
115 office 1 # PHP FFmpeg
2  
3 [![Build Status](https://secure.travis-ci.org/PHP-FFMpeg/PHP-FFMpeg.png?branch=master)](http://travis-ci.org/PHP-FFMpeg/PHP-FFMpeg)
4  
5 [![SensioLabsInsight](https://insight.sensiolabs.com/projects/607f3111-e2d7-44e8-8bcc-54dd64521983/big.png)](https://insight.sensiolabs.com/projects/607f3111-e2d7-44e8-8bcc-54dd64521983)
6  
7 An Object Oriented library to convert video/audio files with FFmpeg / AVConv.
8  
9 Check another amazing repo: [PHP FFMpeg extras](https://github.com/alchemy-fr/PHP-FFMpeg-Extras), you will find lots of Audio/Video formats there.
10  
11 ## Your attention please
12  
13 ### How this library works:
14  
15 This library requires a working FFMpeg install. You will need both FFMpeg and FFProbe binaries to use it.
16 Be sure that these binaries can be located with system PATH to get the benefit of the binary detection,
17 otherwise you should have to explicitly give the binaries path on load.
18  
19 For Windows users : Please find the binaries at http://ffmpeg.zeranoe.com/builds/.
20  
21 ### Known issues:
22  
23 - Using rotate and resize will produce a corrupted output when using
24 [libav](http://libav.org/) 0.8. The bug is fixed in version 9. This bug does not
25 appear in latest ffmpeg version.
26  
27 ## Installation
28  
29 The recommended way to install PHP-FFMpeg is through [Composer](https://getcomposer.org).
30  
31 ```bash
32 $ composer require php-ffmpeg/php-ffmpeg
33 ```
34  
35 ## Basic Usage
36  
37 ```php
38 $ffmpeg = FFMpeg\FFMpeg::create();
39 $video = $ffmpeg->open('video.mpg');
40 $video
41 ->filters()
42 ->resize(new FFMpeg\Coordinate\Dimension(320, 240))
43 ->synchronize();
44 $video
45 ->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(10))
46 ->save('frame.jpg');
47 $video
48 ->save(new FFMpeg\Format\Video\X264(), 'export-x264.mp4')
49 ->save(new FFMpeg\Format\Video\WMV(), 'export-wmv.wmv')
50 ->save(new FFMpeg\Format\Video\WebM(), 'export-webm.webm');
51 ```
52  
53 ## Documentation
54  
55 This documentation is an introduction to discover the API. It's recommended
56 to browse the source code as it is self-documented.
57  
58 ### FFMpeg
59  
60 `FFMpeg\FFMpeg` is the main object to use to manipulate medias. To build it,
61 use the static `FFMpeg\FFMpeg::create`:
62  
63 ```php
64 $ffmpeg = FFMpeg\FFMpeg::create();
65 ```
66  
67 FFMpeg will autodetect ffmpeg and ffprobe binaries. If you want to give binary
68 paths explicitly, you can pass an array as configuration. A `Psr\Logger\LoggerInterface`
69 can also be passed to log binary executions.
70  
71 ```php
72 $ffmpeg = FFMpeg\FFMpeg::create(array(
73 'ffmpeg.binaries' => '/opt/local/ffmpeg/bin/ffmpeg',
74 'ffprobe.binaries' => '/opt/local/ffmpeg/bin/ffprobe',
75 'timeout' => 3600, // The timeout for the underlying process
76 'ffmpeg.threads' => 12, // The number of threads that FFMpeg should use
77 ), $logger);
78 ```
79  
80 ### Manipulate media
81  
82 `FFMpeg\FFMpeg` creates media based on URIs. URIs could be either a pointer to a
83 local filesystem resource, an HTTP resource or any resource supported by FFmpeg.
84  
85 **Note**: To list all supported resource type of your FFmpeg build, use the
86 `-protocols` command:
87  
88 ```
89 ffmpeg -protocols
90 ```
91  
92 To open a resource, use the `FFMpeg\FFMpeg::open` method.
93  
94 ```php
95 $ffmpeg->open('video.mpeg');
96 ```
97  
98 Two types of media can be resolved: `FFMpeg\Media\Audio` and `FFMpeg\Media\Video`.
99 A third type, `FFMpeg\Media\Frame`, is available through videos.
100  
101 ### Video
102  
103 `FFMpeg\Media\Video` can be transcoded, ie: change codec, isolate audio or
104 video. Frames can be extracted.
105  
106 ##### Transcoding
107  
108 You can transcode videos using the `FFMpeg\Media\Video:save` method. You will
109 pass a `FFMpeg\Format\FormatInterface` for that.
110  
111 Please note that audio and video bitrate are set on the format.
112  
113 ```php
114 $format = new FFMpeg\Format\Video\X264();
115 $format->on('progress', function ($video, $format, $percentage) {
116 echo "$percentage % transcoded";
117 });
118  
119 $format
120 ->setKiloBitrate(1000)
121 ->setAudioChannels(2)
122 ->setAudioKiloBitrate(256);
123  
124 $video->save($format, 'video.avi');
125 ```
126  
127 Transcoding progress can be monitored in realtime, see Format documentation
128 below for more informations.
129  
130 ##### Extracting image
131  
132 You can extract a frame at any timecode using the `FFMpeg\Media\Video::frame`
133 method.
134  
135 This code returns a `FFMpeg\Media\Frame` instance corresponding to the second 42.
136 You can pass any `FFMpeg\Coordinate\TimeCode` as argument, see dedicated
137 documentation below for more information.
138  
139 ```php
140 $frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(42));
141 $frame->save('image.jpg');
142 ```
143  
144 If you want to extract multiple images from your video, you can use the following filter:
145  
146 ```php
147 $video
148 ->filters()
149 ->extractMultipleFrames(FFMpeg\Filters\Video\ExtractMultipleFramesFilter::FRAMERATE_EVERY_10SEC, '/path/to/destination/folder/')
150 ->synchronize();
151  
152 $video
153 ->save(new FFMpeg\Format\Video\X264(), '/path/to/new/file');
154 ```
155  
156 ##### Generate a waveform
157  
158 You can generate a waveform of an audio file using the `FFMpeg\Media\Audio::waveform`
159 method.
160  
161 This code returns a `FFMpeg\Media\Waveform` instance.
162 You can optionally pass dimensions as arguments, see dedicated
163 documentation below for more information.
164  
165 The ouput file MUST use the PNG extension.
166  
167 ```php
168 $waveform = $audio->waveform(640, 120);
169 $waveform->save('waveform.png');
170 ```
171  
172 If you want to get a waveform from a video, convert it in an audio file first.
173  
174 ```php
175 // Open your video file
176 $video = $ffmpeg->open( 'video.mp4' );
177  
178 // Set an audio format
179 $audio_format = new FFMpeg\Format\Audio\Mp3();
180  
181 // Extract the audio into a new file
182 $video->save('audio.mp3');
183  
184 // Set the audio file
185 $audio = $ffmpeg->open( 'audio.mp3' );
186  
187 // Create the waveform
188 $waveform = $audio->waveform();
189 $waveform->save( 'waveform.png' );
190 ```
191  
192 ##### Filters
193  
194 You can apply filters on `FFMpeg\Media\Video` with the `FFMpeg\Media\Video::addFilter`
195 method. Video accepts Audio and Video filters.
196  
197 You can build your own filters and some are bundled in PHP-FFMpeg - they are
198 accessible through the `FFMpeg\Media\Video::filters` method.
199  
200 Filters are chainable
201  
202 ```php
203 $video
204 ->filters()
205 ->resize($dimension, $mode, $useStandards)
206 ->framerate($framerate, $gop)
207 ->synchronize();
208 ```
209  
210 ###### Rotate
211  
212 Rotates a video to a given angle.
213  
214 ```php
215 $video->filters()->rotate($angle);
216 ```
217  
218 The `$angle` parameter must be one of the following constants :
219  
220 - `FFMpeg\Filters\Video\RotateFilter::ROTATE_90`: 90° clockwise
221 - `FFMpeg\Filters\Video\RotateFilter::ROTATE_180`: 180°
222 - `FFMpeg\Filters\Video\RotateFilter::ROTATE_270`: 90° counterclockwise
223  
224 ###### Resize
225  
226 Resizes a video to a given size.
227  
228 ```php
229 $video->filters()->resize($dimension, $mode, $useStandards);
230 ```
231  
232 The resize filter takes three parameters:
233  
234 - `$dimension`, an instance of `FFMpeg\Coordinate\Dimension`
235 - `$mode`, one of the constants `FFMpeg\Filters\Video\ResizeFilter::RESIZEMODE_*` constants
236 - `$useStandards`, a boolean to force the use of the nearest aspect ratio standard.
237  
238 If you want a video in a non-standard ratio, you can use the padding filter to resize your video in the desired size, and wrap it into black bars.
239  
240 ```php
241 $video->filters()->pad($dimension);
242 ```
243  
244 The pad filter takes one parameter:
245  
246 - `$dimension`, an instance of `FFMpeg\Coordinate\Dimension`
247  
248 Don't forget to save it afterwards.
249  
250 ```php
251 $video->save(new FFMpeg\Format\Video\X264(), $new_file);
252 ```
253  
254 ###### Watermark
255  
256 Watermark a video with a given image.
257  
258 ```php
259 $video
260 ->filters()
261 ->watermark($watermarkPath, array(
262 'position' => 'relative',
263 'bottom' => 50,
264 'right' => 50,
265 ));
266 ```
267  
268 The watermark filter takes two parameters:
269  
270 `$watermarkPath`, the path to your watermark file.
271 `$coordinates`, an array defining how you want your watermark positioned. You can use relative positioning as demonstrated above or absolute as such:
272  
273 ```php
274 $video
275 ->filters()
276 ->watermark($watermarkPath, array(
277 'position' => 'absolute',
278 'x' => 1180,
279 'y' => 620,
280 ));
281 ```
282  
283 ###### Framerate
284  
285 Changes the frame rate of the video.
286  
287 ```php
288 $video->filters()->framerate($framerate, $gop);
289 ```
290  
291 The framerate filter takes two parameters:
292  
293 - `$framerate`, an instance of `FFMpeg\Coordinate\Framerate`
294 - `$gop`, a [GOP](https://wikipedia.org/wiki/Group_of_pictures) value (integer)
295  
296 ###### Synchronize
297  
298 Synchronizes audio and video.
299  
300 Some containers may use a delay that results in desynchronized outputs. This
301 filters solves this issue.
302  
303 ```php
304 $video->filters()->synchronize();
305 ```
306  
307 ###### Clip
308  
309 Cuts the video at a desired point.
310  
311 ```php
312 $video->filters()->clip(FFMpeg\Coordinate\TimeCode::fromSeconds(30), FFMpeg\Coordinate\TimeCode::fromSeconds(15));
313 ```
314  
315 The clip filter takes two parameters:
316  
317 - `$start`, an instance of `FFMpeg\Coordinate\TimeCode`, specifies the start point of the clip
318 - `$duration`, optional, an instance of `FFMpeg\Coordinate\TimeCode`, specifies the duration of the clip
319  
320 ### Audio
321  
322 `FFMpeg\Media\Audio` can be transcoded too, ie: change codec, isolate audio or
323 video. Frames can be extracted.
324  
325 ##### Transcoding
326  
327 You can transcode audios using the `FFMpeg\Media\Audio:save` method. You will
328 pass a `FFMpeg\Format\FormatInterface` for that.
329  
330 Please note that audio kilobitrate is set on the audio format.
331  
332 ```php
333 $ffmpeg = FFMpeg\FFMpeg::create();
334 $audio = $ffmpeg->open('track.mp3');
335  
336 $format = new FFMpeg\Format\Audio\Flac();
337 $format->on('progress', function ($audio, $format, $percentage) {
338 echo "$percentage % transcoded";
339 });
340  
341 $format
342 ->setAudioChannels(2)
343 ->setAudioKiloBitrate(256);
344  
345 $audio->save($format, 'track.flac');
346 ```
347  
348 Transcoding progress can be monitored in realtime, see Format documentation
349 below for more informations.
350  
351 ##### Filters
352  
353 You can apply filters on `FFMpeg\Media\Audio` with the `FFMpeg\Media\Audio::addFilter`
354 method. It only accepts audio filters.
355  
356 You can build your own filters and some are bundled in PHP-FFMpeg - they are
357 accessible through the `FFMpeg\Media\Audio::filters` method.
358  
359 ##### Clipping
360 Cuts the audio at a desired point.
361  
362 ```php
363 $audio->filters()->clip(FFMpeg\Coordinate\TimeCode::fromSeconds(30), FFMpeg\Coordinate\TimeCode::fromSeconds(15));
364 ```
365  
366  
367 ###### Metadata
368  
369 Add metadata to audio files. Just pass an array of key=value pairs of all
370 metadata you would like to add. If no arguments are passed into the filter
371 all metadata will be removed from input file. Currently supported data is
372 title, artist, album, artist, composer, track, year, description, artwork
373  
374 ```php
375 $audio->filters()->addMetadata(["title" => "Some Title", "track" => 1]);
376  
377 //remove all metadata and video streams from audio file
378 $audio->filters()->addMetadata();
379 ```
380  
381 Add artwork to the audio file
382 ```php
383 $audio->filters()->addMetadata(["artwork" => "/path/to/image/file.jpg"]);
384 ```
385 NOTE: at present ffmpeg (version 3.2.2) only supports artwork output for .mp3
386 files
387  
388 ###### Resample
389  
390 Resamples an audio file.
391  
392 ```php
393 $audio->filters()->resample($rate);
394 ```
395  
396 The resample filter takes two parameters :
397  
398 - `$rate`, a valid audio sample rate value (integer)
399  
400 #### Frame
401  
402 A frame is a image at a timecode of a video ; see documentation above about
403 frame extraction.
404  
405 You can save frames using the `FFMpeg\Media\Frame::save` method.
406  
407 ```php
408 $frame->save('target.jpg');
409 ```
410  
411 This method has a second optional boolean parameter. Set it to true to get
412 accurate images ; it takes more time to execute.
413  
414 #### Gif
415  
416 A gif is an animated image extracted from a sequence of the video.
417  
418 You can save gif files using the `FFMpeg\Media\Gif::save` method.
419  
420 ```php
421 $video = $ffmpeg->open( '/path/to/video' );
422 $video
423 ->gif(FFMpeg\Coordinate\TimeCode::fromSeconds(2), new FFMpeg\Coordinate\Dimension(640, 480), 3)
424 ->save($new_file);
425 ```
426  
427 This method has a third optional boolean parameter, which is the duration of the animation.
428 If you don't set it, you will get a fixed gif image.
429  
430 #### Concatenation
431  
432 This feature allows you to generate one audio or video file, based on multiple sources.
433  
434 There are two ways to concatenate videos, depending on the codecs of the sources.
435 If your sources have all been encoded with the same codec, you will want to use the `FFMpeg\Media\Concatenate::saveFromSameCodecs` which has way better performances.
436 If your sources have been encoded with different codecs, you will want to use the `FFMpeg\Media\Concatenate::saveFromDifferentCodecs`.
437  
438 The first function will use the initial codec as the one for the generated file.
439 With the second function, you will be able to choose which codec you want for the generated file.
440  
441 You also need to pay attention to the fact that, when using the saveFromDifferentCodecs method,
442 your files MUST have video and audio streams.
443  
444 In both cases, you will have to provide an array of files.
445  
446 To concatenate videos encoded with the same codec, do as follow:
447  
448 ```php
449 // In order to instantiate the video object, you HAVE TO pass a path to a valid video file.
450 // We recommand that you put there the path of any of the video you want to use in this concatenation.
451 $video = $ffmpeg->open( '/path/to/video' );
452 $video
453 ->concat(array('/path/to/video1', '/path/to/video2'))
454 ->saveFromSameCodecs('/path/to/new_file', TRUE);
455 ```
456  
457 The boolean parameter of the save function allows you to use the copy parameter which accelerates drastically the generation of the encoded file.
458  
459 To concatenate videos encoded with the same codec, do as follow:
460  
461 ```php
462 // In order to instantiate the video object, you HAVE TO pass a path to a valid video file.
463 // We recommand that you put there the path of any of the video you want to use in this concatenation.
464 $video = $ffmpeg->open( '/path/to/video' );
465  
466 $format = new FFMpeg\Format\Video\X264();
467 $format->setAudioCodec("libmp3lame");
468  
469 $video
470 ->concat(array('/path/to/video1', '/path/to/video2'))
471 ->saveFromDifferentCodecs($format, '/path/to/new_file');
472 ```
473  
474 More details about concatenation in FFMPEG can be found [here](https://trac.ffmpeg.org/wiki/Concatenate), [here](https://ffmpeg.org/ffmpeg-formats.html#concat-1) and [here](https://ffmpeg.org/ffmpeg.html#Stream-copy).
475  
476 #### Formats
477  
478 A format implements `FFMpeg\Format\FormatInterface`. To save to a video file,
479 use `FFMpeg\Format\VideoInterface`, and `FFMpeg\Format\AudioInterface` for
480 audio files.
481  
482 Format can also extends `FFMpeg\Format\ProgressableInterface` to get realtime
483 informations about the transcoding.
484  
485 Predefined formats already provide progress informations as events.
486  
487 ```php
488 $format = new FFMpeg\Format\Video\X264();
489 $format->on('progress', function ($video, $format, $percentage) {
490 echo "$percentage % transcoded";
491 });
492  
493 $video->save($format, 'video.avi');
494 ```
495  
496 The callback provided for the event can be any callable.
497  
498 ##### Add additional parameters
499  
500 You can add additional parameters to your encoding requests based on your video format.
501  
502 The argument of the setAdditionalParameters method is an array.
503  
504 ```php
505 $format = new FFMpeg\Format\Video\X264();
506 $format->setAdditionalParameters(array('foo', 'bar'));
507 $video->save($format, 'video.avi');
508 ```
509  
510 ##### Create your own format
511  
512 The easiest way to create a format is to extend the abstract
513 `FFMpeg\Format\Video\DefaultVideo` and `FFMpeg\Format\Audio\DefaultAudio`.
514 and implement the following methods.
515  
516 ```php
517 class CustomWMVFormat extends FFMpeg\Format\Video\DefaultVideo
518 {
519 public function __construct($audioCodec = 'wmav2', $videoCodec = 'wmv2')
520 {
521 $this
522 ->setAudioCodec($audioCodec)
523 ->setVideoCodec($videoCodec);
524 }
525  
526 public function supportBFrames()
527 {
528 return false;
529 }
530  
531 public function getAvailableAudioCodecs()
532 {
533 return array('wmav2');
534 }
535  
536 public function getAvailableVideoCodecs()
537 {
538 return array('wmv2');
539 }
540 }
541 ```
542  
543 #### Coordinates
544  
545 FFMpeg use many units for time and space coordinates.
546  
547 - `FFMpeg\Coordinate\AspectRatio` represents an aspect ratio.
548 - `FFMpeg\Coordinate\Dimension` represent a dimension.
549 - `FFMpeg\Coordinate\FrameRate` represent a framerate.
550 - `FFMpeg\Coordinate\Point` represent a point.
551 - `FFMpeg\Coordinate\TimeCode` represent a timecode.
552  
553 ### FFProbe
554  
555 `FFMpeg\FFProbe` is used internally by `FFMpeg\FFMpeg` to probe medias. You can
556 also use it to extract media metadata.
557  
558 ```php
559 $ffprobe = FFMpeg\FFProbe::create();
560 $ffprobe
561 ->streams('/path/to/video/mp4') // extracts streams informations
562 ->videos() // filters video streams
563 ->first() // returns the first video stream
564 ->get('codec_name'); // returns the codec_name property
565 ```
566  
567 ```php
568 $ffprobe = FFMpeg\FFProbe::create();
569 $ffprobe
570 ->format('/path/to/video/mp4') // extracts file informations
571 ->get('duration'); // returns the duration property
572 ```
573  
574 ## Using with Silex Microframework
575  
576 Service provider is easy to set up:
577  
578 ```php
579 $app = new Silex\Application();
580 $app->register(new FFMpeg\FFMpegServiceProvider());
581  
582 $video = $app['ffmpeg']->open('video.mpeg');
583 ```
584  
585 Available options are as follow:
586  
587 ```php
588 $app->register(new FFMpeg\FFMpegServiceProvider(), array(
589 'ffmpeg.configuration' => array(
590 'ffmpeg.threads' => 4,
591 'ffmpeg.timeout' => 300,
592 'ffmpeg.binaries' => '/opt/local/ffmpeg/bin/ffmpeg',
593 'ffprobe.timeout' => 30,
594 'ffprobe.binaries' => '/opt/local/ffmpeg/bin/ffprobe',
595 ),
596 'ffmpeg.logger' => $logger,
597 ));
598 ```
599  
600 ## API Browser
601  
602 Browse the [API](https://ffmpeg-php.readthedocs.io/en/latest/_static/API/)
603  
604 ## License
605  
606 This project is licensed under the [MIT license](http://opensource.org/licenses/MIT).