### Installation and Setup Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Instructions for installing the Laravel FFMpeg package via Composer and configuring it in Laravel's app.php file. Includes publishing the configuration file. ```bash composer require pbmedia/laravel-ffmpeg ``` ```php // config/app.php 'providers' => [ ... ProtoneMedia\LaravelFFMpeg\Support\ServiceProvider::class, ... ]; 'aliases' => [ ... 'FFMpeg' => ProtoneMedia\LaravelFFMpeg\Support\FFMpeg::class ... ]; ``` ```bash php artisan vendor:publish --provider="ProtoneMedia\LaravelFFMpeg\Support\ServiceProvider" ``` -------------------------------- ### Install Spatie Image Package Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Command to install the Spatie Image package, which is required for watermark manipulation. ```bash composer require spatie/image ``` -------------------------------- ### Complex Filter Graph Example (Horizontal Stack) Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Provides an example of using a complex filter graph to stack two input videos horizontally and append the audio from the first video to the resulting video. This demonstrates advanced filter usage with multiple inputs and outputs. ```php use ProtoneMedia\LaravelFFMpeg\Filesystem\Media; use FFMpeg\Format\Video\X264; FFMpeg::fromDisk('local') ->open(['video.mp4', 'video2.mp4']) ->export() ->addFilter('[0:v][1:v]', 'hstack', '[v]') // $in, $parameters, $out ->addFormatOutputMapping(new X264, Media::make('local', 'stacked_video.mp4'), ['0:a', '[v]') ->save(); ``` -------------------------------- ### Basic HLS Export Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Exports a video file into multiple HLS formats with different bitrates. This is the basic setup for adaptive bitrate streaming. ```php $lowBitrate = (new X264)->setKiloBitrate(250); $midBitrate = (new X264)->setKiloBitrate(500); $highBitrate = (new X264)->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'); ``` -------------------------------- ### Accessing Underlying Driver Methods Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md This example illustrates how to access the underlying driver's Media object in Laravel-FFMpeg. By calling the Media object as a function (invoking it), you can get direct access to the driver's specific methods, allowing for more advanced manipulations beyond the standard Laravel-FFMpeg interface. ```php $media = FFMpeg::fromDisk('videos')->open('video.mp4'); // Accessing methods directly on the underlying Media object $codec = $media->getVideoStream()->get('codec_name'); // Getting the underlying driver's Media object instance $baseMedia = $media(); ``` -------------------------------- ### Applying Video Filters with Filter Objects Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Applies video filters using specific Filter objects, such as `ClipFilter` to extract a segment of the video. This example clips the video starting from 5 seconds. ```php $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'); ``` -------------------------------- ### Get Video Dimensions (laravel-ffmpeg) Source: https://github.com/protonemedia/laravel-ffmpeg/wiki/Get-the-dimensions-of-a-Video-file Demonstrates how to obtain the dimensions of a video stream using the laravel-ffmpeg package. It provides examples for both current (v7.0+) and older versions of the library, highlighting the API changes. ```php // v7.0 and later: FFMpeg::open('video.mp4') ->getVideoStream() ->getDimensions(); // pre v7.0: FFMpeg::open('video.mp4') ->getStreams() ->videos() ->first() ->getDimensions(); ``` -------------------------------- ### Configure Temporary Filesystem for Encrypted HLS Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Provides an example of configuring the `temporary_files_encrypted_hls` key in `config/laravel-ffmpeg.php` to specify a different storage location for temporary files, which can improve performance on slower filesystems. ```php // config/laravel-ffmpeg.php return [ 'temporary_files_encrypted_hls' => '/dev/shm' ]; ``` -------------------------------- ### Applying Video Filters with Closure Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Applies video filters using a closure that modifies `VideoFilters`. This example resizes the video to 640x480 dimensions. ```php use FFMpeg\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'); ``` -------------------------------- ### Get Process Output Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md This code snippet shows how to retrieve the raw process output from FFMpeg operations. It uses the `getProcessOutput` method, which returns a `ProcessOutput` object. This object provides methods to access all lines, errors, or standard output from the process, useful for analysis like using the `volumedetect` filter. ```php $processOutput = FFMpeg::open('video.mp4') ->export() ->addFilter(['-filter:a', 'volumedetect', '-f', 'null']) ->getProcessOutput(); $processOutput->all(); $processOutput->errors(); $processOutput->out(); ``` -------------------------------- ### Modifying FFmpeg Commands Before Saving Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md This example shows how to modify the FFmpeg commands before they are executed by using the `beforeSaving` method. A callback function receives the command array, allowing you to add or alter commands. Note that this functionality is not compatible with concatenation or frame exports. ```php FFMpeg::open('video.mp4') ->export() ->inFormat(new X264) ->beforeSaving(function ($commands) { $commands[] = '-hello'; return $commands; }) ->save('concat.mp4'); ``` -------------------------------- ### Using Filesystem Instance for Opening Files Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Opens a media file using an instance of `Illuminate\Contracts\Filesystem\Filesystem` instead of `fromDisk`. This provides flexibility when working with custom filesystem configurations. ```php $media = FFMpeg::fromFilesystem($filesystem)->open('yesterday.mp3'); ``` -------------------------------- ### Testing Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md This command executes the test suite for the laravel-ffmpeg package. ```bash $ composer test ``` -------------------------------- ### Opening Multiple Input Files Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Demonstrates how to open multiple video files for processing, either by chaining the 'open' method or passing an array of files. It also shows how to handle inputs from different storage disks. ```php FFMpeg::open('video1.mp4')->open('video2.mp4'); FFMpeg::open(['video1.mp4', 'video2.mp4']); FFMpeg::fromDisk('uploads') ->open('video1.mp4') ->fromDisk('archive') ->open('video2.mp4'); ``` -------------------------------- ### Create a Timelapse Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Demonstrates how to create a timelapse video from a sequence of images. The `asTimelapseWithFramerate` method is used on the exporter to specify the framerate, and the output format can be set using `inFormat`. ```php FFMpeg::open('feature_%04d.png') ->export() ->asTimelapseWithFramerate(1) ->inFormat(new X264) ->save('timelapse.mp4'); ``` -------------------------------- ### Upgrading Notes Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Key changes and considerations when upgrading to v7 and v8 of the Laravel FFMpeg package, including namespace changes, configuration updates, and compatibility notes. ```markdown ## Upgrading to v8 * The `set_command_and_error_output_on_exception` configuration key now defaults to `true`, making exceptions more informative. Read more at the [Handling exceptions](#handling-exceptions) section. * The `enable_logging` configuration key has been replaced by `log_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 to `false`. * The *segment length* and *keyframe interval* of [HLS exports](#HLS) should be `2` or more; less is not supported anymore. * As Laravel 9 has migrated from [Flysystem 1.x to 3.x](https://laravel.com/docs/9.x/upgrade#flysystem-3), this version is not compatible with Laravel 8 or earlier. * If you're using the [Watermark manipulation](#watermark-manipulation) feature, make sure you upgrade [`spatie/image`](https://github.com/spatie/image) to v2. ## Upgrading to v7 * The namespace has changed to `ProtoneMedia\LaravelFFMpeg`, the facade has been renamed to `ProtoneMedia\LaravelFFMpeg\Support\FFMpeg`, and the Service Provider has been renamed to `ProtoneMedia\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](#using-custom-segment-patterns)). 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` and `filter_complex` features. It might be sufficient to replace all calls to `addFilter` with `addLegacyFilter`, but some filters should be migrated manually. Please read the [documentation on HLS](#hls) to find out more about adding filters. ``` -------------------------------- ### Basic File Conversion Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Converts an audio or video file from one disk to another using a specified format. It demonstrates the use of `fromDisk`, `open`, `export`, `toDisk`, `inFormat`, and `save` methods. ```php FFMpeg::fromDisk('songs') ->open('yesterday.mp3') ->export() ->toDisk('converted_songs') ->inFormat(new \FFMpeg\Format\Audio\Aac) ->save('yesterday.aac'); ``` -------------------------------- ### Video Transcoding with Custom Format and Progress Source: https://github.com/protonemedia/laravel-ffmpeg/wiki/Monitoring-the-transcoding-progress Demonstrates how to create a custom video format (X264) and attach a progress callback to monitor the transcoding process. This requires the FFMpeg PHP library. ```php $format = new \FFMpeg\Format\Video\X264; $format->on('progress', function($video, $format, $percentage) { echo "$percentage % transcoded"; }); ``` -------------------------------- ### Mapping Multiple Inputs to Output Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Explains how to map multiple input streams (video and audio) to a single output file using the 'addFormatOutputMapping' method, specifying output labels for the filter complex. It requires creating a Media instance for the output. ```php use ProtoneMedia\LaravelFFMpeg\Filesystem\Media; use FFMpeg\Format\Video\X264; FFMpeg::fromDisk('local') ->open(['video.mp4', 'audio.m4a']) ->export() ->addFormatOutputMapping(new X264, Media::make('local', 'new_video.mp4'), ['0:v', '1:a']) ->save(); ``` -------------------------------- ### Opening Files from URLs Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Illustrates how to open media files directly from web URLs using the 'openUrl' method. It supports passing an array of URLs and custom HTTP headers for authentication or other purposes. ```php 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==', ]); ``` -------------------------------- ### Exception Handling during Encoding Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Demonstrates how to catch `EncodingException` thrown when encoding fails. It shows how to retrieve the executed command and the error output log using `getCommand` and `getErrorOutput` methods. ```php try { FFMpeg::open('yesterday.mp3') ->export() ->inFormat(new Aac) ->save('yesterday.aac'); } catch (EncodingException $exception) { $command = $exception->getCommand(); $errorLog = $exception->getErrorOutput(); } ``` -------------------------------- ### HLS Export with Progress Callback Source: https://github.com/protonemedia/laravel-ffmpeg/wiki/Monitoring-the-transcoding-progress Shows how to export a video file for HLS streaming using the laravel-ffmpeg package. It includes a progress callback to display the percentage of the export process. ```php $exporter = FFMpeg::open('steve_howe.mp4') ->exportForHLS() ->onProgress(function ($percentage) { echo "$percentage % transcoded"; }); ``` -------------------------------- ### Chaining openUrl with Custom Headers Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Demonstrates how to chain the 'openUrl' method to process multiple remote files, each with potentially different HTTP headers, allowing for specific authentication or configuration per URL. ```php FFMpeg::openUrl('https://videocoursebuilder.com/lesson-5.mp4', [ 'Authorization' => 'Basic YWRtaW46MTIzNA==', ])->openUrl('https://videocoursebuilder.com/lesson-6.mp4', [ 'Authorization' => 'Basic bmltZGE6NDMyMQ==', ]); ``` -------------------------------- ### HLS Export with Custom Filters per Format Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Demonstrates how to add custom filters or use helper methods like `scale` for each HLS format. It also shows how to use legacy filters for backward compatibility. ```php $lowBitrate = (new X264)->setKiloBitrate(250); $midBitrate = (new X264)->setKiloBitrate(500); $highBitrate = (new X264)->setKiloBitrate(1000); $superBitrate = (new X264)->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 FFMpegCoordinateDimension(2560, 1920)); }); }) ->save('adaptive_steve.m3u8'); ``` -------------------------------- ### Create Tiles of Frames Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Enables the creation of tiled images from video frames using the `exportTile` method. This method allows customization of the grid layout, frame scaling, interval, margins, padding, and quality. It also supports generating a WebVTT file for preview thumbnails. ```php use ProtoneMedia\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'); ``` ```php 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 and Each Method Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Illustrates how to perform multiple video export operations sequentially. This can be achieved by chaining export and save methods within a loop or by utilizing the `each` method, which iterates over a collection of parameters to perform exports. ```php $mediaOpener = FFMpeg::open('video.mp4'); foreach ([5, 15, 25] as $key => $seconds) { $mediaOpener = $mediaOpener->getFrameFromSeconds($seconds) ->export() ->save("thumb_{$key}.png"); } ``` ```php FFMpeg::open('video.mp4')->each([5, 15, 25], function ($ffmpeg, $seconds, $key) { $ffmpeg->getFrameFromSeconds($seconds)->export()->save("thumb_{$key}.png"); }); ``` -------------------------------- ### Dynamic HLS Playlist for Encryption Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md This snippet demonstrates how to protect HLS encryption keys by creating dynamic playlists. It involves two routes: one for serving encryption keys and another for serving modified playlists. The DynamicHLSPlaylist class handles on-the-fly modifications, allowing integration of authentication and authorization logic. ```php 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) { return route('video.key', ['key' => $key]); }) ->setMediaUrlResolver(function ($mediaFilename) { return Storage::disk('public')->url($mediaFilename); }) ->setPlaylistUrlResolver(function ($playlistFilename) { return route('video.playlist', ['playlist' => $playlistFilename]); }); })->name('video.playlist'); ``` -------------------------------- ### Progress Monitoring with Remaining Time and Rate Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Enhances progress monitoring by providing a callback that includes the remaining time in seconds and the current transcoding rate, in addition to the percentage. ```php FFMpeg::open('steve_howe.mp4') ->export() ->onProgress(function ($percentage, $remaining, $rate) { echo "{$remaining} seconds left at rate: {$rate}"; }); ``` -------------------------------- ### Decorating Progress Listener Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md This snippet demonstrates how to decorate a format with `ProgressListenerDecorator` to access the underlying FFmpeg progress listener. It allows retrieving the current pass, total passes, and current time during transcoding. This feature is experimental. ```php use FFMpeg\Format\ProgressListener\AbstractProgressListener; use ProtoneMedia\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'); ``` -------------------------------- ### Chain Multiple Conversions Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Illustrates chaining multiple export operations to convert a video to different formats and save them to various disks, including setting file visibility. ```php // 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(new FFMpeg\Format\Video\WebM) ->save('my_movie.webm') // optionally you could set the visibility // of the exported file ->export() ->inFormat(new FFMpeg\Format\Video\WebM) ->withVisibility('public') ->save('my_movie.webm') ``` -------------------------------- ### Applying Filters After Export Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Demonstrates applying filters after the `export` method has been called. This allows for a different chaining order for applying transformations. ```php use FFMpeg\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'); ``` -------------------------------- ### Watermark Manipulation with Spatie Image Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Shows how to manipulate watermarks using Spatie's Image package, including setting dimensions and applying effects like greyscale. Requires `composer require spatie/image`. ```php FFMpeg::open('steve_howe.mp4') ->addWatermark(function(WatermarkFactory $watermark) { $watermark->open('logo.png') ->right(25) ->bottom(25) ->width(100) ->height(100) ->greyscale(); }); ``` -------------------------------- ### Progress Monitoring with Percentage Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Monitors the transcoding progress by providing a callback to the `onProgress` method. The callback receives the completed percentage of the transcoding process. ```php FFMpeg::open('steve_howe.mp4') ->export() ->onProgress(function ($percentage) { echo "{$percentage}% transcoded"; }); ``` -------------------------------- ### Using Callbacks for Complex Filters Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Shows how to pass a callback function to the 'addFilter' method, providing access to the ComplexFilters instance for more dynamic filter graph construction. ```php use FFMpeg\Filters\AdvancedMedia\ComplexFilters; FFMpeg::open(['video.mp4', 'video2.mp4']) ->export() ->addFilter(function(ComplexFilters $filters) { // $filters->watermark(...); }); ``` -------------------------------- ### Concatenating Files With Transcoding Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Demonstrates how to concatenate multiple video files while allowing for transcoding. This method enables joining files with different codecs or parameters by re-encoding them into a specified format. ```php use FFMpeg\Format\Video\X264; FFMpeg::fromDisk('local') ->open(['video.mp4', 'video2.mp4']) ->export() ->inFormat(new X264) ->concatWithTranscoding($hasVideo = true, $hasAudio = true) ->save('concat.mp4'); ``` -------------------------------- ### Open Watermark from URL Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Demonstrates opening a watermark image directly from a URL using the openUrl method, with support for custom HTTP headers and advanced cURL options. ```php 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==', ]); }); ``` ```php $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); }); ``` -------------------------------- ### Apply Custom Filters Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Demonstrates how to apply custom FFmpeg filters to video files using the addFilter method. Filters can be provided as an array of arguments or as separate string arguments. ```php FFMpeg::fromDisk('videos') ->open('steve_howe.mp4') ->addFilter(['-itsoffset', 1]); ``` ```php FFMpeg::fromDisk('videos') ->open('steve_howe.mp4') ->addFilter('-itsoffset', 1); ``` -------------------------------- ### Opening Files from the Web Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Opens media files directly from a web URL using the `openUrl` method. Custom HTTP headers can be provided as an optional second parameter. ```php FFMpeg::openUrl('https://videocoursebuilder.com/lesson-1.mp4'); FFMpeg::openUrl('https://videocoursebuilder.com/lesson-2.mp4', [ 'Authorization' => 'Basic YWRtaW46MTIzNA==', ]); ``` -------------------------------- ### Add Watermark with Positioning Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Shows how to add a watermark to a video using the addWatermark method and position it using top, right, bottom, and left offsets. The watermark file can be opened from a specified disk. ```php use ProtoneMedia\LaravelFFMpeg\Filters\WatermarkFactory; FFMpeg::fromDisk('videos') ->open('steve_howe.mp4') ->addWatermark(function(WatermarkFactory $watermark) { $watermark->fromDisk('local') ->open('logo.png') ->right(25) ->bottom(25); }); ``` -------------------------------- ### Opening Uploaded Files Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Opens uploaded files directly from a Laravel `Request` instance. It's recommended to save the file first, but `UploadedFile` instances can be opened directly. ```php class UploadVideoController { public function __invoke(Request $request) { FFMpeg::open($request->file('video')); } } ``` -------------------------------- ### Add Watermark with Alignment Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Illustrates adding a watermark with horizontal and vertical alignment using constants like WatermarkFactory::LEFT and WatermarkFactory::TOP, along with optional offsets. ```php FFMpeg::open('steve_howe.mp4') ->addWatermark(function(WatermarkFactory $watermark) { $watermark->open('logo.png') ->horizontalAlignment(WatermarkFactory::LEFT, 25) ->verticalAlignment(WatermarkFactory::TOP, 25); }); ``` -------------------------------- ### Implement Rotating AES-128 Encryption Keys for HLS Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Shows how to enable rotating encryption keys for HLS exports using `withRotatingEncryptionKey`. A callback function is provided to handle the storage of generated keys, demonstrating both file-based and database-based storage methods. ```php 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'); ``` -------------------------------- ### Resizing Video Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Applies a dedicated `resize` method to change the video dimensions. It supports different modes like 'fit', 'inset', 'width', 'height' and an option to force standard ratios. ```php FFMpeg::open('steve_howe.mp4') ->export() ->inFormat(new \FFMpeg\Format\Video\X264) ->resize(640, 480) ->save('steve_howe_resized.mp4'); ``` -------------------------------- ### HLS Export with Custom Segment Filename Generator Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Shows how to define a custom pattern for naming HLS segments and playlists using the `useSegmentFilenameGenerator` method. ```php 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"); }); ``` -------------------------------- ### Applying Custom Filters with addFilter Source: https://github.com/protonemedia/laravel-ffmpeg/wiki/Custom-filters Demonstrates how to add custom FFmpeg filters to a processing pipeline. The `addFilter` method can accept filters as individual string arguments or as an array of arguments, allowing for flexible filter configuration. ```php FFMpeg::fromDisk('images') ->open('image%04d.jpg') ->addFilter('-r', 60) ->addFilter(['-f', 'image2']) ``` -------------------------------- ### Export Without Transcoding Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Demonstrates exporting a video file to a different container format without re-encoding the streams using the CopyFormat class. ```php use ProtoneMedia\LaravelFFMpeg\FFMpeg\CopyFormat; FFMpeg::open('video.mp4') ->export() ->inFormat(new CopyFormat) ->save('video.mkv'); ``` -------------------------------- ### WEVTT Sprite Sheet Coordinates Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/tests/__snapshots__/VTTPreviewThumbnailsGeneratorTest__it_can_generate_a_vtt_file__1.txt This snippet demonstrates the format of a WEBVTT file used for sprite sheet generation. Each entry specifies the image file and the bounding box (x, y, width, height) for a particular frame within the sprite sheet, along with its corresponding timestamp. ```vtt 00:00:00.000 --> 00:00:05.000 sprite_1.jpg#xywh=0,0,160,90 00:00:05.000 --> 00:00:10.000 sprite_1.jpg#xywh=160,0,160,90 00:00:10.000 --> 00:00:15.000 sprite_1.jpg#xywh=320,0,160,90 ``` -------------------------------- ### Parse WEBVTT for Sprite Sheet Frames Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/tests/__snapshots__/VTTPreviewThumbnailsGeneratorTest__it_can_generate_a_vtt_file_and_keep_the_margin_and_padding_in_account__1.txt This snippet demonstrates how to parse a WEBVTT file to extract frame information, including image source and coordinates (xywh). This data is crucial for generating sprite sheets by defining the position and size of each frame within the sheet. ```PHP 00:00:10.000 sprite_1.jpg#xywh=5,5,160,90 00:00:10.000 --> 00:00:20.000 sprite_1.jpg#xywh=180,5,160,90 VTT; $frames = []; $lines = explode('\n', $vttContent); foreach ($lines as $line) { if (str_contains($line, '#xywh=')) { $parts = explode('#xywh=', $line); $imageInfo = $parts[0]; // e.g., sprite_1.jpg $xywh = $parts[1]; // e.g., 5,5,160,90 $coordinates = explode(',', $xywh); $frames[] = [ 'image' => $imageInfo, 'x' => (int) $coordinates[0], 'y' => (int) $coordinates[1], 'width' => (int) $coordinates[2], 'height' => (int) $coordinates[3], ]; } } // $frames now contains an array of frame data // Example: print_r($frames); ?> ``` -------------------------------- ### Cleaning Up Temporary Files Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Provides instructions on how to clean up temporary files created during the processing of remote disks. The 'cleanupTemporaryFiles' method removes these intermediate files after export or processing is complete. ```php FFMpeg::cleanupTemporaryFiles(); ``` -------------------------------- ### Export Multiple Frames by Interval or Amount Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Provides methods to export multiple frames from a video efficiently. `exportFramesByInterval` exports frames at a fixed time interval, while `exportFramesByAmount` calculates the interval based on video duration. Both methods allow specifying frame dimensions and JPEG quality. ```php FFMpeg::open('video.mp4') ->exportFramesByInterval(2) ->save('thumb_%05d.jpg'); ``` ```php FFMpeg::open('video.mp4') ->exportFramesByAmount(10, 320, 180) ->save('thumb_%05d.png'); ``` ```php FFMpeg::open('video.mp4') ->exportFramesByInterval(2, 640, 360, 5) ->save('thumb_%05d.jpg'); ``` -------------------------------- ### Export a Frame from a Video Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Demonstrates how to extract a single frame from a video at a specific time. Supports extraction by seconds, time string, or TimeCode object. The extracted frame can be saved to a disk or its raw contents can be retrieved. ```php FFMpeg::fromDisk('videos') ->open('steve_howe.mp4') ->getFrameFromSeconds(10) ->export() ->toDisk('thumnails') ->save('FrameAt10sec.png'); ``` ```php $media = FFMpeg::open('steve_howe.mp4'); $frame = $media->getFrameFromString('00:00:13.37'); ``` ```php $timecode = new FFMpeg\Coordinate\TimeCode(...); $frame = $media->getFrameFromTimecode($timecode); ``` ```php $contents = FFMpeg::open('video.mp4') ->getFrameFromSeconds(2) ->export() ->getFrameContents(); ``` -------------------------------- ### Sprite Sheet Frame Definitions Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/tests/__snapshots__/VTTPreviewThumbnailsGeneratorTest__it_can_generate_a_vtt_file_with_a_non_sqaure_grid__1.txt Defines the coordinates for each frame within a sprite sheet. This format is commonly used in WebVTT files for video sprite sheet mapping. ```APIDOC sprite_sheet_file.jpg#xywh=x,y,width,height - sprite_sheet_file.jpg: The source image file for the sprite sheet. - x: The x-coordinate of the top-left corner of the frame. - y: The y-coordinate of the top-left corner of the frame. - width: The width of the frame. - height: The height of the frame. ``` -------------------------------- ### Concatenating Files Without Transcoding Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Shows how to concatenate multiple video files into a single output file without re-encoding them, preserving the original quality and reducing processing time. This is useful for joining files with identical codecs and parameters. ```php FFMpeg::fromDisk('local') ->open(['video.mp4', 'video2.mp4']) ->export() ->concatWithoutTranscoding() ->save('concat.mp4'); ``` -------------------------------- ### Determining Media Duration Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Explains how to use the Media class to retrieve the duration of a video file in both seconds (integer) and milliseconds (float). This is useful for metadata extraction or time-based operations. ```php $media = FFMpeg::open('wwdc_2006.mp4'); $durationInSeconds = $media->getDurationInSeconds(); // returns an int $durationInMiliseconds = $media->getDurationInMiliseconds(); // returns a float ``` -------------------------------- ### Generate and Use AES-128 Encryption Key for HLS Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Demonstrates how to generate an AES-128 encryption key using `HLSExporter::generateEncryptionKey()` and apply it to an HLS export. The key is stored by default as 'secret.key', but this filename can be customized. ```php use ProtoneMedia\LaravelFFMpeg\Exporters\HLSExporter; $encryptionKey = HLSExporter::generateEncryptionKey(); FFMpeg::open('steve_howe.mp4') ->exportForHLS() ->withEncryptionKey($encryptionKey) ->addFormat($lowBitrate) ->addFormat($midBitrate) ->addFormat($highBitrate) ->save('adaptive_steve.m3u8'); ``` -------------------------------- ### Configure Key Rotation Segment Count Source: https://github.com/protonemedia/laravel-ffmpeg/blob/main/README.md Illustrates how to specify the number of segments that share the same encryption key when using `withRotatingEncryptionKey`. The second argument to the method controls this count, defaulting to 1. ```php FFMpeg::open('steve_howe.mp4') ->exportForHLS() ->withRotatingEncryptionKey($callable, 10); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.