Download the PHP package buggedcom/phpvideotoolkit without Composer
On this page you can find all versions of the php package buggedcom/phpvideotoolkit. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package phpvideotoolkit
PHPVideoToolkit V2...
...is a set of PHP classes aimed to provide a modular, object oriented and accessible interface for interacting with videos and audio through FFmpeg.
PHPVideoToolkit also provides FFmpeg-PHP emulation in pure PHP so you wouldn't need to compile and install the FFmpeg-PHP module, you only require FFmpeg and PHPVideoToolkit. As FFmpeg-PHP has not been updated since 2007 using FFmpeg-PHP with a new version of FFmpeg can often break FFmpeg-PHP. Using PHPVideoToolkits' emulation of FFmpeg-PHP's functionality allows you to upgrade FFmpeg without worrying about breaking functionality of provided through the FFmpeg-PHP API.
IMPORTANT PHPVideoToolkit has only been tested with v1.1.2 of FFmpeg. Whilst the majority of functionality should work regardless of your version of FFmpeg I cannot guarantee it. If you find a bug or have a patch please open a ticket or submit a pull request on https://github.com/buggedcom/phpvideotoolkit-v2
Table of Contents
- License
- Documentation
- Latest Changes
- Usage
- Configuring PHPVideoToolkit
- Accessing Data About FFmpeg
- Accessing Data About media files
- PHPVideoToolkit Timecodes
- PHPVideoToolkit Output Formats
- Extract a Single Frame of a Video
- Extract Multiple Frames from a Segment of a Video
- Extract Multiple Frames of a Video at 1 frame per second
- Extract Multiple Frames of a Video at 1 frame every 'x' seconds
- Caveats of Extracting Multiple Frames
- Combining Multiple Images and Audio to form a Video
- Extracting an Animated Gif
- Resizing Video and Images
- Extracting Audio or Video Channels from a Video
- Extracting a Segment of an Audio or Video file
- Splitting a Audio or Video file into multiple parts
- Purging and then adding Meta Data
- Changing Codecs of the audio or video stream
- Non-Blocking Saves
- Encoding with Progress Handlers
- Information Available to the Progress Handlers
- Encoding Multiple Output Files
- Accessing Executed Commands and the Command Line Buffer
- Supplying custom commands
- Imposing a processing time limit
- Forcing a specific output format whilst using a silly file extension
License
PHPVideoToolkit Copyright (c) 2008-2014 Oliver Lillie
DUAL Licensed under MIT and GPL v2
See LICENSE.md for more details.
Documentation
Extensive documentation and examples are bundled with the download and is available in the documentation directory.
Latest Changes
[2.2.0-beta] [10.04.2014]
WARNING: Potential code breaking changes across the board. Please do not upgrade existing stable scripts to this codebase. Please use 2.1.5 or below for stability.
- merged in multi-output branch so that the master branch now supports multi output from ffmpeg.
- fixed far too many other bugs to mention.
Usage
Whilst the extensive documentation covers just about everything (to be honest there are only a few pages in the documentation as I'm too busy to write too much of it - but the examples below are pretty good), here are a few examples of what you can do.
Configuring PHPVideoToolkit
PHPVideoToolkit requires some basic configuration and is one through the Config class. The Config class is then used in the constructor of most PHPVideoToolkit classes. Any child object initialised within an already configured class will inherit the configuration options of the parent.
Take special note of the second parameter . If set as true then the related Config object is set as the default config instance. This means that once set as the default instance you do not need to supply the Config object to the other PHPVideoToolkit class constructors. If a config object is not defined and supplied to the PHPVideoToolkit classes, then a default Config object is created and assigned to the class.
Every example below assumes that the Config object has been set as the default config object prior in the execution so there is no need to supply config to each example.
Accessing Data About FFmpeg
Simple demonstration about how to access information about FfmpegParser object.
Accessing Data About media files
Simple demonstration about how to access information about media files using the MediaParser object.
PHPVideoToolkit Timecodes
PHPVideoToolkit utilises Timecode objects when extracting data such as duration or start points, or when extracting portions of a media file. They are fairly simple to understand. All of the example timecodes created below are the same time.
You can manipulate timecodes fairly simply.
It's very important to note, as in the last example, that there is a massive difference between accessing and . seconds
is the number of seconds in the remaining minute of the timecode. total_seconds
is the total number of seconds of the timecode. The same logic applies to minutes, hours, milliseconds and their total_ prefixed counterparts.
PHPVideoToolkit Output Formats
PHPVideoToolkit contains a base class Format
. This class is extended by three other important base classes called AudioFormat
, VideoFormat
and ImageFormat
. They extend as follows: Format > AudioFormat > VideoFormat > ImageFormat. This allows each of the later formats to inherit functionality from the previous format.
FFmpeg allows you to set certain import format parameters to the input media. As such these Format classes work for both input and output formatting of media. For the most part, unless you need to do something very specific you do not need to worry about setting an input format for the media you wish to put into FFmpeg. So this documentation will not explain input formatting.
Generally speaking if you are just transcoding from one format to another, you do not even need to worry about supplying an output format either. PHPVideoToolkit will best guess the output format you require and then apply it magically when you call 'save' to encode the media. To this end there are specific Audio, Image and Video formats you can use. These are listed below. If you have specific settings for a specific file output please feel free to create your own media specific output formats and submit a pull request and I will include them in the bundle. These media specific formats are listed below.
Audio
AudioFormat_Acc
AudioFormat_Flac
AudioFormat_Mp3
AudioFormat_Oga
AudioFormat_Wav
Image
ImageFormat_Bmp
ImageFormat_Gif
ImageFormat_Jpeg
ImageFormat_Png
ImageFormat_Ppm
Video
VideoFormat_3gp
VideoFormat_Flv
VideoFormat_H264
VideoFormat_Mkv
VideoFormat_Mp4
VideoFormat_Ogg
VideoFormat_Webm
VideoFormat_Wmv
VideoFormat_Wmv3
For the most part all these format specific Format classes do is set the neccessary codecs and settings required to generate the desired output, however, formats like VideoFormat_Mp4
, VideoFormat_H264
or VideoFormat_Flv
contain further functionality and make use of encoding completion callbacks to further process the media after FFmpeg has finished encoding them. For example the flv format runs the resulting output from FFmpeg through the yamdi server library to inject meta data, or the mp4 format uses qtfaststart to create a fast start streaming mp4.
So getting to the bit you will most likely use... The formatting of outputted media.
AudioFormat
AudioFormat and child classes thereof have the following functions available.
- disableAudio/enableAudio
- setAudioCodec
- setAudioBitrate
- setAudioSampleFrequency
- setAudioChannels
- setVolume
- setAudioQuality
VideoFormat
VideoFormat and child classes thereof have the following functions available.
- disableVideo/enableVideo
- setVideoCodec
- setVideoDimensions
- setVideoScale
- setVideoPadding
- setVideoAspectRatio
- setVideoFrameRate
- setVideoMaxFrames
- setVideoBitrate
- setVideoPixelFormat
- setVideoQuality
- setVideoRotation
- videoFlipVertical
- videoFlipHorizontal
ImageFormat
ImageFormat and the related child classes do not have any further functions.
Basic usage
Below is an example of a very simple manipulation of a video.
Forcing a specific output format whilst using a silly file extension
Because of the advanced nature of the input and output formatters, if supplied you can encode a specific output, but use a silly (or custom) file extension. Not really sure why you would want to but it is possible.
Extract a Single Frame of a Video
The code below extracts a frame from the video at the 40 second mark.
Extract Multiple Frames from a Segment of a Video
The code below extracts frames at the parent videos' frame rate from between 40 and 50 seconds. If the parent video has a frame rate of 24 fps then 240 images would be extracted from this code.
Extract Multiple Frames of a Video at 1 frame per second
There are two ways you can export at a differing frame rate from that of the parent video. The first is to use an output format to set the video frame rate.
The second is to use the $force_frame_rate option of the extractFrames function.
Extract Multiple Frames of a Video at 1 frame every 'x' seconds
The code below uses the argument for , however the same 1/n notation can be used on . This example will output 1 frame every 60 seconds of video.
Caveats of Extracting Multiple Frames
IMPORTANT: It is important to note that if you exporting multiple frames a video you will not always get the expected amount of frames you would expect. This is down to the way FFmpeg treats timecodes. Take the example below into consideration.
You may assume that looking at this example you will get 10 frames outputted because the segment being extracted is 10 seconds long. However you will actually only get 9 frames exported. This is because the end time frame is treated as a less than value rather than a less than and equal to value. So in pseudo code this is what is happening when frames are extracted.
So if we require 10 frames you must actually set your end timecode to a little over 20 seconds like so
Combining Multiple Images and Audio to form a Video
Whilst PHPVideoToolkit does not natively support combing multiple images and audio into a video, it can still be achieved by add custom commands to the process object.
Extracting an Animated Gif
Now, FFmpeg's animated gif support is a pile of doggy do do. I can't understand why. However what PHPVideoToolkit does is bypass the native gif exporting of FFmpeg and provide it's own much better alternative.
There are several options available to you when exporting an animated gif. You can use Gifsicle, Imagemagicks convert, or native PHP GD with the symbio/gif-creator composer library.
For high quality, but very slow encoding a combination of Gifsicle with Convert pre processing is suggested, alternatively for a quicker encode but lower quality, you can use native PHP GD or Convert. The examples below show you how to differentiate between the different methods.
Regards to performance. High frame rates greatly impact how fast a high quality encoding completes. It's suggested that if you need a high quality animated gif, that you limit your frame rate to around 5 frames per second.
High Quality
Gifsicle with Imagemagick Convert
Quick Encoding, but lower quality (still better than FFmpeg mind)
The examples below are listed in order of performance.
Imagemagick Convert
Native PHP GD with symbio/gif-creator library
Gifsicle with native PHP GD
Resizing Video and Images
In order to resize output video and imagery output you need to supply an output format to the save function you call. The below snippet is an example of resizing a video, however you would use same function call to setVideoDimensions
just instead of a VideoFormat
object you would use an ImageFormat
object.
Extracting Audio or Video Channels from a Video
Extracting a Segment of an Audio or Video file
The code below extracts a portion of the video at the from 2 minutes 22 seconds to 3 minutes (ie 180 seconds). Note the different settings for constructing a timecode. The timecode object can accept different formats to create a timecode from.
Splitting a Audio or Video file into multiple parts
There are multiple ways you can configure the split parameters. If an array is supplied as the first argument. It must be an array of either, all Timecode instances detailing the timecodes at which you wish to split the media, or all integers. If integers are supplied the integers are treated as frame numbers you wish to split at. You can however also split at even intervals by suppling a single integer as the first parameter. That integer is treated as the number of seconds that you wish to split at. If you have a video that is 3 minutes 30 seconds long and set the split to 60 seconds, you will get 4 videos. The first three will be 60 seconds in length and the last would be 30 seconds in length.
The code below splits a video into multiple of equal length of 45 seconds each.
Purging and then adding Meta Data
Unfortunately there is no way using FFmpeg to add meta data without re-encoding the file. There are other tools that can do that though, however if you wish to write meta data to the media during encoding you can do so using code like the example below.
Changing Codecs of the audio or video stream
By default PHPVideoToolkit uses the file extension of the output file to automatically generate the required ffmpeg settings (if any) of your desired file format. However if you want to specify different codecs or settings, it is ncessesary to specify them within an output format container. There are three different format objects you can use, depending on the format of your output. They are AudioFormat, VideoFormat and ImageFormat.
Note; the examples below are for demonstration purposes only and may not work.
Changing the audio and video codecs of an outputted video
Changing the audio codec of an audio export
Non-Blocking Saves
The default/main save() function blocks PHP until the encoding process has completed. This means that depending on the size of the media you are encoding it could leave your script running for a long time. To combat this you can call saveNonBlocking() to start the encoding process without blocking PHP.
However there are some caveats you need to be aware of before doing so. Once the non blocking process as started, if your PHP script closes PHPVideoToolkit can not longer "tidy up" temporary files or perform dynamic renaming of %index or %timecode output files. All responsibility is handed over to you. Of course, if you leave the PHP script open until the encode has finished PHPVideoToolkit will do everything for you.
The code below is an example of how to manage a non-blocking save.
Encoding with Progress Handlers
Whilst the code above from Non-Blocking Saves looks like it is a progress handler (and it is in a sense, but it doesn't provide data on the encode), progress handlers provide much more detailed information about the current encoding process.
PHPVideoToolkit allows you to monitor the encoding process of FFmpeg. This is done by using ProgressHandler objects. There are three types of progress handlers.
- ProgressHandlerNative
- ProgressHandlerOutput
- ProgressHandlerPortable
ProgressHandlerNative and ProgressHandlerOutput work and function in the same way, however one uses a native ffmpeg command, and the out outputs ffmpeg output buffer to a temp file. If your copy of FFmpeg is recent you will be able to use ProgressHandlerNative which uses FFmpegs '-progress' command to provide data. The handlers return slightly differing amounts of data, and the more accurate and verbose of the two is ProgressHandlerOutput and it is recommended that you use that progress handler between the two. However they do both return the same essential data and act in the same way and there is no real need to prioritise one over another unless you version of ffmpeg does not support '-progress'. If it doesn't then when you initialise the ProgressHandlerNative an exception will be thrown. Between the two I personally recommend ProgressHandlerOutput because of the more verbose nature of the data available.
The third type of handler ProgressHandlerPortable (shown in example 3 below) operates somewhat differently and is specifically design to work with separate HTTP requests or threads. ProgressHandlerPortable can be initiated in a different script entirely, supplied with the PHPVideoToolkit portable process id and then probed independently of the encoding script. This allows developers to decouple encoding and encoding status scripts.
Progress Handlers can be made to block PHP or can be used in a non blocking fashion. They can even be utilised to work from a separate script once the encoding has been initialised. However for purposes of the first two examples the progress handlers are in the same script essentially blocking the PHP process. Again however, the first two examples shown function very differently.
Example 1. Callback in the handler constructor
This example supplies the progress callback handler as a parameter to the constructor. This function is then called (every second, by default). Creating the callback in this way will block PHP and cannot be assigned as a progress handler when calling saveNonBlocking().
Example 2. Probing the handler
This example initialises a handler but does not supply a callback function. Instead you create your own method for creating a "progress loop" (or similar) and instead just call probe() on the handler.
So you see whilst the two examples look very similar and both block PHP, the second example does not need to block at all.
Example 3. Non Blocking Save with Remote Progress Handling
This example (a better example is found in /examples/progress-handler-portability.php) shows that a non blocking save can be made in one request, and then subsequent requests (i.e. ajax) can be made to a different script to probe the encoding progress.
IMPORTANT: Please remember that any object used in either of the below scripts must be the same in BOTH scripts in order to ensure the progress data can be retrieved in the progress script.
Encoding script:
Probing script:
Progress Handler Caveats
1: When encoding MP4s and having enabled qt-faststart usage either through setting or saves are put into blocking mode as processing with qt-faststart requires further exec calls. Similarly any encoding post processes such as when encoding FLVs will also convert a non blocking save into a blocking one.
2: When outputting files using %timecode or %index and using the ProgressHandlerPortable system it is not possible to currently automatically renaming the resulting temporary file output to their correct output filenames.
Information Available to the Progress Handlers
All of the progress handlers outlined above returned the same information, albeit there are some minor differences as when some of the data is available, however the difference is negligle and for the purposes of this document they really do not matter. Below is a sample output of the data available from
There are 4 different "status" booleans and one specific status code in the output that you should be aware of. They are started, interrupted, completed, finished and status.
started (boolean)
This is set to true once the process file has been found by PHPVideoToolkit and the decode/encode process has been sent to FFmpeg.
interrupted (boolean)
This is set to true if for some reason the server as stopped the encoding process prematurely. If this is ever encountered, it means your encoding process has failed and cannot be restarted other than attempting the encode again.
completed (boolean)
This is set to true once FFmpeg has signaled that the encoding process has finished.
finished (boolean)
This is set to true once PHPVideoToolkit has received the completion signal from the command line. This is typically speaking set after 'completed' is set to true. This is because after the encode has completed, FFmpeg outputs more information after the process has completed and then PHPVideoToolkit does a little tidying of temporary files or post process particular file formats.
status (constant/string)
This is a value that is defined according to the values above using the following constants; ProgressHandlerDefaultData::ENCODING_STATUS_PENDING
, ProgressHandlerDefaultData::ENCODING_STATUS_DECODING
, ProgressHandlerDefaultData::ENCODING_STATUS_ENCODING
, ProgressHandlerDefaultData::ENCODING_STATUS_FINALISING
, ProgressHandlerDefaultData::ENCODING_STATUS_COMPLETED
, ProgressHandlerDefaultData::ENCODING_STATUS_FINISHED
, ProgressHandlerDefaultData::ENCODING_STATUS_INTERRUPTED
, and ProgressHandlerDefaultData::ENCODING_STATUS_ERROR
. You'll notice there are more status than boolean flags. This is because the 'status' key is slightly more verbose. As a result the constant values are explained below.
ProgressHandlerDefaultData::ENCODING_STATUS_PENDING
This means that the process has not yet started decoding the input media. It is followed by...
ProgressHandlerDefaultData::ENCODING_STATUS_DECODING
This means that FFmpeg is currently decoding the input media. Which is then followed by...
ProgressHandlerDefaultData::ENCODING_STATUS_ENCODING
This means that FFmpeg is currently encoding the output files. This is followed by...
ProgressHandlerDefaultData::ENCODING_STATUS_FINALISING
This means that FFmpeg has reached the end of the encoding process and is currently tidying up and we are in the final stages of the encode. This is followed by...
ProgressHandlerDefaultData::ENCODING_STATUS_COMPLETED
Which means that the encoding process has completed but PHPVideoToolkit still requires a little moment to tidy up.
ProgressHandlerDefaultData::ENCODING_STATUS_FINISHED
Then this is given it means the encoding process is totally complete and you can safely move/rename/use your end output media.
If anything as gone wrong in the encoding process you will get either ProgressHandlerDefaultData::ENCODING_STATUS_INTERRUPTED
or ProgressHandlerDefaultData::ENCODING_STATUS_ERROR
at any point of the encoding process. Generally speaking if either of these constants are given both the error and error_message keys within the probed data will also be populated.
The other values returned via the probe data are explained below.
run_time (float)
This is the total time in seconds that the process has taken.
percentage (float)
This is the encoding completion percentage in the range of 0-100. 100 being the encode is complete.
fps (float)
This is the current number of frames per second that are being processed.
fps_avg (float)
This is the average number of frames per second that are being processed.
frame (integer)
This is the current frame that is being processed.
size (string)
This is the current size of the output media.
duration (PHPVideoToolkit\Timecode object)
This is the current duration of the output media (if appropriate - as if you are outputting images only this will be null
)
expected_duration (PHPVideoToolkit\Timecode object)
This is the expected approimate value that the output media's duration will be. The final value held by 'duration' (above) will usually be a few microseconds different that this value.
dup (float)
This value is the number of duplicate frames processed.
drop (float)
This is the number of dropped frames.
output_count (integer)
This value is the number of ouput files expected.
output_file (string/array)
This value is either a) a path value as a string if the above 'output_count' is 1, or b) and array of path strings if the above 'output_count' is greated than 1.
input_count (integer)
This value is the number of input files being used.
input_file (string/array)
This value is either a) a path value as a string if the above 'input_count' is 1, or b) and array of path strings if the above 'input_count' is greated than 1.
process_file (string)
This is a path string pointing to the current process file that the progress handler is using to read the data from.
Encoding Multiple Output Files
FFmpeg allows you to encode multiple output formats from a single command. PHPVideoToolkit allows you to perform this functionality as well. This functionality is essentially the same process as performing multiple saves, however has the added benefit of lower overhead because the input file only has to be read into memory once before the encoding takes place. It is recommended that you use this method if you are outputting more than one version of the media. There are of course several caveats when using this method however.
When splitting files into multiple segments or extracting portions of a video the transformations that take place are performed on all the outputed media. An example of this functionality can be found in . However a quick example is also shown below.
All progress handlers also work with multiple output, however the caveats outlined for the ProgressHandlerPortable still apply.
IMPORTANT Whilst this is technically possibly, depending on your server and the number of outputs you are generating, it can be quicker to simply chain the requests together instead. See the chaining processes example for more information on method chaining.
Accessing Executed Commands and the Command Line Buffer
There may be instances where things go wrong and PHPVideoToolkit hasn't correctly prevented or reported any encoding/decoding errors, or, you may just want to log what is going on. You can access any executed commands and the command lines output fairly simply as the example below shows.
It's important to note, the the ExecBuffer object actually manipulates the raw command string given to it by the FfmpegProcess object. This is done so that the ExecBuffer can successfully track errors and process completion. The data returned by getExecutedCommand() and getBuffer() are values that are expected but not actual.
To get the actual executed command and buffer you can use the following.
Supplying custom commands
Because FFmpeg has a specific order in which certain commands need to be added there are a few functions you should be aware of. First of the code below shows you how to access the code FfmpegProcess object. The process object is itself a wrapper around the ProcessBuilder (helps to build queries) and ExceBuffer (executes and controls the query) objects.
The process object is passed by reference so any changes to the object are also made within the Video object.
Now you have access to the process object you can add specific commands to it.
Now all of the example commands above will cause FFmpeg to fail, and they are just to illustrate a point.
- The function addPreInputCommand() adds commands to be given before the input command (-i) is added to the command string.
- The function addCommand() adds commands to be given after the input command (-i) is added to the command string.
- The function addPostOutputCommand() adds commands to be given after the output file is added to the command string.
To help explain it further, here is a simplified command string using the above custom commands.
HOWEVER, there is an important caveat you need to be aware of, the above command is just and example to show you the position of the added commands. Using the same additional commands as above, the actual executed command looks like this:
Imposing a processing timelimit
You may wish to impose a processing timelimit on encoding. There are various reasons for doing this and should be self explanatory. FFmpeg supplies a command to be able to do this and can be invoked like so...