Play videos on sprites, converted on the server with clips (#402)
A video becomes an asset like a sound: uploaded once, converted to one format by a worker of its own, cut into clips in its tab, and worn by a sprite through its Texture row. Only Chrome is a target, without alpha. - Server: POST ?r=videos queues the upload under the hash of its bytes, so the MP4's name is known at once. The worker (VideoWorker over VideoFormat) writes H.264/AAC, yuv420p, constant frame rate, a keyframe every 15 frames, at most 1920x1080, with a poster and the details beside it. A failed job says why and is tried again on the next upload. - An upload may be up to 2 GB. It is streamed from the request to disk and hashed there, so php-fpm holds none of it in memory. The other routes keep their 256 MB. - The worker runs in the container game-maker-video on stein2, a compose project of its own (tools/video/), and in CI beside the PHP server. The CI image has ffmpeg for it. - Model: asset type video with size, length, frame rate and sound, and clips like a sound's. The clip helpers and commands serve both. - A sprite's Texture row offers videos and clips after the pictures. resolvePicture names a playing video by a key, and the texture library hands it to a VideoLibrary with one player per key. - The editor shows a placed video as a quiet preview. Play starts it over at its clip's start and lets it be heard through the master bus, a pause holds it, Esc makes it quiet again. - Video tab: the picture, a ruler, the clip strip and a track on the Sound tab's time axis. A drag spans a clip, a handle moves an edge, Play plays the picked clip. - The picker shows a video on its way with its progress and adopts an upload from it once it is ready. Dropping a video file does the same. Decided on my own: - Two sprites wearing the same clip share one player and show the same picture. Control per instance belongs to the follow-up with nodes. - A video plays in real time, the game's time scale does not slow it. - The container may use 3 of the 4 cores of stein2. Findings: - The first real upload (279 MB) got 413: the API's own ceiling of 256 MB for every request, not nginx or the Brandmauer. - Chrome has no picture of a video that never played, and a Pixi VideoSource drawn before the first frame stays empty for good. The texture is made in the first frame callback (openVideo). - A player nobody asks for in 2 s is let go. The inspector's PREVIEW asked only on an edit, so with the sprite not on screen its texture was destroyed under it and the batcher threw on every frame. The preview now redraws every frame while it shows a video, like a Time shader. A let-go texture keeps an empty source instead of none. - VideoSource.load() reloads the element and cuts off an earlier play(). Playing starts after loadeddata. Tests: - PHP videos.test.php: 68 checks, with the real ffmpeg - 300 MB upload through Brandmauer and nginx: 201 in 21 s, php-fpm at 13.7 MB RSS at most - Unit videos.test.ts: 20 tests - e2e 66 (stein2, atx was off): ALL PASSED, 18 checks; e2e 04 with the new asset count green - Gate (atx): 294 files, 4520 tests. serialize.test.ts used video as its example of an unknown type and now uses a made-up one. - Counter-checks: a keyframe gap of 30 fails the PHP check, a key that keeps the video's end fails 2 unit tests, a clip without its end fails "plays only its stretch" in e2e 66 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2f376262d3
commit
d48f174caf
63 files changed
+3500
-103
No files matched your search
@@ -0,0 +1,216 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* The one format every uploaded video is turned into (#402), as plain rules: what ffprobe said in,
|
||||
* the ffmpeg arguments out. Nothing here runs a process, so all of it is testable without ffmpeg.
|
||||
*
|
||||
* The target is MP4 with H.264 and AAC, `yuv420p`, at a constant frame rate and with a keyframe
|
||||
* every 15 frames: the editor seeks to clip starts and loops back to them, and a seek can only land
|
||||
* on a keyframe quickly. The picture fits into 1920 × 1080 (1080 × 1920 standing up) and is never
|
||||
* made larger than it came.
|
||||
*/
|
||||
final class VideoFormat
|
||||
{
|
||||
public const MAX_LONG_SIDE = 1920;
|
||||
public const MAX_SHORT_SIDE = 1080;
|
||||
public const MAX_FPS = 60;
|
||||
public const KEYFRAME_EVERY = 15;
|
||||
/** Used when a file does not say its frame rate at all. */
|
||||
private const FALLBACK_FPS = '30';
|
||||
|
||||
/**
|
||||
* What the conversion makes of a probed file: the size it is shown at after rotation, scaled to
|
||||
* fit, the frame rate as ffmpeg takes it, and whether there is sound to keep.
|
||||
*
|
||||
* @param array<string,mixed> $probe ffprobe's `-show_streams -show_format` as JSON
|
||||
* @return array{width:int,height:int,fps:string,audio:bool,duration:float}
|
||||
* @throws InvalidArgumentException when there is no picture in it
|
||||
*/
|
||||
public static function plan(array $probe): array
|
||||
{
|
||||
$streams = is_array($probe['streams'] ?? null) ? $probe['streams'] : [];
|
||||
$video = null;
|
||||
$audio = false;
|
||||
foreach ($streams as $stream) {
|
||||
$type = $stream['codec_type'] ?? '';
|
||||
// A cover picture in a music file is a video stream as well, one that is a single frame.
|
||||
$still = (int) (($stream['disposition'] ?? [])['attached_pic'] ?? 0) === 1;
|
||||
if ($type === 'video' && $video === null && !$still) {
|
||||
$video = $stream;
|
||||
}
|
||||
$audio = $audio || $type === 'audio';
|
||||
}
|
||||
if ($video === null || (int) ($video['width'] ?? 0) <= 0 || (int) ($video['height'] ?? 0) <= 0) {
|
||||
throw new InvalidArgumentException('There is no picture in this file');
|
||||
}
|
||||
|
||||
[$width, $height] = [(int) $video['width'], (int) $video['height']];
|
||||
if (abs(self::rotation($video)) % 180 === 90) {
|
||||
[$width, $height] = [$height, $width];
|
||||
}
|
||||
[$width, $height] = self::fit($width, $height);
|
||||
|
||||
return [
|
||||
'width' => $width,
|
||||
'height' => $height,
|
||||
'fps' => self::fps($video),
|
||||
'audio' => $audio,
|
||||
'duration' => self::duration($probe, $video),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The size inside the box, keeping the shape, both sides even (H.264 in `yuv420p` needs that).
|
||||
*
|
||||
* @return array{0:int,1:int}
|
||||
*/
|
||||
public static function fit(int $width, int $height): array
|
||||
{
|
||||
[$boxW, $boxH] = $width >= $height
|
||||
? [self::MAX_LONG_SIDE, self::MAX_SHORT_SIDE]
|
||||
: [self::MAX_SHORT_SIDE, self::MAX_LONG_SIDE];
|
||||
$scale = min(1.0, $boxW / $width, $boxH / $height);
|
||||
$even = static fn(float $side): int => max(2, 2 * (int) floor(round($side, 3) / 2));
|
||||
return [$even($width * $scale), $even($height * $scale)];
|
||||
}
|
||||
|
||||
/**
|
||||
* The frame rate the file is written at: its own average, unless that is above 60 or unknown.
|
||||
* Kept as ffmpeg's fraction, so 29.97 stays 30000/1001 and frames do not drift against the time.
|
||||
*
|
||||
* @param array<string,mixed> $video
|
||||
*/
|
||||
public static function fps(array $video): string
|
||||
{
|
||||
foreach (['avg_frame_rate', 'r_frame_rate'] as $key) {
|
||||
$rate = self::rate((string) ($video[$key] ?? ''));
|
||||
if ($rate !== null) {
|
||||
return $rate[1] > self::MAX_FPS ? (string) self::MAX_FPS : $rate[0];
|
||||
}
|
||||
}
|
||||
return self::FALLBACK_FPS;
|
||||
}
|
||||
|
||||
/** A fraction such as `30000/1001` as a number of frames per second. */
|
||||
public static function fpsValue(string $fps): float
|
||||
{
|
||||
$rate = self::rate($fps);
|
||||
return $rate === null ? 0.0 : $rate[1];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{width:int,height:int,fps:string,audio:bool} $plan
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function convertArgs(string $source, string $target, array $plan): array
|
||||
{
|
||||
$args = [
|
||||
'ffmpeg', '-nostdin', '-hide_banner', '-loglevel', 'error', '-y',
|
||||
'-i', $source,
|
||||
'-map', '0:v:0',
|
||||
];
|
||||
if ($plan['audio']) {
|
||||
$args = [...$args, '-map', '0:a:0'];
|
||||
}
|
||||
$args = [
|
||||
...$args,
|
||||
'-vf', "scale={$plan['width']}:{$plan['height']}:flags=lanczos,setsar=1",
|
||||
'-r', $plan['fps'], '-fps_mode', 'cfr',
|
||||
'-c:v', 'libx264', '-preset', 'veryfast', '-crf', '21',
|
||||
'-pix_fmt', 'yuv420p',
|
||||
'-g', (string) self::KEYFRAME_EVERY, '-keyint_min', (string) self::KEYFRAME_EVERY, '-sc_threshold', '0',
|
||||
];
|
||||
$args = $plan['audio']
|
||||
? [...$args, '-c:a', 'aac', '-b:a', '160k', '-ac', '2', '-ar', '48000']
|
||||
: [...$args, '-an'];
|
||||
return [...$args, '-sn', '-dn', '-map_metadata', '-1', '-movflags', '+faststart', '-progress', 'pipe:1', '-nostats', '-f', 'mp4', $target];
|
||||
}
|
||||
|
||||
/**
|
||||
* A still from a little way in (not the very first frame, which is often black), as wide as the
|
||||
* picker draws it.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function posterArgs(string $video, string $target, float $duration): array
|
||||
{
|
||||
$at = sprintf('%.3f', max(0.0, min(1.0, $duration / 2)));
|
||||
return [
|
||||
'ffmpeg', '-nostdin', '-hide_banner', '-loglevel', 'error', '-y',
|
||||
'-ss', $at, '-i', $video, '-frames:v', '1',
|
||||
'-vf', 'scale=320:-2', '-q:v', '4', '-f', 'image2', $target,
|
||||
];
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public static function probeArgs(string $path): array
|
||||
{
|
||||
return ['ffprobe', '-v', 'error', '-print_format', 'json', '-show_streams', '-show_format', $path];
|
||||
}
|
||||
|
||||
/**
|
||||
* What the editor is told about a converted file, read back from the file itself rather than
|
||||
* the plan: a crop or a rounding inside ffmpeg is what the editor has to draw.
|
||||
*
|
||||
* @param array<string,mixed> $probe
|
||||
* @return array{width:int,height:int,duration:float,fps:float,audio:bool}
|
||||
*/
|
||||
public static function details(array $probe): array
|
||||
{
|
||||
$plan = self::plan($probe);
|
||||
return [
|
||||
'width' => $plan['width'],
|
||||
'height' => $plan['height'],
|
||||
'duration' => round($plan['duration'], 3),
|
||||
'fps' => round(self::fpsValue($plan['fps']), 3),
|
||||
'audio' => $plan['audio'],
|
||||
];
|
||||
}
|
||||
|
||||
/** The share of the work done, from one `out_time_us=` line of ffmpeg's progress. */
|
||||
public static function progress(string $line, float $duration): ?float
|
||||
{
|
||||
if ($duration <= 0 || !preg_match('/^out_time_us=(\d+)$/', trim($line), $m)) {
|
||||
return null;
|
||||
}
|
||||
return max(0.0, min(1.0, ((int) $m[1]) / 1e6 / $duration));
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $video */
|
||||
private static function rotation(array $video): int
|
||||
{
|
||||
foreach (is_array($video['side_data_list'] ?? null) ? $video['side_data_list'] : [] as $side) {
|
||||
if (isset($side['rotation']) && is_numeric($side['rotation'])) {
|
||||
return (int) $side['rotation'];
|
||||
}
|
||||
}
|
||||
$tag = ($video['tags'] ?? [])['rotate'] ?? null;
|
||||
return is_numeric($tag) ? (int) $tag : 0;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $probe @param array<string,mixed> $video */
|
||||
private static function duration(array $probe, array $video): float
|
||||
{
|
||||
foreach ([$video['duration'] ?? null, ($probe['format'] ?? [])['duration'] ?? null] as $value) {
|
||||
if (is_numeric($value) && (float) $value > 0) {
|
||||
return (float) $value;
|
||||
}
|
||||
}
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
/** @return array{0:string,1:float}|null the fraction as written and its value, null for none */
|
||||
private static function rate(string $text): ?array
|
||||
{
|
||||
if (!preg_match('#^(\d+)(?:/(\d+))?$#', $text, $m)) {
|
||||
return null;
|
||||
}
|
||||
$num = (int) $m[1];
|
||||
$den = isset($m[2]) ? (int) $m[2] : 1;
|
||||
if ($num <= 0 || $den <= 0) {
|
||||
return null;
|
||||
}
|
||||
return [$den === 1 ? (string) $num : "{$num}/{$den}", $num / $den];
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user