Download the PHP package pbmedia/laravel-ffmpeg without Composer
On this page you can find all versions of the php package pbmedia/laravel-ffmpeg. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download pbmedia/laravel-ffmpeg
More information about pbmedia/laravel-ffmpeg
Files in pbmedia/laravel-ffmpeg
Package laravel-ffmpeg
Short Description FFMpeg for Laravel
License MIT
Homepage https://github.com/protonemedia/laravel-ffmpeg
Informations about the package laravel-ffmpeg
Laravel FFMpeg
This package provides an integration with FFmpeg for Laravel 10. Laravel's Filesystem handles the storage of the files.
Sponsor Us
❤️ We proudly support the community by developing Laravel packages and giving them away for free. If this package saves you time or if you're relying on it professionally, please consider sponsoring the maintenance and development and check out our latest premium package: Inertia Table. Keeping track of issues and pull requests takes time, but we're happy to help!
Features
- Super easy wrapper around PHP-FFMpeg, including support for filters and other advanced features.
- Integration with Laravel's Filesystem, configuration system and logging handling.
- Compatible with Laravel 10, support for Package Discovery.
- Built-in support for HLS.
- Built-in support for encrypted HLS (AES-128) and rotating keys (optional).
- Built-in support for concatenation, multiple inputs/outputs, image sequences (timelapse), complex filters (and mapping), frame/thumbnail exports.
- Built-in support for watermarks (positioning and manipulation).
- Built-in support for creating a mosaic/sprite/tile from a video.
- Built-in support for generating VTT Preview Thumbnail files.
- Requires PHP 8.1 or higher.
- Tested with FFmpeg 4.4 and 5.0.
Installation
Verify you have the latest version of FFmpeg installed:
You can install the package via composer:
Add the Service Provider and Facade to your config file if you're not using Package Discovery.
Publish the config file using the artisan CLI tool:
Upgrading to v8
- The
set_command_and_error_output_on_exception
configuration key now defaults totrue
, making exceptions more informative. Read more at the Handling exceptions section. - The
enable_logging
configuration key has been replaced bylog_channel
to choose the log channel used when writing messages to the logs. If you still want to disable logging entirely, you may set the new configuration key tofalse
. - The segment length and keyframe interval of HLS exports should be
2
or more; less is not supported anymore. - As Laravel 9 has migrated from Flysystem 1.x to 3.x, this version is not compatible with Laravel 8 or earlier.
- If you're using the
spatie/image
to v2.
Upgrading to v7
- The namespace has changed to
ProtoneMedia\LaravelFFMpeg
, the facade has been renamed toProtoneMedia\LaravelFFMpeg\Support\FFMpeg
, and the Service Provider has been renamed toProtoneMedia\LaravelFFMpeg\Support\ServiceProvider
. - Chaining exports are still supported, but you have to reapply filters for each export.
- HLS playlists now include bitrate, framerate and resolution data. The segments also use a new naming pattern (read more). Please verify your exports still work in your player.
- HLS export is now executed as one job instead of exporting each format/stream separately. This uses FFMpeg's
map
andfilter_complex
features. It might be sufficient to replace all calls toaddFilter
withaddLegacyFilter
, but some filters should be migrated manually. Please read the documentation on HLS to find out more about adding filters.
Usage
Convert an audio or video file:
Instead of the method you can also use the method, where is an instance of .
Progress monitoring
You can monitor the transcoding progress. Use the method to provide a callback, which gives you the completed percentage. In previous versions of this package you had to pass the callback to the format object.
The callback may also expose $remaining
(in seconds) and $rate
:
Opening uploaded files
You can open uploaded files directly from the Request
instance. It's probably better to first save the uploaded file in case the request aborts, but if you want to, you can open a UploadedFile
instance:
Open files from the web
You can open files from the web by using the openUrl
method. You can specify custom HTTP headers with the optional second parameter:
Handling exceptions
When the encoding fails, a ProtoneMedia\LaravelFFMpeg\Exporters\EncodingException
shall be thrown, which extends the underlying FFMpeg\Exception\RuntimeException
class. This class has two methods that can help you identify the problem. Using the getCommand
method, you can get the executed command with all parameters. The getErrorOutput
method gives you a full output log.
In previous versions of this package, the message of the exception was always Encoding failed. You can downgrade to this message by updating the set_command_and_error_output_on_exception
configuration key to false
.
Filters
You can add filters through a or by using PHP-FFMpeg's Filter objects:
You can also call the addFilter
method after the export
method:
Resizing
Since resizing is a common operation, we've added a dedicated method for it:
The first argument is the width, and the second argument the height. The optional third argument is the mode. You can choose between fit
(default), inset
, width
or height
. The optional fourth argument is a boolean whether or not to force the use of standards ratios. You can find about these modes in the FFMpeg\Filters\Video\ResizeFilter
class.
Custom filters
Sometimes you don't want to use the built-in filters. You can apply your own filter by providing a set of options. This can be an array or multiple strings as arguments:
Watermark filter
You can easily add a watermark using the addWatermark
method. With the WatermarkFactory
, you can open your watermark file from a specific disk, just like opening an audio or video file. When you discard the fromDisk
method, it uses the default disk specified in the filesystems.php
configuration file.
After opening your watermark file, you can position it with the top
, right
, bottom
, and left
methods. The first parameter of these methods is the offset, which is optional and can be negative.
Instead of using the position methods, you can also use the horizontalAlignment
and verticalAlignment
methods.
For horizontal alignment, you can use the WatermarkFactory::LEFT
, WatermarkFactory::CENTER
and WatermarkFactory::RIGHT
constants. For vertical alignment, you can use the WatermarkFactory::TOP
, WatermarkFactory::CENTER
and WatermarkFactory::BOTTOM
constants. Both methods take an optional second parameter, which is the offset.
The WatermarkFactory
also supports opening files from the web with the openUrl
method. It supports custom HTTP headers as well.
If you want more control over the GET request, you can pass in an optional third parameter, which gives you the Curl resource.
Watermark manipulation
This package can manipulate watermarks by using Spatie's Image package. To get started, install the package with Composer:
Now you can chain one more manipulation methods on the WatermarkFactory
instance:
Check out the documentation for all available methods.
Export without transcoding
This package comes with a ProtoneMedia\LaravelFFMpeg\FFMpeg\CopyFormat
class that allows you to export a file without transcoding the streams. You might want to use this to use another container:
Chain multiple convertions
Export a frame from a video
You can also get the raw contents of the frame instead of saving it to the filesystem:
Export multiple frames at once
There is a TileFilter
that powers the Tile-feature. To make exporting multiple frames faster and simpler, we leveraged this feature to add some helper methods. For example, you may use the exportFramesByInterval
method to export frames by a fixed interval. Alternatively, you may pass the number of frames you want to export to the exportFramesByAmount
method, which will then calculate the interval based on the duration of the video.
Both methods accept an optional second and third argument to specify to width and height of the frames. Instead of passing both the width and height, you may also pass just one of them. FFmpeg will respect the aspect ratio of the source.
Both methods accept an optional fourth argument to specify the quality of the image when you're exporting to a lossy format like JPEG. The range for JPEG is 2-31
, with 2
being the best quality and 31
being the worst.
Creates tiles of frames
You can create tiles from a video. You may call the exportTile
method to specify how your tiles should be generated. In the example below, each generated image consists of a 3x5 grid (thus containing 15 frames) and each frame is 160x90 pixels. A frame will be taken every 5 seconds from the video. Instead of passing both the width and height, you may also pass just one of them. FFmpeg will respect the aspect ratio of the source.
Instead of passing both the width and height, you may also pass just one of them like scale(160)
or scale(null, 90)
. The aspect ratio will be respected. The TileFactory
has margin
, padding
, width
, and height
methods as well. There's also a quality
method to specify the quality when exporting to a lossy format like JPEG. The range for JPEG is 2-31
, with 2
being the best quality and 31
being the worst.
This package can also generate a WebVTT file to add Preview Thumbnails to your video player. This is supported out-of-the-box by JW player and there are community-driven plugins for Video.js available as well. You may call the generateVTT
method on the TileFactory
with the desired filename:
Multiple exports using loops
Chaining multiple conversions works because the save
method of the MediaExporter
returns a fresh instance of the MediaOpener
. You can use this to loop through items, for example, to exports multiple frames from one video:
The MediaOpener
comes with an each
method as well. The example above could be refactored like this:
Create a timelapse
You can create a timelapse from a sequence of images by using the asTimelapseWithFramerate
method on the exporter
Multiple inputs
You can open multiple inputs, even from different disks. This uses FFMpeg's map
and filter_complex
features. You can open multiple files by chaining the open
method of by using an array. You can mix inputs from different disks.
When you open multiple inputs, you have to add mappings so FFMpeg knows how to route them. This package provides a addFormatOutputMapping
method, which takes three parameters: the format, the output, and the output labels of the -filter_complex
part.
The output (2nd argument) should be an instanceof ProtoneMedia\LaravelFFMpeg\Filesystem\Media
. You can instantiate with the make
method, call it with the name of the disk and the path (see example).
Check out this example, which maps separate video and audio inputs into one output.
This is an example from the underlying library:
Just like single inputs, you can also pass a callback to the addFilter
method. This will give you an instance of \FFMpeg\Filters\AdvancedMedia\ComplexFilters
:
Opening files from the web works similarly. You can pass an array of URLs to the openUrl
method, optionally with custom HTTP headers.
If you want to use another set of HTTP headers for each URL, you can chain the openUrl
method:
Concat files without transcoding
Concat files with transcoding
Determinate duration
With the class you can determinate the duration of a file:
Handling remote disks
When opening or saving files from or to a remote disk, temporary files will be created on your server. After you're done exporting or processing these files, you could clean them up by calling the method:
By default, the root of the temporary directories is evaluated by PHP's sys_get_temp_dir()
method, but you can modify it by setting the temporary_files_root
configuration key to a custom path.
HLS
You can create a M3U8 playlist to do HLS.
The method of the HLS exporter takes an optional second parameter which can be a callback method. This allows you to add different filters per format. First, check out the Multiple inputs section to understand how complex filters are handled.
You can use the addFilter
method to add a complex filter (see $lowBitrate
example). Since the scale
filter is used a lot, there is a helper method (see $midBitrate
example). You can also use a callable to get access to the ComplexFilters
instance. The package provides the $in
and $out
arguments so you don't have to worry about it (see $highBitrate
example).
HLS export is built using FFMpeg's map
and filter_complex
features. This is a breaking change from earlier versions (1.x - 6.x) which performed a single export for each format. If you're upgrading, replace the addFilter
calls with addLegacyFilter
calls and verify the result (see $superBitrate
example). Not all filters will work this way and some need to be upgraded manually.
Using custom segment patterns
You can use a custom pattern to name the segments and playlists. The useSegmentFilenameGenerator
gives you 5 arguments. The first, second and third argument provide information about the basename of the export, the format of the current iteration and the key of the current iteration. The fourth argument is a callback you should call with your segments pattern. The fifth argument is a callback you should call with your playlist pattern. Note that this is not the name of the primary playlist, but the name of the playlist of each format.
Encrypted HLS
You can encrypt each HLS segment using AES-128 encryption. To do this, call the withEncryptionKey
method on the HLS exporter with a key. We provide a generateEncryptionKey
helper method on the HLSExporter
class to generate a key. Make sure you store the key well, as the exported result is worthless without the key. By default, the filename of the key is secret.key
, but you can change that with the optional second parameter of the withEncryptionKey
method.
To secure your HLS export even further, you can rotate the key on each exported segment. By doing so, it will generate multiple keys that you'll need to store. Use the withRotatingEncryptionKey
method to enable this feature and provide a callback that implements the storage of the keys.
The withRotatingEncryptionKey
method has an optional second argument to set the number of segments that use the same key. This defaults to 1
.
Some filesystems, especially on cheap and slow VPSs, are not fast enough to handle the rotating key. This may lead to encoding exceptions, like No key URI specified in key info file
. One possible solution is to use a different storage for the keys, which you can specify using the temporary_files_encrypted_hls
configuration key. On UNIX-based systems, you may use a tmpfs
filesystem to increase read/write speeds:
Protecting your HLS encryption keys
To make working with encrypted HLS even better, we've added a DynamicHLSPlaylist
class that modifies playlists on-the-fly and specifically for your application. This way, you can add your authentication and authorization logic. As we're using a plain Laravel controller, you can use features like Gates and Middleware.
In this example, we've saved the HLS export to the public
disk, and we've stored the encryption keys to the secrets
disk, which isn't publicly available. As the browser can't access the encryption keys, it won't play the video. Each playlist has paths to the encryption keys, and we need to modify those paths to point to an accessible endpoint.
This implementation consists of two routes. One that responses with an encryption key and one that responses with a modified playlist. The first route (video.key
) is relatively simple, and this is where you should add your additional logic.
The second route (video.playlist
) uses the DynamicHLSPlaylist
class. Call the dynamicHLSPlaylist
method on the FFMpeg
facade, and similar to opening media files, you can open a playlist utilizing the fromDisk
and open
methods. Then you must provide three callbacks. Each of them gives you a relative path and expects a full path in return. As the DynamicHLSPlaylist
class implements the Illuminate\Contracts\Support\Responsable
interface, you can return the instance.
The first callback (KeyUrlResolver) gives you the relative path to an encryption key. The second callback (MediaUrlResolver) gives you the relative path to a media segment (.ts files). The third callback (PlaylistUrlResolver) gives you the relative path to a playlist.
Now instead of using Storage::disk('public')->url('adaptive_steve.m3u8')
to get the full url to your primary playlist, you can use route('video.playlist', ['playlist' => 'adaptive_steve.m3u8'])
. The DynamicHLSPlaylist
class takes care of all the paths and urls.
Live Coding Session
Here you can find a Live Coding Session about HLS encryption:
https://www.youtube.com/watch?v=WlbzWoAcez4
Process Output
You can get the raw process output by calling the getProcessOutput
method. Though the use-case is limited, you can use it to analyze a file (for example, with the volumedetect
filter). It returns a ProtoneMedia\LaravelFFMpeg\Support\ProcessOutput
class that has three methods: all
, errors
and output
. Each method returns an array with the corresponding lines.
Advanced
The Media object you get when you 'open' a file, actually holds the Media object that belongs to the underlying driver. It handles dynamic method calls as you can see here. This way all methods of the underlying driver are still available to you.
If you want direct access to the underlying object, call the object as a function (invoke):
Experimental
The progress listener exposes the transcoded percentage, but the underlying package also has an internal AbstractProgressListener
that exposes the current pass and the current time. Though the use-case is limited, you might want to get access to this listener instance. You can do this by decorating the format with the ProgressListenerDecorator
. This feature is highly experimental, so be sure the test this thoroughly before using it in production.
Since we can't get rid of some of the underlying options, you can interact with the final FFmpeg command by adding a callback to the exporter. You can add one or more callbacks by using the beforeSaving
method:
Note: this does not work with concatenation and frame exports
Example app
Here's a blog post that will help you get started with this package:
https://protone.media/en/blog/how-to-use-ffmpeg-in-your-laravel-projects
Using Video.js to play HLS in any browser
Here's a 20-minute overview how to get started with Video.js. It covers including Video.js from a CDN, importing it as an ES6 module with Laravel Mix (Webpack) and building a reusable Vue.js component.
https://www.youtube.com/watch?v=nA1Jy8BPjys
Wiki
- Custom filters
- FFmpeg failed to execute command
- Get the dimensions of a Video file
- Monitoring the transcoding progress
- Unable to load FFProbe
Changelog
Please see CHANGELOG for more information about what has changed recently.
Testing
Contributing
Please see CONTRIBUTING for details.
Other Laravel packages
Inertia Table
: The Ultimate Table for Inertia.js with built-in Query Builder.Laravel Blade On Demand
: Laravel package to compile Blade templates in memory.Laravel Cross Eloquent Search
: Laravel package to search through multiple Eloquent models.Laravel Eloquent Scope as Select
: Stop duplicating your Eloquent query scopes and constraints in PHP. This package lets you re-use your query scopes and constraints by adding them as a subquery.Laravel MinIO Testing Tools
: Run your tests against a MinIO S3 server.Laravel Mixins
: A collection of Laravel goodies.Laravel Paddle
: Paddle.com API integration for Laravel with support for webhooks/events.Laravel Task Runner
: Write Shell scripts like Blade Components and run them locally or on a remote server.Laravel Verify New Email
: This package adds support for verifying new email addresses: when a user updates its email address, it won't replace the old one until the new one is verified.Laravel XSS Protection
: Laravel Middleware to protect your app against Cross-site scripting (XSS). It sanitizes request input, and it can sanatize Blade echo statements.
Security
If you discover any security-related issues, please email [email protected] instead of using the issue tracker. Please do not email any questions, open an issue if you have a question.
Credits
- Pascal Baljet
- All Contributors
License
The MIT License (MIT). Please see License File for more information.
All versions of laravel-ffmpeg with dependencies
illuminate/contracts Version ^10.0|^11.0
php-ffmpeg/php-ffmpeg Version ^1.2
ramsey/collection Version ^2.0