Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

This package provides an integration with FFmpeg for Laravel. Laravel's Filesystem handles the storage of the files.

License

NotificationsYou must be signed in to change notification settings

protonemedia/laravel-ffmpeg

Repository files navigation

Latest Version on PackagistSoftware Licenserun-testsTotal Downloads

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 considersponsoring 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 aroundPHP-FFMpeg, including support for filters and other advanced features.
  • Integration withLaravel's Filesystem,configuration system andlogging handling.
  • Compatible with Laravel 10, support forPackage 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 generatingVTT 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:

ffmpeg -version

You can install the package via composer:

composer require pbmedia/laravel-ffmpeg

Add the Service Provider and Facade to yourapp.php config file if you're not using Package Discovery.

// config/app.php'providers' => [    ...ProtoneMedia\LaravelFFMpeg\Support\ServiceProvider::class,    ...];'aliases' => [    ...'FFMpeg' =>ProtoneMedia\LaravelFFMpeg\Support\FFMpeg::class    ...];

Publish the config file using the artisan CLI tool:

php artisan vendor:publish --provider="ProtoneMedia\LaravelFFMpeg\Support\ServiceProvider"

Upgrading to v8

  • Theset_command_and_error_output_on_exception configuration key now defaults totrue, making exceptions more informative. Read more at theHandling exceptions section.
  • Theenable_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.
  • Thesegment length andkeyframe interval ofHLS exports should be2 or more; less is not supported anymore.
  • As Laravel 9 has migrated fromFlysystem 1.x to 3.x, this version is not compatible with Laravel 8 or earlier.
  • If you're using theWatermark manipulation feature, make sure you upgradespatie/image to v2.

Upgrading to v7

  • The namespace has changed toProtoneMedia\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 asone job instead of exporting each format/stream separately. This uses FFMpeg'smap andfilter_complex features. It might be sufficient to replace all calls toaddFilter withaddLegacyFilter, but some filters should be migrated manually. Please read thedocumentation on HLS to find out more about adding filters.

Usage

Convert an audio or video file:

FFMpeg::fromDisk('songs')    ->open('yesterday.mp3')    ->export()    ->toDisk('converted_songs')    ->inFormat(new \FFMpeg\Format\Audio\Aac)    ->save('yesterday.aac');

Instead of thefromDisk() method you can also use thefromFilesystem() method, where$filesystem is an instance ofIlluminate\Contracts\Filesystem\Filesystem.

$media = FFMpeg::fromFilesystem($filesystem)->open('yesterday.mp3');

Progress monitoring

You can monitor the transcoding progress. Use theonProgress 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.

FFMpeg::open('steve_howe.mp4')    ->export()    ->onProgress(function ($percentage) {echo"{$percentage}% transcoded";    });

The callback may also expose$remaining (in seconds) and$rate:

FFMpeg::open('steve_howe.mp4')    ->export()    ->onProgress(function ($percentage,$remaining,$rate) {echo"{$remaining} seconds left at rate:{$rate}";    });

Opening uploaded files

You can open uploaded files directly from theRequest instance. It's probably better to first save the uploaded file in case the request aborts, but if you want to, you can open aUploadedFile instance:

class UploadVideoController{publicfunction__invoke(Request$request)    {        FFMpeg::open($request->file('video'));    }}

Open files from the web

You can open files from the web by using theopenUrl method. You can specify custom HTTP headers with the optional second parameter:

FFMpeg::openUrl('https://videocoursebuilder.com/lesson-1.mp4');FFMpeg::openUrl('https://videocoursebuilder.com/lesson-2.mp4', ['Authorization' =>'Basic YWRtaW46MTIzNA==',]);

Handling exceptions

When the encoding fails, aProtoneMedia\LaravelFFMpeg\Exporters\EncodingException shall be thrown, which extends the underlyingFFMpeg\Exception\RuntimeException class. This class has two methods that can help you identify the problem. Using thegetCommand method, you can get the executed command with all parameters. ThegetErrorOutput method gives you a full output log.

