Passed
Push — master ( 91e9bd...cb70ec )
by Sébastien
03:14
created

ThumbService::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 3
dl 0
loc 5
ccs 4
cts 4
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;
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\UnsupportedParamException;
13
use Soluble\MediaTools\Common\Exception\UnsupportedParamValueException;
14
use Soluble\MediaTools\Common\Process\ProcessFactory;
15
use Soluble\MediaTools\Common\Process\ProcessParamsInterface;
16
use Soluble\MediaTools\Video\Config\FFMpegConfigInterface;
17
use Soluble\MediaTools\Video\Exception\ConversionExceptionInterface;
18
use Soluble\MediaTools\Video\Exception\ConversionProcessExceptionInterface;
19
use Soluble\MediaTools\Video\Exception\InvalidParamException;
20
use Soluble\MediaTools\Video\Exception\MissingInputFileException;
21
use Soluble\MediaTools\Video\Exception\MissingTimeException;
22
use Soluble\MediaTools\Video\Exception\ProcessFailedException;
23
use Soluble\MediaTools\Video\Exception\ProcessSignaledException;
24
use Soluble\MediaTools\Video\Exception\ProcessTimedOutException;
25
use Soluble\MediaTools\Video\Exception\RuntimeException;
26
use Symfony\Component\Process\Exception as SPException;
27
use Symfony\Component\Process\Process;
28
29
class ThumbService implements ThumbServiceInterface
30
{
31
    public const DEFAULT_QUALITY_SCALE = 2;
32
33
    use PathAssertionsTrait;
34
35
    /** @var FFMpegConfigInterface */
36
    protected $ffmpegConfig;
37
38
    /** @var int */
39
    protected $defaultQualityScale;
40
41
    /** @var LoggerInterface|NullLogger */
42
    protected $logger;
43
44 7
    public function __construct(FFMpegConfigInterface $ffmpegConfig, ?LoggerInterface $logger = null, int $defaultQualityScale = self::DEFAULT_QUALITY_SCALE)
45
    {
46 7
        $this->ffmpegConfig        = $ffmpegConfig;
47 7
        $this->defaultQualityScale = $defaultQualityScale;
48 7
        $this->logger              = $logger ?? new NullLogger();
49 7
    }
50
51
    /**
52
     * Return ready-to-run symfony process object that you can use
53
     * to `run()` or `start()` programmatically. Useful if you want
54
     * handle the process your way...
55
     *
56
     * @see https://symfony.com/doc/current/components/process.html
57
     *
58
     * @throws UnsupportedParamException
59
     * @throws UnsupportedParamValueException
60
     */
61 4
    public function getSymfonyProcess(string $videoFile, string $thumbnailFile, ThumbParamsInterface $thumbParams, ?ProcessParamsInterface $processParams = null): Process
62
    {
63 4
        $adapter = $this->ffmpegConfig->getAdapter();
64
65 4
        $conversionParams = (new ConversionParams());
66
67 4
        if ($adapter->getDefaultThreads() !== null) {
68
            $conversionParams->withThreads($adapter->getDefaultThreads());
69
        }
70
71
        // TIME must be the first !!!
72
73 4
        $conversionParams = $conversionParams->withSeekStart(
74 4
            $thumbParams->getParam(ThumbParamsInterface::PARAM_SEEK_TIME)
75
        );
76
77
        // Only one frame
78 4
        $conversionParams = $conversionParams->withVideoFrames(1);
79
80 4
        if ($thumbParams->hasParam(ThumbParamsInterface::PARAM_VIDEO_FILTER)) {
81 2
            $conversionParams = $conversionParams->withVideoFilter(
82 2
                $thumbParams->getParam(ThumbParamsInterface::PARAM_VIDEO_FILTER)
83
            );
84
        }
85
86 4
        if ($thumbParams->hasParam(ThumbParamsInterface::PARAM_QUALITY_SCALE)) {
87
            $conversionParams = $conversionParams->withVideoQualityScale(
88
                $thumbParams->getParam(ThumbParamsInterface::PARAM_QUALITY_SCALE)
89
            );
90
        } else {
91 4
            $conversionParams = $conversionParams->withVideoQualityScale(
92 4
                $this->defaultQualityScale
93
            );
94
        }
95
96 4
        $arguments = $adapter->getMappedConversionParams($conversionParams);
97 4
        $ffmpegCmd = $adapter->getCliCommand($arguments, $videoFile, $thumbnailFile);
98
99 4
        $pp = $processParams ?? $this->ffmpegConfig->getProcessParams();
100
101 4
        return (new ProcessFactory($ffmpegCmd, $pp))();
102
    }
103
104
    /**
105
     * @throws ConversionExceptionInterface        Base exception class for conversion exceptions
106
     * @throws ConversionProcessExceptionInterface Base exception class for process conversion exceptions
107
     * @throws MissingInputFileException
108
     * @throws MissingTimeException
109
     * @throws ProcessTimedOutException
110
     * @throws ProcessFailedException
111
     * @throws ProcessSignaledException
112
     * @throws RuntimeException
113
     * @throws InvalidParamException
114
     */
115 7
    public function makeThumbnail(string $videoFile, string $thumbnailFile, ThumbParamsInterface $thumbParams, ?callable $callback = null, ?ProcessParamsInterface $processParams = null): void
116
    {
117
        try {
118
            try {
119 7
                $this->ensureFileExists($videoFile);
120
121 4
                $process = $this->getSymfonyProcess($videoFile, $thumbnailFile, $thumbParams, $processParams);
122 4
                $process->mustRun($callback);
123 5
            } catch (FileNotFoundException $e) {
124 3
                throw new MissingInputFileException($e->getMessage());
125 2
            } catch (UnsupportedParamValueException | UnsupportedParamException $e) {
126
                throw new InvalidParamException($e->getMessage());
127 2
            } catch (SPException\ProcessTimedOutException $e) {
128 1
                throw new ProcessTimedOutException($e->getProcess(), $e);
129 1
            } catch (SPException\ProcessSignaledException $e) {
130
                throw new ProcessSignaledException($e->getProcess(), $e);
131 1
            } catch (SPException\ProcessFailedException $e) {
132 1
                throw new ProcessFailedException($e->getProcess(), $e);
133
            } catch (SPException\RuntimeException $e) {
134 2
                throw new RuntimeException($e->getMessage());
135
            }
136 5
        } catch (\Throwable $e) {
137 5
            $exceptionNs = explode('\\', get_class($e));
138 5
            $this->logger->log(
139 5
                ($e instanceof MissingInputFileException) ? LogLevel::WARNING : LogLevel::ERROR,
140 5
                sprintf(
141 5
                    'Video thumbnailing failed \'%s\' with \'%s\'. "%s(%s, %s,...)"',
142 5
                    $exceptionNs[count($exceptionNs) - 1],
143 5
                    __METHOD__,
144 5
                    $e->getMessage(),
145 5
                    $videoFile,
146 5
                    $thumbnailFile
147
                )
148
            );
149 5
            throw $e;
150
        }
151 2
    }
152
}
153