Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Ffmpeg Bundle Laravel Package

azraelir/ffmpeg-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle:

    composer require fmonts/ffmpeg-bundle "^0.7"
    
    • Automatically registers the bundle in bundles.php (Symfony Flex handles this).
  2. Configure FFmpeg Binaries (in config/packages/dubture_f_fmpeg.yaml):

    dubture_f_fmpeg:
        ffmpeg_binary: /usr/bin/ffmpeg
        ffprobe_binary: /usr/bin/ffprobe
        binary_timeout: 300  # 5 minutes
        threads_count: 4
    
  3. First Use Case: Transcode a Video Inject the service in a controller or command:

    use FFMpeg\FFMpeg;
    use FFMpeg\Format\Video\X264;
    
    public function transcode(FFMpeg $ffmpeg)
    {
        $video = $ffmpeg->open('input.mp4');
        $video->save(new X264(), 'output.mp4');
    }
    
    • Key: The bundle exposes FFMpeg as a Symfony service (dubture_ffmpeg.ffmpeg).

Implementation Patterns

Core Workflows

1. Video Processing Pipeline

$video = $ffmpeg->open('input.mp4');
$video
    ->filters()
    ->resize(new Dimension(1280, 720), ResizeFilter::RESIZEMODE_INSET)
    ->synchronize();
$video->save(new X264(), 'output.mp4');
  • Pattern: Chain filters (resize, crop, watermark) before saving.
  • Tip: Use FFMpeg\Coordinate\TimeCode for precise trimming:
    $video->save(new X264(), 'trimmed.mp4', [
        'start' => new TimeCode('00:00:10'),
        'end' => new TimeCode('00:00:20'),
    ]);
    

2. Async Processing with Queues

// Dispatch a job
ProcessVideoJob::dispatch('input.mp4', 'output.mp4');

// Job handler
public function handle()
{
    $ffmpeg = app('dubture_ffmpeg.ffmpeg');
    $ffmpeg->open($this->input)->save(new X264(), $this->output);
}
  • Why: FFmpeg tasks are CPU-intensive; offload to queues (e.g., database, redis).

3. Thumbnail Generation

$video = $ffmpeg->open('input.mp4');
$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(10));
$frame->save('thumbnail.jpg');
  • Use Case: User uploads, video previews, or analytics dashboards.

4. Metadata Extraction

$video = $ffmpeg->open('input.mp4');
$format = $video->getFormat();
$duration = $format->getDuration(); // in seconds
$codec = $format->getVideoCodec();
  • Tip: Store metadata in a database for search/filtering.

Integration Tips

  • Environment-Specific Configs: Use Symfony’s %env% for binaries:

    dubture_f_fmpeg:
        ffmpeg_binary: "%env(FFMPEG_BINARY)%"
    

    Set via .env:

    FFMPEG_BINARY=/usr/local/bin/ffmpeg
    
  • Error Handling: Wrap FFmpeg calls in try-catch:

    try {
        $video->save(...);
    } catch (\FFMpeg\Exception\ExecutionException $e) {
        Log::error('FFmpeg failed: ' . $e->getMessage());
        throw new \RuntimeException('Video processing failed');
    }
    
  • Testing: Use FFMpeg\FFProbe to validate inputs:

    $ffprobe = $ffmpeg->getFFProbe();
    $format = $ffprobe->format('input.mp4');
    $this->assertEquals('mp4', $format->getFormat());
    

Gotchas and Tips

Pitfalls

  1. Binary Paths:

    • Issue: Hardcoded paths (e.g., /usr/bin/ffmpeg) fail across environments.
    • Fix: Use %env% or Docker volumes to mount FFmpeg binaries.
  2. FFmpeg Version Mismatch:

    • Issue: php-ffmpeg:^0.13 may require FFmpeg ≥4.0. Older binaries (e.g., 3.x) cause errors.
    • Fix: Check compatibility here.
  3. Threading Limits:

    • Issue: threads_count > CPU cores degrades performance.
    • Fix: Set to min(4, sysconf('SC_NPROCESSORS_ONLN')) dynamically.
  4. Timeouts:

    • Issue: Long-running tasks (e.g., 4K transcoding) hit binary_timeout.
    • Fix: Increase timeout or split into smaller jobs.
  5. Symfony 5+ Deprecations:

    • Issue: The bundle targets Symfony 4.2. Some TreeBuilder usages may need updates.
    • Fix: Extend the bundle or use a newer fork (e.g., php-ffmpeg/php-ffmpeg-bundle).

Debugging

  • Log FFmpeg Commands: Enable verbose logging in config/packages/dubture_f_fmpeg.yaml:

    dubture_f_fmpeg:
        ffmpeg_binary: /usr/bin/ffmpeg -loglevel verbose
    

    Or use Symfony’s monolog:

    $ffmpeg->getFFMpeg()->on('progress', function ($progress) {
        Log::debug('FFmpeg progress:', ['progress' => $progress]);
    });
    
  • Check FFmpeg Output: Redirect stderr to a file:

    ffmpeg_binary: /usr/bin/ffmpeg -errdetect ignore_err -y 2> /tmp/ffmpeg.log
    

Extension Points

  1. Custom Filters: Extend FFMpeg\Filter\FilterInterface and register in the bundle’s config:

    dubture_f_fmpeg:
        custom_filters:
            - App\FFmpeg\CustomFilter
    
  2. Queue Handlers: Create a base job class for shared FFmpeg logic:

    abstract class FFmpegJob implements ShouldQueue
    {
        protected $ffmpeg;
    
        public function __construct()
        {
            $this->ffmpeg = app('dubture_ffmpeg.ffmpeg');
        }
    }
    
  3. Event Listeners: Hook into FFmpeg events (e.g., onProgress) via Symfony’s event dispatcher:

    $dispatcher = $ffmpeg->getFFMpeg()->getDispatcher();
    $dispatcher->addListener('progress', function ($event) { ... });
    

Performance Tips

  • Reuse FFmpeg Instances: The bundle provides a singleton service. Avoid recreating $ffmpeg in loops.

  • Optimize Formats: Prefer X264 for videos and Lame for audio:

    $video->save(new X264(['crf' => 23])); // Higher CRF = smaller file
    
  • Parallel Processing: Use Laravel’s parallel helper for batch jobs:

    parallel([
        fn() => ProcessVideoJob::dispatch('video1.mp4'),
        fn() => ProcessVideoJob::dispatch('video2.mp4'),
    ]);
    

Security

  • Validate Inputs: Sanitize file paths to prevent directory traversal:

    $path = str_replace(['../', '..\\'], '', $inputPath);
    
  • Resource Limits: Set binary_timeout and memory_limit in php.ini to prevent DoS:

    dubture_f_fmpeg:
        binary_timeout: 600  # 10 minutes max
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity