Passed
Push — master ( d0bcc1...2a69c8 )
by Sébastien
02:28
created

VideoThumbGenerator::getSymfonyProcess()   B

Complexity

Conditions 7
Paths 9

Size

Total Lines 52
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 7.2007

Importance

Changes 0
Metric Value
eloc 29
dl 0
loc 52
ccs 21
cts 25
cp 0.84
rs 8.5226
c 0
b 0
f 0
cc 7
nc 9
nop 4
crap 7.2007

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Soluble\MediaTools\Video;
6
7
use Psr\Log\LoggerInterface;
8
use Psr\Log\LogLevel;
9
use Psr\Log\NullLogger;
10
use Soluble\MediaTools\Common\Assert\PathAssertionsTrait;
11
use Soluble\MediaTools\Common\Exception\FileNotFoundException;
12
use Soluble\MediaTools\Common\Exception\FileNotReadableException;
13
use Soluble\MediaTools\Common\Exception\UnsupportedParamException;
14
use Soluble\MediaTools\Common\Exception\UnsupportedParamValueException;
15
use Soluble\MediaTools\Common\Process\ProcessFactory;
16
use Soluble\MediaTools\Common\Process\ProcessParamsInterface;
17
use Soluble\MediaTools\Video\Config\FFMpegConfigInterface;
18
use Soluble\MediaTools\Video\Exception\ConverterExceptionInterface;
19
use Soluble\MediaTools\Video\Exception\ConverterProcessExceptionInterface;
20
use Soluble\MediaTools\Video\Exception\InvalidParamException;
21
use Soluble\MediaTools\Video\Exception\MissingInputFileException;
22
use Soluble\MediaTools\Video\Exception\MissingTimeException;
23
use Soluble\MediaTools\Video\Exception\NoOutputGeneratedException;
24
use Soluble\MediaTools\Video\Exception\ProcessFailedException;
25
use Soluble\MediaTools\Video\Exception\ProcessSignaledException;
26
use Soluble\MediaTools\Video\Exception\ProcessTimedOutException;
27
use Soluble\MediaTools\Video\Exception\RuntimeReaderException;
28
use Soluble\MediaTools\Video\Filter\SelectFilter;
29
use Soluble\MediaTools\Video\Filter\VideoFilterChain;
30
use Symfony\Component\Process\Exception as SPException;
31
use Symfony\Component\Process\Process;
32
33
class VideoThumbGenerator implements VideoThumbGeneratorInterface
34
{
35
    public const DEFAULT_QUALITY_SCALE = 2;
36
37
    use PathAssertionsTrait;
38
39
    /** @var FFMpegConfigInterface */
40
    protected $ffmpegConfig;
41
42
    /** @var int */
43
    protected $defaultQualityScale;
44
45
    /** @var LoggerInterface */
46
    protected $logger;
47
48 14
    public function __construct(FFMpegConfigInterface $ffmpegConfig, ?LoggerInterface $logger = null, int $defaultQualityScale = self::DEFAULT_QUALITY_SCALE)
49
    {
50 14
        $this->ffmpegConfig        = $ffmpegConfig;
51 14
        $this->defaultQualityScale = $defaultQualityScale;
52 14
        $this->logger              = $logger ?? new NullLogger();
53 14
    }
54
55
    /**
56
     * Return ready-to-run symfony process object that you can use
57
     * to `run()` or `start()` programmatically. Useful if you want
58
     * handle the process your way...
59
     *
60
     * @see https://symfony.com/doc/current/components/process.html
61
     *
62
     * @throws UnsupportedParamException
63
     * @throws UnsupportedParamValueException
64
     * @throws MissingTimeException
65
     */
66 11
    public function getSymfonyProcess(string $videoFile, string $thumbnailFile, VideoThumbParamsInterface $thumbParams, ?ProcessParamsInterface $processParams = null): Process
67
    {
68 11
        $adapter = $this->ffmpegConfig->getAdapter();
69
70 11
        $conversionParams = (new VideoConvertParams());
71
72 11
        if (!$thumbParams->hasParam(VideoThumbParamsInterface::PARAM_SEEK_TIME)
73 11
         && !$thumbParams->hasParam(VideoThumbParamsInterface::PARAM_WITH_FRAME)) {
74
            throw new MissingTimeException('Missing seekTime/time or frame selection parameter');
75
        }
76
77 11
        if ($thumbParams->hasParam(VideoThumbParamsInterface::PARAM_SEEK_TIME)) {
78
            // TIME params are separated from the rest, so we can inject them
79
            // before input file
80 7
            $timeParams = (new VideoConvertParams())->withSeekStart(
81 7
                $thumbParams->getParam(VideoThumbParamsInterface::PARAM_SEEK_TIME)
82
            );
83
        } else {
84 4
            $timeParams = null;
85
        }
86
87 11
        if ($adapter->getDefaultThreads() !== null) {
88
            $conversionParams = $conversionParams->withThreads($adapter->getDefaultThreads());
89
        }
90
91
        // Only one frame for thumbnails :)
92
        $conversionParams = $conversionParams
93 11
            ->withVideoFrames(1)
94 11
            ->withVideoFilter($this->getThumbFilters($thumbParams));
95
96 11
        if ($thumbParams->hasParam(VideoThumbParamsInterface::PARAM_QUALITY_SCALE)) {
97
            $conversionParams = $conversionParams->withVideoQualityScale(
98
                $thumbParams->getParam(VideoThumbParamsInterface::PARAM_QUALITY_SCALE)
99
            );
100
        } else {
101 11
            $conversionParams = $conversionParams->withVideoQualityScale(
102 11
                $this->defaultQualityScale
103
            );
104
        }
105
106 11
        $arguments = $adapter->getMappedConversionParams($conversionParams);
107
108 11
        $ffmpegCmd = $adapter->getCliCommand(
109 11
            $arguments,
110
            $videoFile,
111
            $thumbnailFile,
112 11
            $timeParams !== null ? $adapter->getMappedConversionParams($timeParams) : []
113
        );
114
115 11
        $pp = $processParams ?? $this->ffmpegConfig->getProcessParams();
116
117 11
        return (new ProcessFactory($ffmpegCmd, $pp))();
118
    }
119
120
    /**
121
     * @throws ConverterExceptionInterface        Base exception class for conversion exceptions
122
     * @throws ConverterProcessExceptionInterface Base exception class for process conversion exceptions
123
     * @throws MissingInputFileException
124
     * @throws MissingTimeException
125
     * @throws ProcessTimedOutException
126
     * @throws ProcessFailedException
127
     * @throws ProcessSignaledException
128
     * @throws RuntimeReaderException
129
     * @throws InvalidParamException
130
     * @throws NoOutputGeneratedException
131
     */
132 9
    public function makeThumbnail(string $videoFile, string $thumbnailFile, VideoThumbParamsInterface $thumbParams, ?callable $callback = null, ?ProcessParamsInterface $processParams = null): void
133
    {
134
        try {
135
            try {
136 9
                $this->ensureFileReadable($videoFile);
137
138 6
                $process = $this->getSymfonyProcess($videoFile, $thumbnailFile, $thumbParams, $processParams);
139 6
                $process->mustRun($callback);
140 5
            } catch (FileNotFoundException | FileNotReadableException $e) {
141 3
                throw new MissingInputFileException($e->getMessage());
142 2
            } catch (UnsupportedParamValueException | UnsupportedParamException $e) {
143
                throw new InvalidParamException($e->getMessage());
144 2
            } catch (SPException\ProcessTimedOutException $e) {
145 1
                throw new ProcessTimedOutException($e->getProcess(), $e);
146 1
            } catch (SPException\ProcessSignaledException $e) {
147
                throw new ProcessSignaledException($e->getProcess(), $e);
148 1
            } catch (SPException\ProcessFailedException $e) {
149 1
                throw new ProcessFailedException($e->getProcess(), $e);
150
            } catch (SPException\RuntimeException $e) {
151
                throw new RuntimeReaderException($e->getMessage());
152
            }
153
154 4
            if (!file_exists($thumbnailFile) || filesize($thumbnailFile) === 0) {
155 1
                $stdErr        = array_filter(explode("\n", trim($process->getErrorOutput())));
156 1
                $lastErrorLine = count($stdErr) > 0 ? $stdErr[count($stdErr) - 1] : 'no error message';
157 1
                throw new NoOutputGeneratedException(sprintf(
158 4
                    'Thumbnail was not generated, probably an invalid time/frame selection (ffmpeg: %s)',
159
                    $lastErrorLine
160
                ));
161
            }
162 6
        } catch (\Throwable $e) {
163 6
            $exceptionNs = explode('\\', get_class($e));
164 6
            $this->logger->log(
165 6
                ($e instanceof MissingInputFileException) ? LogLevel::WARNING : LogLevel::ERROR,
166 6
                sprintf(
167 6
                    'Video thumbnailing failed \'%s\' with \'%s\'. "%s(%s, %s,...)"',
168 6
                    $exceptionNs[count($exceptionNs) - 1],
169 6
                    __METHOD__,
170 6
                    $e->getMessage(),
171
                    $videoFile,
172
                    $thumbnailFile
173
                )
174
            );
175 6
            throw $e;
176
        }
177 3
    }
178
179 11
    private function getThumbFilters(VideoThumbParamsInterface $thumbParams): VideoFilterChain
180
    {
181 11
        $videoFilters = new VideoFilterChain();
182
183
        // Let's choose a frame
184 11
        if ($thumbParams->hasParam(VideoThumbParamsInterface::PARAM_WITH_FRAME)) {
185 4
            $frame      = $thumbParams->getParam(VideoThumbParamsInterface::PARAM_WITH_FRAME);
186 4
            $expression = sprintf('eq(n\,%d)', max(0, $frame - 1));
187 4
            $videoFilters->addFilter(new SelectFilter($expression));
188
        }
189
190
        // Let's add the remaning filters
191 11
        if ($thumbParams->hasParam(VideoThumbParamsInterface::PARAM_VIDEO_FILTER)) {
192 4
            $videoFilters->addFilter(
193 4
                $thumbParams->getParam(VideoThumbParamsInterface::PARAM_VIDEO_FILTER)
194
            );
195
        }
196
197 11
        return $videoFilters;
198
    }
199
}
200