Skip to content

Commit

Permalink
add FFmpeg conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
QuentinGab committed Jan 12, 2025
1 parent d800be9 commit 436cdc4
Showing 1 changed file with 89 additions and 0 deletions.
89 changes: 89 additions & 0 deletions src/Definitions/MediaConversionFFmpeg.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
<?php

declare(strict_types=1);

namespace Elegantly\Media\Definitions;

use Closure;
use Elegantly\Media\Enums\MediaType;
use Elegantly\Media\Models\Media;
use Elegantly\Media\Models\MediaConversion;
use Illuminate\Contracts\Filesystem\Filesystem;
use ProtoneMedia\LaravelFFMpeg\Exporters\MediaExporter;
use ProtoneMedia\LaravelFFMpeg\Support\FFMpeg;
use Spatie\TemporaryDirectory\TemporaryDirectory as SpatieTemporaryDirectory;

class MediaConversionFFmpeg extends MediaConversionDefinition
{
/**
* @param Closure(MediaExporter $ffmpeg):void $manipulate
* @param Closure(Media $media, ?MediaConversion $parent):string $fileName
*/
public function __construct(
public string $name,
public Closure $manipulate,
public Closure $fileName,
public null|bool|Closure $when = null,
public ?Closure $onCompleted = null,
public bool $immediate = true,
public bool $queued = true,
public ?string $queue = null,
public array $conversions = [],
) {

parent::__construct(
name: $name,
handle: fn () => null,
when: $when,
onCompleted: $onCompleted,
immediate: $immediate,
queued: $queued,
queue: $queue,
conversions: $conversions
);
}

public function shouldExecute(Media $media, ?MediaConversion $parent): bool
{
if ($this->when !== null) {
return parent::shouldExecute($media, $parent);
}

$source = $parent ?? $media;

return in_array($source->type, [MediaType::Video, MediaType::Audio]);
}

public function handle(
Media $media,
?MediaConversion $parent,
?string $file,
Filesystem $filesystem,
SpatieTemporaryDirectory $temporaryDirectory
): ?MediaConversion {

if (! $file) {
return null;
}

$fileName = $this->fileName;
$manipulate = $this->manipulate;

$newFile = $fileName($media, $parent);

$ffmpeg = FFMpeg::fromFilesystem($filesystem)
->open($file)
->export();

$manipulate($ffmpeg);

$ffmpeg->save($newFile);

return $media->addConversion(
file: $filesystem->path($newFile),
conversionName: $this->name,
parent: $parent,
);

}
}

0 comments on commit 436cdc4

Please sign in to comment.