In previous versions of this package, the message of the exception was alwaysEncoding failed. You can downgrade to this message by updating theset_command_and_error_output_on_exception configuration key tofalse.

try {    FFMpeg::open('yesterday.mp3')        ->export()        ->inFormat(newAac)        ->save('yesterday.aac');}catch (EncodingException$exception) {$command =$exception->getCommand();$errorLog =$exception->getErrorOutput();}

Filters

You can add filters through aClosure or by using PHP-FFMpeg's Filter objects:

useFFMpeg\Filters\Video\VideoFilters;FFMpeg::fromDisk('videos')    ->open('steve_howe.mp4')    ->addFilter(function (VideoFilters$filters) {$filters->resize(new \FFMpeg\Coordinate\Dimension(640,480));    })    ->export()    ->toDisk('converted_videos')    ->inFormat(new \FFMpeg\Format\Video\X264)    ->save('small_steve.mkv');// or$start = \FFMpeg\Coordinate\TimeCode::fromSeconds(5)$clipFilter =new \FFMpeg\Filters\Video\ClipFilter($start);FFMpeg::fromDisk('videos')    ->open('steve_howe.mp4')    ->addFilter($clipFilter)    ->export()    ->toDisk('converted_videos')    ->inFormat(new \FFMpeg\Format\Video\X264)    ->save('short_steve.mkv');

You can also call theaddFilter methodafter theexport method:

useFFMpeg\Filters\Video\VideoFilters;FFMpeg::fromDisk('videos')    ->open('steve_howe.mp4')    ->export()    ->toDisk('converted_videos')    ->inFormat(new \FFMpeg\Format\Video\X264)    ->addFilter(function (VideoFilters$filters) {$filters->resize(new \FFMpeg\Coordinate\Dimension(640,480));    })    ->save('small_steve.mkv');

Resizing

Since resizing is a common operation, we've added a dedicated method for it:

FFMpeg::open('steve_howe.mp4')    ->export()    ->inFormat(new \FFMpeg\Format\Video\X264)    ->resize(640,480)    ->save('steve_howe_resized.mp4');

The first argument is the width, and the second argument the height. The optional third argument is the mode. You can choose betweenfit (default),inset,width orheight. The optional fourth argument is a boolean whether or not to force the use of standards ratios. You can find about these modes in theFFMpeg\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:

FFMpeg::fromDisk('videos')    ->open('steve_howe.mp4')    ->addFilter(['-itsoffset',1]);// orFFMpeg::fromDisk('videos')    ->open('steve_howe.mp4')    ->addFilter('-itsoffset',1);

Watermark filter

You can easily add a watermark using theaddWatermark method. With theWatermarkFactory, you can open your watermark file from a specific disk, just like opening an audio or video file. When you discard thefromDisk method, it uses the default disk specified in thefilesystems.php configuration file.

After opening your watermark file, you can position it with thetop,right,bottom, andleft methods. The first parameter of these methods is the offset, which is optional and can be negative.

useProtoneMedia\LaravelFFMpeg\Filters\WatermarkFactory;FFMpeg::fromDisk('videos')    ->open('steve_howe.mp4')    ->addWatermark(function(WatermarkFactory$watermark) {$watermark->fromDisk('local')            ->open('logo.png')            ->right(25)            ->bottom(25);    });

Instead of using the position methods, you can also use thehorizontalAlignment andverticalAlignment methods.

For horizontal alignment, you can use theWatermarkFactory::LEFT,WatermarkFactory::CENTER andWatermarkFactory::RIGHT constants. For vertical alignment, you can use theWatermarkFactory::TOP,WatermarkFactory::CENTER andWatermarkFactory::BOTTOM constants. Both methods take an optional second parameter, which is the offset.

FFMpeg::open('steve_howe.mp4')    ->addWatermark(function(WatermarkFactory$watermark) {$watermark->open('logo.png')            ->horizontalAlignment(WatermarkFactory::LEFT,25)            ->verticalAlignment(WatermarkFactory::TOP,25);    });

TheWatermarkFactory also supports opening files from the web with theopenUrl method. It supports custom HTTP headers as well.

FFMpeg::open('steve_howe.mp4')    ->addWatermark(function(WatermarkFactory$watermark) {$watermark->openUrl('https://videocoursebuilder.com/logo.png');// or$watermark->openUrl('https://videocoursebuilder.com/logo.png', ['Authorization' =>'Basic YWRtaW46MTIzNA==',        ]);    });

If you want more control over the GET request, you can pass in an optional third parameter, which gives you the Curl resource.

$watermark->openUrl('https://videocoursebuilder.com/logo.png', ['Authorization' =>'Basic YWRtaW46MTIzNA==',],function($curl) {curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,0);curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);});

Watermark manipulation

This package can manipulate watermarks by usingSpatie's Image package. To get started, install the package with Composer:

composer require spatie/image

Now you can chain one more manipulation methods on theWatermarkFactory instance:

FFMpeg::open('steve_howe.mp4')    ->addWatermark(function(WatermarkFactory$watermark) {$watermark->open('logo.png')            ->right(25)            ->bottom(25)            ->width(100)            ->height(100)            ->greyscale();    });

Check outthe documentation for all available methods.

Export without transcoding

This package comes with aProtoneMedia\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:

useProtoneMedia\LaravelFFMpeg\FFMpeg\CopyFormat;FFMpeg::open('video.mp4')    ->export()    ->inFormat(newCopyFormat)    ->save('video.mkv');

Chain multiple convertions

// The 'fromDisk()' method is not required, the file will now// be opened from the default 'disk', as specified in// the config file.FFMpeg::open('my_movie.mov')// export to FTP, converted in WMV    ->export()    ->toDisk('ftp')    ->inFormat(new \FFMpeg\Format\Video\WMV)    ->save('my_movie.wmv')// export to Amazon S3, converted in X264    ->export()    ->toDisk('s3')    ->inFormat(new \FFMpeg\Format\Video\X264)    ->save('my_movie.mkv');// you could even discard the 'toDisk()' method,// now the converted file will be saved to// the same disk as the source!    ->export()    ->inFormat(newFFMpeg\Format\Video\WebM)    ->save('my_movie.webm')// optionally you could set the visibility// of the exported file    ->export()    ->inFormat(newFFMpeg\Format\Video\WebM)    ->withVisibility('public')    ->save('my_movie.webm')

Export a frame from a video

FFMpeg::fromDisk('videos')    ->open('steve_howe.mp4')    ->getFrameFromSeconds(10)    ->export()    ->toDisk('thumnails')    ->save('FrameAt10sec.png');// Instead of the 'getFrameFromSeconds()' method, you could// also use the 'getFrameFromString()' or the// 'getFrameFromTimecode()' methods:$media = FFMpeg::open('steve_howe.mp4');$frame =$media->getFrameFromString('00:00:13.37');// or$timecode =newFFMpeg\Coordinate\TimeCode(...);$frame =$media->getFrameFromTimecode($timecode);

You can also get the raw contents of the frame instead of saving it to the filesystem:

$contents = FFMpeg::open('video.mp4')    ->getFrameFromSeconds(2)    ->export()    ->getFrameContents();

Export multiple frames at once

There is aTileFilter that powers theTile-feature. To make exporting multiple frames faster and simpler, we leveraged this feature to add some helper methods. For example, you may use theexportFramesByInterval method to export frames by a fixed interval. Alternatively, you may pass the number of frames you want to export to theexportFramesByAmount method, which will then calculate the interval based on the duration of the video.

FFMpeg::open('video.mp4')    ->exportFramesByInterval(2)    ->save('thumb_%05d.jpg');

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.

