Passed
Push — master ( 9db3d8...7e1106 )
by Sébastien
10:58 queued 08:23
created

FFMpegAdapter::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Soluble\MediaTools\Video\Adapter;
6
7
use Soluble\MediaTools\Common\Exception\InvalidArgumentException;
8
use Soluble\MediaTools\Common\Exception\UnsupportedParamException;
9
use Soluble\MediaTools\Common\Exception\UnsupportedParamValueException;
10
use Soluble\MediaTools\Common\IO\UnescapedFileInterface;
11
use Soluble\MediaTools\Video\Adapter\Validator\FFMpegParamValidator;
12
use Soluble\MediaTools\Video\Config\FFMpegConfigInterface;
13
use Soluble\MediaTools\Video\Exception\ParamValidationException;
14
use Soluble\MediaTools\Video\Exception\UnexpectedValueException;
15
use Soluble\MediaTools\Video\VideoConvertParamsInterface;
16
17
class FFMpegAdapter implements ConverterAdapterInterface
18
{
19
    /** @var FFMpegConfigInterface */
20
    protected $ffmpegConfig;
21
22 31
    public function __construct(FFMpegConfigInterface $ffmpegConfig)
23
    {
24 31
        $this->ffmpegConfig = $ffmpegConfig;
25 31
    }
26
27
    /**
28
     * @return array<string, array<string, string>>
29
     */
30 30
    public function getParamsOptions(): array
31
    {
32
        return [
33 30
            VideoConvertParamsInterface::PARAM_OUTPUT_FORMAT => [
34
                'pattern' => '-f %s',
35
            ],
36 30
            VideoConvertParamsInterface::PARAM_VIDEO_CODEC => [
37
                'pattern' => '-c:v %s',
38
            ],
39 30
            VideoConvertParamsInterface::PARAM_VIDEO_BITRATE => [
40
                'pattern' => '-b:v %s',
41
            ],
42 30
            VideoConvertParamsInterface::PARAM_VIDEO_MIN_BITRATE => [
43
                'pattern' => '-minrate %s',
44
            ],
45 30
            VideoConvertParamsInterface::PARAM_VIDEO_MAX_BITRATE => [
46
                'pattern' => '-maxrate %s',
47
            ],
48 30
            VideoConvertParamsInterface::PARAM_AUDIO_CODEC => [
49
                'pattern' => '-c:a %s',
50
            ],
51 30
            VideoConvertParamsInterface::PARAM_AUDIO_BITRATE => [
52
                'pattern' => '-b:a %s',
53
            ],
54 30
            VideoConvertParamsInterface::PARAM_PIX_FMT => [
55
                'pattern' => '-pix_fmt %s',
56
            ],
57 30
            VideoConvertParamsInterface::PARAM_PRESET => [
58
                'pattern' => '-preset %s',
59
            ],
60 30
            VideoConvertParamsInterface::PARAM_SPEED => [
61
                'pattern' => '-speed %d',
62
            ],
63 30
            VideoConvertParamsInterface::PARAM_THREADS => [
64
                'pattern' => '-threads %d',
65
            ],
66 30
            VideoConvertParamsInterface::PARAM_KEYFRAME_SPACING => [
67
                'pattern' => '-g %d',
68
            ],
69 30
            VideoConvertParamsInterface::PARAM_QUALITY => [
70
                'pattern' => '-quality %s',
71
            ],
72 30
            VideoConvertParamsInterface::PARAM_VIDEO_QUALITY_SCALE => [
73
                'pattern' => '-qscale:v %d',
74
            ],
75 30
            VideoConvertParamsInterface::PARAM_CRF => [
76
                'pattern' => '-crf %d',
77
            ],
78 30
            VideoConvertParamsInterface::PARAM_STREAMABLE => [
79
                'pattern' => '-movflags +faststart',
80
            ],
81 30
            VideoConvertParamsInterface::PARAM_FRAME_PARALLEL => [
82
                'pattern' => '-frame-parallel %s',
83
            ],
84 30
            VideoConvertParamsInterface::PARAM_TILE_COLUMNS => [
85
                'pattern' => '-tile-columns %s',
86
            ],
87 30
            VideoConvertParamsInterface::PARAM_TUNE => [
88
                'pattern' => '-tune %s',
89
            ],
90 30
            VideoConvertParamsInterface::PARAM_VIDEO_FILTER => [
91
                'pattern' => '-filter:v %s',
92
            ],
93 30
            VideoConvertParamsInterface::PARAM_OVERWRITE => [
94
                'pattern' => '-y',
95
            ],
96 30
            VideoConvertParamsInterface::PARAM_VIDEO_FRAMES => [
97
                'pattern' => '-frames:v %d',
98
            ],
99 30
            VideoConvertParamsInterface::PARAM_NOAUDIO => [
100
                'pattern' => '-an',
101
            ],
102 30
            VideoConvertParamsInterface::PARAM_SEEK_START => [
103
                'pattern' => '-ss %s',
104
            ],
105 30
            VideoConvertParamsInterface::PARAM_SEEK_END => [
106
                'pattern' => '-to %s',
107
            ],
108 30
            VideoConvertParamsInterface::PARAM_PASSLOGFILE => [
109
                'pattern' => '-passlogfile %s',
110
            ],
111 30
            VideoConvertParamsInterface::PARAM_PASS => [
112
                'pattern' => '-pass %s',
113
            ],
114 30
            VideoConvertParamsInterface::PARAM_AUTO_ALT_REF => [
115
                'pattern' => '-auto-alt-ref %s',
116
            ],
117 30
            VideoConvertParamsInterface::PARAM_LAG_IN_FRAMES => [
118
                'pattern' => '-lag-in-frames %s',
119
            ],
120
        ];
121
    }
122
123
    /**
124
     * Return an array version of params suitable for ffmpeg cli.
125
     *
126
     * @param bool $validateParams whether to run ffmpeg validation process validation
127
     *
128
     * @return array<string, string>
129
     *
130
     * @throws UnsupportedParamException
131
     * @throws UnsupportedParamValueException
132
     * @throws ParamValidationException
133
     */
134 30
    public function getMappedConversionParams(VideoConvertParamsInterface $conversionParams, bool $validateParams = true): array
135
    {
136 30
        $args             = [];
137 30
        $supportedOptions = $this->getParamsOptions();
138
139
        // Add default overwrite option if not set
140 30
        $overwriteParam = VideoConvertParamsInterface::PARAM_OVERWRITE;
141 30
        if (!$conversionParams->hasParam($overwriteParam)) {
142 26
            $conversionParams = $conversionParams->withBuiltInParam(
143 26
                $overwriteParam,
144 26
                true
145
            );
146
        }
147
148 30
        foreach ($conversionParams->toArray() as $paramName => $value) {
149 30
            if (!array_key_exists($paramName, $supportedOptions)) {
150
                throw new UnsupportedParamException(
151
                    sprintf(
152
                        'FFMpegAdapter does not support param \'%s\'',
153
                        $paramName
154
                    )
155
                );
156
            }
157 30
            $pattern = $supportedOptions[$paramName]['pattern'];
158 30
            if (is_bool($value)) {
159 29
                $args[$paramName] = $value ? $pattern : '';
160 27
            } elseif ($value instanceof FFMpegCLIValueInterface) {
161
                // Will test also FFMpegVideoFilterInterface
162 15
                $args[$paramName] = sprintf($pattern, $value->getFFmpegCLIValue());
163 25
            } elseif (is_string($value) || is_int($value)) {
164 24
                $args[$paramName] = sprintf($pattern, $value);
165
            } else {
166 1
                throw new UnsupportedParamValueException(
167 1
                    sprintf(
168 1
                        'Param \'%s\' has an unsupported type: \'%s\'',
169 1
                        $paramName,
170 30
                        is_object($value) ? get_class($value) : gettype($value)
171
                    )
172
                );
173
            }
174
        }
175
176
        // Validation
177 29
        if ($validateParams) {
178 29
            (new FFMpegParamValidator($conversionParams))->validate();
179
        }
180
181 28
        return $args;
182
    }
183
184
    /**
185
     * @param array<string,string>               $arguments        args that will be added
186
     * @param null|string                        $inputFile
187
     * @param null|string|UnescapedFileInterface $outputFile
188
     * @param array<string,string>               $prependArguments args that must be added at the beginning of the command
189
     *
190
     * @throws InvalidArgumentException
191
     */
192 24
    public function getCliCommand(array $arguments, ?string $inputFile, $outputFile = null, array $prependArguments = []): string
193
    {
194 24
        $inputArg = ($inputFile !== null && $inputFile !== '')
195 24
                        ? sprintf('-i %s', escapeshellarg($inputFile))
196 24
                        : '';
197
198 24
        $outputArg = '';
199 24
        if ($outputFile instanceof UnescapedFileInterface) {
200 5
            $outputArg = $outputFile->getFile();
201 21
        } elseif (is_string($outputFile)) {
202 19
            $outputArg = sprintf('%s', escapeshellarg($outputFile));
203 2
        } elseif ($outputFile !== null) {
0 ignored issues
show
introduced by
The condition $outputFile !== null is always false.
Loading history...
204 2
            throw new InvalidArgumentException(sprintf(
205 2
                'Output file must be either a non empty string, null or PlatformNullFile (type %s)',
206 2
                gettype($outputFile)
207
            ));
208
        }
209
210 22
        $ffmpegCmd = preg_replace(
211 22
            '/(\ ){2,}/',
212 22
            ' ',
213 22
            trim(sprintf(
214 22
                '%s %s %s %s %s',
215 22
                $this->ffmpegConfig->getBinary(),
216 22
                implode(' ', $prependArguments),
217 22
                $inputArg,
218 22
                implode(' ', $arguments),
219 22
                $outputArg
220
            ))
221
        );
222
223 22
        if ($ffmpegCmd === null) {
224
            throw new UnexpectedValueException(
225
                'Cannot generate ffmpeg cli command'
226
            );
227
        }
228
229 22
        return $ffmpegCmd;
230
    }
231
232 17
    public function getDefaultThreads(): ?int
233
    {
234 17
        return $this->ffmpegConfig->getThreads();
235
    }
236
}
237