pbmedia / laravel-ffmpeg
FFMpeg for Laravel
Fund package maintenance!
Requires
- php: ^8.4
- ext-dom: *
- laravel/framework: ^13.44.1
- laravel/serializable-closure: ^2.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.95
- intervention/image: ^4.2
- larastan/larastan: ^3.9
- laravel/pint: ^1.14
- league/flysystem-aws-s3-v3: ^3.25.1
- league/flysystem-memory: ^3.10
- league/flysystem-path-prefixing: ^3.0
- league/flysystem-read-only: ^3.0
- mockery/mockery: ^1.4.4
- nesbot/carbon: ^2.66|^3.0
- orchestra/testbench: ^11.0
- phpunit/phpunit: ^11.5.3|^12.5.12
- rector/rector: ^2.3
Suggests
- intervention/image: Required to edit watermark images, for example grayscale() or blur() (^4.2).
Provides
None
Conflicts
None
Replaces
None
- dev-main
- 9.0.7
- 9.0.6
- 9.0.5
- 9.0.4
- 9.0.3
- 9.0.2
- 9.0.1
- 9.0.0
- 8.x-dev
- 8.10.0
- 8.9.0
- 8.8.0
- 8.7.1
- 8.7.0
- 8.6.0
- 8.5.0
- 8.4.0
- 8.3.0
- 8.2.2
- 8.2.1
- 8.2.0
- 8.1.2
- 8.1.1
- 8.1.0
- 8.0.2
- 8.0.1
- 8.0.0
- 7.x-dev
- 7.8.1
- 7.8.0
- 7.7.3
- 7.7.2
- 7.7.1
- 7.7.0
- 7.6.0
- 7.5.12
- 7.5.11
- 7.5.10
- 7.5.9
- 7.5.8
- 7.5.7
- 7.5.6
- 7.5.5
- 7.5.4
- 7.5.3
- 7.5.2
- 7.5.1
- 7.5.0
- 7.4.1
- 7.4.0
- 7.3.0
- 7.2.0
- 7.1.0
- 7.0.5
- 7.0.4
- 7.0.3
- 7.0.2
- 7.0.1
- 7.0.0
- 6.0.0
- 5.0.1
- 5.0.0
- 4.1.0
- 4.0.1
- 4.0.0
- 3.0.2
- 3.0.1
- 3.0.0
- 2.1.1
- 2.1.0
- 2.0.1
- 2.0.0
- 1.3.0
- 1.2.0
- 1.1.12
- 1.1.11
- 1.1.10
- 1.1.9
- 1.1.8
- 1.1.7
- 1.1.6
- 1.1.5
- 1.1.4
- 1.1.3
- 1.1.2
- 1.1.1
- 1.1.0
- 1.0.1
- 1.0.0
This package is auto-updated.
Last update: 2026-11-26 18:13:08 UTC
README
Laravel FFmpeg provides a fluent API for encoding video, processing audio, and publishing adaptive streams. It is built on Laravel's Process, Storage, Http, and Queue features, so it works with your existing disks and queue connections:
use ProtoneMedia\LaravelFFMpeg\Support\FFMpeg; $result = FFMpeg::open('lessons/original.mp4') ->export() ->resize(width: 1280) ->video('libx264', crf: 23) ->audio('aac', bitrate: '128k') ->save('lessons/720p.mp4');
You may run an export immediately or dispatch it to a queue, and each completed export lists its generated files, including playlists, segments, and keys.
Important
Version 9 replaces PHP-FFMpeg and removes its format and filter objects, so consult the upgrade guide when upgrading from version 8. The version 8 documentation lives on the 8.x branch.
- Support Laravel FFmpeg
- Getting Started
- Working With Media
- Transforming Media
- Streaming
- Running Exports
- Deployment and Development
- Community
Support Laravel FFmpeg
Laravel FFmpeg is free and open source. To support its development, check out Inertia UI, a set of Laravel-first components for Inertia.js apps with Vue 3 and React 19. Inertia Table and Inertia Forms are premium packages, and Inertia Modal and Inertia Notifications are free:
- Inertia Table defines the query, sorting, filters, exports, saved views, and bulk actions of a table in one PHP class.
- Inertia Forms builds forms with over 30 field types, validation, uploads, model binding, and wizards from one PHP class.
- Inertia Modal opens any route in a modal or slideover without changes to your routes or controllers.
- Inertia Notifications adds toasts, a notification inbox, and preferences that users set themselves.
You may also sponsor the development through GitHub Sponsors.
Getting Started
Installation
Laravel FFmpeg requires PHP 8.4 or later, Laravel 13.44.1 or later, and matching FFmpeg and FFprobe binaries of release 9.0 or later; setup and CI use 9.0.2. Applications on Laravel 9 to 12 may use version 8 instead. You may install the package using Composer:
composer require pbmedia/laravel-ffmpeg
Laravel discovers the service provider and facade automatically. To edit watermark images, you should also install Intervention Image, which powers Laravel's image manipulation:
composer require intervention/image:^4.2
To give AI agents the version 9 guidance, follow the Laravel Boost steps: an agent that runs boost:install --no-interaction installs the guidance only when your boost.json file already lists the package.
Publishing the Configuration
To customize binary paths, timeouts, or queue defaults, you may publish the config/laravel-ffmpeg.php file using the vendor:publish Artisan command:
php artisan vendor:publish --provider="ProtoneMedia\LaravelFFMpeg\Support\ServiceProvider" --tag=config
Binaries are validated only when used, so configuration caching never launches FFmpeg. Set the executable paths and an existing, writable temporary directory in your environment:
FFMPEG_BINARIES=/opt/ffmpeg/bin/ffmpeg FFPROBE_BINARIES=/opt/ffmpeg/bin/ffprobe FFMPEG_TEMPORARY_FILES_ROOT=/var/tmp/media
Your build must include the encoders, filters, and protocols your application uses; the repository's .agents/install-ffmpeg script builds the tested pair.
Finding and Verifying the Executables
By default, ffmpeg and ffprobe are resolved through the process's PATH, which may differ between your shell, web server, and queue workers:
command -v ffmpeg command -v ffprobe
Set FFMPEG_BINARIES and FFPROBE_BINARIES, or the ffmpeg.binaries and ffprobe.binaries options, to full executable paths, including the file name, such as /usr/bin/ffmpeg rather than /usr/bin. An application in a Docker container needs the paths inside the container, not on the host. Both must report the same numbered release, 9.0 or later, so development snapshots that report a version such as N-120345-g1a2b3c4d5e are refused. Test them as your web server or queue worker user:
sudo -u www-data /opt/ffmpeg-9.0.2/bin/ffmpeg -version sudo -u www-data /opt/ffmpeg-9.0.2/bin/ffprobe -version
You may skip this release check, such as to run a development snapshot, by setting FFMPEG_VERIFY_VERSION or the verify_version option to false. The package only supports the releases the check accepts, and an executable that cannot start still fails with the launch category.
The application may still fail after both commands succeed. You should then check permissions and write access to the temporary root and Storage destinations. After changing paths, rebuild the configuration cache and restart queue workers.
Failures throw a MediaException whose phase, category, and bounded diagnostics explain the cause. Categories name conditions, such as launch for an executable that cannot be found, run, or load its shared libraries, version for an unsupported or mismatched pair, input for media that FFprobe or FFmpeg cannot read, encoder for an encoder the FFmpeg build lacks, dimensions for odd frame sizes, duration for a frame time or clip start past the end of the media, permission for a local destination the process may not write, metadata for an unknown duration, mapping for a missing track, signal for a process that another process or the operating system stopped, such as the out-of-memory killer, and interrupted for an export that a queue worker stopped after a signal. Other process failures have the exit category.
Warning
Raw commands and unredacted process exceptions may contain credentials, so never publish them in logs or error responses.
Inspecting Capabilities
The ffmpeg:doctor Artisan command checks matching versions, compiled-in support, and a temporary-workspace write, and exits nonzero when a repeatable --encoder, --muxer, --filter, --protocol, --bsf, or --hwaccel requirement is missing:
php artisan ffmpeg:doctor --encoder=libx264 --muxer=dash --filter=scale php artisan ffmpeg:doctor --json
Within your application, the capabilities method captures a fresh report on each call:
$capabilities = FFMpeg::capabilities(); $capabilities->has('encoders', 'libx264'); $capabilities->require(['encoders' => ['libx264', 'aac'], 'muxers' => ['dash']]); $capabilities->toArray();
Note
Compiled-in hardware support does not prove device access, driver compatibility, or encoder usability.
Laravel Boost
The package includes Laravel Boost guidelines and a developing-laravel-ffmpeg skill, so AI agents write version 9 code instead of calls from earlier releases. The boost:install Artisan command offers them in its package prompt, and you may add them to an existing installation using the --discover option of the boost:update command:
php artisan boost:install php artisan boost:update --discover
Both prompts need a terminal. Without one, such as when an AI agent or a CI job runs the command, Boost installs only the packages that your boost.json file already lists, and boost:update still reports success. To install the guidance without a prompt, add the package to the packages list in boost.json:
"packages": [ "pbmedia/laravel-ffmpeg" ]
Then run the boost:install command without interaction. Later boost:update runs keep the guidance installed:
php artisan boost:install --no-interaction
To check the installation, search your agent's guidelines file, such as AGENTS.md or CLAUDE.md, for the package's rules heading, === pbmedia/laravel-ffmpeg/core rules ===:
grep 'pbmedia/laravel-ffmpeg/core' AGENTS.md
No match means Boost skipped the package, so you should add it to boost.json and run the command again.
Working With Media
Encoding and Copying
To encode a video, open the source, call the export method, and configure the codecs. Each call to export creates an independent configuration:
use ProtoneMedia\LaravelFFMpeg\Support\FFMpeg; $media = FFMpeg::disk('uploads') ->open('lesson.mov'); $result = $media->export() ->video('libx264', crf: 23, preset: 'medium') ->audio('aac', bitrate: '128k') ->resize(width: 1280) ->toDisk('videos', ['visibility' => 'private']) ->save('lesson.mp4');
Without the toDisk method, outputs publish to the first input's disk, or to your filesystems.default disk for uploads, local files, and URLs. To change only the visibility of the published files, you may call the visibility method, such as ->visibility('public').
Other formats work the same way, such as VP9 and Opus in WebM, or MP3 audio. An export to an audio-only file, such as .mp3, .m4a, or .wav, keeps only the source's first audio stream:
$media->export() ->video('libvpx-vp9', crf: 31) ->audio('libopus', bitrate: '128k') ->videoOptions(['-row-mt', '1']) ->save('lesson.webm'); $media->export() ->audio('libmp3lame', bitrate: '192k') ->save('lesson.mp3');
Copying Streams
To change only the container, pass copy to the video and audio methods. Copying requires a compatible container and cannot be combined with filters or accurate clipping:
$media->export() ->video('copy') ->audio('copy') ->save('lesson.mkv');
To offer an HLS presentation as a download, you may copy an unencrypted variant playlist into a single MP4:
FFMpeg::disk('streams') ->open('lessons/42/720p/index.m3u8') ->export() ->video('copy') ->audio('copy') ->save('downloads/lesson-42.mp4');
Configuring Video Quality
The crf argument sets constant quality, while the bitrate argument accepts positive integer bits per second, such as 2500000, or a unit string, such as '2500k', but not floats or unitless strings. The two may not be combined. The preset argument trades encoding speed for compression, so a faster preset, such as veryfast, finishes sooner but produces a larger file.
Pixel Formats
Every video track encoded with libx264, including HLS variants and two-pass outputs, uses the 8-bit 4:2:0 yuv420p pixel format of the High profile, which browsers and Apple devices play. A 10-bit, 4:2:2, or 4:4:4 source, such as a phone's HEVC recording or a ProRes master, is converted to it. Other encoders keep the source's pixel format.
You may choose another pixel format using the videoOptions method, such as yuv420p10le for the High 10 profile:
$media->export() ->video('libx264') ->videoOptions(['-pix_fmt', 'yuv420p10le']) ->save('lesson-10-bit.mp4');
HDR and SDR Video
An export keeps the PQ (smpte2084) or HLG (arib-std-b67) color tags of an HDR source, along with its HDR10 mastering display and content light level metadata, even after converting the pixel format. The color method only relabels the video: it changes the tags, and a transfer other than PQ or HLG also drops the HDR10 metadata, but the pixel values stay HDR.
Converting HDR to SDR requires a tonemapping filter, such as zscale together with tonemap, or libplacebo. You may check for them using the capabilities method, then pass the chain to the videoFilter method and signal the SDR result with color:
$capabilities = FFMpeg::capabilities(); if ($capabilities->has('filters', 'zscale') && $capabilities->has('filters', 'tonemap')) { $media->export() ->videoFilter('zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,' .'tonemap=tonemap=hable:desat=0,zscale=t=bt709:m=bt709:r=tv,format=yuv420p') ->color('bt709', 'bt709', 'bt709') ->video('libx264') ->save('lesson-sdr.mp4'); }
Two-Pass Encoding and Clipping
Two-pass encoding requires a target video bitrate. You may enable it using the twoPass method, which keeps private statistics for each output. The clip method cuts accurately by default, transcoding the affected streams, while seek: 'keyframe' allows stream copying but may start early:
$media->export() ->video('libx264', bitrate: '2500k') ->audio('aac') ->twoPass() ->save('two-pass.mp4'); $media->export() ->video('libx264') ->audio('aac') ->clip('00:00:12.500', duration: 8) ->save('accurate.mp4'); $media->export() ->video('copy') ->audio('copy') ->clip(12.5, end: 20.5, seek: 'keyframe') ->save('keyframe.mkv');
Without a duration or an end, the clip runs to the end of the media, so clip(30) drops the first 30 seconds. Timeline changes omit chapters unless you map them explicitly.
Opening and Probing Media
The open method accepts a path on the default disk or an UploadedFile or File instance. You may select another disk using the disk method and open HTTP sources using the openUrl method:
use Illuminate\Http\File; use Illuminate\Support\Facades\Storage; $media = FFMpeg::open('lesson.mp4'); // Current filesystems.default. $media = FFMpeg::disk(Storage::disk('s3')) ->open('lesson.mp4'); $media = FFMpeg::open($request->file('video')); // In a controller. $media = FFMpeg::open(new File('/absolute/path/lesson.mp4')); $public = FFMpeg::openUrl('https://cdn.example.com/lesson.mp4'); $private = FFMpeg::openUrl( 'https://media.example.com/private/lesson.mp4', headers: ['Authorization' => 'Bearer '.config('services.media.token')], download: true, );
Paths are never URLs or absolute local paths, and opened media keeps its disk if your configuration changes. Nothing is read until an export runs: local files are read in place, while other disks stream into a private workspace. Scoped and read-only input disks keep their boundaries, and publishing to a read-only destination fails. An export checks local destinations before encoding and fails with the permission category when the nearest existing directory is not writable, while remote destinations are only written at publication.
Warning
HTTP inputs with credentials require download: true, which streams to a private file with deadlines, no redirects, and HTTPS verification. Otherwise the URL appears in FFmpeg's arguments, so never put reusable credentials in it. URL inputs publish to filesystems.default unless you call toDisk.
Inspecting Media
The probe method returns the source's duration, streams, chapters, and other metadata:
$metadata = $media->probe(); $metadata->duration(); // Nullable seconds. $metadata->video() ->width(); $metadata->audioStreams(); $metadata->chapters(); $metadata->get('format.tags.title'); $metadata->toArray();
The isValid method returns false instead of throwing when FFprobe cannot read the media or finds no video or audio stream, which is useful for validating uploads:
if (! FFMpeg::open($request->file('video'))->isValid()) { // ... }
The isValid method reads only the container header, so it does not prove that every frame decodes. A truncated upload whose header comes first, such as a faststart MP4 cut short, still passes, and its export then fails with the input category.
Caching Metadata
To cache a probe result, pass a cache repository, a versioned key, and a lifetime in seconds to the probeCached method:
use Illuminate\Support\Facades\Cache; $metadata = $media->probeCached( Cache::store('redis'), versionedKey: 'tenant:42:lesson:7:object-version:abc123', ttl: 600, );
Change the versionedKey whenever the source bytes or object version change; ordinary exports still probe their staged inputs.
Warning
A cache hit neither checks Storage nor reauthorizes the source. Your application owns freshness, tenant isolation, access, and eviction, and should protect cached metadata like the source itself.
Hardware Acceleration
To decode with hardware, pass the inputOptions argument when opening the source and select a matching encoder:
$gpuInput = FFMpeg::disk('uploads') ->open('lesson.mp4', inputOptions: [ '-hwaccel', 'cuda', '-hwaccel_device', '0', '-hwaccel_output_format', 'cuda', ]); $gpuInput->export() ->video('h264_nvenc') ->audio('copy') ->save('gpu.mp4');
The -hwaccel option accepts cuda, vaapi, qsv, vulkan, videotoolbox, d3d11va, or dxva2, but not auto. Filters that consume CPU frames may need an explicit hardware download and format conversion.
Note
Hardware is never selected automatically and has no CPU fallback. This example needs a CUDA-enabled build, an NVIDIA device, and a compatible decoder and encoder; hardware execution is not validated in the test environment.
Capturing Camera Snapshots
The openRtsp method returns an RtspCamera for bounded snapshots, and its frame method captures one frame into a private PNG that is then processed and published like any other image:
FFMpeg::openRtsp(config('services.camera.url'), transport: 'tcp', timeout: 10) ->frame() ->resize(width: 640) ->toDisk('images') ->save('camera.jpg');
The transport may be tcp or udp, with a positive timeout of at most 300 seconds.
Warning
Camera URLs should be trusted configuration. Restrict reachable hosts and protect camera credentials, which may appear in process arguments.
Querying Frames and Packets
For frame or packet data, use the probeQuery method, which returns a ProbeResult rather than full-asset Metadata:
$query = $media->probeQuery() ->selectStreams('v:0') ->keyframes() ->readInterval(12, 5) ->entries(['frame' => ['pts_time', 'key_frame', 'pict_type']]) ->limits(outputBytes: 4194304, timeout: 30) ->get(); $query->frames(); $query->bounds(); $query->toArray(); $packets = $media->probeQuery() ->selectStreams('a:0') ->packets() ->readPackets(100, start: 2) ->countPackets() ->get();
A query reads the first 10 seconds by default; seeking is approximate, and packet limits are not frame limits. Intervals are capped at 300 seconds, packets at 100,000, output at 16 MiB (default 4 MiB), and the cumulative timeout at 120 seconds (default 30), within global process limits and the input's staging, transport, and redaction rules.
Selecting Tracks and Metadata
By default, an export selects the first motion-video and audio stream. An audio-only destination, whose extension is aac, aif, aiff, caf, flac, m4a, m4b, mka, mp3, oga, ogg, opus, or wav, selects only the first audio stream, which must exist. The mapVideo, mapAudio, and map methods replace that selection; subtitles and cover art must be mapped explicitly with container-compatible codecs, such as mov_text for SRT subtitles in MP4. Stream tags and dispositions address output order:
$media->export() ->mapVideo() ->mapAudio(language: 'eng') ->video('copy') ->audio('copy') ->metadata('title', 'English lesson') ->streamMetadata('a:0', 'language', 'eng') ->disposition('a:0', ['default', 'comment']) ->save('english.mkv'); $media->export() ->map('0:V:0') ->map('0:a') ->map('0:s') ->map('0:v:1') ->video('copy') ->audio('copy') ->outputOptions(['-c:s', 'copy']) ->save('subtitles-and-cover.mp4'); $media->export() ->video('copy') ->audio('copy') ->withoutMetadata(chapters: true) ->save('without-tags.mkv');
Each probed Stream offers the language, isForced, isDefault, and isCoverArt methods, plus raw fields through get.
Either default stream may be missing, so an audio-only source exports its audio. An export or HLS variant that configures its video, such as through video, resize, or videoFilter, requires a video stream instead and throws a MediaException with the mapping category for an audio-only source. An audio-only destination ignores video settings, and watermarks and twoPass reject it. Copying the video with video('copy') keeps whatever streams the source has.
To turn audio into a video, you may generate the frames in a custom filter graph, such as a black background that lasts as long as the audio:
$podcast = FFMpeg::disk('uploads') ->open('episode.mp3'); $duration = $podcast->probe()->duration(); $podcast->export() ->filterComplex("color=c=black:s=1280x720:r=25:d={$duration}[video]") ->map('[video]') ->map('0:a:0') ->video('libx264') ->audio('aac') ->save('episode.mp4');
A [0:a]showwaves=s=1280x720:mode=line,format=yuv420p[video] graph draws the waveform instead.
Attaching Cover Art
The coverArt method attaches a PNG or JPEG to an MP4, M4A, or MP3 while copying its tracks. It refuses sources with existing art and cannot be combined with encoding, filters, clipping, custom maps, or disposition overrides:
$cover = FFMpeg::disk('assets') ->open('album.png'); $media->export() ->coverArt($cover) ->toDisk('videos') ->save('with-cover.mp4');
Configuring Individual Video Tracks
The videoStream method configures one output video track, counted from zero after mapping. Each track may be configured once and overrides the video method's settings:
$media->export() ->map('0:a:0') ->map('0:v:0') ->map('0:v:0') ->audio('copy') ->videoStream(0, fn ($track) => $track ->codec('libx264') ->crf(20) ->preset('medium')) ->videoStream(1, fn ($track) => $track ->codec('mpeg4') ->bitrate('800k')) ->save('two-video-tracks.mp4');
CRF and bitrate may not be combined, even through inherited settings, and per-track settings do not support two-pass encoding.
Extracting WebVTT Subtitles
To extract a text subtitle track as WebVTT, map it explicitly and select the webvtt codec. Speech recognition and bitmap subtitle conversion are not supported:
$media->export() ->map('0:s:0') ->outputOptions(['-c:s', 'webvtt']) ->toDisk('captions') ->save('english.vtt');
Configuring Encoders and Individual Audio Tracks
The audioStream method works the same way; here, the source's second audio track becomes the first output track:
$media->export() ->map('0:v:0') ->map('0:a:1') ->map('0:a:0') ->video('libx264', crf: 22) ->audio('aac', bitrate: '128k') ->videoOptions(['-x264-params', 'keyint=48:scenecut=0']) ->color('bt709', 'bt709', 'bt709') ->audioStream(0, fn ($audio) => $audio ->sampleRate(48000) ->channels(2)) ->audioStream(1, fn ($audio) => $audio ->bitrate('96k') ->filter('volume=0.5')) ->save('selected.mp4');
A missing output track fails before encoding, and only the callbacks' scalar settings are kept, not the closures. Audio tracks may set the codec, bitrate, quality, sample rate, channels, sample format, channel layout, compression level, and filters, which run after shared filters.
The aac encoder keeps the source's channel layout, so a 5.1 source stays 5.1. To encode stereo for web playback, you may pass -ac to the audioOptions method, or call the channels method on an individual audio track:
$media->export() ->video('libx264') ->audio('aac', bitrate: '128k') ->audioOptions(['-ac', '2']) ->save('stereo.mp4'); $media->export() ->video('libx264') ->audio('aac', bitrate: '128k') ->audioStream(0, fn ($audio) => $audio->channels(2)) ->save('stereo-track.mp4');
The videoOptions and audioOptions methods accept curated pairs, such as numeric x264 and x265 parameters, SVT-AV1's lp level of parallelism, selected VPx, AV1, and NVENC settings, color signaling, variable bitrate quality, such as ['-q', '4'] for libmp3lame, and ['-strict', 'experimental'] for experimental audio encoders such as FFmpeg's native vorbis; unknown parameters and file-producing options are rejected. The color method only sets metadata, so use a color-conversion filter to change pixel values, as HDR and SDR Video shows. A transfer other than PQ (smpte2084) or HLG (arib-std-b67) also drops the HDR10 mastering display and content light level metadata. The GIF, loudness, audio-mix, concat, and DASH builders have no per-track methods, and DASH representations reject per-track overrides.
The outputOptions method also accepts single-file muxer settings and argument-free bitstream filters, such as ['-bsf:v', 'h264_mp4toannexb'], but not sidecar paths. It accepts -fpsmax to cap a video's frame rate without raising a lower one, and the -shortest flag, the only option without a value, to end the output with its shortest stream, such as added audio that is shorter than the video. A stream that a filter graph generates, such as a color source, may run past that end by the frames the encoder buffers, so you should give it a duration instead. You may pass options outside the allow list by disabling the option restrictions. The globalOptions method accepts named hardware device declarations, where a derived device must reference an earlier one:
$export = $media->export() ->globalOptions([ '-init_hw_device', 'vaapi=base:/dev/dri/renderD128', '-init_hw_device', 'qsv=derived@base', '-filter_hw_device', 'derived', ]);
Warning
Multithreaded SVT-AV1 2.3 encodes, including those of Ubuntu 26.04's libsvtav1enc2 package, may differ between runs and occasionally contain a frame that decoders reject. You should use SVT-AV1 3.1.2 or later, or pass ['-svtav1-params', 'lp=1'] to the videoOptions method, which encodes with one level of parallelism at a lower speed.
Transforming Media
You configure transformations on the builder returned by the export method. Filters run in the order you register them, while operations that own their filter graph follow the rules in their own sections.
Geometry and Filters
You may crop, rotate, pad, or fit a video to your output canvas:
$media->export() ->video('libx264') ->audio('copy') ->crop(1280, 720, x: 40, y: 20) ->rotate(90) ->pad(800, 1280, background: 'black') ->save('portrait.mp4');
The contain and cover methods work like their Laravel image counterparts and produce square pixels:
$media->export() ->contain(1280, 720, background: 'black') ->video('libx264') ->save('contained.mp4'); $media->export() ->cover(1280, 720) // Center crop. ->video('libx264') ->save('covered.mp4');
Passing one dimension to resize preserves the display aspect ratio, while two dimensions stretch the video. Resize, crop, and pad take positive even dimensions, crop and pad center the video unless you pass offsets, and rotate accepts clockwise quarter turns or their negative equivalents, applied after the input's autorotation. FFmpeg validates geometry that depends on the source.
Most video encoders, including libx264, require even frame dimensions. A source with odd dimensions, such as 1081x607, therefore needs an even resize or crop, or the export fails with the dimensions category:
$media->export() ->resize(width: 1080) ->video('libx264') ->save('even.mp4');
Raw probe dimensions are the encoded size, but sizing follows the autorotated display, so a portrait video stays portrait:
$media->export() ->resize(height: 1920) ->video('libx264') ->audio('copy') ->save('portrait-height.mp4'); $media->export() ->contain(1080, 1920) // Exact portrait canvas. ->video('libx264') ->audio('copy') ->save('portrait-canvas.mp4');
The export builder offers many other filters:
$media->export() ->video('libx264') ->audio('aac') ->deinterlace() // Before resizing; mode: 'field' gives a frame per field. ->frameRate('30000/1001') ->flipHorizontally() ->grayscale() ->volume(0.5) // Linear multiplier; zero mutes. ->delayAudio(0.25) ->fadeIn(1) ->fadeOut(1, start: 9) ->save('treated.mp4');
The frameRate method drops or duplicates frames without changing playback speed, and delayAudio pads every channel with silence. Fades affect video and audio unless you pass video: false or audio: false. A flipVertically method is also available, and filtered streams must be encoded, not copied.
For other trusted FFmpeg expressions, you may use the videoFilter and audioFilter methods:
$media->export() ->videoFilter('hqdn3d') ->audioFilter('highpass=f=200') ->video('libx264') ->audio('aac') ->save('filtered.mp4');
Filter graphs longer than 16 KB, such as thousands of drawbox filters, reach FFmpeg through a file in the workspace, since the operating system limits the length of a single argument. The inspect method still returns the graph itself.
The drawText and burnSubtitles methods stage their files privately instead of interpolating paths into filter strings, so text is drawn literally:
$font = FFMpeg::disk('assets') ->open('Brand.ttf'); $captions = FFMpeg::disk('assets') ->open('captions.srt'); $media->export() ->drawText('100%: café [literal]', $font, size: 24, x: 12, y: 18) ->burnSubtitles($captions) ->video('libx264') ->audio('copy') ->save('captioned.mp4');
Warning
Filters are trusted application code, not a sandbox for untrusted media.
Frames, Timelapses, and Storyboards
The frame method extracts a single image, which you may save or retrieve as bytes:
$media->frame(at: 12.5) ->resize(width: 640) ->toDisk('images') ->save('poster.jpg'); $bytes = $media->frame(at: 12.5) ->get();
A frame time, or a gif clip start, at or beyond the source's known duration throws a MediaException with the duration category before FFmpeg runs.
Frames, image sequences, and storyboards always have square pixels. Anamorphic video, such as DVD footage, is stretched to its display aspect ratio first, because image viewers ignore the pixel aspect ratio.
The frames method samples at an interval or as an evenly spaced count. Patterns need one integer placeholder:
$media->frames(every: 2) ->resize(width: 320) ->outputOptions(['-q:v', '3']) // JPEG quality. ->save('frames/frame-%05d.jpg'); $media->frames(count: 10) ->save('frames/frame-%05d.png');
The openSequence method turns numbered images into a timelapse:
FFMpeg::disk('images') ->openSequence('frame-%04d.png', count: 90, framerate: '30000/1001', start: 1) ->export() ->video('libx264') ->save('timelapse.mp4');
The storyboard method builds sprite sheets, and vtt writes WebVTT cues whose references are relative to the cue file:
$media->storyboard(every: 5, columns: 5, rows: 3, margin: 2, padding: 1) ->resize(width: 160) ->vtt('cues/lesson.vtt') ->toDisk('images') ->save('sheets/lesson-%03d.jpg');
Each tile shows the frame nearest the middle of its interval, so the first tile of this storyboard shows the video at about 2.5 seconds. A video that ends before the middle of its last interval shows its final frame in the last tile.
The waveform method renders a PNG, distinct from waveform peaks data. Its colors argument takes a name such as 'blue' or an RGB or RGBA hex value prefixed with # or 0x, or a list of them; a single string is never split into several colors:
$media->waveform(width: 800, height: 120, colors: 'blue') ->clip(2, duration: 10) ->save('waveform.png');
Creating Videos From Images
The still method turns a PNG or JPEG into a video, such as a title card:
FFMpeg::disk('images') ->open('title.png') ->still(duration: 5, frameRate: 25) ->resize(width: 1280) ->toDisk('videos') ->save('title.mp4');
It encodes H.264 with yuv420p by default and offers the export builder's video codec, geometry, filter, metadata, and publication methods, but no audio, clipping, or extra-input methods, since it creates no audio track. The image may come from any disk or a downloaded URL and takes no input options. Most encoders, including libx264, need even dimensions, so you should resize or crop an odd-sized image, or the export fails with the dimensions category. The frame rate is an integer from 1 to 240, and frame rounding can affect the duration.
Changing Playback Speed and Making GIFs
The speed method changes playback speed without changing the audio pitch:
$media->speed(2) ->save('double-speed.mp4'); $media->speed(0.5) ->save('half-speed.mp4');
The factor must be finite and positive. Audio must start at a nonnegative time and, when the source has video, the container and video must start at zero. Existing audio delays scale with the speed, while an audio-only source that starts later loses its leading offset. Stream copy, clipping, input options, custom graphs, watermarks, and multiple outputs are not supported, so encode a clip first to retime part of a source.
The gif method creates a looping preview from the first video stream, without audio:
$media->gif(width: 480, frameRate: 12, loop: true) ->clip(4, duration: 3) ->toDisk('images') ->save('preview.gif');
Pass loop: false to play once, or loops: 3 to repeat three times after the first play. Clipping runs before palette generation, and the builder has no map, graph, extra input or output, audio, encoder, or raw output methods.
Note
Instead of buffering in memory, the gif method writes a private lossless intermediate file, which adds disk use and processing passes, so keep previews short and small.
Mixing Audio and Adding Background Music
The backgroundMusic method mixes a quieter, looping track under a video's audio. The at method delays the music, and loop: false plays it once:
$video = FFMpeg::open($request->file('video')); $music = FFMpeg::disk('music') ->open('background.mp3'); // Start the music at 2.5 seconds, then repeat it at 20% volume until the video ends. $video->backgroundMusic($music) ->at(2.5) ->video('copy') ->audio('aac', bitrate: '192k') ->save('with-music.mp4'); // Play the added track once, then fill the remaining time with silence. $video->backgroundMusic($music, volume: 0.2, loop: false) ->video('copy') ->audio('aac') ->save('one-shot.mp4');
The mixAudio method sets both gains and plays the added track once unless you call loop:
// Set both gains, divide the mixed signal by two, then fade the final audio. $video->mixAudio($music, volume: 0.4, originalVolume: 0.8, normalize: true) ->fadeIn(1, video: false) ->fadeOut(2, start: 18, video: false) ->video('copy') ->audio('aac') ->save('mixed.mp4');
A mix combines the first audio stream of each input into stereo at 48000 Hz, so audio must be encoded, while video may be copied unless you filter it. The volume, audioFilter, and fade methods apply after mixing. A mix has one output and owns its graph and maps, so custom maps, graphs, watermarks, clips, and two-pass encoding are not supported.
Timing and Duration
The primary input sets the output length: a shorter added track ends in silence unless it loops, and a longer one is trimmed. A silent video receives only the added music, and audio-only inputs work too. The at offset delays only the added track from its first decoded sample, rounds to the nearest 48 kHz sample, and replaces any earlier offset. Loops do not repeat the initial silence, and an offset beyond the primary adds nothing.
Both sources need finite positive durations, and the added one must contain audio. A primary with video needs zero container and video origins and a known nonnegative audio origin. To loop URL audio, open it with FFMpeg::openUrl($url, download: true).
Mixing Levels
Gains are nonnegative amplitude multipliers. By default, the signals are added and can clip, while normalize: true halves both branches when original audio is present.
Note
The normalize argument is not loudness normalization; use normalizeLoudness for that.
Waveform Peaks Data
The waveformPeaks method computes minimum and maximum sample data for your own renderer. The get method returns it without publishing a file:
$peaks = $media->waveformPeaks(samplesPerBucket: 256) ->audioTrack(1) // Zero-based audio track, not a stream index. ->clip(10, duration: 30) ->mono() // Mix channels with equal weights. ->buckets(1000) // At most 1,000 buckets. ->get(); $peaks->sampleRate; $peaks->duration(); $peaks->channels; // Channel-major signed 16-bit [min, max] pairs. $peaks->bucketFrames; $peaks->toArray();
The save method publishes version 1 JSON and returns the same peaks, so you need no second run:
$result = $media->waveformPeaks() ->buckets(2000) ->toDisk('waveforms') ->save('lesson.json'); $result->peaks;
Results are capped at 100,000 channel-buckets, and the private PCM file is deleted after the operation.
Two-Pass Loudness Normalization
The normalizeLoudness method measures one audio track, then normalizes it to your target in a single audio-only output:
$result = $media->normalizeLoudness(integrated: -18, truePeak: -2, range: 7, linear: true, sampleRate: 48000, audio: 1) ->clip(3, duration: 4) ->audioFilter('pan=mono|c0=c0,volume=0.5') ->audio('pcm_s24le') ->toDisk('audio') ->save('normalized.wav'); $result->measurement; // Non-finite statistics, such as for silence, are null. $result->normalization; $result->requestedMode; $result->actualMode(); // FFmpeg can fall back to dynamic normalization.
Both passes read the same private lossless decode. Use audioFilter for channel processing; graphs, extra inputs or outputs, stream copy, and video settings are rejected.
Adding a Watermark
The watermark method overlays an image, configured by a closure that receives a Watermark instance:
use ProtoneMedia\LaravelFFMpeg\Watermark; $logo = FFMpeg::disk('assets') ->open('logo.png'); $media->export() ->resize(width: 1280) ->watermark($logo, fn (Watermark $watermark) => $watermark ->right(20) ->bottom(15) ->size(width: 160) ->opacity(0.8)) ->video('libx264') ->audio('copy') ->toDisk('videos') ->save('branded.mp4');
Without a closure, the mark appears at its original size in the bottom-right corner. The center method centers any axis no edge method pins, and pinning opposite edges throws an exception. Call watermark again to add another mark. Watermarks accept PNG, JPEG, and GIF images from any disk, work with multiple outputs and HLS variants, and require video encoding; with custom maps, graphs, or extra inputs, use a custom filter graph.
Note
Marks are drawn after all output video filters, wherever you call watermark.
Editing the Watermark Image
The Watermark instance also accepts Laravel's image edits: grayscale, blur, sharpen, rotate, crop (with required x and y), flipHorizontally, and flipVertically. Edits require intervention/image and run in call order on a private copy, so the original never changes:
$logo = FFMpeg::disk('assets') ->open('logo.png'); $media->export() ->watermark($logo, fn (Watermark $watermark) => $watermark ->right(25) ->bottom(25) ->size(width: 100) ->grayscale() ->blur(10)) ->video('libx264') ->save('branded.mp4');
Edits use the image's pixels, while placement, size, and opacity use output pixels.
Joining Clips
The concatTranscoded method encodes clips with different formats to a common one, while concat joins clips that share codec parameters, so you may copy their video:
$first = FFMpeg::disk('clips') ->open('first.mp4'); $second = FFMpeg::disk('archive') ->open('second.mp4'); $first->concatTranscoded($second) ->conformVideo(1280, 720, frameRate: 30, fit: 'contain') // Or 'cover' or 'stretch'. ->conformAudio(sampleRate: 48000, channels: 2) ->video('libx264') ->audio('aac') ->toDisk('videos') ->save('joined.mp4'); $first->concat($second) ->export() ->video('copy') ->audio('aac') ->save('joined.mkv');
The concatTranscoded method requires conformVideo and either conformAudio or withoutAudio, uses each source's first video and audio streams, and rejects stream copy. Sources need zero container and video origins, and conforming audio requires audio in every source. The concat method never falls back to transcoding, and URL inputs need download: true. You should still encode AAC audio, because FFmpeg rejects copied AAC timestamps that overlap at the boundary between clips. Neither keeps chapters, and both publish to the first input's disk unless you call toDisk.
Composing Multiple Inputs and Outputs
Each output closure configures one output. The lut3d method applies a privately staged LUT to each output separately:
use ProtoneMedia\LaravelFFMpeg\ExportOutput; $look = FFMpeg::disk('assets') ->open('looks/grade.cube'); $media->export() ->output('full.mp4', fn (ExportOutput $out) => $out ->lut3d($look) ->resize(width: 1920) ->video('libx264') ->audio('aac') ->toDisk('videos')) ->output('preview.mp4', fn (ExportOutput $out) => $out ->lut3d($look) ->resize(width: 640) ->video('libx264') ->audio('aac') ->toDisk('previews')) ->save();
To grade once and then branch, use resource with split in a custom filter graph.
Custom Filter Graphs
The addInput and filterComplex methods let you write the graph yourself; addInput returns the input's index:
use ProtoneMedia\LaravelFFMpeg\ExportOutput; $export = $media->export(); $image = FFMpeg::disk('assets') ->open('logo.png'); $logo = $export->addInput($image); $result = $export ->filterComplex('[0:v]['.$logo.':v]overlay=x=W-w-20:y=H-h-20,split[full][small];[small]scale=640:360[preview]') ->output('full.mp4', fn (ExportOutput $out) => $out ->map('[full]') ->map('0:a:0?') ->video('libx264') ->audio('copy') ->metadataFrom(0) ->chaptersFrom(null) ->toDisk('videos')) ->output('preview.mp4', fn (ExportOutput $out) => $out ->map('[preview]') ->video('libx264') ->withoutMetadata(chapters: true) ->toDisk('previews')) ->save();
Each output needs explicit maps and a metadata and chapter policy, and each label may be consumed once, so branch with split or asplit. Every filterComplex call appends its chains to the same graph, separated by a semicolon, so you may build a graph in a loop. Declare files with resource('look', $media) and use the placeholder as the whole value, as in lut3d=file={{look}}.
Streaming
The hls and dash methods publish finite presentations after encoding and validation, while the liveHls method publishes a sliding playlist as the encoder runs.
Adaptive HLS and Encryption
An adaptive presentation contains the variants a player may choose between. To encrypt it, pass the encrypt method a private key disk and a closure that returns each key's authorized URL:
use ProtoneMedia\LaravelFFMpeg\HlsVariant; $result = $media->hls(segmentDuration: 6) ->variant('360p', fn (HlsVariant $variant) => $variant ->resize(height: 360) ->video('libx264', bitrate: '800k')) ->variant('720p', fn (HlsVariant $variant) => $variant ->resize(height: 720) ->video('libx264', bitrate: '2500k'), playlist: 'lists/720p/index.m3u8', segments: 'segments/720p/part-%03d.ts') ->encrypt('secrets', static fn (string $keyPath) => route('lesson.key', ['key' => basename($keyPath)]), rotateEvery: 3, directory: 'lessons/42/keys') ->toDisk('streams') ->save('lessons/42/master.m3u8'); $result->playlist(); $result->variant('720p') ->files(); $result->files() ->where('role', 'hls-key');
Variants may also copy the source's streams with video('copy') and audio('copy'), but a copied stream is only cut at its keyframes, so a source with a keyframe every 10 seconds gives 10-second segments whatever the segmentDuration.
Note
The RESOLUTION and CODECS attributes of each variant come from FFmpeg, which only measures a variant's bandwidth from segments longer than half a second. With a segment duration of 0.5 seconds or less, the master playlist lists the variants without these attributes, whatever the codec, so you should keep the duration above that. Apple's HLS authoring guidelines recommend 6 seconds.
Playlist Types
Playlists are vod by default; you may pass event to the playlistType method for EXT-X-PLAYLIST-TYPE:EVENT, or live to omit the tag. Every type keeps all segments and ends with EXT-X-ENDLIST, so none plays during encoding (see continuous HLS). Parallel queued composition and mergeHls require vod.
HEVC and Hardware Encoders
For HEVC, pass libx265 to the video method and add the hvc1 tag so FFmpeg advertises the codec in the master:
$result = $media->hls() ->video('libx265', crf: 28, preset: 'fast') ->outputOptions(['-tag:v', 'hvc1']) ->variant('720p', fn (HlsVariant $variant) => $variant->resize(height: 720)) ->toDisk('streams') ->save('lessons/42/master.m3u8');
Both MPEG-TS and fMP4 work, but check player support. Hardware encoders such as hevc_nvenc use the same method; nothing selects hardware or falls back to software automatically, so your binary, drivers, device, and filter graph must support the path.
Watermarks and Variant Selection
HLS exports accept static PNG and JPEG or animated GIF watermarks, without input options:
use ProtoneMedia\LaravelFFMpeg\Watermark; $animated = FFMpeg::disk('assets') ->open('badge.gif'); $result = $media->hls() ->watermark($animated, fn (Watermark $watermark) => $watermark ->right(16) ->bottom(16) ->size(width: 96) ->loop()) ->variant('720p', fn (HlsVariant $variant) => $variant ->resize(height: 720) ->video('libx264', bitrate: '2500k')) ->toDisk('streams') ->save('animated/master.m3u8');
A GIF plays once and holds its last frame unless you call loop, whatever its embedded loop count. Video filters, including each variant's resize, always precede the overlay.
The playbackForVariants method persists playback for only the variants a viewer may access:
// $lesson is the model that stores playback (see "Storing the Playback Inventory"). $lesson->hls_playback = $result->playbackForVariants(['720p']) ->toArray();
It keeps the selected variants' audio, subtitle, initialization, and key dependencies, and protected playback renders a filtered master without touching published playlists.
Encryption and Publication
Segments are MPEG-TS by default. Paths are disk-relative, and playlist references are relative to their playlist, except key references, which are the URIs your encrypt closure returns. Protected playback and the keyUrlsUsing resolver replace those URIs when they serve a playlist, while players that read the published playlists directly use them as written, so an absolute route URL carries the host of the process that ran the export, such as a queue worker's APP_URL. For a key route on the host that serves the playlists, you may pass absolute: false to the route helper. Keys go to the private disk passed to encrypt and publish before media. A custom key must be 16 raw bytes and cannot rotate; otherwise each save generates fresh keys, shared across variants per rotation group. Every segment gets a random IV, and OpenSSL is required. After validation, segments, playlists, and the master publish in that order, but not transactionally.
Warning
AES-128 is not DRM. Your application must authorize each key request before serving its 16 raw bytes.
Customizing Playlists
The playlistUsing closure receives each playlist's text, path, and variant name, and returns the text to write, so you may add comments and supported non-resource tags:
$media->hls() ->variant('720p', fn (HlsVariant $variant) => $variant->resize(height: 720)) ->playlistUsing(fn (string $text, string $path, ?string $variant) => str_replace("#EXTM3U\n", "#EXTM3U\n# Lesson playlist\n", $text)) ->save('master.m3u8');
It cannot remove or change generated timing, references, stream attributes, or encryption directives.
fMP4 and Alternate HLS Groups
The fmp4 method packages HLS as fragmented MP4, and the audioGroup and subtitleGroup methods let variants share alternate renditions:
$result = $media->hls(segmentDuration: 6) ->fmp4() ->video('libx264', bitrate: '2500k') ->twoPass() ->variant('360p', fn (HlsVariant $variant) => $variant ->resize(height: 360) ->video(bitrate: '800k') ->audioGroup('sound') ->subtitleGroup('captions')) ->variant('720p', fn (HlsVariant $variant) => $variant ->resize(height: 720) ->audioGroup('sound') ->subtitleGroup('captions'), playlist: 'video/720p/index.m3u8', segments: 'video/720p/part-%03d.m4s', init: 'video/720p/start.mp4') ->audioRendition('sound', 'English', fn (HlsVariant $rendition) => $rendition ->map('0:a:0') ->audio('aac', bitrate: '128k'), language: 'en', default: true) ->audioRendition('sound', 'Español', fn (HlsVariant $rendition) => $rendition ->map('0:a:1') ->audio('aac', bitrate: '128k'), language: 'es') ->subtitleRendition('captions', 'English', fn (HlsVariant $rendition) => $rendition ->map('0:s:0'), language: 'en', default: true) ->toDisk('streams') ->save('lesson/master.m3u8'); $result->audioRendition('sound', 'English') ->playlist(); $result->subtitleRendition('captions', 'English') ->files(); $result->files() ->where('role', 'hls-init');
Each rendition needs one explicit map of its type and its variants' clip. Audio renditions are encoded once and replace muxed audio in their group's variants. Subtitle renditions are one WebVTT segment, so they need a known duration, no complex timing graph, and aligned variant clocks. fMP4 writes one init file per audio and video playlist plus .m4s segments, both published before playlists. Encryption is rejected with fMP4 or alternate subtitles. Dynamic responses rewrite init references through mediaUrlsUsing and traverse alternate playlists through playlistUrlsUsing.
A subtitle rendition may also come from a separate file, such as an SRT file, which you add with the addInput method:
$export = $media->hls(); $captions = $export->addInput(FFMpeg::disk('subtitles')->open('lesson.en.srt')); $export->variant('720p', fn (HlsVariant $variant) => $variant ->map('0:v:0') ->map('0:a:0') ->subtitleGroup('captions')) ->subtitleRendition('captions', 'English', fn (HlsVariant $rendition) => $rendition ->map("{$captions}:s:0"), language: 'en', default: true) ->metadataFrom(0) ->chaptersFrom(0) ->save('lesson/master.m3u8');
Subtitle files have no duration of their own, so the rendition spans the video and audio inputs.
DASH and Shared HLS Segments
The dash method builds a presentation from adaptation sets and their representations, and the sharedHls method adds HLS playlists that reuse the same segments:
$result = $media->dash(segmentDuration: 2) ->adaptationSet('picture', 'video') ->adaptationSet('sound', 'audio') ->representation('low', 'picture', fn ($video) => $video ->map('0:v:0') ->resize(width: 640) ->video(bitrate: '800k')) ->representation('high', 'picture', fn ($video) => $video ->map('0:v:0') ->video(bitrate: '2500k')) ->representation('audio', 'sound', fn ($audio) => $audio ->map('0:a:0') ->audio(bitrate: '128k')) ->sharedHls() ->toDisk('videos') ->save('course/manifest.mpd'); $result->manifest(); $result->hlsPlaylist(); // Available only with sharedHls(). $result->playback(); // Protected HLS inventory; requires sharedHls(). $result->adaptationSets(); $result->representation('low') ->files();
DASH supports finite, clear H.264 or VP9 video with AAC audio: each representation maps one stream into a declared set, all share one accurate clip, and the builder owns muxers and GOP alignment. Representations encode H.264 unless you pass libvpx-vp9 to their video method. Players switch between the representations of one set without reinitializing their decoder, so the representations of a set must share an encoder, and you should declare H.264 and VP9 in separate sets. Live DASH, two-pass, encryption, DRM, and protected playback descriptors are unsupported. After validating the bounded XML and owned inventory, segments, playlists, and the MPD publish in that order, not atomically. Results use dash-init, dash-segment, and dash-manifest roles, and queueing, cancellation, and events work as usual.
With sharedHls, the playback method and the queued completion event provide an HlsPresentation for the protected HLS routes. It covers the HLS master, playlists, and shared media, but not the MPD, which has no protected route. Master entries are named after representations, so playbackForVariants(['low']) keeps that representation with all audio. The mergeHls method does not accept DASH output.
Combining Completed HLS Presentations
The mergeHls method combines completed presentations of the same timeline into one master playlist without transcoding or copying media:
use ProtoneMedia\LaravelFFMpeg\Support\FFMpeg; // $firstResult and $secondResult are HlsExportResult instances from earlier hls() exports, // and $lesson is the model that stores playback. $merged = FFMpeg::mergeHls(['main' => $firstResult, 'alternate' => $secondResult]) ->toDisk('streams') ->save('combined/master.m3u8'); $publishedPath = $merged->playlist()->path; // Includes a generated version suffix. $lesson->hls_playback = $merged->playback() ->toArray();
It accepts two or more completed v9 HlsExportResult instances, HlsPresentation instances, or stored inventory arrays; optional string keys prefix each presentation's variant names. Inputs must be VOD with separate destinations, matching packaging, clips, and durations, and media on one disk, which is also the default for toDisk. Keys may live elsewhere. Store the versioned playlist()->path, not the path you requested.
Warning
The merged result owns only the new master; the source inventories still own segments, playlists, and keys. Deleting an original breaks the combination, so keep source inventories and reference counts until nothing uses those files.
Publishing Continuous HLS
The liveHls method publishes a sliding playlist while FFmpeg runs:
// $trustedCameraUrl comes from your own configuration, never from user input. $session = FFMpeg::liveHls($trustedCameraUrl, segmentDuration: 2, window: 6) ->toDisk('videos') ->retry(maxRetries: 3, delay: 1) ->timeout(3600) ->cancelWhen(fn () => $this->shouldStop()) // Your own stop condition. ->onPublish(function ($snapshot) { // The playlist and its referenced segments are readable now. }); $result = $session->run('live/unique-session-id'); // Realtime playback of a finite input uses the same lifecycle. $result = $media->liveHls(segmentDuration: 2, window: 6) ->toDisk('videos') ->run('live/another-session-id');
The run method blocks while publishing one H.264/AAC MPEG-TS rendition over a sliding window of segments, keeping one extra window for stale readers.
A clean EOF returns completed with ENDLIST; stop or cancelWhen returns cancelled and the timeout timed_out, keeping the last playlist without ENDLIST. The retry budget is finite, and reconnectOnEof: true reconnects after clean EOF too. Restarts keep sequence numbers monotonic, with discontinuities. Storage and exhausted-source failures throw a sanitized MediaException with a bounded published inventory; global process deadlines remain hard limits.
Continuous HLS has no adaptive masters, fMP4, encryption, or low-latency mode. Sources must be HTTP, HTTPS, or RTSP URLs without user information; openRtsp stays the snapshot API. Local, HTTP, and RTSP ingestion are acceptance-tested, the RTSP case against a MediaMTX server. FFmpeg treats a camera or relay that closes the stream as a clean end of stream. To wait for the source to return, you should pass reconnectOnEof: true to the retry method.
Warning
Use a fresh, empty namespace per session, supervise the worker, and guarantee one writer per namespace on storage that replaces objects atomically. A restarted PHP worker cannot resume a session. URL validation does not prevent SSRF, so restrict reachable hosts.
Serving Protected HLS
The Hls facade registers signed playback routes: a stored inventory decides which files are served, and your authorization callback decides who sees them.
Storing the Playback Inventory
Playback requires named private disks for media and keys. Add a JSON hls_playback column to your lessons table and cast it to an array:
use Illuminate\Database\Eloquent\Model; class Lesson extends Model { protected function casts(): array { return ['hls_playback' => 'array']; } }
After an export, persist the root result's inventory:
// $result is the HlsExportResult returned by save(), and $lesson is a Lesson model. $lesson->hls_playback = $result->playback() ->toArray(); $lesson->save();
A single variant's playback also keeps the key references it needs, even though its files exclude shared keys.
Registering Playback Routes
Next, register the definition and an explicit model binding in your AppServiceProvider's boot method:
use App\Models\Lesson; use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Route; use ProtoneMedia\LaravelFFMpeg\Http\HlsPresentation; use ProtoneMedia\LaravelFFMpeg\Support\Hls; Route::model('lesson', Lesson::class); Hls::define('lesson', resolve: fn (Lesson $lesson) => HlsPresentation::fromArray($lesson->hls_playback), authorize: fn (Lesson $lesson) => Gate::authorize('view', $lesson), );
The authorize callback and your view policy are mandatory. Laravel does not infer implicit bindings from these callbacks, so call Route::model for each model parameter. Then register the route in routes/web.php:
use ProtoneMedia\LaravelFFMpeg\Support\Hls; Hls::routes('/lessons/{lesson}/hls', name: 'lessons.hls', playback: 'lesson');
The route uses the web and auth middleware by default and a controller action, so route:cache works; keep your own closures out of route actions. With Sanctum, pass middleware: ['api', 'auth:sanctum']. Bearer-URL playback with middleware: ['web'] is acceptable only if URLs are issued behind an authorized endpoint: the URLs become bearer credentials with no global authentication, so authorize must enforce your policy on every request, including sessionless ones.
Laravel redirects guests to the route named login, which a new application does not define, so a guest's playback request fails with a 500 error. You may define a login route, although players then receive a redirect to an HTML page, and auth:sanctum redirects guests the same way. To answer guests with a 401 response instead, you may customize Laravel's guest redirect in your application's bootstrap/app.php file:
use Illuminate\Http\Request; // Inside the withMiddleware callback, which receives the $middleware configuration. $middleware->redirectGuestsTo( fn (Request $request) => $request->routeIs('lessons.hls') ? null : route('login'), );
Generating Playback URLs
Issue an entry URL from an authorized controller; expires defaults to 30 minutes:
// $lesson is resolved by route model binding. Gate::authorize('view', $lesson); $url = Hls::url('lessons.hls', ['lesson' => $lesson], expires: now()->addMinutes(10));
Child playlists, segments, init files, and keys get signed URLs with the entry URL's exact deadline, never renewed, keeping validated signed query context such as grants, with route parameters taking precedence. Every request revalidates its signature and reruns authorize. The controller serves only inventory-owned files by opaque ID, never by disk path, with private, no-store and nosniff. Media supports single byte ranges and HEAD; keys return 16 raw bytes, not hex or Base64. CORS and trusted proxies are yours to configure.
The entry URL ends in index.m3u8, such as /lessons/42/hls/index.m3u8, and every other playback URL ends in its file's extension. Players such as Video.js and Android's Media3 detect HLS from the URL without a type option, and FFmpeg reads the stream without extra input options.
Warning
Keep the inventory server-side, never in request data or public responses. Media and keys must stay private and immutable, so publish replacements to new paths and swap the stored inventory. Neither signed playback nor AES-128 is DRM.
Customizing Raw HLS Responses
For application-owned URL rewriting, use the lower-level playlist API; resolvers receive the disk target, the containing playlist's key, and the original URI:
use Illuminate\Support\Facades\Storage; // Inside an authorized controller: $lesson comes from route model binding, // $path from its stored inventory, and keys() is your own relationship. return FFMpeg::disk('streams') ->playlist($path) ->playlistUrlsUsing(fn (?string $target, string $source, string $uri) => $target === null ? $uri : route('lesson.playlist', ['lesson' => $lesson->id, 'path' => $target])) ->mediaUrlsUsing(fn (?string $target, string $source, string $uri) => $target === null ? $uri : Storage::disk('streams') ->temporaryUrl($target, now()->addMinutes(10))) ->keyUrlsUsing(function (?string $target, string $source, string $uri) use ($lesson) { $key = $lesson->keys() ->where('playlist_uri', $uri) ->firstOrFail(); return route('lesson.key', ['lesson' => $lesson->id, 'key' => $key->id]); });
HTTP(S) and root-relative references have a null target. The playlist is Responsable, with the HLS content type and private, no-store. The get and all methods return the rendered text:
$playlist = FFMpeg::disk('streams') ->playlist('lessons/42/master.m3u8'); $text = $playlist->get(); // Selected playlist only. $all = $playlist->all(); // Local playlists keyed by their original disk paths.
Rendering never fetches external URLs or reads media or keys, each call signs fresh URLs, and traversal and sizes are bounded.
Warning
Your application owns authorization, scoped signatures, key lookup, CORS, and cache policy here. Never expose a generic disk or key download route.
Running Exports
The save method runs an export synchronously and returns an inventory of the generated files, while queued conversions deliver that inventory through a completion event.
Progress, Results, and Failures
To receive progress updates, you may pass a callback to the onProgress method. Throwing an ExportCancelled exception from the callback stops and reaps the encoder before the workspace is cleaned up:
use ProtoneMedia\LaravelFFMpeg\Progress; $export = $media->export() ->onProgress(function (Progress $progress) { if ($progress->isEncoding()) { $progress->percentage; // Nullable, like speed and remainingSeconds. $progress->pass; // Out of $progress->totalPasses. } });
The result exposes the generated files and redacted process summaries. The save method throws a MediaException instead if encoding, validation, or publication fails:
use ProtoneMedia\LaravelFFMpeg\Exceptions\MediaException; try { $result = $export->video('libx264') ->audio('aac') ->save('lesson.mp4'); $file = $result->file(); $file->path; $result->file('lesson.mp4', disk: 'uploads'); $result->files(); $result->processes(); $stream = $file->readStream(); // You are responsible for closing this stream. } catch (MediaException $exception) { // phase, category, diagnostics, published, and destination describe the failure. }
Analysis requests do not throw on a nonzero exit unless you call the throw method:
$analysis = $media->analyze('volumedetect', audio: 0); $analysis->successful(); $analysis->errorOutput(); $analysis->throw();
Every export also dispatches the ExportStarting, ExportProgress, ExportFailed, ExportCancelled, and ExportCompleted events, the last after publication and cleanup. Exceptions from progress callbacks and synchronous listeners propagate unchanged.
Listening for Export Events
To observe every export without configuring each builder, you may listen for the ExportProgress event:
use Illuminate\Support\Facades\Event; use ProtoneMedia\LaravelFFMpeg\Events\ExportProgress; Event::listen(ExportProgress::class, function (ExportProgress $event) { $operationId = $event->operationId; $outputs = $event->outputs; // Destination disk names (or null) and paths, never input URLs. $progress = $event->progress; });
Progress events cover every phase of ordinary, HLS, and queued exports, so some have no percentage. Each operation has its own ID, so use QueuedExportCompleted for whole-workflow completion. Worker cancellation is checked before listeners run, and synchronous listeners may cancel by throwing ExportCancelled, while asynchronous listeners cannot.
Setting FFMPEG_ENABLE_EVENTS to false suppresses all package events, including QueuedExportCompleted, while callbacks, cancellation, publication, and queue chains still run, so keep events enabled if listeners retain your completion inventories.
Handling Partial Publication
A failed export reports, but never deletes, the siblings it already published, and existing objects may already be replaced. Workspaces and pass statistics are cleaned up on success, failure, or cancellation.
Deleting Generated Files
After authorizing the deletion, you may delete the files an export owns through the root result's inventory, not a variant view:
// $result is the result returned by the save method. foreach ($result->files() as $file) { if ($file->owned && ! $file->delete()) { throw new \RuntimeException('Cannot delete '.$file->path); } }
The delete method removes exactly that path, never a prefix, and returns false for borrowed files without touching storage. Filesystem exceptions propagate.
Warning
Your application owns authorization and reference tracking, since another presentation may still use an owned file. Deletion is not transactional and does not revoke cached copies. Retain HLS inventories, because reopening a playlist does not establish ownership of its segments or keys, and merged masters borrow shared files.
For older playlists without a retained inventory, the deleteAllFiles method discovers the master, nested playlists, segments, initialization files, and same-disk keys, and deletes nothing until your callback approves every path:
// $exclusivePaths comes from application-owned records, never from the request. $approvedPaths = array_fill_keys($exclusivePaths, true); FFMpeg::disk('streams') ->playlist('lesson/master.m3u8') ->deleteAllFiles(fn (string $path): bool => isset($approvedPaths[$path]));
External or root-relative references abort before deletion. Keys on other disks are not found and adapter failures may leave a partial deletion, so prevent concurrent playlist changes and prefer a retained inventory.
Limiting Execution Time
The timeout method sets a total budget in seconds for one execution, from probing to publication, while the idleTimeout method limits how long a child process may run without output:
$result = $media->export() ->timeout(900) ->idleTimeout(30) ->video('libx264', bitrate: '2500k') ->twoPass() ->save('lesson.mp4');
Passing null removes an override. The configured per-process timeout and idle_timeout still apply, so the first limit reached wins. A timeout reaps the child before cleanup, and published files stay in the exception's published inventory. Budgets are checked between storage transfers and callbacks, not during them, so configure network timeouts on your adapters.
Queueing Conversions
Encoding may take minutes and a large amount of memory, so you should not run it during a web request. To run an export on a queue worker, call the queued method after configuring it. The save method then returns Laravel's PendingDispatch, and the configureJob method lets you adjust the job:
$pending = FFMpeg::disk('uploads') ->open('lesson.mp4') ->export() ->toDisk('media') ->video('libx264', preset: 'fast') ->audio('aac') ->queued(connection: 'redis', queue: 'conversions', delay: 10) ->configureJob(function ($job) { $job->tries = 3; $job->backoff = [30, 120]; $job->timeout = 1800; }); $exportId = $pending->id; // Also carried by the completion event. $pending->save('lessons/encoded.mp4') ->afterCommit();
Inputs and destinations must use named disks that every worker can read, so store uploads first; uploaded files and open streams are rejected before dispatch. Worker callbacks must be static closures that capture only scalars or arrays. Jobs implement ShouldBeEncrypted, so workers need your encryption key.
Timeouts and Retries
The job timeout defaults to the operation's timeout, or the configured FFmpeg timeout, plus 30 seconds, and is zero when neither is set. The queue configuration holds defaults that the queued arguments override, and configureJob runs last. Deadlines start in the worker, not while the job waits.
Warning
Set the connection's retry_after or visibility timeout above the job timeout, which is 3630 seconds by default, while Laravel's connections default retry_after to 90 seconds. Otherwise, a second worker starts the same export while the first one still runs. The ffmpeg:doctor command warns about a retry_after that does not exceed the job timeout. Retries restart the conversion, and delivery is at-least-once, not exactly-once.
A worker that receives SIGTERM, SIGINT, or SIGQUIT stops FFmpeg, deletes the workspace, and publishes no further files. The attempt then throws a MediaException with the interrupted category, so Laravel retries it while tries remain and fails it otherwise. A job that reaches its timeout stops FFmpeg and deletes the workspace in the same way before Laravel fails it.
SIGKILL cannot be intercepted, so a killed worker leaves FFmpeg running and its private workspace behind, which retries do not reclaim. Prune stale workspaces without touching active jobs. Laravel's Supervisor configuration sets stopasgroup and killasgroup, so both signals also reach FFmpeg. Its stopwaitsecs should cover the longest storage transfer of an export, since the worker stops between transfers and then cleans up:
[program:laravel-worker] command=php /var/www/html/artisan queue:work redis --queue=conversions stopasgroup=true killasgroup=true stopwaitsecs=60
For SQLite batch metadata with concurrent workers, enable WAL and a busy timeout and set transaction_mode to 'IMMEDIATE'.
Job Chains and Batches
The job method builds the job without dispatching it, so you may use it in Laravel chains and batches:
use Illuminate\Support\Facades\Bus; $job = FFMpeg::disk('uploads') ->open('lesson.mp4') ->frame(2) ->toDisk('media') ->queued() ->job('lessons/preview.jpg'); // $lessonId identifies the lesson in your application. Bus::chain([$job, new \App\Jobs\NotifyLessonReady($lessonId)]) ->onConnection('redis') ->onQueue('conversions') ->dispatch();
Batch cancellation skips pending work and stops running encoders at the next progress check without failing their jobs, as Laravel does for skipped jobs, but cannot roll back published files.
Running HLS Conversions in Parallel
To encode independent HLS variants on separate workers, pass parallel: true to the queued method:
FFMpeg::disk('uploads') ->open('lesson.mp4') ->hls(segmentDuration: 4) ->toDisk('media') ->video(preset: 'fast') ->audio('aac') ->variant('small', fn ($v) => $v ->resize(width: 640) ->video(bitrate: '800k')) ->variant('large', fn ($v) => $v ->resize(width: 1280) ->video(bitrate: '2400k')) ->queued(connection: 'redis', queue: 'conversions', parallel: true) ->save('lessons/master.m3u8');
Each independent variant group runs as a job in a Laravel batch, which requires the batch repository, while variants that share audio or subtitle groups stay together. Parts are published as live media under laravel-ffmpeg/queued/{exportId}/parts/, then a finalizer publishes a versioned master such as lessons/master.<version>.m3u8, so read its path from the completion event. The export owns the files of its parts, including their keys, so deleting every owned file in the completion event removes the whole export. The finalizer removes the private masters and inventories of the parts itself.
A failed part blocks the master and downstream jobs, while completed parts remain until you clean them up. Once every part has run, or once the finalizer fails, the package dispatches an ExportFailed event whose operationId is the export ID and whose published property lists every file that the completed parts published, including their keys and private inventories:
use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Storage; use ProtoneMedia\LaravelFFMpeg\Events\ExportFailed; Event::listen(ExportFailed::class, function (ExportFailed $event) { // Other failed exports report their own operation ID, so only stored export IDs match. $conversion = \App\Models\Conversion::firstWhere('export_id', $event->operationId); if ($conversion === null) { return; } foreach ($event->published as $file) { Storage::disk($file['disk'])->delete($file['path']); } });
Parallel exports do not support custom playlist callbacks, complex graphs, or unreferenced alternate groups. Compose them with Bus::chain() rather than inside another batch, and keep batch records until finalization finishes.
Retaining Queue Results
After publication, queued exports deliver their file and playback inventories through the QueuedExportCompleted event, which you may persist in a listener:
use Illuminate\Support\Facades\Event; use ProtoneMedia\LaravelFFMpeg\Events\QueuedExportCompleted; Event::listen(QueuedExportCompleted::class, function ($event) { \App\Models\Conversion::where('export_id', $event->exportId) ->update([ 'files' => $event->files, // Disk, path, size, role, and owned for each artifact. 'playback' => $event->playback, // A serializable protected-HLS inventory, or null. ]); });
Listeners must tolerate duplicate delivery and should keep the inventories for cleanup. The final master of a parallel export owns the files of its parts, while a mergeHls composition borrows its sources. See the application integration recipes for versioned profiles, durable inventories, and media-library integration.
Deployment and Development
Configuration and Security
The configuration is published as config/laravel-ffmpeg.php. The inspect method returns the arguments without running anything, and the globalOptions and outputOptions methods and inputOptions argument accept scoped options, but reserved filenames, binaries, and progress and statistics paths cannot be overridden.
Warning
Output validation is not a sandbox. Isolate untrusted inputs at the operating-system level with resource limits.
Option Restrictions
The inputOptions argument and the outputOptions and globalOptions methods only accept the options the package allows, and the exception names the option it rejects. You may lift this allow list by setting the restrict_options option to false:
return [ // ... 'restrict_options' => false, ];
The package then passes every other option and its value to FFmpeg as is. The options it sets itself, such as -i, -map, -progress, and the filter options, stay reserved, and the videoOptions and audioOptions methods and the per-track methods still accept only their curated options, although without checking their values.
Warning
Without the allow list, options such as -passlogfile and -vstats_file may write to any path the worker can reach, so only pass options that your own code decides.
Credential Redaction
Credential redaction is disabled by default. To enable it, set FFMPEG_REDACT_CREDENTIALS to true:
return [ // ... 'redact_credentials' => env('FFMPEG_REDACT_CREDENTIALS', false), ];
The package then replaces these strings in MediaException diagnostics, process summaries, and analyze, probe, and probeQuery output:
| String | Replacement |
|---|---|
The whole openUrl() URL |
[url] |
| The whole RTSP URL | [rtsp] |
| The whole query string | [query] |
A query value whose name contains token, sig, key, auth, pass, secret, credential, or policy |
[redacted] |
| Any other query value of 16 or more characters | [redacted] |
The RTSP user:password pair, and the password alone |
[redacted] |
Query values match in raw and URL-decoded form, longest first. Shorter values with other names, such as dl=1, and RTSP usernames are kept. Placeholders such as [input:0] replace staged paths and direct URLs either way.
Warning
Redaction never changes FFmpeg's arguments, so direct signed URLs remain visible in process arguments.
Testing and Development
To set up a development environment and run the tests, use the setup script and PHPUnit:
.agents/setup
FFMPEG_9_FFPROBE=/opt/ffmpeg-9.0.2/bin/ffprobe vendor/bin/phpunit --order-by random \
--display-deprecations --display-phpunit-deprecations \
--fail-on-deprecation --fail-on-phpunit-deprecation
Real-media tests are skipped unless FFMPEG_9_FFPROBE points to FFprobe 9.0 or later with a matching ffmpeg beside it, and font tests need /usr/share/fonts/truetype/dejavu/DejaVuSans.ttf. CI runs PHP 8.4, 8.5, and 8.6 on Ubuntu 26.04 with lowest and stable dependencies.
Community
Contributing and Security
See CONTRIBUTING and CHANGELOG. Report security issues to code@protone.media, not the public issue tracker.
Credits
License
The MIT license.