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>
151 lines
5.8 KiB
PHP
151 lines
5.8 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
/**
|
|
* Converts what waits in the VideoQueue, one video at a time (#402). Runs in the container
|
|
* `game-maker-video` through `tools/video-worker.php`, and in CI beside the PHP server.
|
|
*
|
|
* Each job goes: probe the upload, convert it into a temp file beside its target, read the result
|
|
* back for its details, cut a poster, then move all three into place and drop the job. Whatever
|
|
* fails on the way fails the job with ffmpeg's own words, and the temp files go.
|
|
*/
|
|
final class VideoWorker
|
|
{
|
|
/** How often a running conversion writes its progress, in seconds. */
|
|
private const PROGRESS_EVERY = 0.5;
|
|
|
|
public function __construct(private readonly VideoStore $store, private readonly string $videos)
|
|
{
|
|
}
|
|
|
|
/** Converts the oldest waiting video; false when there was none. */
|
|
public function runOnce(): bool
|
|
{
|
|
$job = $this->store->queue()->next();
|
|
if ($job === null) {
|
|
return false;
|
|
}
|
|
$this->convert((string) $job['folder'], (string) $job['hash']);
|
|
return true;
|
|
}
|
|
|
|
private function convert(string $folder, string $hash): void
|
|
{
|
|
$queue = $this->store->queue();
|
|
if (!$queue->update($folder, $hash, ['state' => VideoQueue::CONVERTING, 'progress' => 0, 'error' => ''])) {
|
|
return;
|
|
}
|
|
$dir = "{$this->videos}/{$folder}";
|
|
$tag = bin2hex(random_bytes(4));
|
|
$tmpVideo = "{$dir}/{$hash}.{$tag}.tmp.mp4";
|
|
$tmpPoster = "{$dir}/{$hash}.{$tag}.tmp.jpg";
|
|
try {
|
|
$plan = VideoFormat::plan(self::probe($queue->source($folder, $hash)));
|
|
$finished = $this->run(
|
|
VideoFormat::convertArgs($queue->source($folder, $hash), $tmpVideo, $plan),
|
|
$plan['duration'],
|
|
static fn(float $p): bool => $queue->update($folder, $hash, ['progress' => round($p, 3)]),
|
|
);
|
|
if (!$finished) {
|
|
return;
|
|
}
|
|
$details = VideoFormat::details(self::probe($tmpVideo));
|
|
$this->run(VideoFormat::posterArgs($tmpVideo, $tmpPoster, $details['duration']), 0, null);
|
|
if ($queue->job($folder, $hash) === null) {
|
|
return;
|
|
}
|
|
chmod($tmpVideo, AtomicFile::SERVED);
|
|
chmod($tmpPoster, AtomicFile::SERVED);
|
|
VideoStore::writeDetails($dir, $hash, $details);
|
|
rename($tmpPoster, "{$dir}/{$hash}.jpg");
|
|
rename($tmpVideo, "{$dir}/{$hash}.mp4");
|
|
$queue->remove($folder, $hash);
|
|
} catch (Throwable $e) {
|
|
$queue->dropSource($folder, $hash);
|
|
$queue->update($folder, $hash, ['state' => VideoQueue::FAILED, 'error' => self::shorten($e->getMessage())]);
|
|
} finally {
|
|
foreach ([$tmpVideo, $tmpPoster] as $path) {
|
|
if (is_file($path)) {
|
|
unlink($path);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/** @return array<string,mixed> */
|
|
private static function probe(string $path): array
|
|
{
|
|
[$code, $out, $err] = self::capture(VideoFormat::probeArgs($path));
|
|
$probe = json_decode($out, true);
|
|
if ($code !== 0 || !is_array($probe)) {
|
|
throw new RuntimeException('ffmpeg cannot read this file' . ($err === '' ? '' : ": {$err}"));
|
|
}
|
|
return $probe;
|
|
}
|
|
|
|
/**
|
|
* Runs ffmpeg, reporting progress from its `-progress pipe:1` lines to `$report`. Returns false
|
|
* when `$report` says the job is gone, after stopping ffmpeg.
|
|
*
|
|
* @param list<string> $args
|
|
* @param (callable(float):bool)|null $report
|
|
*/
|
|
private function run(array $args, float $duration, ?callable $report): bool
|
|
{
|
|
$err = tempnam(sys_get_temp_dir(), 'video-err-');
|
|
$process = proc_open($args, [0 => ['file', '/dev/null', 'r'], 1 => ['pipe', 'w'], 2 => ['file', $err, 'w']], $pipes);
|
|
if (!is_resource($process)) {
|
|
throw new RuntimeException('Cannot start ffmpeg');
|
|
}
|
|
$last = 0.0;
|
|
$alive = true;
|
|
while (($line = fgets($pipes[1])) !== false) {
|
|
$share = $report === null ? null : VideoFormat::progress($line, $duration);
|
|
if ($share !== null && microtime(true) - $last >= self::PROGRESS_EVERY) {
|
|
$last = microtime(true);
|
|
if (!$report($share)) {
|
|
$alive = false;
|
|
proc_terminate($process);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
fclose($pipes[1]);
|
|
$code = proc_close($process);
|
|
$message = trim((string) file_get_contents($err));
|
|
unlink($err);
|
|
if (!$alive) {
|
|
return false;
|
|
}
|
|
if ($code !== 0) {
|
|
throw new RuntimeException($message === '' ? "ffmpeg stopped with code {$code}" : $message);
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* @param list<string> $args
|
|
* @return array{0:int,1:string,2:string}
|
|
*/
|
|
private static function capture(array $args): array
|
|
{
|
|
$process = proc_open($args, [0 => ['file', '/dev/null', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes);
|
|
if (!is_resource($process)) {
|
|
throw new RuntimeException('Cannot start ffprobe');
|
|
}
|
|
$out = (string) stream_get_contents($pipes[1]);
|
|
$err = trim((string) stream_get_contents($pipes[2]));
|
|
fclose($pipes[1]);
|
|
fclose($pipes[2]);
|
|
return [proc_close($process), $out, $err];
|
|
}
|
|
|
|
/** The last lines of what ffmpeg said: enough to tell why, not a log. */
|
|
private static function shorten(string $message): string
|
|
{
|
|
$lines = array_values(array_filter(array_map('trim', explode("\n", $message)), static fn(string $l): bool => $l !== ''));
|
|
$text = implode(' · ', array_slice($lines, -2));
|
|
return mb_strlen($text) > 300 ? mb_substr($text, 0, 300) . '…' : $text;
|
|
}
|
|
}
|