Passed
Push — master ( 55b9e7...e379f9 )
by Sébastien
02:48 queued 11s
created

ResolvePreset::getParams()   A

Complexity

Conditions 6
Paths 4

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
eloc 15
nc 4
nop 3
dl 0
loc 25
ccs 0
cts 19
cp 0
crap 42
rs 9.2222
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Soluble\MediaTools\Preset\Prod;
6
7
use Soluble\MediaTools\Cli\Service\MediaToolsServiceInterface;
8
use Soluble\MediaTools\Preset\PresetInterface;
9
use Soluble\MediaTools\Video\Filter\ScaleFilter;
10
use Soluble\MediaTools\Video\Filter\VideoFilterChain;
11
use Soluble\MediaTools\Video\VideoConvertParams;
12
use Soluble\MediaTools\Video\VideoInfoInterface;
13
14
class ResolvePreset implements PresetInterface
15
{
16
    /** @var MediaToolsServiceInterface */
17
    private $mediaTools;
18
19
    /** @var VideoInfoInterface */
20
    private $videoInfo;
21
22
    public function __construct(MediaToolsServiceInterface $mediaTools)
23
    {
24
        $this->mediaTools = $mediaTools;
25
    }
26
27
    public function getName(): string
28
    {
29
        return __CLASS__;
30
    }
31
32
    private function getVideoInfo(string $file): VideoInfoInterface
33
    {
34
        if ($this->videoInfo === null) {
35
            $this->videoInfo = $this->mediaTools->getReader()->getInfo($file);
36
        }
37
38
        return $this->videoInfo;
39
    }
40
41
    public function getParams(string $file, ?int $width = null, ?int $height = null): VideoConvertParams
42
    {
43
        $info = $this->getVideoInfo($file);
44
45
        $firstAudio = $info->getAudioStreams()->getFirst();
46
        $firstVideo = $info->getVideoStreams()->getFirst();
47
48
        $filters = new VideoFilterChain();
49
50
        if (($width !== null && $firstVideo->getWidth() !== $width) ||
51
            ($height !== null && $firstVideo->getHeight() !== $height)) {
52
            $filters->addFilter(new ScaleFilter($width, $height));
53
        }
54
55
        $params = (new VideoConvertParams())
56
            ->withVideoCodec('libx264')
57
            ->withStreamable(true)
58
            ->withVideoFilter($filters)
59
            ->withOutputFormat('mp4');
60
61
        if (mb_strtolower($firstAudio->getCodecName()) !== 'aac') {
62
            $params = $params->withAudioCodec('aac');
63
        }
64
65
        return $params;
66
    }
67
}
68