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