Skip to content

feat: Add hardware acceleration, x265 codec options, and image-to-vid… #536

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 60 additions & 22 deletions src/Drivers/PHPFFMpeg.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,20 @@ public function __construct(FFMpeg $ffmpeg)
$this->pendingComplexFilters = new Collection;
}

/**
* Enable hardware acceleration with specified codec.
*
* @param string $codec e.g., 'h264_nvenc', 'hevc_nvenc'
* @return $this
*/
public function withHardwareAcceleration(string $codec): self
{
if ($this->isVideo()) {
$this->get()->getVideoStream()->setVideoCodec($codec);
}
return $this;
}

/**
* Returns a fresh instance of itself with only the underlying FFMpeg instance.
*/
Expand Down Expand Up @@ -117,29 +131,53 @@ public function open(MediaCollection $mediaCollection): self
if ($mediaCollection->count() === 1 && ! $this->forceAdvanced) {
$media = Arr::first($mediaCollection->collection());

$this->ffmpeg->setFFProbe(
FFProbe::make($this->ffmpeg->getFFProbe())->setMedia($media)
);

$ffmpegMedia = $this->ffmpeg->open($media->getLocalPath());

// this should be refactored to a factory...
if ($ffmpegMedia instanceof Video) {
$this->media = VideoMedia::make($ffmpegMedia);
} elseif ($ffmpegMedia instanceof Audio) {
$this->media = AudioMedia::make($ffmpegMedia);
} else {
$this->media = $ffmpegMedia;
}

if (method_exists($this->media, 'setHeaders')) {
$this->media->setHeaders(Arr::first($mediaCollection->getHeaders()) ?: []);
try {
$this->ffmpeg->setFFProbe(
FFProbe::make($this->ffmpeg->getFFProbe())->setMedia($media)
);

$ffmpegMedia = $this->ffmpeg->open($media->getLocalPath());

// this should be refactored to a factory...
if ($ffmpegMedia instanceof Video) {
$this->media = VideoMedia::make($ffmpegMedia);
} elseif ($ffmpegMedia instanceof Audio) {
$this->media = AudioMedia::make($ffmpegMedia);
} else {
$this->media = $ffmpegMedia;
}

if (method_exists($this->media, 'setHeaders')) {
$this->media->setHeaders(Arr::first($mediaCollection->getHeaders()) ?: []);
}
} catch (Exception $exception) {
throw new \RuntimeException(
sprintf(
"Failed to open media file: %s. Error: %s",
$media->getLocalPath(),
$exception->getMessage()
),
0,
$exception
);
}
} else {
$ffmpegMedia = $this->ffmpeg->openAdvanced($mediaCollection->getLocalPaths());

$this->media = AdvancedMedia::make($ffmpegMedia)
->setHeaders($mediaCollection->getHeaders());
try {
$ffmpegMedia = $this->ffmpeg->openAdvanced($mediaCollection->getLocalPaths());

$this->media = AdvancedMedia::make($ffmpegMedia)
->setHeaders($mediaCollection->getHeaders());
} catch (Exception $exception) {
throw new \RuntimeException(
sprintf(
"Failed to open advanced media: %s. Error: %s",
implode(', ', $mediaCollection->getLocalPaths()),
$exception->getMessage()
),
0,
$exception
);
}
}

return $this;
Expand Down Expand Up @@ -256,4 +294,4 @@ public function __call($method, $arguments)

return ($result === $media) ? $this : $result;
}
}
}
57 changes: 43 additions & 14 deletions src/Exporters/HLSExporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace ProtoneMedia\LaravelFFMpeg\Exporters;

use Closure;
use FFMpeg\Exception\RuntimeException;
use FFMpeg\Format\Audio\DefaultAudio;
use FFMpeg\Format\AudioInterface;
use FFMpeg\Format\FormatInterface;
Expand All @@ -17,7 +18,6 @@ class HLSExporter extends MediaExporter
use EncryptsHLSSegments;

public const HLS_KEY_INFO_FILENAME = 'hls_encryption.keyinfo';

public const ENCRYPTION_LISTENER = 'listen-encryption-key';

/**
Expand Down Expand Up @@ -45,13 +45,39 @@ class HLSExporter extends MediaExporter
*/
private $segmentFilenameGenerator = null;

/**
* Enable x265 codec for HLS encoding.
*
* @return $this
*/
public function useX265(): self
{
if ($this->format instanceof DefaultVideo) {
$this->format->setVideoCodec('libx265');
}
return $this;
}

/**
* Enable hardware acceleration with specified codec.
*
* @param string $codec e.g., 'h264_nvenc', 'hevc_nvenc'
* @return $this
*/
public function withHardwareAcceleration(string $codec): self
{
if ($this->driver->isVideo()) {
$this->driver->get()->getVideoStream()->setVideoCodec($codec);
}
return $this;
}

/**
* Setter for the segment length
*/
public function setSegmentLength(int $length): self
{
$this->segmentLength = max(2, $length);

return $this;
}

Expand All @@ -61,7 +87,6 @@ public function setSegmentLength(int $length): self
public function setKeyFrameInterval(int $interval): self
{
$this->keyFrameInterval = max(2, $interval);

return $this;
}

Expand All @@ -72,7 +97,6 @@ public function setKeyFrameInterval(int $interval): self
public function withPlaylistGenerator(PlaylistGenerator $playlistGenerator): self
{
$this->playlistGenerator = $playlistGenerator;

return $this;
}

Expand All @@ -87,11 +111,9 @@ private function getPlaylistGenerator(): PlaylistGenerator
public function withoutPlaylistEndLine(): self
{
$playlistGenerator = $this->getPlaylistGenerator();

if ($playlistGenerator instanceof HLSPlaylistGenerator) {
$playlistGenerator->withoutEndLine();
}

return $this;
}

Expand All @@ -101,7 +123,6 @@ public function withoutPlaylistEndLine(): self
public function useSegmentFilenameGenerator(Closure $callback): self
{
$this->segmentFilenameGenerator = $callback;

return $this;
}

Expand Down Expand Up @@ -185,7 +206,6 @@ private function applyFiltersCallback(callable $filtersCallback, int $formatKey)
);

$filterCount = $hlsVideoFilters->count();

$outs = [$filterCount ? HLSVideoFilters::glue($formatKey, $filterCount) : '0:v'];

if ($this->getAudioStream()) {
Expand Down Expand Up @@ -236,7 +256,6 @@ private function prepareSaving(?string $path = null): Collection
}

$media = $this->getDisk()->makeMedia($path);

$baseName = $media->getDirectory().$media->getFilenameWithoutExtension();

return $this->pendingFormats->map(function (array $formatAndCallback, $key) use ($baseName) {
Expand All @@ -249,7 +268,6 @@ private function prepareSaving(?string $path = null): Collection
);

$disk = $this->getDisk()->clone();

$this->addHLSParametersToFormat($format, $segmentsPattern, $disk, $key);

if ($filtersCallback) {
Expand All @@ -272,7 +290,6 @@ private function prepareSaving(?string $path = null): Collection
public function getCommand(?string $path = null)
{
$this->prepareSaving($path);

return parent::getCommand(null);
}

Expand All @@ -285,7 +302,20 @@ public function getCommand(?string $path = null)
public function save(?string $mainPlaylistPath = null): MediaOpener
{
return $this->prepareSaving($mainPlaylistPath)->pipe(function ($segmentPlaylists) use ($mainPlaylistPath) {
$result = parent::save();
try {
$result = parent::save();
} catch (RuntimeException $exception) {
$errorOutput = $this->driver->getErrorOutput() ?? 'No error output available';
throw new RuntimeException(
sprintf(
"Failed to encode HLS playlist: %s. FFmpeg error output: %s",
$exception->getMessage(),
$errorOutput
),
0,
$exception
);
}

$playlist = $this->getPlaylistGenerator()->get(
$segmentPlaylists->all(),
Expand Down Expand Up @@ -351,7 +381,6 @@ public function getAvailableVideoCodecs()
}

$this->pendingFormats->push([$format, $filtersCallback]);

return $this;
}
}
}
Loading