/** * If the first frame is orange, use the orage to detect the viewport * and re-number the remaining frames * * @param mixed $videoDir * @param mixed $viewport */ function FindAVIViewport($videoDir, $startOffset, &$viewport) { $files = glob("{$videoDir}/video-*.png"); if ($files && count($files)) { if (IsOrangeAVIFrame($files[0])) { // load the image and figure out the viewport area (orange) $im = imagecreatefrompng($files[0]); if ($im) { $width = imagesx($im); $height = imagesy($im); $x = floor($width / 2); $y = floor($height / 2); $orange = imagecolorat($im, $x, $y); $left = null; while (!isset($left) && $x >= 0) { if (!PixelColorsClose(imagecolorat($im, $x, $y), $orange)) { $left = $x + 1; } else { $x--; } } if (!isset($left)) { $left = 0; } $x = floor($width / 2); $right = null; while (!isset($right) && $x < $width) { if (!PixelColorsClose(imagecolorat($im, $x, $y), $orange)) { $right = $x - 1; } else { $x++; } } if (!isset($right)) { $right = $width; } $x = floor($width / 2); $top = null; while (!isset($top) && $y >= 0) { if (!PixelColorsClose(imagecolorat($im, $x, $y), $orange)) { $top = $y + 1; } else { $y--; } } if (!isset($top)) { $top = 0; } $y = floor($height / 2); $bottom = null; while (!isset($bottom) && $y < $height) { if (!PixelColorsClose(imagecolorat($im, $x, $y), $orange)) { $bottom = $y - 1; } else { $y++; } } if (!isset($bottom)) { $bottom = $height; } if ($left || $top || $right != $width || $bottom != $height) { $viewport = array('x' => $left, 'y' => $top, 'width' => $right - $left, 'height' => $bottom - $top); } } // Remove all of the orange video frames. do { $file = array_shift($files); unlink($file); } while (count($files) && IsOrangeAVIFrame($files[0])); } $fileCount = count($files); $firstFrame = null; for ($i = 0; $i < $fileCount; $i++) { $file = $files[$i]; if (preg_match('/video-(?P<frame>[0-9]+).png$/', $file, $matches)) { $currentFrame = intval($matches['frame']); if (!isset($firstFrame)) { $firstFrame = $currentFrame; } $frameTime = $currentFrame - $firstFrame; if ($startOffset) { $frameTime = max($frameTime - $startOffset, 0); } $dest = "{$videoDir}/image-" . sprintf('%06d', $frameTime) . ".png"; if (is_file($dest)) { unlink($dest); } rename($file, $dest); } } } }
/** * See if we can find the viewport from the first frame of the video and crop down to that * * @param mixed $videoFile * @param mixed $videoDir */ function FindVideoCrop($videoFile, $videoDir) { $crop = ''; $image = "{$videoDir}/viewport.png"; if (is_file($image)) { unlink($image); } $command = "ffmpeg -i \"{$videoFile}\" -frames:v 1 \"{$image}\" 2>&1"; $result; exec($command, $output, $result); if (is_file($image)) { if (IsOrangeAVIFrame($image) || IsBlankAVIFrame($image)) { $viewport = GetImageViewport($image); if (isset($viewport)) { $crop = "crop={$viewport['width']}:{$viewport['height']}:{$viewport['x']}:{$viewport['y']},"; } } unlink($image); } return $crop; }