FFMpeg::open('video.mp4')    ->exportFramesByAmount(10,320,180)    ->save('thumb_%05d.png');

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 is2-31, with2 being the best quality and31 being the worst.

FFMpeg::open('video.mp4')    ->exportFramesByInterval(2,640,360,5)    ->save('thumb_%05d.jpg');

Creates tiles of frames

You can create tiles from a video. You may call theexportTile 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.

useProtoneMedia\LaravelFFMpeg\Filters\TileFactory;FFMpeg::open('steve_howe.mp4')    ->exportTile(function (TileFactory$factory) {$factory->interval(5)            ->scale(160,90)            ->grid(3,5);    })    ->save('tile_%05d.jpg');

Instead of passing both the width and height, you may also pass just one of them likescale(160) orscale(null, 90). The aspect ratio will be respected. TheTileFactory hasmargin,padding,width, andheight methods as well. There's also aquality method to specify the quality when exporting to a lossy format like JPEG. The range for JPEG is2-31, with2 being the best quality and31 being the worst.

This package can also generate a WebVTT file to addPreview Thumbnails to your video player. This is supported out-of-the-box byJW player and there are community-driven plugins for Video.js available as well. You may call thegenerateVTT method on theTileFactory with the desired filename:

FFMpeg::open('steve_howe.mp4')    ->exportTile(function (TileFactory$factory) {$factory->interval(10)            ->scale(320,180)            ->grid(5,5)            ->generateVTT('thumbnails.vtt');    })    ->save('tile_%05d.jpg');

Multiple exports using loops

Chaining multiple conversions works because thesave method of theMediaExporter returns a fresh instance of theMediaOpener. You can use this to loop through items, for example, to exports multiple frames from one video:

$mediaOpener = FFMpeg::open('video.mp4');foreach ([5,15,25]as$key =>$seconds) {$mediaOpener =$mediaOpener->getFrameFromSeconds($seconds)        ->export()        ->save("thumb_{$key}.png");}

TheMediaOpener comes with aneach method as well. The example above could be refactored like this:

FFMpeg::open('video.mp4')->each([5,15,25],function ($ffmpeg,$seconds,$key) {$ffmpeg->getFrameFromSeconds($seconds)->export()->save("thumb_{$key}.png");});

Create a timelapse

You can create a timelapse from a sequence of images by using theasTimelapseWithFramerate method on the exporter

FFMpeg::open('feature_%04d.png')    ->export()    ->asTimelapseWithFramerate(1)    ->inFormat(newX264)    ->save('timelapse.mp4');

Multiple inputs

You can open multiple inputs, even from different disks. This uses FFMpeg'smap andfilter_complex features. You can open multiple files by chaining theopen method of by using an array. You can mix inputs from different disks.

FFMpeg::open('video1.mp4')->open('video2.mp4');FFMpeg::open(['video1.mp4','video2.mp4']);FFMpeg::fromDisk('uploads')    ->open('video1.mp4')    ->fromDisk('archive')    ->open('video2.mp4');

When you open multiple inputs, you have to add mappings so FFMpeg knows how to route them. This package provides aaddFormatOutputMapping 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 instanceofProtoneMedia\LaravelFFMpeg\Filesystem\Media. You can instantiate with themake 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.

FFMpeg::fromDisk('local')    ->open(['video.mp4','audio.m4a'])    ->export()    ->addFormatOutputMapping(newX264, Media::make('local','new_video.mp4'), ['0:v','1:a'])    ->save();

This is an examplefrom the underlying library:

// This code takes 2 input videos, stacks they horizontally in 1 output video and// adds to this new video the audio from the first video. (It is impossible// with a simple filter graph that has only 1 input and only 1 output).FFMpeg::fromDisk('local')    ->open(['video.mp4','video2.mp4'])    ->export()    ->addFilter('[0:v][1:v]','hstack','[v]')// $in, $parameters, $out    ->addFormatOutputMapping(newX264, Media::make('local','stacked_video.mp4'), ['0:a','[v]'])    ->save();

