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

Media Info Bundle Laravel Package

ac/media-info-bundle

Symfony bundle wrapping the mediainfo CLI to extract multimedia metadata. Configure the mediainfo binary path, then scan files to get a normalized, structured PHP array (keys lowercased). Includes a console command to export scan results (e.g., YAML).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    • Require the package via Composer:
      composer require ac/media-info-bundle:~1.2.0
      
    • Register the bundle in config/bundles.php (Laravel) or AppKernel.php (Symfony):
      AC\MediaInfoBundle\ACMediaInfoBundle::class,
      
    • Configure the mediainfo executable path in .env or config/services.php:
      'mediainfo.path' => env('MEDIAINFO_PATH', '/usr/bin/mediainfo'),
      
  2. First Use Case:

    • Inject the service into a controller or command:
      use AC\MediaInfoBundle\MediaInfo;
      
      public function __construct(private MediaInfo $mediaInfo) {}
      
    • Scan a file and retrieve metadata:
      $metadata = $mediaInfo->scan(storage_path('videos/example.mp4'));
      

Where to Look First

  • Service Configuration: Check config/services.php or .env for the mediainfo path.
  • Service Container: Use Laravel’s dependency injection to access MediaInfo.
  • Output Structure: Review the normalized lowercase keys in the returned array (e.g., $metadata['file']['general']['title']).

Implementation Patterns

Core Workflows

  1. Metadata Extraction:

    • Scan files dynamically (e.g., in upload handlers, file processors):
      $metadata = $mediaInfo->scan($filePath);
      $title = $metadata['file']['general']['title'] ?? null;
      
    • Batch processing (loop through files in a directory):
      foreach (Storage::files('videos') as $file) {
          $metadata = $mediaInfo->scan(storage_path($file->path()));
          // Process metadata (e.g., validate, store in DB)
      }
      
  2. Integration with Laravel Features:

    • File Uploads: Use with Illuminate\Http\Request to extract metadata on upload:
      public function store(Request $request) {
          $file = $request->file('video');
          $metadata = $mediaInfo->scan($file->path());
          // Save metadata to DB or validate before storage
      }
      
    • Artisan Commands: Create custom commands for bulk metadata extraction:
      use Illuminate\Console\Command;
      
      class ExtractMetadata extends Command {
          protected $signature = 'media:extract {path}';
          public function handle(MediaInfo $mediaInfo) {
              $metadata = $mediaInfo->scan($this->argument('path'));
              $this->info(json_encode($metadata, JSON_PRETTY_PRINT));
          }
      }
      
  3. Normalized Data Handling:

    • Flatten nested arrays for easier access (e.g., using array_walk_recursive):
      $flatMetadata = [];
      array_walk_recursive($metadata, function($value, $key) use (&$flatMetadata) {
          $flatMetadata[$key] = $value;
      });
      
    • Use Laravel Collections for cleaner manipulation:
      collect($metadata['file']['general'])->filter()->toArray();
      

Advanced Patterns

  • Caching: Cache metadata for frequently accessed files (e.g., using Laravel’s cache):
    $cacheKey = 'mediainfo:' . md5($filePath);
    $metadata = Cache::remember($cacheKey, now()->addHours(1), function() use ($mediaInfo, $filePath) {
        return $mediaInfo->scan($filePath);
    });
    
  • Validation: Validate metadata against expected formats (e.g., video duration, codec):
    $duration = $metadata['file']['general']['duration'] ?? 0;
    if ($duration > 3600) { // >1 hour
        throw new \Exception('Video too long');
    }
    

Gotchas and Tips

Pitfalls

  1. Executable Path:

    • Issue: mediainfo not found. The bundle throws exceptions if the path is incorrect or the executable is missing.
    • Fix: Verify the path in config/services.php or .env and ensure mediainfo is installed system-wide (sudo apt install mediainfo on Ubuntu).
    • Debug: Test the path manually:
      /usr/bin/mediainfo --version
      
  2. Nested Array Structure:

    • Issue: Keys like count_of_stream may contain arrays (e.g., ['count_of_stream'] => ['0' => '2']), leading to confusion.
    • Fix: Normalize or flatten the array post-scan:
      $count = $metadata['file']['general']['count_of_stream'][0] ?? null;
      
  3. Performance:

    • Issue: Scanning large files or many files sequentially can be slow.
    • Fix: Use Laravel queues for async processing or batch scans with caching.
  4. Character Encoding:

    • Issue: Metadata with special characters (e.g., é, ü) may cause issues.
    • Fix: Ensure the mediainfo output is UTF-8 encoded or decode the response:
      mb_convert_encoding($metadata, 'UTF-8');
      

Debugging Tips

  • Log Raw Output: Temporarily log the raw mediainfo output to debug:
    $rawOutput = $mediaInfo->getRawOutput($filePath);
    \Log::debug('MediaInfo Raw Output:', ['output' => $rawOutput]);
    
  • Validate with CLI: Cross-check results with the mediainfo CLI:
    mediainfo --Output="JSON" /path/to/file.mp4
    
  • Handle Exceptions: Wrap calls in try-catch blocks:
    try {
        $metadata = $mediaInfo->scan($filePath);
    } catch (\RuntimeException $e) {
        \Log::error('MediaInfo scan failed: ' . $e->getMessage());
        return response()->json(['error' => 'Invalid media file'], 400);
    }
    

Extension Points

  1. Custom Output Formats:

    • Extend the bundle to support custom output formats (e.g., JSON, XML) by overriding the scan method in a decorator:
      class CustomMediaInfo extends MediaInfo {
          public function scan($filePath) {
              $raw = parent::scan($filePath);
              return json_decode($raw, true);
          }
      }
      
    • Register the decorator in config/services.php:
      'mediainfo' => \App\Services\CustomMediaInfo::class,
      
  2. Add Metadata Transformers:

    • Create a service to transform raw metadata into domain-specific objects:
      class VideoMetadataTransformer {
          public function transform(array $metadata): VideoMetadata {
              return new VideoMetadata(
                  $metadata['file']['general']['title'] ?? null,
                  $metadata['file']['general']['duration'] ?? 0
              );
          }
      }
      
  3. Support for Multiple mediainfo Versions:

    • Handle version-specific output quirks by checking the version key in the response:
      if ($metadata['version'] >= '0.8.0') {
          // New format handling
      }
      
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.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime