ffmpeg-mappable-media/src/Map.php

105 lines
2.5 KiB
PHP
Raw Normal View History

2022-08-21 20:47:05 -05:00
<?php
namespace Danjones\FFMpeg;
2022-09-05 21:17:44 -05:00
use FFMpeg\Format\ProgressableInterface;
use FFMpeg\Format\ProgressListener\AbstractProgressListener;
2022-08-21 20:47:05 -05:00
class Map
{
use Traits\HasMetadata;
2022-08-21 20:47:05 -05:00
protected MappableMedia $media;
protected string $path;
2022-08-21 22:42:02 -05:00
/** @var Stream[] */
protected array $streams = [];
2022-09-10 22:52:40 -05:00
/** @var Attachment[] */
protected array $attachments = [];
2022-09-05 21:17:44 -05:00
/** @var AbstractProgressListener[] */
protected array $listeners = [];
2022-08-21 20:47:05 -05:00
public function __construct(MappableMedia $media)
{
$this->media = $media;
}
public function saveMap(): MappableMedia
{
$this->media->saveMap($this);
return $this->media;
}
public function saveAs(string $path): static
{
$this->path = $path;
return $this;
}
2022-08-21 22:42:02 -05:00
2022-09-10 22:52:40 -05:00
protected function doStream(Stream $stream, callable $callback = null): Stream|static
2022-08-21 22:42:02 -05:00
{
if (!$callback) {
return $stream;
2022-08-21 22:42:02 -05:00
}
$callback($stream);
$this->saveStream($stream);
return $this;
}
2022-09-10 22:52:40 -05:00
public function stream(callable $callback = null): Stream|static
{
return $this->doStream(new Stream($this), $callback);
}
public function attach(string $file = '', callable $callback = null): Attachment|static
{
return $this->doStream(new Attachment($this, $file), $callback);
}
public function saveStream(Stream $stream): static
{
2022-09-10 22:52:40 -05:00
if ($stream instanceof Attachment){
$this->attachments[] = $stream;
return $this;
}
$this->streams[] = $stream;
2022-09-05 21:17:44 -05:00
$format = $stream->getCodec();
if ($format instanceof ProgressableInterface) {
$listener = $format->createProgressListener(
$this->media,
$this->media->getFFProbe(),
1, 1, 0
);
$this->listeners = array_merge($this->listeners, $listener);
}
2022-08-21 22:42:02 -05:00
return $this;
}
2022-09-05 21:17:44 -05:00
public function getListeners(): array
{
return $this->listeners;
}
2022-08-21 22:42:02 -05:00
public function buildCommand(): array
{
$commands = [];
2022-09-10 22:52:40 -05:00
$streams = $this->streams;
array_push($streams, ...$this->attachments);
foreach ($streams as $idx => $stream) {
2022-08-21 22:42:02 -05:00
array_push($commands, ...$stream->buildCommand($idx));
}
foreach ($this->metadata as $k => $v) {
array_push($commands, '-metadata', "{$k}={$v}");
}
$commands[] = $this->path;
return $commands;
}
2022-08-21 20:47:05 -05:00
}