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>
235 lines
8.6 KiB
PHP
235 lines
8.6 KiB
PHP
<?php
|
||
declare(strict_types=1);
|
||
|
||
/**
|
||
* Videos (#402): `data/videos/{folder}/{hash}.mp4`, beside it `{hash}.jpg` (the poster) and
|
||
* `{hash}.meta.json` (size, length, frame rate, sound), all served as they are.
|
||
*
|
||
* Unlike an image or a sound a video is not kept as it came: the upload goes into the VideoQueue,
|
||
* and the worker writes the MP4 when it is done (see VideoFormat). The hash is the one of the
|
||
* uploaded bytes, so the name a project stores is known the moment the upload is in, long before
|
||
* the file exists, and uploading the same file twice converts it once.
|
||
*/
|
||
final class VideoStore extends HashedFileStore
|
||
{
|
||
/**
|
||
* What an upload has to start with to be sent to ffmpeg at all: the ISO family (MP4, MOV, M4V,
|
||
* 3GP), Matroska (MKV, WebM), AVI and MPEG transport streams. ffmpeg has the last word.
|
||
*/
|
||
private const SIGNATURE_HINT = 'MP4, MOV, WebM, MKV or AVI';
|
||
|
||
private readonly VideoQueue $queue;
|
||
|
||
public function __construct(private readonly string $root)
|
||
{
|
||
parent::__construct($root);
|
||
$this->queue = new VideoQueue("{$root}/queue");
|
||
}
|
||
|
||
protected static function filePattern(): string
|
||
{
|
||
return '[a-f0-9]{64}\.mp4';
|
||
}
|
||
|
||
public function queue(): VideoQueue
|
||
{
|
||
return $this->queue;
|
||
}
|
||
|
||
/**
|
||
* Takes an upload: a file already converted answers as it is, anything else waits in the
|
||
* queue, a failed one is tried again.
|
||
*
|
||
* @return array<string,mixed>
|
||
* @throws InvalidVideoException when the bytes cannot be a video
|
||
*/
|
||
public function store(string $bytes, string $originalName, string $folder): array
|
||
{
|
||
$in = fopen('php://memory', 'r+b');
|
||
fwrite($in, $bytes);
|
||
rewind($in);
|
||
try {
|
||
return $this->storeStream($in, strlen($bytes), $originalName, $folder);
|
||
} finally {
|
||
fclose($in);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Like store(), straight from the request: the bytes go to disk as they come, and only their
|
||
* first ones and their hash are looked at, so a video of 2 GB needs no 2 GB of memory.
|
||
*
|
||
* @param resource $in
|
||
* @return array<string,mixed>
|
||
* @throws VideoTooLargeException when the stream has more than `$maxBytes`
|
||
* @throws InvalidVideoException when the bytes cannot be a video
|
||
*/
|
||
public function storeStream($in, int $maxBytes, string $originalName, string $folder): array
|
||
{
|
||
$upload = $this->queue->receive($in, $maxBytes);
|
||
try {
|
||
if (!self::looksLikeVideo((string) file_get_contents($upload, false, null, 0, 256))) {
|
||
throw new InvalidVideoException('Not a video file – use ' . self::SIGNATURE_HINT);
|
||
}
|
||
if (!preg_match('/^' . UserStore::FOLDER_PATTERN . '$/', $folder)) {
|
||
throw new InvalidArgumentException("Invalid folder: {$folder}");
|
||
}
|
||
$hash = hash_file('sha256', $upload);
|
||
$dir = "{$this->root}/{$folder}";
|
||
if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
|
||
throw new RuntimeException("Cannot create directory {$dir}");
|
||
}
|
||
OriginalName::write($dir, "{$hash}.mp4", $originalName);
|
||
if (!is_file("{$dir}/{$hash}.mp4")) {
|
||
$job = $this->queue->job($folder, $hash);
|
||
if ($job === null || $job['state'] === VideoQueue::FAILED) {
|
||
$this->queue->add($folder, $hash, $upload, OriginalName::sanitize($originalName));
|
||
}
|
||
}
|
||
return $this->record("{$folder}/{$hash}.mp4");
|
||
} finally {
|
||
if (is_file($upload)) {
|
||
unlink($upload);
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* One file as the picker shows it, done or not; null when there is neither file nor job.
|
||
*
|
||
* @return array<string,mixed>|null
|
||
*/
|
||
public function record(string $file): ?array
|
||
{
|
||
if (!self::isValidName($file)) {
|
||
return null;
|
||
}
|
||
if (is_file("{$this->root}/{$file}")) {
|
||
$folder = self::folderOf($file);
|
||
$dir = $folder === '' ? $this->root : "{$this->root}/{$folder}";
|
||
return [
|
||
'file' => $file,
|
||
'name' => OriginalName::read($dir, basename($file)),
|
||
...$this->details("{$this->root}/{$file}"),
|
||
'bytes' => (int) filesize("{$this->root}/{$file}"),
|
||
];
|
||
}
|
||
$job = $this->jobOf($file);
|
||
return $job === null ? null : $this->pending($job);
|
||
}
|
||
|
||
/** A video is there for deleting while it is converted or failed, too. */
|
||
public function exists(string $file): bool
|
||
{
|
||
return parent::exists($file) || $this->jobOf($file) !== null;
|
||
}
|
||
|
||
/** Lists the converted files like every store does, and the ones on their way after them. */
|
||
public function list(string $folder, bool $seesAll, array $owners): array
|
||
{
|
||
$items = parent::list($folder, $seesAll, $owners);
|
||
foreach ($this->queue->jobs() as $job) {
|
||
if ($seesAll || $job['folder'] === $folder) {
|
||
$items[] = $this->pending($job) + [
|
||
'updatedAt' => (string) $job['createdAt'],
|
||
'owner' => $owners[$job['folder']] ?? '',
|
||
'deletable' => true,
|
||
];
|
||
}
|
||
}
|
||
return $items;
|
||
}
|
||
|
||
public function delete(string $file): bool
|
||
{
|
||
if (!self::isValidName($file)) {
|
||
return false;
|
||
}
|
||
$folder = self::folderOf($file);
|
||
$hash = basename($file, '.mp4');
|
||
$removed = $folder !== '' && $this->queue->remove($folder, $hash);
|
||
if (is_file("{$this->root}/{$file}")) {
|
||
$removed = parent::delete($file) || $removed;
|
||
$dir = $folder === '' ? $this->root : "{$this->root}/{$folder}";
|
||
foreach (["{$dir}/{$hash}.jpg", "{$dir}/{$hash}.meta.json"] as $path) {
|
||
if (is_file($path)) {
|
||
unlink($path);
|
||
}
|
||
}
|
||
} elseif ($removed) {
|
||
OriginalName::delete("{$this->root}/{$folder}", "{$hash}.mp4");
|
||
}
|
||
return $removed;
|
||
}
|
||
|
||
/** Called by the worker once the MP4 is in place: what the editor reads instead of probing. */
|
||
public static function writeDetails(string $dir, string $hash, array $details): void
|
||
{
|
||
$json = json_encode($details, JSON_UNESCAPED_SLASHES);
|
||
AtomicFile::write("{$dir}/{$hash}.meta.json", (string) $json, AtomicFile::SERVED, 'video details');
|
||
}
|
||
|
||
/** @return array<string,mixed> */
|
||
protected function details(string $path): array
|
||
{
|
||
$meta = substr($path, 0, -strlen('.mp4')) . '.meta.json';
|
||
$raw = is_file($meta) ? file_get_contents($meta) : false;
|
||
$details = $raw === false ? null : json_decode($raw, true);
|
||
$details = is_array($details) ? $details : [];
|
||
$file = substr($path, strlen($this->root) + 1);
|
||
return [
|
||
'status' => 'ready',
|
||
'width' => (int) ($details['width'] ?? 0),
|
||
'height' => (int) ($details['height'] ?? 0),
|
||
'duration' => (float) ($details['duration'] ?? 0),
|
||
'fps' => (float) ($details['fps'] ?? 0),
|
||
'audio' => (bool) ($details['audio'] ?? false),
|
||
'poster' => substr($file, 0, -strlen('.mp4')) . '.jpg',
|
||
];
|
||
}
|
||
|
||
/** @return array<string,mixed>|null */
|
||
private function jobOf(string $file): ?array
|
||
{
|
||
$folder = self::folderOf($file);
|
||
return $folder === '' ? null : $this->queue->job($folder, basename($file, '.mp4'));
|
||
}
|
||
|
||
/**
|
||
* @param array<string,mixed> $job
|
||
* @return array<string,mixed>
|
||
*/
|
||
private function pending(array $job): array
|
||
{
|
||
return [
|
||
'file' => "{$job['folder']}/{$job['hash']}.mp4",
|
||
'name' => (string) $job['name'],
|
||
'status' => (string) $job['state'],
|
||
'progress' => (float) $job['progress'],
|
||
'error' => (string) $job['error'],
|
||
'bytes' => 0,
|
||
];
|
||
}
|
||
|
||
private static function looksLikeVideo(string $bytes): bool
|
||
{
|
||
if (strlen($bytes) < 16) {
|
||
return false;
|
||
}
|
||
return substr($bytes, 4, 4) === 'ftyp'
|
||
|| str_starts_with($bytes, "\x1A\x45\xDF\xA3")
|
||
|| (str_starts_with($bytes, 'RIFF') && substr($bytes, 8, 4) === 'AVI ')
|
||
|| ($bytes[0] === "\x47" && strlen($bytes) > 188 && $bytes[188] === "\x47");
|
||
}
|
||
}
|
||
|
||
/** Thrown by VideoStore::store when the uploaded bytes cannot be a video. */
|
||
final class InvalidVideoException extends RuntimeException
|
||
{
|
||
}
|
||
|
||
/** Thrown by VideoQueue::receive when an upload is bigger than the API takes. */
|
||
final class VideoTooLargeException extends RuntimeException
|
||
{
|
||
}
|