Total Complexity | 125 |
Total Lines | 936 |
Duplicated Lines | 0 % |
Changes | 0 |
Complex classes like Transcode often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Transcode, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
36 | class Transcode extends Component |
||
37 | { |
||
38 | // Constants |
||
39 | // ========================================================================= |
||
40 | |||
41 | // Suffixes to add to the generated filename params |
||
42 | const SUFFIX_MAP = [ |
||
43 | 'videoFrameRate' => 'fps', |
||
44 | 'videoBitRate' => 'bps', |
||
45 | 'audioBitRate' => 'bps', |
||
46 | 'audioChannels' => 'c', |
||
47 | 'height' => 'h', |
||
48 | 'width' => 'w', |
||
49 | 'timeInSecs' => 's', |
||
50 | ]; |
||
51 | |||
52 | // Params that should be excluded from being part of the generated filename |
||
53 | const EXCLUDE_PARAMS = [ |
||
54 | 'videoEncoder', |
||
55 | 'audioEncoder', |
||
56 | 'fileSuffix', |
||
57 | 'sharpen', |
||
58 | ]; |
||
59 | |||
60 | // Mappings for getFileInfo() summary values |
||
61 | const INFO_SUMMARY = [ |
||
62 | 'format' => [ |
||
63 | 'filename' => 'filename', |
||
64 | 'duration' => 'duration', |
||
65 | 'size' => 'size', |
||
66 | ], |
||
67 | 'audio' => [ |
||
68 | 'codec_name' => 'audioEncoder', |
||
69 | 'bit_rate' => 'audioBitRate', |
||
70 | 'sample_rate' => 'audioSampleRate', |
||
71 | 'channels' => 'audioChannels', |
||
72 | ], |
||
73 | 'video' => [ |
||
74 | 'codec_name' => 'videoEncoder', |
||
75 | 'bit_rate' => 'videoBitRate', |
||
76 | 'avg_frame_rate' => 'videoFrameRate', |
||
77 | 'height' => 'height', |
||
78 | 'width' => 'width', |
||
79 | ], |
||
80 | ]; |
||
81 | |||
82 | // Public Methods |
||
83 | // ========================================================================= |
||
84 | |||
85 | /** |
||
86 | * Returns a URL to the transcoded video or "" if it doesn't exist (at which |
||
87 | * time it will create it). |
||
88 | * |
||
89 | * @param $filePath string path to the original video -OR- an Asset |
||
90 | * @param $videoOptions array of options for the video |
||
91 | * @param bool $generate whether the video should be encoded |
||
92 | * |
||
93 | * @return string URL of the transcoded video or "" |
||
94 | */ |
||
95 | public function getVideoUrl($filePath, $videoOptions, $generate = true): string |
||
96 | { |
||
97 | |||
98 | $result = ''; |
||
99 | $settings = Transcoder::$plugin->getSettings(); |
||
100 | $subfolder = ''; |
||
101 | |||
102 | // sub folder check |
||
103 | if(\is_object($filePath) && ($filePath instanceof Asset) && $settings['createSubfolders']) { |
||
104 | $subfolder = $filePath->folderPath; |
||
105 | } |
||
106 | |||
107 | // file path |
||
108 | $filePath = $this->getAssetPath($filePath); |
||
109 | |||
110 | if (!empty($filePath)) { |
||
111 | $destVideoPath = $this->localDestPath('video', $subfolder); |
||
112 | $videoOptions = $this->coalesceOptions('defaultVideoOptions', $videoOptions); |
||
113 | |||
114 | // Get the video encoder presets to use |
||
115 | $videoEncoders = $settings['videoEncoders']; |
||
116 | $thisEncoder = $videoEncoders[$videoOptions['videoEncoder']]; |
||
117 | |||
118 | $videoOptions['fileSuffix'] = $thisEncoder['fileSuffix']; |
||
119 | |||
120 | // Build the basic command for ffmpeg |
||
121 | $ffmpegCmd = $settings['ffmpegPath'] |
||
122 | .' -i '.escapeshellarg($filePath) |
||
123 | .' -vcodec '.$thisEncoder['videoCodec'] |
||
124 | .' '.$thisEncoder['videoCodecOptions'] |
||
125 | .' -bufsize 1000k' |
||
126 | .' -threads '.$thisEncoder['threads']; |
||
127 | |||
128 | // Set the framerate if desired |
||
129 | if (!empty($videoOptions['videoFrameRate'])) { |
||
130 | $ffmpegCmd .= ' -r '.$videoOptions['videoFrameRate']; |
||
131 | } |
||
132 | |||
133 | // Set the bitrate if desired |
||
134 | if (!empty($videoOptions['videoBitRate'])) { |
||
135 | $ffmpegCmd .= ' -b:v '.$videoOptions['videoBitRate'].' -maxrate '.$videoOptions['videoBitRate']; |
||
136 | } |
||
137 | |||
138 | // Adjust the scaling if desired |
||
139 | $ffmpegCmd = $this->addScalingFfmpegArgs( |
||
140 | $videoOptions, |
||
141 | $ffmpegCmd |
||
142 | ); |
||
143 | |||
144 | // Handle any audio transcoding |
||
145 | if (empty($videoOptions['audioBitRate']) |
||
146 | && empty($videoOptions['audioSampleRate']) |
||
147 | && empty($videoOptions['audioChannels']) |
||
148 | ) { |
||
149 | // Just copy the audio if no options are provided |
||
150 | $ffmpegCmd .= ' -c:a copy'; |
||
151 | } else { |
||
152 | // Do audio transcoding based on the settings |
||
153 | $ffmpegCmd .= ' -acodec '.$thisEncoder['audioCodec']; |
||
154 | if (!empty($videoOptions['audioBitRate'])) { |
||
155 | $ffmpegCmd .= ' -b:a '.$videoOptions['audioBitRate']; |
||
156 | } |
||
157 | if (!empty($videoOptions['audioSampleRate'])) { |
||
158 | $ffmpegCmd .= ' -ar '.$videoOptions['audioSampleRate']; |
||
159 | } |
||
160 | if (!empty($videoOptions['audioChannels'])) { |
||
161 | $ffmpegCmd .= ' -ac '.$videoOptions['audioChannels']; |
||
162 | } |
||
163 | $ffmpegCmd .= ' '.$thisEncoder['audioCodecOptions']; |
||
164 | } |
||
165 | |||
166 | // Create the directory if it isn't there already |
||
167 | if (!is_dir($destVideoPath)) { |
||
168 | try { |
||
169 | FileHelper::createDirectory($destVideoPath); |
||
170 | } catch (Exception $e) { |
||
171 | Craft::error($e->getMessage(), __METHOD__); |
||
172 | } |
||
173 | } |
||
174 | |||
175 | $destVideoFile = $this->getFilename($filePath, $videoOptions); |
||
176 | |||
177 | // File to store the video encoding progress in |
||
178 | $progressFile = sys_get_temp_dir().DIRECTORY_SEPARATOR.$destVideoFile.'.progress'; |
||
179 | |||
180 | // Assemble the destination path and final ffmpeg command |
||
181 | $destVideoPath .= $destVideoFile; |
||
182 | $ffmpegCmd .= ' -f ' |
||
183 | .$thisEncoder['fileFormat'] |
||
184 | .' -y '.escapeshellarg($destVideoPath) |
||
185 | .' 1> '.$progressFile.' 2>&1 & echo $!'; |
||
186 | |||
187 | // Make sure there isn't a lockfile for this video already |
||
188 | $lockFile = sys_get_temp_dir().DIRECTORY_SEPARATOR.$destVideoFile.'.lock'; |
||
189 | $oldPid = @file_get_contents($lockFile); |
||
190 | if ($oldPid !== false) { |
||
191 | exec("ps $oldPid", $ProcessState); |
||
192 | if (\count($ProcessState) >= 2) { |
||
193 | return $result; |
||
194 | } |
||
195 | // It's finished transcoding, so delete the lockfile and progress file |
||
196 | @unlink($lockFile); |
||
197 | @unlink($progressFile); |
||
198 | } |
||
199 | |||
200 | // If the video file already exists and hasn't been modified, return it. Otherwise, start it transcoding |
||
201 | if (!$this->shouldGenerateAsset('video', $destVideoPath, $filePath)) { |
||
202 | $url = $settings['transcoderUrls']['video'] ?? $settings['transcoderUrls']['default']; |
||
203 | $result = Craft::getAlias($url).$destVideoFile; |
||
204 | |||
205 | // skip encoding |
||
206 | } elseif (!$generate) { |
||
207 | $result = ""; |
||
208 | } else { |
||
209 | // Kick off the transcoding |
||
210 | $pid = $this->executeShellCommand($ffmpegCmd); |
||
211 | Craft::info($ffmpegCmd."\nffmpeg PID: ".$pid, __METHOD__); |
||
212 | |||
213 | // Create a lockfile in tmp |
||
214 | file_put_contents($lockFile, $pid); |
||
215 | } |
||
216 | |||
217 | if ($remoteUrl = $this->moveAssetToVolume('video', $destVideoPath)) { |
||
218 | $result = $remoteUrl; |
||
219 | } |
||
220 | return $result; |
||
221 | } |
||
222 | |||
223 | return $result; |
||
224 | } |
||
225 | |||
226 | /** |
||
227 | * Returns a URL to a video thumbnail |
||
228 | * |
||
229 | * @param string $filePath path to the original video or an Asset |
||
230 | * @param array $thumbnailOptions of options for the thumbnail |
||
231 | * @param bool $generate whether the thumbnail should be |
||
232 | * generated if it doesn't exists |
||
233 | * @param bool $asPath Whether we should return a path or not |
||
234 | * |
||
235 | * @return string|false|null URL or path of the video thumbnail |
||
236 | */ |
||
237 | public function getVideoThumbnailUrl($filePath, $thumbnailOptions, $generate = true, $asPath = false) |
||
238 | { |
||
239 | $result = null; |
||
240 | $settings = Transcoder::$plugin->getSettings(); |
||
241 | $subfolder = ''; |
||
242 | |||
243 | // sub folder check |
||
244 | if(\is_object($filePath) && ($filePath instanceof Asset) && $settings['createSubfolders']) { |
||
245 | $subfolder = $filePath->folderPath; |
||
246 | } |
||
247 | |||
248 | $filePath = $this->getAssetPath($filePath); |
||
249 | |||
250 | if (!empty($filePath)) { |
||
251 | $destThumbnailPath = $this->localDestPath('thumbnail', $subfolder); |
||
252 | |||
253 | $thumbnailOptions = $this->coalesceOptions('defaultThumbnailOptions', $thumbnailOptions); |
||
254 | |||
255 | // Build the basic command for ffmpeg |
||
256 | $ffmpegCmd = $settings['ffmpegPath'] |
||
257 | .' -i '.escapeshellarg($filePath) |
||
258 | .' -vcodec mjpeg' |
||
259 | .' -vframes 1'; |
||
260 | |||
261 | // Adjust the scaling if desired |
||
262 | $ffmpegCmd = $this->addScalingFfmpegArgs( |
||
263 | $thumbnailOptions, |
||
264 | $ffmpegCmd |
||
265 | ); |
||
266 | |||
267 | // Set the timecode to get the thumbnail from if desired |
||
268 | if (!empty($thumbnailOptions['timeInSecs'])) { |
||
269 | $timeCode = gmdate('H:i:s', $thumbnailOptions['timeInSecs']); |
||
270 | $ffmpegCmd .= ' -ss '.$timeCode.'.00'; |
||
271 | } |
||
272 | |||
273 | // Create the directory if it isn't there already |
||
274 | if (!is_dir($destThumbnailPath)) { |
||
275 | try { |
||
276 | FileHelper::createDirectory($destThumbnailPath); |
||
277 | } catch (Exception $e) { |
||
278 | Craft::error($e->getMessage(), __METHOD__); |
||
279 | } |
||
280 | } |
||
281 | |||
282 | $destThumbnailFile = $this->getFilename($filePath, $thumbnailOptions); |
||
283 | |||
284 | // Assemble the destination path and final ffmpeg command |
||
285 | $destThumbnailPath .= $destThumbnailFile; |
||
286 | $ffmpegCmd .= ' -f image2 -y '.escapeshellarg($destThumbnailPath).' >/dev/null 2>/dev/null &'; |
||
287 | |||
288 | // If the thumbnail file already exists, return it. Otherwise, generate it and return it |
||
289 | if ($this->shouldGenerateAsset('thumbnail', $destThumbnailPath)) { |
||
290 | if ($generate) { |
||
291 | /** @noinspection PhpUnusedLocalVariableInspection */ |
||
292 | $shellOutput = $this->executeShellCommand($ffmpegCmd); |
||
293 | Craft::info($ffmpegCmd, __METHOD__); |
||
294 | |||
295 | // if ffmpeg fails which we can't check because the process is ran in the background |
||
296 | // dont return the future path of the image or else we can't check this in the front end |
||
297 | |||
298 | return false; |
||
299 | |||
300 | } else { |
||
301 | Craft::info('Thumbnail does not exist, but not asked to generate it: '.$filePath, __METHOD__); |
||
302 | |||
303 | // The file doesn't exist, and we weren't asked to generate it |
||
304 | return false; |
||
305 | } |
||
306 | } |
||
307 | |||
308 | if ($remoteUrl = $this->moveAssetToVolume('thumbnail', $destThumbnailPath)) { |
||
309 | return $remoteUrl; |
||
310 | } |
||
311 | |||
312 | // Return either a path or a URL |
||
313 | if ($asPath) { |
||
314 | $result = $destThumbnailPath; |
||
315 | } else { |
||
316 | $url = $settings['transcoderUrls']['thumbnail'] . $subfolder ?? $settings['transcoderUrls']['default']; |
||
317 | $result = Craft::getAlias($url).$destThumbnailFile; |
||
318 | } |
||
319 | } |
||
320 | |||
321 | return $result; |
||
322 | } |
||
323 | |||
324 | /** |
||
325 | * Returns a URL to the transcoded audio file or "" if it doesn't exist |
||
326 | * (at which time it will create it). |
||
327 | * |
||
328 | * @param $filePath string path to the original audio file -OR- an Asset |
||
329 | * @param $audioOptions array of options for the audio file |
||
330 | * |
||
331 | * @return string URL of the transcoded audio file or "" |
||
332 | */ |
||
333 | public function getAudioUrl($filePath, $audioOptions): string |
||
433 | } |
||
434 | |||
435 | /** |
||
436 | * Extract information from a video/audio file |
||
437 | * |
||
438 | * @param $filePath |
||
439 | * @param bool $summary |
||
440 | * |
||
441 | * @return null|array |
||
442 | */ |
||
443 | public function getFileInfo($filePath, $summary = false) |
||
444 | { |
||
445 | $result = null; |
||
446 | $settings = Transcoder::$plugin->getSettings(); |
||
447 | $filePath = $this->getAssetPath($filePath); |
||
448 | |||
449 | if (!empty($filePath)) { |
||
450 | // Build the basic command for ffprobe |
||
451 | $ffprobeOptions = $settings['ffprobeOptions']; |
||
452 | $ffprobeCmd = $settings['ffprobePath'] |
||
453 | .' '.$ffprobeOptions |
||
454 | .' '.escapeshellarg($filePath); |
||
455 | |||
456 | $shellOutput = $this->executeShellCommand($ffprobeCmd); |
||
457 | Craft::info($ffprobeCmd, __METHOD__); |
||
458 | $result = JsonHelper::decodeIfJson($shellOutput, true); |
||
459 | Craft::info(print_r($result, true), __METHOD__); |
||
460 | |||
461 | // Trim down the arrays to just a summary |
||
462 | if ($summary && !empty($result)) { |
||
463 | $summaryResult = []; |
||
464 | foreach ($result as $topLevelKey => $topLevelValue) { |
||
465 | switch ($topLevelKey) { |
||
466 | // Format info |
||
467 | case 'format': |
||
468 | foreach (self::INFO_SUMMARY['format'] as $settingKey => $settingValue) { |
||
469 | if (!empty($topLevelValue[$settingKey])) { |
||
470 | $summaryResult[$settingValue] = $topLevelValue[$settingKey]; |
||
471 | } |
||
472 | } |
||
473 | break; |
||
474 | // Stream info |
||
475 | case 'streams': |
||
476 | foreach ($topLevelValue as $stream) { |
||
477 | $infoSummaryType = $stream['codec_type']; |
||
478 | if (in_array($infoSummaryType, self::INFO_SUMMARY, false)) { |
||
479 | foreach (self::INFO_SUMMARY[$infoSummaryType] as $settingKey => $settingValue) { |
||
480 | if (!empty($stream[$settingKey])) { |
||
481 | $summaryResult[$settingValue] = $stream[$settingKey]; |
||
482 | } |
||
483 | } |
||
484 | } |
||
485 | } |
||
486 | break; |
||
487 | // Unknown info |
||
488 | default: |
||
489 | break; |
||
490 | } |
||
491 | } |
||
492 | // Handle cases where the framerate is returned as XX/YY |
||
493 | if (!empty($summaryResult['videoFrameRate']) |
||
494 | && (strpos($summaryResult['videoFrameRate'], '/') !== false) |
||
495 | ) { |
||
496 | $parts = explode('/', $summaryResult['videoFrameRate']); |
||
497 | $summaryResult['videoFrameRate'] = (float)$parts[0] / (float)$parts[1]; |
||
498 | } |
||
499 | $result = $summaryResult; |
||
500 | } |
||
501 | } |
||
502 | |||
503 | return $result; |
||
504 | } |
||
505 | |||
506 | /** |
||
507 | * Get the name of a video file from a path and options |
||
508 | * |
||
509 | * @param $filePath |
||
510 | * @param $videoOptions |
||
511 | * |
||
512 | * @return string |
||
513 | */ |
||
514 | public function getVideoFilename($filePath, $videoOptions): string |
||
515 | { |
||
516 | $settings = Transcoder::$plugin->getSettings(); |
||
517 | $videoOptions = $this->coalesceOptions('defaultVideoOptions', $videoOptions); |
||
518 | |||
519 | // Get the video encoder presets to use |
||
520 | $videoEncoders = $settings['videoEncoders']; |
||
521 | $thisEncoder = $videoEncoders[$videoOptions['videoEncoder']]; |
||
522 | |||
523 | $videoOptions['fileSuffix'] = $thisEncoder['fileSuffix']; |
||
524 | |||
525 | return $this->getFilename($filePath, $videoOptions); |
||
526 | } |
||
527 | |||
528 | /** |
||
529 | * Get the name of an audio file from a path and options |
||
530 | * |
||
531 | * @param $filePath |
||
532 | * @param $audioOptions |
||
533 | * |
||
534 | * @return string |
||
535 | */ |
||
536 | public function getAudioFilename($filePath, $audioOptions): string |
||
537 | { |
||
538 | $settings = Transcoder::$plugin->getSettings(); |
||
539 | $audioOptions = $this->coalesceOptions('defaultAudioOptions', $audioOptions); |
||
540 | |||
541 | // Get the video encoder presets to use |
||
542 | $audioEncoders = $settings['audioEncoders']; |
||
543 | $thisEncoder = $audioEncoders[$audioOptions['audioEncoder']]; |
||
544 | |||
545 | $audioOptions['fileSuffix'] = $thisEncoder['fileSuffix']; |
||
546 | |||
547 | return $this->getFilename($filePath, $audioOptions); |
||
548 | } |
||
549 | |||
550 | /** |
||
551 | * Get the name of a gif video file from a path and options |
||
552 | * |
||
553 | * @param $filePath |
||
554 | * @param $gifOptions |
||
555 | * |
||
556 | * @return string |
||
557 | */ |
||
558 | public function getGifFilename($filePath, $gifOptions): string |
||
559 | { |
||
560 | $settings = Transcoder::$plugin->getSettings(); |
||
561 | $gifOptions = $this->coalesceOptions('defaultGifOptions', $gifOptions); |
||
562 | |||
563 | // Get the video encoder presets to use |
||
564 | $videoEncoders = $settings['videoEncoders']; |
||
565 | $thisEncoder = $videoEncoders[$gifOptions['videoEncoder']]; |
||
566 | |||
567 | $gifOptions['fileSuffix'] = $thisEncoder['fileSuffix']; |
||
568 | |||
569 | return $this->getFilename($filePath, $gifOptions); |
||
570 | } |
||
571 | |||
572 | /** |
||
573 | * Handle generated a thumbnail for the Control Panel |
||
574 | * |
||
575 | * @param AssetThumbEvent $event |
||
576 | * |
||
577 | * @return null|false|string |
||
578 | */ |
||
579 | public function handleGetAssetThumbPath(AssetThumbEvent $event) |
||
580 | { |
||
581 | $options = [ |
||
582 | 'width' => $event->width, |
||
583 | 'height' => $event->height, |
||
584 | ]; |
||
585 | $thumbPath = $this->getVideoThumbnailUrl($event->asset, $options, $event->generate, true); |
||
586 | |||
587 | return $thumbPath; |
||
588 | } |
||
589 | |||
590 | // Protected Methods |
||
591 | // ========================================================================= |
||
592 | |||
593 | /** |
||
594 | * Returns a URL to a encoded GIF file (mp4) |
||
595 | * |
||
596 | * @param string $filePath path to the original video or an Asset |
||
597 | * @param array $gifOptions of options for the GIF file |
||
598 | * |
||
599 | * @return string|false|null URL or path of the GIF file |
||
600 | */ |
||
601 | |||
602 | public function getGifUrl($filePath, $gifOptions): string |
||
603 | { |
||
604 | $result = ''; |
||
605 | $settings = Transcoder::$plugin->getSettings(); |
||
606 | $subfolder = ''; |
||
607 | |||
608 | // sub folder check |
||
609 | if(\is_object($filePath) && ($filePath instanceof Asset) && $settings['createSubfolders']) { |
||
610 | $subfolder = $filePath->folderPath; |
||
611 | } |
||
612 | |||
613 | $filePath = $this->getAssetPath($filePath); |
||
614 | |||
615 | if (!empty($filePath)) { |
||
616 | // Dest path |
||
617 | $destVideoPath = $this->localDestPath('gif', $subfolder); |
||
618 | |||
619 | // Options |
||
620 | $gifOptions = $this->coalesceOptions('defaultGifOptions', $gifOptions); |
||
621 | |||
622 | // Get the video encoder presets to use |
||
623 | $videoEncoders = $settings['videoEncoders']; |
||
624 | $thisEncoder = $videoEncoders[$gifOptions['videoEncoder']]; |
||
625 | $gifOptions['fileSuffix'] = $thisEncoder['fileSuffix']; |
||
626 | |||
627 | // Build the basic command for ffmpeg |
||
628 | $ffmpegCmd = $settings['ffmpegPath'] |
||
629 | .' -f gif' |
||
630 | .' -i '.escapeshellarg($filePath) |
||
631 | .' -vcodec '.$thisEncoder['videoCodec'] |
||
632 | .' '.$thisEncoder['videoCodecOptions']; |
||
633 | |||
634 | |||
635 | // Create the directory if it isn't there already |
||
636 | if (!is_dir($destVideoPath)) { |
||
637 | try { |
||
638 | FileHelper::createDirectory($destVideoPath); |
||
639 | } catch (Exception $e) { |
||
640 | Craft::error($e->getMessage(), __METHOD__); |
||
641 | } |
||
642 | } |
||
643 | |||
644 | $destVideoFile = $this->getFilename($filePath, $gifOptions); |
||
645 | |||
646 | // File to store the video encoding progress in |
||
647 | $progressFile = sys_get_temp_dir().DIRECTORY_SEPARATOR.$destVideoFile.'.progress'; |
||
648 | |||
649 | // Assemble the destination path and final ffmpeg command |
||
650 | $destVideoPath .= $destVideoFile; |
||
651 | $ffmpegCmd .= ' ' |
||
652 | .' -y '.escapeshellarg($destVideoPath) |
||
653 | .' 1> '.$progressFile.' 2>&1 & echo $!'; |
||
654 | |||
655 | // Make sure there isn't a lockfile for this video already |
||
656 | $lockFile = sys_get_temp_dir().DIRECTORY_SEPARATOR.$destVideoFile.'.lock'; |
||
657 | $oldPid = @file_get_contents($lockFile); |
||
658 | if ($oldPid !== false) { |
||
659 | exec("ps $oldPid", $ProcessState); |
||
660 | if (\count($ProcessState) >= 2) { |
||
661 | return $result; |
||
662 | } |
||
663 | // It's finished transcoding, so delete the lockfile and progress file |
||
664 | @unlink($lockFile); |
||
665 | @unlink($progressFile); |
||
666 | } |
||
667 | |||
668 | // If the video file already exists and hasn't been modified, return it. Otherwise, start it transcoding |
||
669 | if ($this->shouldGenerateAsset('gif', $destVideoPath, $filePath)) { |
||
670 | $url = $settings['transcoderUrls']['gif'] . $subfolder ?? $settings['transcoderUrls']['default']; |
||
671 | $result = Craft::getAlias($url).$destVideoFile; |
||
672 | } else { |
||
673 | // Kick off the transcoding |
||
674 | $pid = $this->executeShellCommand($ffmpegCmd); |
||
675 | Craft::info($ffmpegCmd."\nffmpeg PID: ".$pid, __METHOD__); |
||
676 | |||
677 | // Create a lockfile in tmp |
||
678 | file_put_contents($lockFile, $pid); |
||
679 | } |
||
680 | |||
681 | if ($remoteUrl = $this->moveAssetToVolume('gif', $destVideoPath)) { |
||
682 | $result = $remoteUrl; |
||
683 | } |
||
684 | } |
||
685 | |||
686 | return $result; |
||
687 | } |
||
688 | |||
689 | /** |
||
690 | * Get the name of a file from a path and options |
||
691 | * |
||
692 | * @param $filePath |
||
693 | * @param $options |
||
694 | * |
||
695 | * @return string |
||
696 | */ |
||
697 | protected function getFilename($filePath, $options): string |
||
698 | { |
||
699 | $settings = Transcoder::$plugin->getSettings(); |
||
700 | $filePath = $this->getAssetPath($filePath); |
||
701 | |||
702 | $validator = new UrlValidator(); |
||
703 | $error = ''; |
||
704 | if ($validator->validate($filePath, $error)) { |
||
705 | $urlParts = parse_url($filePath); |
||
706 | $pathParts = pathinfo($urlParts['path']); |
||
707 | } else { |
||
708 | $pathParts = pathinfo($filePath); |
||
709 | } |
||
710 | $fileName = $pathParts['filename']; |
||
711 | |||
712 | // Add our options to the file name |
||
713 | foreach ($options as $key => $value) { |
||
714 | if (!empty($value)) { |
||
715 | $suffix = ''; |
||
716 | if (!empty(self::SUFFIX_MAP[$key])) { |
||
717 | $suffix = self::SUFFIX_MAP[$key]; |
||
718 | } |
||
719 | if (\is_bool($value)) { |
||
720 | $value = $value ? $key : 'no'.$key; |
||
721 | } |
||
722 | if (!\in_array($key, self::EXCLUDE_PARAMS, true)) { |
||
723 | $fileName .= '_'.$value.$suffix; |
||
724 | } |
||
725 | } |
||
726 | } |
||
727 | // See if we should use a hash instead |
||
728 | if ($settings['useHashedNames']) { |
||
729 | $fileName = $pathParts['filename'].md5($fileName); |
||
730 | } |
||
731 | $fileName .= $options['fileSuffix']; |
||
732 | |||
733 | return $fileName; |
||
734 | } |
||
735 | |||
736 | /** |
||
737 | * Extract a file system path if $filePath is an Asset object |
||
738 | * |
||
739 | * @param $filePath |
||
740 | * |
||
741 | * @return string |
||
742 | */ |
||
743 | protected function getAssetPath($filePath): string |
||
744 | { |
||
745 | // If we're passed an Asset, extract the path from it |
||
746 | if (\is_object($filePath) && ($filePath instanceof Asset)) { |
||
747 | /** @var Asset $asset */ |
||
748 | $asset = $filePath; |
||
749 | $assetVolume = null; |
||
750 | try { |
||
751 | $assetVolume = $asset->getVolume(); |
||
752 | } catch (InvalidConfigException $e) { |
||
753 | Craft::error($e->getMessage(), __METHOD__); |
||
754 | } |
||
755 | |||
756 | if ($assetVolume) { |
||
757 | // If it's local, get a path to the file |
||
758 | if ($assetVolume instanceof Local) { |
||
759 | $sourcePath = rtrim($assetVolume->path, DIRECTORY_SEPARATOR); |
||
760 | $sourcePath .= '' === $sourcePath ? '': DIRECTORY_SEPARATOR; |
||
761 | $folderPath = ''; |
||
762 | try { |
||
763 | $folderPath = rtrim($asset->getFolder()->path, DIRECTORY_SEPARATOR); |
||
764 | } catch (InvalidConfigException $e) { |
||
765 | Craft::error($e->getMessage(), __METHOD__); |
||
766 | } |
||
767 | $folderPath .= '' === $folderPath ? '': DIRECTORY_SEPARATOR; |
||
768 | |||
769 | $filePath = $sourcePath.$folderPath.$asset->filename; |
||
770 | } else { |
||
771 | // Otherwise, get a URL |
||
772 | $filePath = $asset->getUrl(); |
||
773 | } |
||
774 | } |
||
775 | } |
||
776 | |||
777 | $filePath = Craft::getAlias($filePath); |
||
778 | |||
779 | // Make sure that $filePath is either an existing file, or a valid URL |
||
780 | if (!file_exists($filePath)) { |
||
781 | $validator = new UrlValidator(); |
||
782 | $error = ''; |
||
783 | if (!$validator->validate($filePath, $error)) { |
||
784 | Craft::error($error, __METHOD__); |
||
785 | $filePath = ''; |
||
786 | } |
||
787 | } |
||
788 | |||
789 | return $filePath; |
||
790 | } |
||
791 | |||
792 | /** |
||
793 | * Set the width & height if desired |
||
794 | * |
||
795 | * @param $options |
||
796 | * @param $ffmpegCmd |
||
797 | * |
||
798 | * @return string |
||
799 | */ |
||
800 | protected function addScalingFfmpegArgs($options, $ffmpegCmd): string |
||
801 | { |
||
802 | if (!empty($options['width']) && !empty($options['height'])) { |
||
803 | // Handle "none", "crop", and "letterbox" aspectRatios |
||
804 | $aspectRatio = ''; |
||
805 | if (!empty($options['aspectRatio'])) { |
||
806 | switch ($options['aspectRatio']) { |
||
807 | // Scale to the appropriate aspect ratio, padding |
||
808 | case 'letterbox': |
||
809 | $letterboxColor = ''; |
||
810 | if (!empty($options['letterboxColor'])) { |
||
811 | $letterboxColor = ':color='.$options['letterboxColor']; |
||
812 | } |
||
813 | $aspectRatio = ':force_original_aspect_ratio=decrease' |
||
814 | .',pad='.$options['width'].':'.$options['height'].':(ow-iw)/2:(oh-ih)/2' |
||
815 | .$letterboxColor; |
||
816 | break; |
||
817 | // Scale to the appropriate aspect ratio, cropping |
||
818 | case 'crop': |
||
819 | $aspectRatio = ':force_original_aspect_ratio=increase' |
||
820 | .',crop='.$options['width'].':'.$options['height']; |
||
821 | break; |
||
822 | // No aspect ratio scaling at all |
||
823 | default: |
||
824 | $aspectRatio = ':force_original_aspect_ratio=disable'; |
||
825 | $options['aspectRatio'] = 'none'; |
||
826 | break; |
||
827 | } |
||
828 | } |
||
829 | $sharpen = ''; |
||
830 | if (!empty($options['sharpen']) && ($options['sharpen'] !== false)) { |
||
831 | $sharpen = ',unsharp=5:5:1.0:5:5:0.0'; |
||
832 | } |
||
833 | $ffmpegCmd .= ' -vf "scale=' |
||
834 | .$options['width'].':'.$options['height'] |
||
835 | .$aspectRatio |
||
836 | .$sharpen |
||
837 | .'"'; |
||
838 | } |
||
839 | |||
840 | return $ffmpegCmd; |
||
841 | } |
||
842 | |||
843 | // Protected Methods |
||
844 | // ========================================================================= |
||
845 | |||
846 | /** |
||
847 | * Combine the options arrays |
||
848 | * |
||
849 | * @param $defaultName |
||
850 | * @param $options |
||
851 | * |
||
852 | * @return array |
||
853 | */ |
||
854 | protected function coalesceOptions($defaultName, $options): array |
||
855 | { |
||
856 | // Default options |
||
857 | $settings = Transcoder::$plugin->getSettings(); |
||
858 | $defaultOptions = $settings[$defaultName]; |
||
859 | |||
860 | // Coalesce the passed in $options with the $defaultOptions |
||
861 | $options = array_merge($defaultOptions, $options); |
||
862 | |||
863 | return $options; |
||
864 | } |
||
865 | |||
866 | /** |
||
867 | * Execute a shell command |
||
868 | * |
||
869 | * @param string $command |
||
870 | * |
||
871 | * @return string |
||
872 | */ |
||
873 | protected function executeShellCommand(string $command): string |
||
892 | } |
||
893 | |||
894 | protected function shouldGenerateAsset(string $type, string $destVideoFilePath, string $originalFilePath = null) |
||
895 | { |
||
896 | $settings = Transcoder::$plugin->getSettings(); |
||
897 | $destSettings = $settings['transcoderPaths'][$type] ?? $settings['transcoderPaths']['default']; |
||
898 | |||
899 | if (file_exists($destVideoFilePath) && (@filemtime($destVideoFilePath) >= @filemtime($originalFilePath))) { |
||
900 | return false; |
||
901 | } |
||
902 | |||
903 | if (!is_array($destSettings)) { |
||
904 | return true; |
||
905 | } |
||
906 | |||
907 | $filename = basename($destVideoFilePath); |
||
908 | |||
909 | $volume = Craft::$app->getVolumes()->getVolumeByHandle($destSettings['volume']); |
||
910 | /** @var Asset $asset */ |
||
911 | $asset = Asset::findOne(['volumeId' => $volume->id, 'filename' => $filename]); |
||
912 | |||
913 | if ($asset && $asset->dateModified->getTimestamp() >= @filemtime($originalFilePath)) { |
||
914 | return false; |
||
915 | } |
||
916 | return true; |
||
917 | } |
||
918 | |||
919 | protected function localDestPath(string $type, string $subfolder) { |
||
920 | $settings = Transcoder::$plugin->getSettings(); |
||
921 | $destSettings = $settings['transcoderPaths'][$type] ?? $settings['transcoderPaths']['default']; |
||
922 | if (is_array($destSettings)) { |
||
923 | return sys_get_temp_dir(); |
||
924 | } |
||
925 | if (isset($settings['transcoderPaths'][$type])) { |
||
926 | $destSettings .= $subfolder; |
||
927 | } |
||
928 | return Craft::getAlias($destSettings); |
||
929 | } |
||
930 | |||
931 | protected function moveAssetToVolume(string $type, string $filePath) |
||
972 | } |
||
973 | } |
||
974 |