Just like single inputs, you can also pass a callback to theaddFilter method. This will give you an instance of\FFMpeg\Filters\AdvancedMedia\ComplexFilters:

useFFMpeg\Filters\AdvancedMedia\ComplexFilters;FFMpeg::open(['video.mp4','video2.mp4'])    ->export()    ->addFilter(function(ComplexFilters$filters) {// $filters->watermark(...);    });

Opening files from the web works similarly. You can pass an array of URLs to theopenUrl method, optionally with custom HTTP headers.

FFMpeg::openUrl(['https://videocoursebuilder.com/lesson-3.mp4','https://videocoursebuilder.com/lesson-4.mp4',]);FFMpeg::openUrl(['https://videocoursebuilder.com/lesson-3.mp4','https://videocoursebuilder.com/lesson-4.mp4',], ['Authorization' =>'Basic YWRtaW46MTIzNA==',]);

If you want to use another set of HTTP headers for each URL, you can chain theopenUrl method:

FFMpeg::openUrl('https://videocoursebuilder.com/lesson-5.mp4', ['Authorization' =>'Basic YWRtaW46MTIzNA==',])->openUrl('https://videocoursebuilder.com/lesson-6.mp4', ['Authorization' =>'Basic bmltZGE6NDMyMQ==',]);

Concat files without transcoding

FFMpeg::fromDisk('local')    ->open(['video.mp4','video2.mp4'])    ->export()    ->concatWithoutTranscoding()    ->save('concat.mp4');

Concat files with transcoding

FFMpeg::fromDisk('local')    ->open(['video.mp4','video2.mp4'])    ->export()    ->inFormat(newX264)    ->concatWithTranscoding($hasVideo =true,$hasAudio =true)    ->save('concat.mp4');

Determinate duration

With theMedia class you can determinate the duration of a file:

$media = FFMpeg::open('wwdc_2006.mp4');$durationInSeconds =$media->getDurationInSeconds();// returns an int$durationInMiliseconds =$media->getDurationInMiliseconds();// returns a float

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 thecleanupTemporaryFiles() method:

FFMpeg::cleanupTemporaryFiles();

By default, the root of the temporary directories is evaluated by PHP'ssys_get_temp_dir() method, but you can modify it by setting thetemporary_files_root configuration key to a custom path.

HLS

You can create a M3U8 playlist to doHLS.

$lowBitrate = (newX264)->setKiloBitrate(250);$midBitrate = (newX264)->setKiloBitrate(500);$highBitrate = (newX264)->setKiloBitrate(1000);FFMpeg::fromDisk('videos')    ->open('steve_howe.mp4')    ->exportForHLS()    ->setSegmentLength(10)// optional    ->setKeyFrameInterval(48)// optional    ->addFormat($lowBitrate)    ->addFormat($midBitrate)    ->addFormat($highBitrate)    ->save('adaptive_steve.m3u8');

TheaddFormat 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 theMultiple inputs section to understand how complex filters are handled.

You can use theaddFilter method to add a complex filter (see$lowBitrate example). Since thescale filter is used a lot, there is a helper method (see$midBitrate example). You can also use a callable to get access to theComplexFilters 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'smap andfilter_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 theaddFilter calls withaddLegacyFilter calls and verify the result (see$superBitrate example). Not all filters will work this way and some need to be upgraded manually.

$lowBitrate = (newX264)->setKiloBitrate(250);$midBitrate = (newX264)->setKiloBitrate(500);$highBitrate = (newX264)->setKiloBitrate(1000);$superBitrate = (newX264)->setKiloBitrate(1500);FFMpeg::open('steve_howe.mp4')    ->exportForHLS()    ->addFormat($lowBitrate,function($media) {$media->addFilter('scale=640:480');    })    ->addFormat($midBitrate,function($media) {$media->scale(960,720);    })    ->addFormat($highBitrate,function ($media) {$media->addFilter(function ($filters,$in,$out) {$filters->custom($in,'scale=1920:1200',$out);// $in, $parameters, $out        });    })    ->addFormat($superBitrate,function($media) {$media->addLegacyFilter(function ($filters) {$filters->resize(new \FFMpeg\Coordinate\Dimension(2560,1920));        });    })    ->save('adaptive_steve.m3u8');

Using custom segment patterns

You can use a custom pattern to name the segments and playlists. TheuseSegmentFilenameGenerator 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 yoursegments pattern. The fifth argument is a callback you should call with yourplaylist pattern. Note that this is not the name of the primary playlist, but the name of the playlist of each format.

FFMpeg::fromDisk('videos')    ->open('steve_howe.mp4')    ->exportForHLS()    ->useSegmentFilenameGenerator(function ($name,$format,$key,callable$segments,callable$playlist) {$segments("{$name}-{$format->getKiloBitrate()}-{$key}-%03d.ts");$playlist("{$name}-{$format->getKiloBitrate()}-{$key}.m3u8");    });

Encrypted HLS

You can encrypt each HLS segment using AES-128 encryption. To do this, call thewithEncryptionKey method on the HLS exporter with a key. We provide agenerateEncryptionKey helper method on theHLSExporter 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 issecret.key, but you can change that with the optional second parameter of thewithEncryptionKey method.

useProtoneMedia\LaravelFFMpeg\Exporters\HLSExporter;$encryptionKey = HLSExporter::generateEncryptionKey();FFMpeg::open('steve_howe.mp4')    ->exportForHLS()    ->withEncryptionKey($encryptionKey)    ->addFormat($lowBitrate)    ->addFormat($midBitrate)    ->addFormat($highBitrate)    ->save('adaptive_steve.m3u8');

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 thewithRotatingEncryptionKey method to enable this feature and provide a callback that implements the storage of the keys.

FFMpeg::open('steve_howe.mp4')    ->exportForHLS()    ->withRotatingEncryptionKey(function ($filename,$contents) {$videoId =1;// use this callback to store the encryption keys        Storage::disk('secrets')->put($videoId .'/' .$filename,$contents);// or...DB::table('hls_secrets')->insert(['video_id' =>$videoId,'filename' =>$filename,'contents' =>$contents,        ]);    })    ->addFormat($lowBitrate)    ->addFormat($midBitrate)    ->addFormat($highBitrate)    ->save('adaptive_steve.m3u8');

ThewithRotatingEncryptionKey method has an optional second argument to set the number of segments that use the same key. This defaults to1.

FFMpeg::open('steve_howe.mp4')    ->exportForHLS()    ->withRotatingEncryptionKey($callable,10);

Some filesystems, especially on cheap and slow VPSs, are not fast enough to handle the rotating key. This may lead to encoding exceptions, likeNo key URI specified in key info file. One possible solution is to use a different storage for the keys, which you can specify using thetemporary_files_encrypted_hls configuration key. On UNIX-based systems, you may use atmpfs filesystem to increase read/write speeds:

// config/laravel-ffmpeg.phpreturn ['temporary_files_encrypted_hls' =>'/dev/shm'];

Protecting your HLS encryption keys

To make working with encrypted HLS even better, we've added aDynamicHLSPlaylist 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 likeGates andMiddleware.

In this example, we've saved the HLS export to thepublic disk, and we've stored the encryption keys to thesecrets 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 theDynamicHLSPlaylist class. Call thedynamicHLSPlaylist method on theFFMpeg facade, and similar to opening media files, you can open a playlist utilizing thefromDisk andopen methods. Then you must provide three callbacks. Each of them gives you a relative path and expects a full path in return. As theDynamicHLSPlaylist class implements theIlluminate\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 usingStorage::disk('public')->url('adaptive_steve.m3u8') to get the full url to your primary playlist, you can useroute('video.playlist', ['playlist' => 'adaptive_steve.m3u8']). TheDynamicHLSPlaylist class takes care of all the paths and urls.

Route::get('/video/secret/{key}',function ($key) {return Storage::disk('secrets')->download($key);})->name('video.key');Route::get('/video/{playlist}',function ($playlist) {return FFMpeg::dynamicHLSPlaylist()        ->fromDisk('public')        ->open($playlist)        ->setKeyUrlResolver(function ($key) {returnroute('video.key', ['key' =>$key]);        })        ->setMediaUrlResolver(function ($mediaFilename) {return Storage::disk('public')->url($mediaFilename);        })        ->setPlaylistUrlResolver(function ($playlistFilename) {returnroute('video.playlist', ['playlist' =>$playlistFilename]);        });})->name('video.playlist');

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 thegetProcessOutput method. Though the use-case is limited, you can use it to analyze a file (for example, with thevolumedetect filter). It returns aProtoneMedia\LaravelFFMpeg\Support\ProcessOutput class that has three methods:all,errors andoutput. Each method returns an array with the corresponding lines.

$processOutput = FFMpeg::open('video.mp4')    ->export()    ->addFilter(['-filter:a','volumedetect','-f','null'])    ->getProcessOutput();$processOutput->all();$processOutput->errors();$processOutput->out();

Advanced

The Media object you get when you 'open' a file, actually holds the Media object that belongs to theunderlying driver. It handles dynamic method calls as you can seehere. This way all methods of the underlying driver are still available to you.

// This gives you an instance of ProtoneMedia\LaravelFFMpeg\MediaOpener$media = FFMpeg::fromDisk('videos')->open('video.mp4');// The 'getStreams' method will be called on the underlying Media object since// it doesn't exists on this object.$codec =$media->getVideoStream()->get('codec_name');

If you want direct access to the underlying object, call the object as a function (invoke):

// This gives you an instance of ProtoneMedia\LaravelFFMpeg\MediaOpener$media = FFMpeg::fromDisk('videos')->open('video.mp4');// This gives you an instance of FFMpeg\Media\MediaTypeInterface$baseMedia =$media();

Experimental

Theprogress listener exposes the transcoded percentage, but the underlying package also has an internalAbstractProgressListener 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 theProgressListenerDecorator. This feature is highly experimental, so be sure the test this thoroughly before using it in production.

useFFMpeg\Format\ProgressListener\AbstractProgressListener;useProtoneMedia\LaravelFFMpeg\FFMpeg\ProgressListenerDecorator;$format =new \FFMpeg\Format\Video\X264;$decoratedFormat = ProgressListenerDecorator::decorate($format);FFMpeg::open('video.mp4')    ->export()    ->inFormat($decoratedFormat)    ->onProgress(function ()use ($decoratedFormat) {$listeners =$decoratedFormat->getListeners();// array of listeners$listener =$listeners[0];// instance of AbstractProgressListener$listener->getCurrentPass();$listener->getTotalPass();$listener->getCurrentTime();    })    ->save('new_video.mp4');

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 thebeforeSaving method:

FFMpeg::open('video.mp4')    ->export()    ->inFormat(newX264)    ->beforeSaving(function ($commands) {$commands[] ='-hello';return$commands;    })    ->save('concat.mp4');

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

Changelog

Please seeCHANGELOG for more information about what has changed recently.

Testing

$ composertest

Contributing

Please seeCONTRIBUTING 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 emailcode@protone.media instead of using the issue tracker. Please do not email any questions, open an issue if you have a question.

Credits

License

The MIT License (MIT). Please seeLicense File for more information.

About

This package provides an integration with FFmpeg for Laravel. Laravel's Filesystem handles the storage of the files.

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published

Languages


[8]ページ先頭

©2009-2025 Movatter.jp