Choose size, rate and what follows when recording the editor
The editor recording had fixed settings: the canvas size at 60 fps,
always converted and imported. Recording in 4K needs a choice, and the
server shrank every video to 1080p anyway. Start recording... now opens
a dialog, and a recording always goes to the server as it is.
- The dialog holds name, resolution (Screen, 1080p, 1440p, 4K), fps
(60 or 30), mouse pointer, sound, Convert and Import after
conversion. Import is greyed out while Convert is off. The browser
keeps the last choice, not the name.
- A larger resolution makes the editor draw finer while it records,
so 4K is sharp, not stretched. It is never below the screen's own
resolution and goes back after Stop.
- Stop always uploads. Without Convert the file only stays on the
server. Without Import it is converted but no asset is added. Both
are found in the video picker.
- The server keeps the original next to each MP4 for every upload, so
Download in the video tab and the picker gives the original. Videos
from before have none, they still download their MP4.
- A file left unconverted shows in the picker as not converted, with
a Convert button. POST videos/{file}/convert queues it, and upload
takes convert=0.
- The worker now caps a video at 3840x2160 instead of 1920x1080. Videos
converted before stay as they are.
Tests:
- PHP videos.test.php: 81 checks green, with the original, convert=0,
a later Convert and the 4K cap.
- Unit recording: 5 new, green. Red without the rule that a recording
is never below the screen's resolution.
- e2e 67e-ii: the video tab downloads the .source.mkv, a Matroska
file. 67f: 1440p from a 1280x800 window gives 2304x1440 at 30 fps
without sound, kept and not imported, then converted in the picker.
Both red with the MP4 download and without the finer drawing.
- The README names 2045 e2e checks.
- Gate on melektaus-atx: 304 files, 4699 tests green.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
93190e185c
commit
ba01d146e9
26 files changed
+1009
-127
No files matched your search
@@ -47,7 +47,7 @@ npm run build # writes dist/ and regenerates index.html; the folder is wh
|
||||
The browser suite and the three example games need a machine with a GPU:
|
||||
|
||||
```bash
|
||||
node tools/seed-e2e.mjs && node tools/e2e.mjs # the editor, 2043 checks (GM_STEPS=20 for one step)
|
||||
node tools/seed-e2e.mjs && node tools/e2e.mjs # the editor, 2045 checks (GM_STEPS=20 for one step)
|
||||
# every tool signs in first – see the Accounts page
|
||||
node tools/seed-jumprun.mjs && node tools/smoke-jumprun.mjs
|
||||
node tools/seed-tetris.mjs && node tools/smoke-tetris.mjs
|
||||
|
||||
+27
-6
@@ -63,12 +63,16 @@ declare(strict_types=1);
|
||||
* POST ?r=sounds&name=x.wav raw sound bytes → {file,name,bytes}
|
||||
* DELETE ?r=sounds/{file} → 204 | 403 | 404 | 409
|
||||
*
|
||||
* GET ?r=videos → [{file,name,status,…,owner,deletable}]
|
||||
* POST ?r=videos&name=x.mov raw video bytes → {file,name,status,…}
|
||||
* GET ?r=videos → [{file,name,status,…,original,owner,deletable}]
|
||||
* POST ?r=videos&name=x.mov[&convert=0] raw video bytes → {file,name,status,…}
|
||||
* POST ?r=videos/{file}/convert → {file,name,status,…} | 403 | 404
|
||||
* DELETE ?r=videos/{file} → 204 | 403 | 404 | 409
|
||||
* (an upload is converted by the worker in `game-maker-video` (#402):
|
||||
* `status` is queued, converting with `progress`, failed with `error`,
|
||||
* or ready with width, height, duration, fps, audio and `poster`)
|
||||
* or ready with width, height, duration, fps, audio and `poster`;
|
||||
* with `convert=0` it is only kept, `unconverted`, until it is asked
|
||||
* to be. `original` is the upload as it came, null for a video
|
||||
* uploaded before uploads were kept)
|
||||
*
|
||||
* Uploads land in the uploader's own folder, and `file` carries it: `{folder}/{sha256}.{ext}`
|
||||
* (#344). A `file` without a folder belongs to nobody. A list shows the files of the one asking and
|
||||
@@ -538,7 +542,8 @@ function routeFiles(
|
||||
// A video is too big for memory and goes from the request straight to disk.
|
||||
if ($store instanceof VideoStore) {
|
||||
$in = fopen('php://input', 'rb');
|
||||
Response::json($store->storeStream($in, $maxBytes, $name, $users->folderOf($user, true)), 201);
|
||||
$convert = ($_GET['convert'] ?? '1') !== '0';
|
||||
Response::json($store->storeStream($in, $maxBytes, $name, $users->folderOf($user, true), $convert), 201);
|
||||
}
|
||||
$bytes = Response::rawBody();
|
||||
if (strlen($bytes) > $maxBytes) {
|
||||
@@ -557,6 +562,20 @@ function routeFiles(
|
||||
Response::error('Method not allowed', 405);
|
||||
}
|
||||
|
||||
// A video kept without being converted is converted later, at its owner's word.
|
||||
if ($store instanceof VideoStore && $method === 'POST' && end($parts) === 'convert') {
|
||||
$file = implode('/', array_slice($parts, 1, -1));
|
||||
$folder = HashedFileStore::folderOf($file);
|
||||
if (!$isAdmin && ($folder === '' || $folder !== $users->folderOf($user))) {
|
||||
Response::error('Only its owner may convert this video', 403);
|
||||
}
|
||||
$record = $store->convert($file);
|
||||
if ($record === null) {
|
||||
Response::error("{$noun} not found", 404);
|
||||
}
|
||||
Response::json($record);
|
||||
}
|
||||
|
||||
if ($method === 'DELETE') {
|
||||
$file = implode('/', array_slice($parts, 1));
|
||||
// Asked before whether there is one: somebody else's folder tells a stranger nothing.
|
||||
@@ -637,10 +656,12 @@ try {
|
||||
}
|
||||
|
||||
// A project reaches deepest, `projects/{id}/snapshots/{snapshotId}/restore`; a stored file is
|
||||
// `textures/{folder}/{file}`; everything else stops at two parts.
|
||||
// `textures/{folder}/{file}`, a video to convert `videos/{folder}/{file}/convert`; everything
|
||||
// else stops at two parts.
|
||||
$depth = match ($parts[0] ?? '') {
|
||||
'projects' => 5,
|
||||
'textures', 'fonts', 'sounds', 'videos' => 3,
|
||||
'videos' => 4,
|
||||
'textures', 'fonts', 'sounds' => 3,
|
||||
default => 2,
|
||||
};
|
||||
if (count($parts) < 1 || count($parts) > $depth) {
|
||||
|
||||
@@ -7,13 +7,13 @@ declare(strict_types=1);
|
||||
*
|
||||
* 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.
|
||||
* on a keyframe quickly. The picture fits into 3840 × 2160 (2160 × 3840 standing up), so a 4K
|
||||
* recording of the editor stays 4K, 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_LONG_SIDE = 3840;
|
||||
public const MAX_SHORT_SIDE = 2160;
|
||||
public const MAX_FPS = 60;
|
||||
public const KEYFRAME_EVERY = 15;
|
||||
/** Used when a file does not say its frame rate at all. */
|
||||
|
||||
+27
-12
@@ -2,15 +2,17 @@
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* The videos waiting to be converted (#402): `data/videos/queue/{folder}-{hash}.src` holds the
|
||||
* uploaded bytes, `{folder}-{hash}.json` what became of them. The API adds to it, the worker in the
|
||||
* The videos waiting to be converted (#402): `data/videos/queue/{folder}-{hash}.json` says what
|
||||
* became of an upload, and its `source` where the upload lies – kept as it came beside the MP4,
|
||||
* `{folder}/{hash}.source.{ext}`, for downloading it. The API adds to it, the worker in the
|
||||
* container `game-maker-video` takes from it, one at a time, oldest first.
|
||||
*
|
||||
* A job is `queued`, `converting` (with `progress` from 0 to 1) or `failed` (with `error`). A done
|
||||
* one is no job any more: its MP4 lies in the account's folder and the job is gone. A failed one
|
||||
* stays, so the picker can say why, until the file is deleted or uploaded again.
|
||||
*
|
||||
* Both files are hidden from the web server: the upload is not what anybody should be served.
|
||||
* A job from before the uploads were kept has no `source`: its bytes wait hidden in the queue as
|
||||
* `{folder}-{hash}.src` and go once they are converted.
|
||||
*/
|
||||
final class VideoQueue
|
||||
{
|
||||
@@ -27,7 +29,7 @@ final class VideoQueue
|
||||
|
||||
/**
|
||||
* Copies an upload into a temp file beside the jobs, never more than `$maxBytes` of it: a video
|
||||
* is too big to be held in memory. The caller hands the file to add() or deletes it.
|
||||
* is too big to be held in memory. The caller keeps the file or deletes it.
|
||||
*
|
||||
* @param resource $in
|
||||
* @throws VideoTooLargeException when the stream has more than `$maxBytes`
|
||||
@@ -48,15 +50,16 @@ final class VideoQueue
|
||||
return $tmp;
|
||||
}
|
||||
|
||||
/** Queues the upload received into `$upload`, which is moved and gone afterwards. */
|
||||
public function add(string $folder, string $hash, string $upload, string $name): void
|
||||
/**
|
||||
* Queues the upload kept at `$source`, a path inside the videos' directory such as
|
||||
* `{folder}/{hash}.source.mkv`. The upload stays where it is.
|
||||
*/
|
||||
public function add(string $folder, string $hash, string $source, string $name): void
|
||||
{
|
||||
if (!chmod($upload, AtomicFile::HIDDEN) || !rename($upload, $this->source($folder, $hash))) {
|
||||
throw new RuntimeException('Cannot write uploaded video');
|
||||
}
|
||||
$this->write($folder, $hash, [
|
||||
'folder' => $folder,
|
||||
'hash' => $hash,
|
||||
'source' => $source,
|
||||
'name' => $name,
|
||||
'state' => self::QUEUED,
|
||||
'progress' => 0,
|
||||
@@ -134,10 +137,11 @@ final class VideoQueue
|
||||
return $count;
|
||||
}
|
||||
|
||||
/** Drops the job, and an old one's hidden upload; a kept upload is the store's to delete. */
|
||||
public function remove(string $folder, string $hash): bool
|
||||
{
|
||||
$removed = false;
|
||||
foreach ([$this->source($folder, $hash), $this->jobPath($folder, $hash)] as $path) {
|
||||
foreach ([$this->hiddenUpload($folder, $hash), $this->jobPath($folder, $hash)] as $path) {
|
||||
if (is_file($path)) {
|
||||
$removed = unlink($path) || $removed;
|
||||
}
|
||||
@@ -145,16 +149,27 @@ final class VideoQueue
|
||||
return $removed;
|
||||
}
|
||||
|
||||
/** Drops the upload once it is converted or cannot be; the job itself says what happened. */
|
||||
/**
|
||||
* Drops an old job's hidden upload once it cannot be converted; the job itself says why. A kept
|
||||
* upload stays: it can still be downloaded as it came.
|
||||
*/
|
||||
public function dropSource(string $folder, string $hash): void
|
||||
{
|
||||
$path = $this->source($folder, $hash);
|
||||
$path = $this->hiddenUpload($folder, $hash);
|
||||
if (is_file($path)) {
|
||||
unlink($path);
|
||||
}
|
||||
}
|
||||
|
||||
/** Where the bytes of a job lie, for ffmpeg to read. */
|
||||
public function source(string $folder, string $hash): string
|
||||
{
|
||||
$source = (string) ($this->job($folder, $hash)['source'] ?? '');
|
||||
$kept = '#^' . UserStore::FOLDER_PATTERN . '/[a-f0-9]{64}\.source\.[a-z0-9]+$#';
|
||||
return preg_match($kept, $source) ? dirname($this->dir) . "/{$source}" : $this->hiddenUpload($folder, $hash);
|
||||
}
|
||||
|
||||
private function hiddenUpload(string $folder, string $hash): string
|
||||
{
|
||||
return "{$this->dir}/{$folder}-{$hash}.src";
|
||||
}
|
||||
|
||||
+144
-19
@@ -2,22 +2,31 @@
|
||||
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.
|
||||
* Videos (#402): `data/videos/{folder}/{hash}.mp4`, beside it `{hash}.jpg` (the poster),
|
||||
* `{hash}.meta.json` (size, length, frame rate, sound) and `{hash}.source.{ext}`, the upload as it
|
||||
* came, 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.
|
||||
* What a project plays is the MP4 the worker makes of the upload (see VideoFormat), which waits in
|
||||
* the VideoQueue until then. The upload itself is kept for downloading it, and one sent up without
|
||||
* being converted stays only that until it is asked to be. 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. Videos uploaded before the uploads
|
||||
* were kept have none.
|
||||
*/
|
||||
final class VideoStore extends HashedFileStore
|
||||
{
|
||||
/** An upload kept, waiting for nobody to convert it. */
|
||||
public const UNCONVERTED = 'unconverted';
|
||||
|
||||
/**
|
||||
* 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';
|
||||
|
||||
/** The endings a kept upload may have, taken from its name; anything else is told by its bytes. */
|
||||
private const SOURCE_EXTENSIONS = ['mp4', 'mov', 'm4v', '3gp', 'mkv', 'webm', 'avi', 'ts', 'mts', 'm2ts'];
|
||||
|
||||
private readonly VideoQueue $queue;
|
||||
|
||||
public function __construct(private readonly string $root)
|
||||
@@ -38,18 +47,18 @@ final class VideoStore extends HashedFileStore
|
||||
|
||||
/**
|
||||
* Takes an upload: a file already converted answers as it is, anything else waits in the
|
||||
* queue, a failed one is tried again.
|
||||
* queue, a failed one is tried again. Without `$convert` it is only kept.
|
||||
*
|
||||
* @return array<string,mixed>
|
||||
* @throws InvalidVideoException when the bytes cannot be a video
|
||||
*/
|
||||
public function store(string $bytes, string $originalName, string $folder): array
|
||||
public function store(string $bytes, string $originalName, string $folder, bool $convert = true): array
|
||||
{
|
||||
$in = fopen('php://memory', 'r+b');
|
||||
fwrite($in, $bytes);
|
||||
rewind($in);
|
||||
try {
|
||||
return $this->storeStream($in, strlen($bytes), $originalName, $folder);
|
||||
return $this->storeStream($in, strlen($bytes), $originalName, $folder, $convert);
|
||||
} finally {
|
||||
fclose($in);
|
||||
}
|
||||
@@ -64,11 +73,12 @@ final class VideoStore extends HashedFileStore
|
||||
* @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
|
||||
public function storeStream($in, int $maxBytes, string $originalName, string $folder, bool $convert = true): array
|
||||
{
|
||||
$upload = $this->queue->receive($in, $maxBytes);
|
||||
try {
|
||||
if (!self::looksLikeVideo((string) file_get_contents($upload, false, null, 0, 256))) {
|
||||
$head = (string) file_get_contents($upload, false, null, 0, 256);
|
||||
if (!self::looksLikeVideo($head)) {
|
||||
throw new InvalidVideoException('Not a video file – use ' . self::SIGNATURE_HINT);
|
||||
}
|
||||
if (!preg_match('/^' . UserStore::FOLDER_PATTERN . '$/', $folder)) {
|
||||
@@ -80,12 +90,15 @@ final class VideoStore extends HashedFileStore
|
||||
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));
|
||||
if ($this->sourceOf($folder, $hash) === null) {
|
||||
$source = "{$dir}/{$hash}.source." . self::sourceExtension($originalName, $head);
|
||||
if (!chmod($upload, AtomicFile::SERVED) || !rename($upload, $source)) {
|
||||
throw new RuntimeException('Cannot write uploaded video');
|
||||
}
|
||||
}
|
||||
if ($convert) {
|
||||
$this->enqueue($folder, $hash);
|
||||
}
|
||||
return $this->record("{$folder}/{$hash}.mp4");
|
||||
} finally {
|
||||
if (is_file($upload)) {
|
||||
@@ -94,6 +107,35 @@ final class VideoStore extends HashedFileStore
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an upload that was kept without: it waits in the queue like any other, a failed one
|
||||
* is tried again. Null when there is no such video.
|
||||
*
|
||||
* @return array<string,mixed>|null
|
||||
*/
|
||||
public function convert(string $file): ?array
|
||||
{
|
||||
$folder = self::isValidName($file) ? self::folderOf($file) : '';
|
||||
if ($folder === '') {
|
||||
return null;
|
||||
}
|
||||
$this->enqueue($folder, basename($file, '.mp4'));
|
||||
return $this->record($file);
|
||||
}
|
||||
|
||||
/** Queues a kept upload, unless it is converted or on its way already. */
|
||||
private function enqueue(string $folder, string $hash): void
|
||||
{
|
||||
$source = $this->sourceOf($folder, $hash);
|
||||
if ($source === null || is_file("{$this->root}/{$folder}/{$hash}.mp4")) {
|
||||
return;
|
||||
}
|
||||
$job = $this->queue->job($folder, $hash);
|
||||
if ($job === null || $job['state'] === VideoQueue::FAILED) {
|
||||
$this->queue->add($folder, $hash, $source, OriginalName::read("{$this->root}/{$folder}", "{$hash}.mp4"));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One file as the picker shows it, done or not; null when there is neither file nor job.
|
||||
*
|
||||
@@ -115,16 +157,23 @@ final class VideoStore extends HashedFileStore
|
||||
];
|
||||
}
|
||||
$job = $this->jobOf($file);
|
||||
return $job === null ? null : $this->pending($job);
|
||||
if ($job !== null) {
|
||||
return $this->pending($job);
|
||||
}
|
||||
$folder = self::folderOf($file);
|
||||
return $folder === '' ? null : $this->unconverted($folder, basename($file, '.mp4'));
|
||||
}
|
||||
|
||||
/** A video is there for deleting while it is converted or failed, too. */
|
||||
/** A video is there for deleting while it is converted, failed or only kept, too. */
|
||||
public function exists(string $file): bool
|
||||
{
|
||||
return parent::exists($file) || $this->jobOf($file) !== null;
|
||||
return $this->record($file) !== null;
|
||||
}
|
||||
|
||||
/** Lists the converted files like every store does, and the ones on their way after them. */
|
||||
/**
|
||||
* Lists the converted files like every store does, then the ones on their way, then the ones
|
||||
* kept without being converted.
|
||||
*/
|
||||
public function list(string $folder, bool $seesAll, array $owners): array
|
||||
{
|
||||
$items = parent::list($folder, $seesAll, $owners);
|
||||
@@ -137,6 +186,20 @@ final class VideoStore extends HashedFileStore
|
||||
];
|
||||
}
|
||||
}
|
||||
foreach (glob("{$this->root}/*/*.source.*") ?: [] as $path) {
|
||||
$owner = basename(dirname($path));
|
||||
if (!preg_match('/^([a-f0-9]{64})\.source\.[a-z0-9]+$/', basename($path), $m) || (!$seesAll && $owner !== $folder)) {
|
||||
continue;
|
||||
}
|
||||
$record = $this->unconverted($owner, $m[1]);
|
||||
if ($record !== null) {
|
||||
$items[] = $record + [
|
||||
'updatedAt' => gmdate('c', (int) filemtime($path)),
|
||||
'owner' => $owners[$owner] ?? '',
|
||||
'deletable' => true,
|
||||
];
|
||||
}
|
||||
}
|
||||
return $items;
|
||||
}
|
||||
|
||||
@@ -148,6 +211,10 @@ final class VideoStore extends HashedFileStore
|
||||
$folder = self::folderOf($file);
|
||||
$hash = basename($file, '.mp4');
|
||||
$removed = $folder !== '' && $this->queue->remove($folder, $hash);
|
||||
$source = $folder === '' ? null : $this->sourceOf($folder, $hash);
|
||||
if ($source !== null) {
|
||||
$removed = unlink("{$this->root}/{$source}") || $removed;
|
||||
}
|
||||
if (is_file("{$this->root}/{$file}")) {
|
||||
$removed = parent::delete($file) || $removed;
|
||||
$dir = $folder === '' ? $this->root : "{$this->root}/{$folder}";
|
||||
@@ -177,6 +244,7 @@ final class VideoStore extends HashedFileStore
|
||||
$details = $raw === false ? null : json_decode($raw, true);
|
||||
$details = is_array($details) ? $details : [];
|
||||
$file = substr($path, strlen($this->root) + 1);
|
||||
$folder = self::folderOf($file);
|
||||
return [
|
||||
'status' => 'ready',
|
||||
'width' => (int) ($details['width'] ?? 0),
|
||||
@@ -185,9 +253,65 @@ final class VideoStore extends HashedFileStore
|
||||
'fps' => (float) ($details['fps'] ?? 0),
|
||||
'audio' => (bool) ($details['audio'] ?? false),
|
||||
'poster' => substr($file, 0, -strlen('.mp4')) . '.jpg',
|
||||
'original' => $folder === '' ? null : $this->sourceOf($folder, basename($file, '.mp4')),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the upload of a video is kept, `{folder}/{hash}.source.{ext}` as it is served; null for
|
||||
* one uploaded before uploads were kept.
|
||||
*/
|
||||
private function sourceOf(string $folder, string $hash): ?string
|
||||
{
|
||||
foreach (glob("{$this->root}/{$folder}/{$hash}.source.*") ?: [] as $path) {
|
||||
if (preg_match('/^[a-f0-9]{64}\.source\.[a-z0-9]+$/', basename($path))) {
|
||||
return "{$folder}/" . basename($path);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A kept upload that is neither converted nor on its way, as the picker shows it; null when
|
||||
* the video is either, or there is no upload.
|
||||
*
|
||||
* @return array<string,mixed>|null
|
||||
*/
|
||||
private function unconverted(string $folder, string $hash): ?array
|
||||
{
|
||||
$source = $this->sourceOf($folder, $hash);
|
||||
if ($source === null || is_file("{$this->root}/{$folder}/{$hash}.mp4") || $this->queue->job($folder, $hash) !== null) {
|
||||
return null;
|
||||
}
|
||||
return [
|
||||
'file' => "{$folder}/{$hash}.mp4",
|
||||
'name' => OriginalName::read("{$this->root}/{$folder}", "{$hash}.mp4"),
|
||||
'status' => self::UNCONVERTED,
|
||||
'progress' => 0,
|
||||
'error' => '',
|
||||
'bytes' => (int) filesize("{$this->root}/{$source}"),
|
||||
'original' => $source,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The ending a kept upload is served with: the one of its name when that is a video's, else the
|
||||
* one its first bytes tell.
|
||||
*/
|
||||
private static function sourceExtension(string $name, string $head): string
|
||||
{
|
||||
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
|
||||
if (in_array($extension, self::SOURCE_EXTENSIONS, true)) {
|
||||
return $extension;
|
||||
}
|
||||
return match (true) {
|
||||
substr($head, 4, 4) === 'ftyp' => substr($head, 8, 4) === 'qt ' ? 'mov' : 'mp4',
|
||||
str_starts_with($head, "\x1A\x45\xDF\xA3") => str_contains($head, 'webm') ? 'webm' : 'mkv',
|
||||
str_starts_with($head, 'RIFF') => 'avi',
|
||||
default => 'ts',
|
||||
};
|
||||
}
|
||||
|
||||
/** @return array<string,mixed>|null */
|
||||
private function jobOf(string $file): ?array
|
||||
{
|
||||
@@ -208,6 +332,7 @@ final class VideoStore extends HashedFileStore
|
||||
'progress' => (float) $job['progress'],
|
||||
'error' => (string) $job['error'],
|
||||
'bytes' => 0,
|
||||
'original' => $this->sourceOf((string) $job['folder'], (string) $job['hash']),
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* Recording the whole editor (main menu → Start recording…): what the dialog offers, and the size
|
||||
* and sharpness a choice comes out at. The browser's side is `editor/EditorRecorder.ts`.
|
||||
*/
|
||||
import { editorRecordingSize } from './recording';
|
||||
|
||||
export type EditorRecordingResolution = 'screen' | '1080p' | '1440p' | '4k';
|
||||
|
||||
export interface EditorRecordingSettings {
|
||||
/** Empty: named after the moment it starts (`recordingName`). */
|
||||
name: string;
|
||||
resolution: EditorRecordingResolution;
|
||||
fps: 30 | 60;
|
||||
/** Whether the mouse pointer is drawn in; the system draws it over the canvas, not into it. */
|
||||
pointer: boolean;
|
||||
/** Whether the master is recorded with it. */
|
||||
sound: boolean;
|
||||
/** Whether the server converts the upload into an MP4 a project can use; else it is only kept. */
|
||||
convert: boolean;
|
||||
/** Whether the converted video becomes an asset of the project; only with `convert`. */
|
||||
adopt: boolean;
|
||||
}
|
||||
|
||||
/** `box` is the frame the picture is fitted into, keeping the window's shape; none records the canvas as it is. */
|
||||
export const EDITOR_RECORDING_RESOLUTIONS: readonly {
|
||||
value: EditorRecordingResolution;
|
||||
label: string;
|
||||
box: { w: number; h: number } | null;
|
||||
}[] = [
|
||||
{ value: 'screen', label: 'Screen', box: null },
|
||||
{ value: '1080p', label: '1080p', box: { w: 1920, h: 1080 } },
|
||||
{ value: '1440p', label: '1440p', box: { w: 2560, h: 1440 } },
|
||||
{ value: '4k', label: '4K', box: { w: 3840, h: 2160 } },
|
||||
];
|
||||
|
||||
export const EDITOR_RECORDING_DEFAULTS: EditorRecordingSettings = {
|
||||
name: '',
|
||||
resolution: 'screen',
|
||||
fps: 60,
|
||||
pointer: true,
|
||||
sound: true,
|
||||
convert: true,
|
||||
adopt: true,
|
||||
};
|
||||
|
||||
/**
|
||||
* The most device pixels a layout pixel is drawn at while recording. A window too small for its
|
||||
* frame even then is scaled up into it, a little soft.
|
||||
*/
|
||||
const MOST_RESOLUTION = 4;
|
||||
|
||||
/** Settings as kept in the browser, whatever was kept: anything unknown is the default. The name is never kept. */
|
||||
export function editorRecordingSettingsOf(raw: unknown): EditorRecordingSettings {
|
||||
const kept = typeof raw === 'object' && raw !== null ? (raw as Record<string, unknown>) : {};
|
||||
const flag = (key: 'pointer' | 'sound' | 'convert' | 'adopt'): boolean =>
|
||||
typeof kept[key] === 'boolean' ? kept[key] : EDITOR_RECORDING_DEFAULTS[key];
|
||||
const resolution = EDITOR_RECORDING_RESOLUTIONS.find((r) => r.value === kept.resolution);
|
||||
return {
|
||||
name: '',
|
||||
resolution: resolution?.value ?? EDITOR_RECORDING_DEFAULTS.resolution,
|
||||
fps: kept.fps === 30 ? 30 : 60,
|
||||
pointer: flag('pointer'),
|
||||
sound: flag('sound'),
|
||||
convert: flag('convert'),
|
||||
adopt: flag('adopt'),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* How an editor recording is made of a screen of `screen` layout pixels drawn at `resolution`:
|
||||
* the size of its frames, even on both sides, and the resolution the editor draws at meanwhile.
|
||||
*
|
||||
* `Screen` is the canvas as it is. A larger frame is drawn for, not scaled up to: the editor draws
|
||||
* more device pixels per layout pixel while it records, so text and lines stay sharp in 4K. On
|
||||
* screen it looks the same, as the browser shows the larger canvas at its layout size. A smaller
|
||||
* frame keeps the screen's resolution and is scaled down when it is copied.
|
||||
*/
|
||||
export function editorRecordingPlan(
|
||||
screen: { w: number; h: number },
|
||||
resolution: number,
|
||||
choice: EditorRecordingResolution,
|
||||
): { size: { w: number; h: number }; resolution: number } {
|
||||
const box = EDITOR_RECORDING_RESOLUTIONS.find((r) => r.value === choice)?.box ?? null;
|
||||
const scale = box ? Math.min(box.w / screen.w, box.h / screen.h) : resolution;
|
||||
return {
|
||||
size: editorRecordingSize({ w: Math.round(screen.w * scale), h: Math.round(screen.h * scale) }),
|
||||
resolution: Math.min(MOST_RESOLUTION, Math.max(resolution, scale)),
|
||||
};
|
||||
}
|
||||
@@ -80,12 +80,9 @@ function even(value: number): number {
|
||||
return Math.max(2, Math.round(value / 2) * 2);
|
||||
}
|
||||
|
||||
/** The editor is recorded at 60 fps, whatever the screen draws. */
|
||||
export const EDITOR_RECORDING_FPS = 60;
|
||||
|
||||
/**
|
||||
* The size of an editor recording: the whole canvas in device pixels, an odd row or column cut off,
|
||||
* since the encoders want both sides even.
|
||||
* The size of an editor recording of a canvas in device pixels: all of it, an odd row or column
|
||||
* cut off, since the encoders want both sides even.
|
||||
*/
|
||||
export function editorRecordingSize(canvas: { w: number; h: number }): { w: number; h: number } {
|
||||
const cut = (value: number) => Math.max(2, Math.floor(value / 2) * 2);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { FileStore, StoredFile, UploadedFile } from './FileStore';
|
||||
import { apiRequest } from './http';
|
||||
import type { StoredVideo, UploadedVideo, VideoStore, VideoUploadOptions } from './VideoStore';
|
||||
|
||||
/**
|
||||
* The API's file collections, one route each; textures, fonts, sounds and videos differ in nothing
|
||||
@@ -13,15 +14,19 @@ export class HttpFileStore<
|
||||
S extends StoredFile = StoredFile,
|
||||
> implements FileStore<U, S> {
|
||||
constructor(
|
||||
private readonly endpoint: string,
|
||||
protected readonly endpoint: string,
|
||||
private readonly route: FileRoute,
|
||||
) {}
|
||||
|
||||
async upload(bytes: Blob | ArrayBuffer, type: string, name = ''): Promise<U> {
|
||||
return this.send(bytes, type, { name });
|
||||
}
|
||||
|
||||
protected async send(bytes: Blob | ArrayBuffer, type: string, query: Record<string, string>): Promise<U> {
|
||||
return apiRequest<U>(this.endpoint, 'POST', this.route, {
|
||||
headers: { 'Content-Type': type },
|
||||
body: bytes,
|
||||
query: { name },
|
||||
query,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -31,9 +36,31 @@ export class HttpFileStore<
|
||||
|
||||
/** The reason a refusal gives is meant for the user, so it is thrown as it is, without the route. */
|
||||
async delete(file: string): Promise<void> {
|
||||
await apiRequest<void>(this.endpoint, 'DELETE', `${this.route}/${file}`, {}, (status, data) => {
|
||||
const error = (data as { error?: unknown } | null)?.error;
|
||||
return status >= 400 && typeof error === 'string' ? new Error(error) : undefined;
|
||||
});
|
||||
await apiRequest<void>(this.endpoint, 'DELETE', `${this.route}/${file}`, {}, refusal);
|
||||
}
|
||||
}
|
||||
|
||||
/** Videos: an upload may be kept without converting it, and converted later. */
|
||||
export class HttpVideoStore extends HttpFileStore<UploadedVideo, StoredVideo> implements VideoStore {
|
||||
constructor(endpoint: string) {
|
||||
super(endpoint, 'videos');
|
||||
}
|
||||
|
||||
override async upload(
|
||||
bytes: Blob | ArrayBuffer,
|
||||
type: string,
|
||||
name = '',
|
||||
options: VideoUploadOptions = {},
|
||||
): Promise<UploadedVideo> {
|
||||
return this.send(bytes, type, { name, convert: options.convert === false ? '0' : '' });
|
||||
}
|
||||
|
||||
async convert(file: string): Promise<UploadedVideo> {
|
||||
return apiRequest<UploadedVideo>(this.endpoint, 'POST', `videos/${file}/convert`, {}, refusal);
|
||||
}
|
||||
}
|
||||
|
||||
function refusal(status: number, data: unknown): Error | undefined {
|
||||
const error = (data as { error?: unknown } | null)?.error;
|
||||
return status >= 400 && typeof error === 'string' ? new Error(error) : undefined;
|
||||
}
|
||||
@@ -2,9 +2,10 @@ import type { FileStore, StoredFile, UploadedFile } from './FileStore';
|
||||
|
||||
/**
|
||||
* Where an upload is on its way to `data/videos/` (#402): the worker converts one after the other,
|
||||
* so a video waits, is converted, and is ready or failed.
|
||||
* so a video waits, is converted, and is ready or failed. One uploaded without converting it stays
|
||||
* `unconverted` until it is asked to be.
|
||||
*/
|
||||
export type VideoStatus = 'queued' | 'converting' | 'ready' | 'failed';
|
||||
export type VideoStatus = 'queued' | 'converting' | 'ready' | 'failed' | 'unconverted';
|
||||
|
||||
/**
|
||||
* What the server says about a video. `file` is known the moment the upload is in, long before the
|
||||
@@ -22,7 +23,27 @@ export interface UploadedVideo extends UploadedFile {
|
||||
audio?: boolean;
|
||||
/** `{folder}/{sha256}.jpg`, beside the MP4. */
|
||||
poster?: string;
|
||||
/**
|
||||
* The upload as it came, `{folder}/{sha256}.source.{ext}` beside the MP4: what Download saves.
|
||||
* Null for a video uploaded before uploads were kept.
|
||||
*/
|
||||
original?: string | null;
|
||||
}
|
||||
|
||||
export type StoredVideo = StoredFile & UploadedVideo;
|
||||
export type VideoStore = FileStore<UploadedVideo, StoredVideo>;
|
||||
|
||||
export interface VideoUploadOptions {
|
||||
/** False keeps the upload as it came, `unconverted`, until `convert` asks for it. */
|
||||
convert?: boolean;
|
||||
}
|
||||
|
||||
export interface VideoStore extends FileStore<UploadedVideo, StoredVideo> {
|
||||
upload(
|
||||
bytes: Blob | ArrayBuffer,
|
||||
type: string,
|
||||
name?: string,
|
||||
options?: VideoUploadOptions,
|
||||
): Promise<UploadedVideo>;
|
||||
/** Converts an upload kept without; answers what the server says of it then. */
|
||||
convert(file: string): Promise<UploadedVideo>;
|
||||
}
|
||||
+2
-3
@@ -1,13 +1,12 @@
|
||||
import type { Application } from 'pixi.js';
|
||||
import type { AuthStore, SignedIn } from '../core/store/AuthStore';
|
||||
import { HttpAuthStore } from '../core/store/HttpAuthStore';
|
||||
import { HttpFileStore } from '../core/store/HttpFileStore';
|
||||
import { HttpFileStore, HttpVideoStore } from '../core/store/HttpFileStore';
|
||||
import { HttpProjectStore } from '../core/store/HttpProjectStore';
|
||||
import { HttpReleaseStore } from '../core/store/HttpReleaseStore';
|
||||
import { HttpSnapshotStore } from '../core/store/HttpSnapshotStore';
|
||||
import { HttpUsersStore } from '../core/store/HttpUsersStore';
|
||||
import type { StoredTexture, UploadedTexture } from '../core/store/TextureStore';
|
||||
import type { StoredVideo, UploadedVideo } from '../core/store/VideoStore';
|
||||
import { loadPhysics } from '../runtime/physics/engine';
|
||||
import { projectPictureFactory } from '../viewport/generatedPictures';
|
||||
import { preloadProjectFiles, setUpProjectFiles } from '../viewport/projectFiles';
|
||||
@@ -93,7 +92,7 @@ export async function startEditor(app: Application, root: VStack): Promise<void>
|
||||
new HttpFileStore<UploadedTexture, StoredTexture>(API_ENDPOINT, 'textures'),
|
||||
new HttpFileStore(API_ENDPOINT, 'fonts'),
|
||||
new HttpFileStore(API_ENDPOINT, 'sounds'),
|
||||
new HttpFileStore<UploadedVideo, StoredVideo>(API_ENDPOINT, 'videos'),
|
||||
new HttpVideoStore(API_ENDPOINT),
|
||||
new HttpSnapshotStore(API_ENDPOINT),
|
||||
new HttpReleaseStore(API_ENDPOINT),
|
||||
{
|
||||
|
||||
+22
-3
@@ -79,6 +79,8 @@ import { Toolbar } from './panels/Toolbar';
|
||||
import { type PlayHost, PlaySession, type WorldSnapshot } from './PlaySession';
|
||||
import { type RecordingUpload, RecordingUploads } from './recordingUploads';
|
||||
import { EditorRecorder } from './EditorRecorder';
|
||||
import { EditorRecordingDialog } from './EditorRecordingDialog';
|
||||
import { editorRecordingSettings, keepEditorRecordingSettings } from './editorRecordingSettings';
|
||||
import type { MadeRecording } from '../viewport/RecordingTake';
|
||||
import { ProjectSession } from './ProjectSession';
|
||||
import { ParticlesEditor } from './particles/ParticlesEditor';
|
||||
@@ -351,6 +353,7 @@ export class Editor implements PlayHost {
|
||||
private readonly toolbar: Toolbar;
|
||||
private readonly passwordDialog = dialogSlot<PasswordDialog>();
|
||||
private readonly generalDialog = dialogSlot<GeneralSettingsDialog>();
|
||||
private readonly recordingDialog = dialogSlot<EditorRecordingDialog>();
|
||||
/** Drawn-frame count at the last measurement, not a counter of its own. */
|
||||
private fpsFrames = 0;
|
||||
private fpsElapsed = 0;
|
||||
@@ -391,7 +394,7 @@ export class Editor implements PlayHost {
|
||||
this.particlesEditor = new ParticlesEditor(state);
|
||||
this.streamKeeper = new StreamKeeper(state, sounds);
|
||||
this.soundEditor = new SoundEditor(state, this.streamKeeper);
|
||||
this.videoEditor = new VideoEditor(state);
|
||||
this.videoEditor = new VideoEditor(state, videos);
|
||||
this.soundFxEditor = new SoundFxEditor(state);
|
||||
this.instrumentEditor = new InstrumentEditor(state);
|
||||
this.patternEditor = new PatternEditor(state, sounds);
|
||||
@@ -421,7 +424,7 @@ export class Editor implements PlayHost {
|
||||
state.setNotice(line);
|
||||
console.warn('[recording]', line);
|
||||
},
|
||||
saved: (recording) => this.recordings.add(recording),
|
||||
saved: (recording, options) => this.recordings.add(recording, options),
|
||||
showBadge: (on) => this.toolbar.showRecording(on),
|
||||
badgeRoom: () => this.toolbar.recordingRoom(),
|
||||
});
|
||||
@@ -815,7 +818,7 @@ export class Editor implements PlayHost {
|
||||
{ separator: true },
|
||||
recorder.isRecording
|
||||
? { label: 'Stop recording', onSelect: () => recorder.stop() }
|
||||
: { label: 'Start recording', onSelect: () => recorder.start() },
|
||||
: { label: 'Start recording…', onSelect: () => this.openEditorRecording() },
|
||||
{ separator: true },
|
||||
{ label: 'General settings…', onSelect: () => this.openGeneralSettings() },
|
||||
...(this.usersPane ? [{ label: 'User management', onSelect: open }] : []),
|
||||
@@ -833,6 +836,21 @@ export class Editor implements PlayHost {
|
||||
return this.generalDialog.current();
|
||||
}
|
||||
|
||||
/** "Start recording…": how the editor is recorded, starting on the last choice made in this browser. */
|
||||
openEditorRecording(): EditorRecordingDialog {
|
||||
return this.recordingDialog.open(
|
||||
new EditorRecordingDialog(editorRecordingSettings(), (settings) => {
|
||||
keepEditorRecordingSettings(settings);
|
||||
this.editorRecorder.start(settings);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** The open "Start recording" dialog, for the check scripts. */
|
||||
editorRecordingDialog(): EditorRecordingDialog | null {
|
||||
return this.recordingDialog.current();
|
||||
}
|
||||
|
||||
/**
|
||||
* The account menu under its button (#182). The name stands in it as an entry that cannot be
|
||||
* picked: it says who is signed in without costing the crowded toolbar another label.
|
||||
@@ -1350,6 +1368,7 @@ export class Editor implements PlayHost {
|
||||
// Closed rather than just thrown away with the overlay below, so the slot lets go of it too.
|
||||
this.passwordDialog.current()?.close();
|
||||
this.generalDialog.current()?.close();
|
||||
this.recordingDialog.current()?.close();
|
||||
// The tooltip is not the editor's to destroy: it leaves the overlay before that is emptied.
|
||||
tooltips.dismiss();
|
||||
// A menu or a picker left open belongs to widgets that are about to be destroyed.
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
import { UPDATE_PRIORITY } from 'pixi.js';
|
||||
import { cursorShape, type CursorShape } from '../core/recording/cursors';
|
||||
import {
|
||||
EDITOR_RECORDING_FPS,
|
||||
editorRecordingSize,
|
||||
elapsedText,
|
||||
fitPicture,
|
||||
recordingName,
|
||||
} from '../core/recording/recording';
|
||||
import { editorRecordingPlan, type EditorRecordingSettings } from '../core/recording/editorRecording';
|
||||
import { elapsedText, fitPicture, recordingName } from '../core/recording/recording';
|
||||
import { renderCount, requestRender, Theme, toHex, ui } from '../ui';
|
||||
import { type FrameSource, Take, type TakeHost, type TakeInfo } from '../viewport/RecordingTake';
|
||||
import { type FrameSource, type MadeRecording, Take, type TakeInfo } from '../viewport/RecordingTake';
|
||||
|
||||
/** What becomes of a recording on the server, as "Start recording…" asked. */
|
||||
export interface RecordingUploadOptions {
|
||||
convert: boolean;
|
||||
adopt: boolean;
|
||||
}
|
||||
|
||||
/** What the editor recorder needs of the editor. */
|
||||
export interface EditorRecorderHost extends TakeHost {
|
||||
export interface EditorRecorderHost {
|
||||
/** A line for the editor's notice. */
|
||||
log(line: string): void;
|
||||
saved(recording: MadeRecording, options: RecordingUploadOptions): void;
|
||||
/** Makes room in the top bar for the badge while recording, or takes it away. */
|
||||
showBadge(on: boolean): void;
|
||||
/** Where the badge goes, in CSS pixels. */
|
||||
@@ -19,12 +23,12 @@ export interface EditorRecorderHost extends TakeHost {
|
||||
}
|
||||
|
||||
/**
|
||||
* Records the whole editor (main menu → Start recording): the canvas as it is on screen, at its size
|
||||
* in device pixels and 60 fps, with the mouse pointer drawn in, since the system draws that over the
|
||||
* canvas. What the editor draws is copied from the canvas right after each render, so recording costs
|
||||
* no second drawing. The badge beside the menu is an HTML element over the canvas, the one exception
|
||||
* to the single canvas: it is never in the recording, and the canvas is drawn once per frame, which a
|
||||
* `desynchronized` canvas needs to show no half-drawn picture.
|
||||
* Records the whole editor (main menu → Start recording…): the canvas as it is on screen, or drawn
|
||||
* sharper to fill a larger frame (`editorRecordingPlan`), with the mouse pointer drawn in, since
|
||||
* the system draws that over the canvas. What the editor draws is copied from the canvas right after
|
||||
* each render, so recording costs no second drawing. The badge beside the menu is an HTML element
|
||||
* over the canvas, the one exception to the single canvas: it is never in the recording, and the
|
||||
* canvas is drawn once per frame, which a `desynchronized` canvas needs to show no half-drawn picture.
|
||||
*/
|
||||
export class EditorRecorder {
|
||||
private take: Take | null = null;
|
||||
@@ -35,6 +39,8 @@ export class EditorRecorder {
|
||||
private startedAt = 0;
|
||||
private shownText = '';
|
||||
private readonly badge = new RecordingBadge();
|
||||
/** The resolution the editor was drawn at before a recording raised it; null while it is not raised. */
|
||||
private screenResolution: number | null = null;
|
||||
|
||||
constructor(private readonly host: EditorRecorderHost) {}
|
||||
|
||||
@@ -42,13 +48,32 @@ export class EditorRecorder {
|
||||
return this.take !== null;
|
||||
}
|
||||
|
||||
start(): void {
|
||||
start(settings: EditorRecordingSettings): void {
|
||||
if (this.take) return;
|
||||
const app = ui().app;
|
||||
const source = new CanvasSource(app.canvas);
|
||||
const take = new Take(recordingName('', new Date()), EDITOR_RECORDING_FPS, source, this.host, () => {
|
||||
const screen = { w: app.screen.width, h: app.screen.height };
|
||||
const plan = editorRecordingPlan(screen, app.renderer.resolution, settings.resolution);
|
||||
if (plan.resolution !== app.renderer.resolution) {
|
||||
this.screenResolution = app.renderer.resolution;
|
||||
app.renderer.resize(screen.w, screen.h, plan.resolution);
|
||||
}
|
||||
const source = new CanvasSource(app.canvas, plan.size, settings.fps, settings.pointer);
|
||||
const upload = { convert: settings.convert, adopt: settings.convert && settings.adopt };
|
||||
const host = {
|
||||
log: (line: string) => this.host.log(line),
|
||||
saved: (recording: MadeRecording) => this.host.saved(recording, upload),
|
||||
};
|
||||
const name = recordingName(settings.name, new Date());
|
||||
const take = new Take(
|
||||
name,
|
||||
settings.fps,
|
||||
source,
|
||||
host,
|
||||
() => {
|
||||
if (this.take === take) this.end();
|
||||
});
|
||||
},
|
||||
{ sound: settings.sound },
|
||||
);
|
||||
this.take = take;
|
||||
this.source = source;
|
||||
this.takes.push(take);
|
||||
@@ -72,7 +97,12 @@ export class EditorRecorder {
|
||||
this.take = null;
|
||||
this.source?.detach();
|
||||
this.source = null;
|
||||
ui().app.ticker.remove(this.tick, this);
|
||||
const app = ui().app;
|
||||
app.ticker.remove(this.tick, this);
|
||||
if (this.screenResolution !== null) {
|
||||
app.renderer.resize(Math.round(app.screen.width), Math.round(app.screen.height), this.screenResolution);
|
||||
this.screenResolution = null;
|
||||
}
|
||||
this.badge.hide();
|
||||
this.host.showBadge(false);
|
||||
requestRender();
|
||||
@@ -102,11 +132,14 @@ export class EditorRecorder {
|
||||
recording: boolean;
|
||||
takes: TakeInfo[];
|
||||
badge: { x: number; y: number; w: number; h: number } | null;
|
||||
/** What the editor is drawn at now, raised while a larger frame is recorded. */
|
||||
resolution: number;
|
||||
} {
|
||||
return {
|
||||
recording: this.isRecording,
|
||||
takes: this.takes.map((take) => take.info()),
|
||||
badge: this.isRecording ? this.host.badgeRoom() : null,
|
||||
resolution: ui().app.renderer.resolution,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -178,7 +211,6 @@ class RecordingBadge {
|
||||
* picture with the mouse pointer drawn over it.
|
||||
*/
|
||||
class CanvasSource implements FrameSource {
|
||||
private readonly size: { w: number; h: number };
|
||||
private readonly picture: OffscreenCanvas;
|
||||
private readonly picturePen: OffscreenCanvasRenderingContext2D;
|
||||
private readonly frame: OffscreenCanvas;
|
||||
@@ -188,13 +220,17 @@ class CanvasSource implements FrameSource {
|
||||
private copied = false;
|
||||
private ready: VideoFrame[] = [];
|
||||
|
||||
constructor(private readonly canvas: HTMLCanvasElement) {
|
||||
this.size = editorRecordingSize({ w: canvas.width, h: canvas.height });
|
||||
constructor(
|
||||
private readonly canvas: HTMLCanvasElement,
|
||||
private readonly size: { w: number; h: number },
|
||||
private readonly fps: number,
|
||||
private readonly showsPointer: boolean,
|
||||
) {
|
||||
this.picture = new OffscreenCanvas(this.size.w, this.size.h);
|
||||
this.picturePen = this.picture.getContext('2d', { alpha: false })!;
|
||||
this.frame = new OffscreenCanvas(this.size.w, this.size.h);
|
||||
this.framePen = this.frame.getContext('2d', { alpha: false })!;
|
||||
this.pointer.attach(canvas);
|
||||
if (showsPointer) this.pointer.attach(canvas);
|
||||
}
|
||||
|
||||
open(): { w: number; h: number } {
|
||||
@@ -230,7 +266,7 @@ class CanvasSource implements FrameSource {
|
||||
this.ready.push(
|
||||
new VideoFrame(this.frame, {
|
||||
timestamp: Math.round(ms * 1000),
|
||||
duration: Math.round(1e6 / EDITOR_RECORDING_FPS),
|
||||
duration: Math.round(1e6 / this.fps),
|
||||
}),
|
||||
);
|
||||
return true;
|
||||
@@ -239,7 +275,7 @@ class CanvasSource implements FrameSource {
|
||||
private drawPointer(): void {
|
||||
const { canvas, pointer } = this;
|
||||
const shape = cursorShape(canvas.style.cursor);
|
||||
if (!pointer.inside || !shape) return;
|
||||
if (!this.showsPointer || !pointer.inside || !shape) return;
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
if (rect.width === 0 || rect.height === 0) return;
|
||||
const at = fitPicture({ w: canvas.width, h: canvas.height }, this.size);
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
import {
|
||||
EDITOR_RECORDING_RESOLUTIONS,
|
||||
editorRecordingPlan,
|
||||
type EditorRecordingResolution,
|
||||
type EditorRecordingSettings,
|
||||
} from '../core/recording/editorRecording';
|
||||
import { type Button, Checkbox, Dropdown, Label, Menu, TextField, ui } from '../ui';
|
||||
import { FormDialog } from './FormDialog';
|
||||
|
||||
const FIELD_WIDTH = 200;
|
||||
const FPS_CHOICES = [60, 30] as const;
|
||||
|
||||
type Switch = 'pointer' | 'sound' | 'convert' | 'adopt';
|
||||
|
||||
/**
|
||||
* "Start recording…" in the main menu: how the whole editor is recorded, and what becomes of the
|
||||
* file. It always goes up to the server; Convert makes the MP4 a project can use of it, and Import
|
||||
* adds that to the project once it is ready.
|
||||
*/
|
||||
export class EditorRecordingDialog extends FormDialog {
|
||||
private settings: EditorRecordingSettings;
|
||||
private readonly nameField: TextField;
|
||||
private readonly resolutionPicker: Dropdown;
|
||||
private readonly fpsPicker: Dropdown;
|
||||
private readonly size: Label;
|
||||
private readonly boxes: Record<Switch, Checkbox>;
|
||||
/** The confirming button, so a check can click it. */
|
||||
readonly startButton: Button;
|
||||
|
||||
constructor(settings: EditorRecordingSettings, onStart: (settings: EditorRecordingSettings) => void) {
|
||||
super(360, 'Start recording');
|
||||
this.settings = { ...settings };
|
||||
|
||||
this.nameField = new TextField(settings.name, {
|
||||
width: FIELD_WIDTH,
|
||||
placeholder: 'Recording <date> <time>',
|
||||
onSubmit: () => this.start(onStart),
|
||||
});
|
||||
this.content.add(this.formRow(this.fieldLabel('Name'), this.nameField));
|
||||
|
||||
this.resolutionPicker = new Dropdown('', {
|
||||
width: FIELD_WIDTH,
|
||||
onClick: () => this.pickResolution(),
|
||||
});
|
||||
this.content.add(this.formRow(this.fieldLabel('Resolution'), this.resolutionPicker));
|
||||
this.fpsPicker = new Dropdown('', { width: FIELD_WIDTH, onClick: () => this.pickFps() });
|
||||
this.content.add(this.formRow(this.fieldLabel('FPS'), this.fpsPicker));
|
||||
this.size = new Label('', { style: 'muted' });
|
||||
this.content.add(this.size);
|
||||
|
||||
const box = (key: Switch, text: string): Checkbox => {
|
||||
const checkbox = new Checkbox(this.settings[key]);
|
||||
checkbox.onChange = (on) => {
|
||||
this.settings[key] = on;
|
||||
this.sync();
|
||||
};
|
||||
this.content.add(this.formRow(checkbox, new Label(text)));
|
||||
return checkbox;
|
||||
};
|
||||
this.boxes = {
|
||||
pointer: box('pointer', 'Mouse pointer'),
|
||||
sound: box('sound', 'Sound'),
|
||||
convert: box('convert', 'Convert'),
|
||||
adopt: box('adopt', 'Import after conversion'),
|
||||
};
|
||||
this.content.add(new Label('Always uploaded. Download saves it as it was recorded.', { style: 'muted' }));
|
||||
this.startButton = this.addButtons('Start recording', 'primary', () => onStart(this.values()));
|
||||
this.sync();
|
||||
}
|
||||
|
||||
/** A switch, so a check can click it. */
|
||||
switchOf(key: Switch): Checkbox {
|
||||
return this.boxes[key];
|
||||
}
|
||||
|
||||
/** The settings as the fields stand (test hook). */
|
||||
values(): EditorRecordingSettings {
|
||||
return { ...this.settings, name: this.nameField.value.trim() };
|
||||
}
|
||||
|
||||
/** Sets the fields as a check script would pick them (test hook). */
|
||||
choose(change: Partial<EditorRecordingSettings>): void {
|
||||
if (change.name !== undefined) this.nameField.setValue(change.name);
|
||||
this.settings = { ...this.settings, ...change };
|
||||
for (const [key, checkbox] of Object.entries(this.boxes) as [Switch, Checkbox][])
|
||||
checkbox.setChecked(this.settings[key]);
|
||||
this.sync();
|
||||
}
|
||||
|
||||
/** Whether "Import after conversion" can be changed (test hook). */
|
||||
get adoptEnabled(): boolean {
|
||||
return this.boxes.adopt.enabled;
|
||||
}
|
||||
|
||||
/** The line under the pickers, which says the size the recording comes out at (test hook). */
|
||||
get sizeText(): string {
|
||||
return this.size.text;
|
||||
}
|
||||
|
||||
private start(onStart: (settings: EditorRecordingSettings) => void): void {
|
||||
const settings = this.values();
|
||||
this.close();
|
||||
onStart(settings);
|
||||
}
|
||||
|
||||
private pickResolution(): void {
|
||||
new Menu(
|
||||
EDITOR_RECORDING_RESOLUTIONS.map((r) => ({
|
||||
label: r.label,
|
||||
current: r.value === this.settings.resolution,
|
||||
onSelect: () => this.choose({ resolution: r.value }),
|
||||
})),
|
||||
).openBelow(this.resolutionPicker);
|
||||
}
|
||||
|
||||
private pickFps(): void {
|
||||
new Menu(
|
||||
FPS_CHOICES.map((fps) => ({
|
||||
label: String(fps),
|
||||
current: fps === this.settings.fps,
|
||||
onSelect: () => this.choose({ fps }),
|
||||
})),
|
||||
).openBelow(this.fpsPicker);
|
||||
}
|
||||
|
||||
/** Import goes with Convert: without an MP4 there is nothing a project could take. */
|
||||
private sync(): void {
|
||||
const { resolution, fps, convert } = this.settings;
|
||||
this.resolutionPicker.setText(labelOf(resolution));
|
||||
this.fpsPicker.setText(String(fps));
|
||||
const { app } = ui();
|
||||
const { size } = editorRecordingPlan(
|
||||
{ w: app.screen.width, h: app.screen.height },
|
||||
app.renderer.resolution,
|
||||
resolution,
|
||||
);
|
||||
this.size.setText(`${size.w} × ${size.h} at ${fps} fps, from this window`);
|
||||
this.boxes.adopt.setEnabled(convert);
|
||||
this.refreshLayout();
|
||||
}
|
||||
}
|
||||
|
||||
function labelOf(resolution: EditorRecordingResolution): string {
|
||||
return EDITOR_RECORDING_RESOLUTIONS.find((r) => r.value === resolution)?.label ?? resolution;
|
||||
}
|
||||
@@ -252,6 +252,8 @@ export abstract class FilePicker<Item extends PickerItem> extends Popup {
|
||||
private readonly words: PickerWords,
|
||||
upload: () => void,
|
||||
private readonly deleteFile: (file: string) => Promise<void>,
|
||||
/** Buttons of a kind of picker of its own, after Delete; `picked` says what is picked. */
|
||||
protected readonly extras: readonly Button[] = [],
|
||||
) {
|
||||
super({ modal: true, padding: Theme.padding * 2, gap: Theme.gap });
|
||||
this.content.add(new Label(words.title, { style: 'bodyBold' }));
|
||||
@@ -278,7 +280,7 @@ export abstract class FilePicker<Item extends PickerItem> extends Popup {
|
||||
this.remove = new Button('Delete', { variant: 'danger' });
|
||||
this.remove.onClick = () => void this.pressDelete();
|
||||
this.remove.setEnabled(false);
|
||||
this.buttons = dialogButtons(this.closeThen(), this.use, [uploadButton, this.remove]);
|
||||
this.buttons = dialogButtons(this.closeThen(), this.use, [uploadButton, this.remove, ...extras]);
|
||||
this.content.add(this.buttons);
|
||||
}
|
||||
|
||||
@@ -350,10 +352,20 @@ export abstract class FilePicker<Item extends PickerItem> extends Popup {
|
||||
this.setDeleteLabel('Delete');
|
||||
this.use.setEnabled(item !== null && this.canUse(item));
|
||||
this.remove.setEnabled(item?.deletable ?? false);
|
||||
this.picked(item);
|
||||
this.detail.setText(item ? this.describe(item) : (this.words.idle ?? ''));
|
||||
this.refreshLayout();
|
||||
}
|
||||
|
||||
/** Says the `extras` what is picked now, null for nothing. */
|
||||
protected picked(_item: Item | null): void {}
|
||||
|
||||
/** Shows a line under the list instead of what is picked, until the pick changes. */
|
||||
protected say(text: string): void {
|
||||
this.detail.setText(text);
|
||||
this.refreshLayout();
|
||||
}
|
||||
|
||||
/** A button does not measure itself again on a new text; the row around it has to (see `Button.setText`). */
|
||||
private setDeleteLabel(label: string): void {
|
||||
this.remove.setText(label);
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { VideoClip } from '../../core/model/Asset';
|
||||
import { findAssetOf } from '../../core/model/Project';
|
||||
import { clipsOf } from '../../core/model/sound';
|
||||
import { videoLibrary } from '../../viewport/VideoLibrary';
|
||||
import type { EditorRecordingDialog } from '../EditorRecordingDialog';
|
||||
import { currentVideoPicker } from '../video/VideoPicker';
|
||||
import { centreOf, type HookContext } from './hookHelpers';
|
||||
|
||||
@@ -31,15 +32,41 @@ export function videoHooks({ state, editor }: HookContext) {
|
||||
rulerAt: (seconds: number) => videoEditor.canvas.rulerAt(seconds),
|
||||
/** The time's zoom, and whether a transition is on its way. */
|
||||
zoom: () => videoEditor.canvas.zoomInfo(),
|
||||
downloadButton: () => centreOf(videoEditor.downloadButton),
|
||||
/** Where the last Download went and under which name. */
|
||||
lastDownload: () => videoEditor.lastDownload,
|
||||
},
|
||||
videoPicker: () => {
|
||||
const picker = currentVideoPicker();
|
||||
return picker ? { ...picker.debugInfo(), waiting: picker.waitingFor } : null;
|
||||
return picker
|
||||
? {
|
||||
...picker.debugInfo(),
|
||||
waiting: picker.waitingFor,
|
||||
extras: picker.extraButtons(),
|
||||
lastDownload: picker.lastDownload,
|
||||
}
|
||||
: null;
|
||||
},
|
||||
videoPickerRow: (file: string) => currentVideoPicker()?.rowGlobal(file) ?? null,
|
||||
/** What each player behind a sprite is doing: its time, whether it runs and is heard. */
|
||||
videos: () => videoLibrary.debugInfo(),
|
||||
/** The recordings of the game view (#405): each take, and its way into the project. */
|
||||
recording: () => editor.recordingInfo(),
|
||||
/** "Start recording…" as it stands, with the centres of its switches and of Start; null while shut. */
|
||||
recordingDialog: () => {
|
||||
const dialog = editor.editorRecordingDialog();
|
||||
if (!dialog) return null;
|
||||
const switches = ['pointer', 'sound', 'convert', 'adopt'] as const;
|
||||
return {
|
||||
values: dialog.values(),
|
||||
size: dialog.sizeText,
|
||||
adoptEnabled: dialog.adoptEnabled,
|
||||
switches: Object.fromEntries(switches.map((key) => [key, centreOf(dialog.switchOf(key))])),
|
||||
start: centreOf(dialog.startButton),
|
||||
};
|
||||
},
|
||||
/** Picks resolution, fps or name in the open "Start recording…" as the menus would. */
|
||||
recordingDialogChoose: (change: Parameters<EditorRecordingDialog['choose']>[0]) =>
|
||||
editor.editorRecordingDialog()?.choose(change),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* The last choice of "Start recording…", kept in this browser like the general settings (#309):
|
||||
* it is about the person recording, not the game. The name is never kept – each recording gets its
|
||||
* own. Best effort: a browser that refuses `localStorage` forgets it with the page.
|
||||
*/
|
||||
import { editorRecordingSettingsOf, type EditorRecordingSettings } from '../core/recording/editorRecording';
|
||||
|
||||
const STORAGE_KEY = 'game-maker.editor-recording';
|
||||
|
||||
let kept: EditorRecordingSettings | null = null;
|
||||
|
||||
function storage(): Pick<Storage, 'getItem' | 'setItem'> | null {
|
||||
try {
|
||||
return typeof window === 'undefined' ? null : window.localStorage;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function editorRecordingSettings(): EditorRecordingSettings {
|
||||
if (!kept) {
|
||||
try {
|
||||
kept = editorRecordingSettingsOf(JSON.parse(storage()?.getItem(STORAGE_KEY) ?? '{}'));
|
||||
} catch {
|
||||
kept = editorRecordingSettingsOf({});
|
||||
}
|
||||
}
|
||||
return { ...kept };
|
||||
}
|
||||
|
||||
export function keepEditorRecordingSettings(settings: EditorRecordingSettings): void {
|
||||
kept = { ...editorRecordingSettingsOf(settings) };
|
||||
try {
|
||||
storage()?.setItem(STORAGE_KEY, JSON.stringify({ ...kept, name: undefined }));
|
||||
} catch {
|
||||
// Kept for this page only.
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
import type { UploadedVideo } from '../core/store/VideoStore';
|
||||
import type { MadeRecording } from '../viewport/RecordingTake';
|
||||
import type { RecordingUploadOptions } from './EditorRecorder';
|
||||
import { adoptVideo, type VideoImportDeps } from './videoImport';
|
||||
|
||||
/** How often the server is asked whether a recording is converted, as the video picker does. */
|
||||
const POLL_MS = 1000;
|
||||
|
||||
type UploadState = 'uploading' | 'converting' | 'added' | 'elsewhere' | 'failed';
|
||||
/** `kept`: uploaded without converting it; `converted`: converted, but not to be imported. */
|
||||
type UploadState = 'uploading' | 'converting' | 'added' | 'kept' | 'converted' | 'elsewhere' | 'failed';
|
||||
|
||||
/** What became of a recording on its way into the project (test hook). */
|
||||
export interface RecordingUpload {
|
||||
@@ -19,16 +21,18 @@ export interface RecordingUpload {
|
||||
}
|
||||
|
||||
/**
|
||||
* Brings a recording of the game view (#405) or of the editor into the project: up to the server, which converts it
|
||||
* like any video, then an asset named after the recording once it is ready. Only while the editor
|
||||
* is not playing: a run plays a copy of the project that is thrown away, and so would the asset be.
|
||||
* Brings a recording of the game view (#405) or of the editor into the project: up to the server,
|
||||
* which converts it like any video, then an asset named after the recording once it is ready. Only
|
||||
* while the editor is not playing: a run plays a copy of the project that is thrown away, and so
|
||||
* would the asset be. An editor recording may stop short of either step ("Start recording…"): it
|
||||
* is always uploaded, and the video picker has it.
|
||||
*/
|
||||
export class RecordingUploads {
|
||||
private readonly uploads: RecordingUpload[] = [];
|
||||
|
||||
constructor(private readonly deps: VideoImportDeps) {}
|
||||
|
||||
add(recording: MadeRecording): void {
|
||||
add(recording: MadeRecording, options: RecordingUploadOptions = { convert: true, adopt: true }): void {
|
||||
const upload: RecordingUpload = {
|
||||
name: recording.name,
|
||||
state: 'uploading',
|
||||
@@ -38,7 +42,7 @@ export class RecordingUploads {
|
||||
error: '',
|
||||
};
|
||||
this.uploads.push(upload);
|
||||
void this.bring(recording, upload).catch((error: unknown) => {
|
||||
void this.bring(recording, upload, options).catch((error: unknown) => {
|
||||
upload.state = 'failed';
|
||||
upload.error = error instanceof Error ? error.message : String(error);
|
||||
this.deps.state.setNotice(`Could not save the recording "${recording.name}": ${upload.error}`, 'error');
|
||||
@@ -49,7 +53,11 @@ export class RecordingUploads {
|
||||
return this.uploads.map((upload) => ({ ...upload }));
|
||||
}
|
||||
|
||||
private async bring(recording: MadeRecording, upload: RecordingUpload): Promise<void> {
|
||||
private async bring(
|
||||
recording: MadeRecording,
|
||||
upload: RecordingUpload,
|
||||
options: RecordingUploadOptions,
|
||||
): Promise<void> {
|
||||
const { state, videos } = this.deps;
|
||||
const projectId = state.project.id;
|
||||
state.setNotice(`Uploading the recording "${recording.name}"…`);
|
||||
@@ -57,14 +65,27 @@ export class RecordingUploads {
|
||||
recording.blob,
|
||||
'application/octet-stream',
|
||||
`${recording.name}.mkv`,
|
||||
{ convert: options.convert },
|
||||
);
|
||||
upload.file = video.file;
|
||||
if (!options.convert) {
|
||||
upload.state = 'kept';
|
||||
state.setNotice(
|
||||
`Uploaded the recording "${recording.name}" without converting it – the video picker has it.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
upload.state = 'converting';
|
||||
while (video.status !== 'ready') {
|
||||
if (video.status === 'failed') throw new Error(video.error ?? 'the server could not convert it');
|
||||
await wait(POLL_MS);
|
||||
video = (await videos.list()).find((v) => v.file === upload.file) ?? video;
|
||||
}
|
||||
if (!options.adopt) {
|
||||
upload.state = 'converted';
|
||||
state.setNotice(`The recording "${recording.name}" is converted – the video picker has it.`);
|
||||
return;
|
||||
}
|
||||
while (state.mode !== 'edit') await wait(POLL_MS);
|
||||
if (state.project.id !== projectId) {
|
||||
upload.state = 'elsewhere';
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { Asset, VideoAsset } from '../../core/model/Asset';
|
||||
import type { VideoStore } from '../../core/store/VideoStore';
|
||||
import { Button, downloadFile } from '../../ui';
|
||||
import { videoFileUrl } from '../../viewport/VideoLibrary';
|
||||
import { AssetTabEditor } from '../AssetTabEditor';
|
||||
@@ -16,10 +17,18 @@ const INFO_WIDTH = 220;
|
||||
export class VideoEditor extends AssetTabEditor<VideoAsset, VideoCanvas> {
|
||||
/** Public for the check scripts. */
|
||||
readonly playButton: Button;
|
||||
/** Saves the MP4 the server made (#405): a recording of the game view is had this way. */
|
||||
/**
|
||||
* Saves the video as it was uploaded (#405): a recording comes out as it was recorded. A video
|
||||
* uploaded before uploads were kept has only its MP4.
|
||||
*/
|
||||
readonly downloadButton: Button;
|
||||
/** Where the last Download went and under which name (test hook). */
|
||||
lastDownload: { href: string; name: string } | null = null;
|
||||
|
||||
constructor(state: EditorState) {
|
||||
constructor(
|
||||
state: EditorState,
|
||||
private readonly videos: VideoStore,
|
||||
) {
|
||||
super(state, { infoWidth: INFO_WIDTH });
|
||||
this.playButton = new Button('Play', {
|
||||
icon: TOOLBAR_ICON_SVG.play,
|
||||
@@ -28,8 +37,8 @@ export class VideoEditor extends AssetTabEditor<VideoAsset, VideoCanvas> {
|
||||
onClick: () => this.togglePlay(),
|
||||
});
|
||||
this.downloadButton = new Button('Download', {
|
||||
tooltip: 'Save the video as an MP4 file',
|
||||
onClick: () => this.download(),
|
||||
tooltip: 'Save the video as it was uploaded',
|
||||
onClick: () => void this.download(),
|
||||
});
|
||||
const canvas = new VideoCanvas(state);
|
||||
canvas.onTogglePlay = () => this.togglePlay();
|
||||
@@ -57,9 +66,21 @@ export class VideoEditor extends AssetTabEditor<VideoAsset, VideoCanvas> {
|
||||
this.syncPlayButton();
|
||||
}
|
||||
|
||||
private download(): void {
|
||||
private async download(): Promise<void> {
|
||||
const asset = this.asset();
|
||||
if (asset?.file) downloadFile(videoFileUrl(asset.file), `${asset.name}.mp4`);
|
||||
if (!asset?.file) return;
|
||||
let original: string | null = null;
|
||||
try {
|
||||
original = (await this.videos.list()).find((v) => v.file === asset.file)?.original ?? null;
|
||||
} catch (error) {
|
||||
this.state.setNotice(
|
||||
`Could not ask the server for the upload, saving the MP4: ${String(error)}`,
|
||||
'error',
|
||||
);
|
||||
}
|
||||
const file = original ?? asset.file;
|
||||
this.lastDownload = { href: videoFileUrl(file), name: `${asset.name}.${file.split('.').pop()}` };
|
||||
downloadFile(this.lastDownload.href, this.lastDownload.name);
|
||||
}
|
||||
|
||||
/** Only called while the tab is visible. */
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Container, Graphics, Sprite, type Text } from 'pixi.js';
|
||||
import type { StoredVideo } from '../../core/store/VideoStore';
|
||||
import { crispText, formatBytes, textStyle, truncate } from '../../ui';
|
||||
import { posterLibrary } from '../../viewport/VideoLibrary';
|
||||
import { Button, crispText, downloadFile, formatBytes, textStyle, truncate } from '../../ui';
|
||||
import { posterLibrary, videoFileUrl } from '../../viewport/VideoLibrary';
|
||||
import { pickFiles } from '../assetImport';
|
||||
import {
|
||||
currentPicker,
|
||||
@@ -84,6 +84,8 @@ class VideoPicker extends FilePicker<VideoItem> {
|
||||
declare protected readonly list: VideoList;
|
||||
private poll: ReturnType<typeof setTimeout> | null = null;
|
||||
private lastItems: VideoItem[] = [];
|
||||
/** Where the last Download went and under which name (test hook). */
|
||||
lastDownload: { href: string; name: string } | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly deps: VideoImportDeps,
|
||||
@@ -95,14 +97,21 @@ class VideoPicker extends FilePicker<VideoItem> {
|
||||
{
|
||||
title: 'Choose a video',
|
||||
loading: 'Loading videos…',
|
||||
idle: 'Videos are converted to MP4 on the server, up to 1080p.',
|
||||
idle: 'Videos are converted to MP4 on the server, up to 4K.',
|
||||
empty: 'No videos on the server yet – upload one.',
|
||||
use: 'Use video',
|
||||
noun: 'video',
|
||||
},
|
||||
() => uploadFromDialog(deps),
|
||||
(file) => deps.videos.delete(file),
|
||||
[
|
||||
new Button('Download', { tooltip: 'Save the video as it was uploaded' }),
|
||||
new Button('Convert', { tooltip: 'Convert it on the server, so a project can use it' }),
|
||||
],
|
||||
);
|
||||
const [download, convert] = this.extras;
|
||||
download!.onClick = () => this.download();
|
||||
convert!.onClick = () => void this.convert();
|
||||
}
|
||||
|
||||
/** Global centre of a row (test hook). */
|
||||
@@ -110,6 +119,49 @@ class VideoPicker extends FilePicker<VideoItem> {
|
||||
return this.list.rowGlobal(file);
|
||||
}
|
||||
|
||||
/** Download and Convert, whether they can be pressed and where (test hook). */
|
||||
extraButtons(): { label: string; enabled: boolean; x: number; y: number }[] {
|
||||
return this.extras.map((button) => {
|
||||
const at = button.getGlobalPosition();
|
||||
return { label: button.text, enabled: button.enabled, x: at.x + button.w / 2, y: at.y + button.h / 2 };
|
||||
});
|
||||
}
|
||||
|
||||
protected override picked(item: VideoItem | null): void {
|
||||
const [download, convert] = this.extras;
|
||||
download!.setEnabled(Boolean(item?.original));
|
||||
convert!.setEnabled(
|
||||
Boolean(item?.original) && (item?.status === 'unconverted' || item?.status === 'failed'),
|
||||
);
|
||||
}
|
||||
|
||||
/** The upload as it came, under the name it came with. */
|
||||
private download(): void {
|
||||
const item = this.list.selected;
|
||||
if (!item?.original) return;
|
||||
const ending = item.original.split('.').pop() ?? 'mp4';
|
||||
const name = item.name || `video.${ending}`;
|
||||
this.lastDownload = { href: videoFileUrl(item.original), name };
|
||||
downloadFile(this.lastDownload.href, name);
|
||||
}
|
||||
|
||||
/** Sends a kept upload to be converted, then watches it on its way like any other. */
|
||||
private async convert(): Promise<void> {
|
||||
const item = this.list.selected;
|
||||
if (!item?.original) return;
|
||||
this.extras[1]!.setEnabled(false);
|
||||
try {
|
||||
await this.deps.videos.convert(item.file);
|
||||
} catch (error) {
|
||||
this.say(`Not converted: ${error instanceof Error ? error.message : String(error)}`);
|
||||
return;
|
||||
}
|
||||
if (this.list.destroyed) return;
|
||||
if (this.poll !== null) clearTimeout(this.poll);
|
||||
this.poll = null;
|
||||
await this.load();
|
||||
}
|
||||
|
||||
/** The uploads it waits for (test hook). */
|
||||
get waitingFor(): string[] {
|
||||
return [...this.waiting];
|
||||
@@ -160,7 +212,8 @@ class VideoPicker extends FilePicker<VideoItem> {
|
||||
}
|
||||
|
||||
protected override describe(item: VideoItem): string {
|
||||
const size = item.status === 'ready' ? ` – ${formatBytes(item.bytes)}` : '';
|
||||
const size =
|
||||
item.status === 'ready' || item.status === 'unconverted' ? ` – ${formatBytes(item.bytes)}` : '';
|
||||
return `${item.name || 'Video'}${size} – ${videoStatusText(item)}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,8 @@ export function videoStatusText(video: UploadedVideo): string {
|
||||
return `Converting… ${Math.round((video.progress ?? 0) * 100)} %`;
|
||||
case 'failed':
|
||||
return `Could not be converted: ${video.error || 'no reason given'}`;
|
||||
case 'unconverted':
|
||||
return 'Not converted – Convert makes it usable';
|
||||
default:
|
||||
return [
|
||||
`${video.width ?? 0} × ${video.height ?? 0}`,
|
||||
|
||||
@@ -127,6 +127,8 @@ export class Take {
|
||||
private readonly source: FrameSource,
|
||||
private readonly host: TakeHost,
|
||||
private readonly gone: () => void,
|
||||
/** `sound: false` records the picture alone. */
|
||||
private readonly options: { sound?: boolean } = {},
|
||||
) {
|
||||
this.gate = new FrameGate(fps);
|
||||
}
|
||||
@@ -179,7 +181,7 @@ export class Take {
|
||||
}
|
||||
if (!config) throw new Error(`this browser cannot encode ${w}x${h} at ${fps} fps`);
|
||||
this.codec = config.codec;
|
||||
await this.openSound();
|
||||
if (this.options.sound !== false) await this.openSound();
|
||||
const writer = new MatroskaWriter(this.audio ? 2 : 1);
|
||||
this.writer = writer;
|
||||
const video = new VideoEncoder({
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { cursorShape } from '../../src/core/recording/cursors';
|
||||
import { editorRecordingPlan, editorRecordingSettingsOf } from '../../src/core/recording/editorRecording';
|
||||
import {
|
||||
avcCodec,
|
||||
editorRecordingSize,
|
||||
@@ -158,6 +159,74 @@ describe('recording the editor', () => {
|
||||
expect(fitPicture({ w: 2560, h: 720 }, { w: 1280, h: 720 })).toEqual({ x: 0, y: 180, w: 1280, h: 360 });
|
||||
});
|
||||
|
||||
it('records the screen as it is, at the resolution it is drawn at', () => {
|
||||
expect(editorRecordingPlan({ w: 1280, h: 685 }, 1.25, 'screen')).toEqual({
|
||||
size: { w: 1600, h: 856 },
|
||||
resolution: 1.25,
|
||||
});
|
||||
});
|
||||
|
||||
it('draws sharper for a larger frame, fitted into it with the window’s shape', () => {
|
||||
expect(editorRecordingPlan({ w: 1920, h: 1080 }, 1, '4k')).toEqual({
|
||||
size: { w: 3840, h: 2160 },
|
||||
resolution: 2,
|
||||
});
|
||||
expect(editorRecordingPlan({ w: 2560, h: 1305 }, 1, '4k')).toEqual({
|
||||
size: { w: 3840, h: 1958 },
|
||||
resolution: 1.5,
|
||||
});
|
||||
expect(editorRecordingPlan({ w: 1280, h: 800 }, 1, '1440p')).toEqual({
|
||||
size: { w: 2304, h: 1440 },
|
||||
resolution: 1.8,
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps the screen’s resolution for a smaller frame, and draws at most four times as fine', () => {
|
||||
expect(editorRecordingPlan({ w: 2560, h: 1440 }, 1, '1080p')).toEqual({
|
||||
size: { w: 1920, h: 1080 },
|
||||
resolution: 1,
|
||||
});
|
||||
expect(editorRecordingPlan({ w: 640, h: 360 }, 1, '4k')).toEqual({
|
||||
size: { w: 3840, h: 2160 },
|
||||
resolution: 4,
|
||||
});
|
||||
});
|
||||
|
||||
it('starts on the defaults, keeps what was chosen and never a name', () => {
|
||||
expect(editorRecordingSettingsOf(null)).toEqual({
|
||||
name: '',
|
||||
resolution: 'screen',
|
||||
fps: 60,
|
||||
pointer: true,
|
||||
sound: true,
|
||||
convert: true,
|
||||
adopt: true,
|
||||
});
|
||||
expect(
|
||||
editorRecordingSettingsOf({
|
||||
name: 'Old',
|
||||
resolution: '4k',
|
||||
fps: 30,
|
||||
pointer: false,
|
||||
sound: false,
|
||||
convert: false,
|
||||
adopt: 'no',
|
||||
}),
|
||||
).toEqual({
|
||||
name: '',
|
||||
resolution: '4k',
|
||||
fps: 30,
|
||||
pointer: false,
|
||||
sound: false,
|
||||
convert: false,
|
||||
adopt: true,
|
||||
});
|
||||
expect(editorRecordingSettingsOf({ resolution: '8k', fps: 25 })).toMatchObject({
|
||||
resolution: 'screen',
|
||||
fps: 60,
|
||||
});
|
||||
});
|
||||
|
||||
it('shows the time it runs in minutes and seconds, hours once there are any', () => {
|
||||
expect(elapsedText(0)).toBe('0:00');
|
||||
expect(elapsedText(7999)).toBe('0:07');
|
||||
|
||||
@@ -226,6 +226,12 @@ describe('what the picker says about a video', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('says what to do with an upload kept without converting it, which waits for nobody', () => {
|
||||
const kept = { file: FILE, name: 'a.mkv', bytes: 10, status: 'unconverted' as const };
|
||||
expect(videoStatusText(kept)).toBe('Not converted – Convert makes it usable');
|
||||
expect(isPending(kept)).toBe(false);
|
||||
});
|
||||
|
||||
it('writes a length as long as it needs', () => {
|
||||
expect([formatDuration(4), formatDuration(59.94), formatDuration(65), formatDuration(3723)]).toEqual([
|
||||
'4 s',
|
||||
|
||||
+33
-12
@@ -38,13 +38,14 @@ function stream(string $type, array $extra = []): array
|
||||
}
|
||||
|
||||
// The rules, without ffmpeg.
|
||||
check('4K fits into 1080p', VideoFormat::fit(3840, 2160) === [1920, 1080], VideoFormat::fit(3840, 2160));
|
||||
check('a standing 4K fits standing up', VideoFormat::fit(2160, 3840) === [1080, 1920], VideoFormat::fit(2160, 3840));
|
||||
check('4:3 is bound by its height', VideoFormat::fit(4000, 3000) === [1440, 1080], VideoFormat::fit(4000, 3000));
|
||||
check('1080p stays', VideoFormat::fit(1920, 1080) === [1920, 1080]);
|
||||
check('8K fits into 4K', VideoFormat::fit(7680, 4320) === [3840, 2160], VideoFormat::fit(7680, 4320));
|
||||
check('a standing 8K fits standing up', VideoFormat::fit(4320, 7680) === [2160, 3840], VideoFormat::fit(4320, 7680));
|
||||
check('4:3 is bound by its height', VideoFormat::fit(4000, 3000) === [2880, 2160], VideoFormat::fit(4000, 3000));
|
||||
check('4K stays', VideoFormat::fit(3840, 2160) === [3840, 2160]);
|
||||
check('so does an editor recorded at 4K in a wider window', VideoFormat::fit(3840, 1958) === [3840, 1958]);
|
||||
check('a small one is not made larger', VideoFormat::fit(640, 360) === [640, 360]);
|
||||
check('odd sides become even, never larger', VideoFormat::fit(641, 361) === [640, 360], VideoFormat::fit(641, 361));
|
||||
check('an ultra-wide one keeps its shape', VideoFormat::fit(5120, 1440) === [1920, 540], VideoFormat::fit(5120, 1440));
|
||||
check('an ultra-wide one keeps its shape', VideoFormat::fit(10240, 2880) === [3840, 1080], VideoFormat::fit(10240, 2880));
|
||||
|
||||
$phone = [
|
||||
'streams' => [
|
||||
@@ -101,12 +102,14 @@ $hash = hash('sha256', $fake);
|
||||
$record = $store->store($fake, 'holiday.mov', $folder);
|
||||
check('an upload is named after its bytes, before it is converted', $record['file'] === "{$folder}/{$hash}.mp4", $record);
|
||||
check('and waits', $record['status'] === 'queued' && $record['name'] === 'holiday.mov', $record);
|
||||
check('the upload is hidden from the web server', (fileperms($store->queue()->source($folder, $hash)) & 0777) === 0640);
|
||||
check('the upload is kept as it came, named after its bytes and its name', $record['original'] === "{$folder}/{$hash}.source.mov", $record);
|
||||
check('it is what the worker reads', $store->queue()->source($folder, $hash) === "{$data}/videos/{$record['original']}");
|
||||
check('and is served, for downloading it', (fileperms("{$data}/videos/{$record['original']}") & 0777) === 0664);
|
||||
check('it is there for the picker', array_column($store->list($folder, false, [$folder => 'ann']), 'status') === ['queued']);
|
||||
check('but not for another account', $store->list('ffffffffffff', false, []) === []);
|
||||
check('an administrator sees it with its owner', $store->list('', true, [$folder => 'ann'])[0]['owner'] === 'ann');
|
||||
check('it counts as there for deleting', $store->exists("{$folder}/{$hash}.mp4"));
|
||||
check('deleting it drops the job and the upload', $store->delete("{$folder}/{$hash}.mp4") && $store->queue()->jobs() === [] && !is_file($store->queue()->source($folder, $hash)));
|
||||
check('deleting it drops the job and the upload', $store->delete("{$folder}/{$hash}.mp4") && $store->queue()->jobs() === [] && !is_file("{$data}/videos/{$record['original']}"));
|
||||
check('and its name', !is_file("{$data}/videos/{$folder}/{$hash}.mp4.json"));
|
||||
|
||||
$store->store($fake, 'holiday.mov', $folder);
|
||||
@@ -132,7 +135,7 @@ $streamed = $fake . 'streamed';
|
||||
check('one byte over the ceiling is turned away', $tooLarge($streamed, strlen($streamed) - 1));
|
||||
$record = $store->storeStream($streamOf($streamed), strlen($streamed), 'streamed.mp4', $folder);
|
||||
check('right at the ceiling it is taken, named after its bytes', $record['file'] === "{$folder}/" . hash('sha256', $streamed) . '.mp4' && $record['status'] === 'queued', $record);
|
||||
check('the streamed upload is hidden as well', (fileperms($store->queue()->source($folder, hash('sha256', $streamed))) & 0777) === 0640);
|
||||
check('the streamed upload is kept as well, with the ending of its name', $record['original'] === "{$folder}/" . hash('sha256', $streamed) . '.source.mp4', $record);
|
||||
check('text from a stream is turned away too', $rejected(str_repeat('hello ', 10)));
|
||||
check('no received upload is left lying around', glob("{$data}/videos/queue/upload-*") === []);
|
||||
$store->delete($record['file']);
|
||||
@@ -149,7 +152,7 @@ $worker = new VideoWorker($store, "{$data}/videos");
|
||||
check('the worker takes the oldest job', $worker->runOnce());
|
||||
$broken = $store->record("{$folder}/{$hash}.mp4");
|
||||
check('bytes ffmpeg cannot read fail the job, with its words', $broken['status'] === 'failed' && str_starts_with($broken['error'], 'ffmpeg cannot read this file'), $broken);
|
||||
check('the upload goes, the job stays to say why', !is_file($store->queue()->source($folder, $hash)) && $store->queue()->job($folder, $hash) !== null);
|
||||
check('the upload stays for downloading, the job stays to say why', is_file("{$data}/videos/{$folder}/{$hash}.source.mov") && $store->queue()->job($folder, $hash) !== null);
|
||||
check('nothing is left half written', glob("{$data}/videos/{$folder}/*.tmp.*") === []);
|
||||
check('nothing waits any more', $worker->runOnce() === false);
|
||||
|
||||
@@ -178,12 +181,12 @@ echo sprintf(" (converted in %.1f s)\n", microtime(true) - $started);
|
||||
|
||||
$done = $store->record($big['file']);
|
||||
check('a converted video is ready', $done['status'] === 'ready', $done);
|
||||
check('4K came out as 1080p', [$done['width'], $done['height']] === [1920, 1080], $done);
|
||||
check('4K stays 4K', [$done['width'], $done['height']] === [3840, 2160], $done);
|
||||
check('it says its length and frame rate', abs($done['duration'] - 1.2) < 0.05 && $done['fps'] === 25.0, $done);
|
||||
check('and that it has sound', $done['audio'] === true);
|
||||
check('its poster lies beside it, named like the file', $done['poster'] === substr($big['file'], 0, -4) . '.jpg' && is_file("{$data}/videos/{$done['poster']}"), $done);
|
||||
check('both are served as they are', (fileperms("{$data}/videos/{$big['file']}") & 0777) === 0664 && (fileperms("{$data}/videos/{$done['poster']}") & 0777) === 0664);
|
||||
check('the job and the upload are gone', $store->queue()->job($folder, basename($big['file'], '.mp4')) === null && !is_file($store->queue()->source($folder, basename($big['file'], '.mp4'))));
|
||||
check('the job is gone, the upload stays as it came', $store->queue()->job($folder, basename($big['file'], '.mp4')) === null && $done['original'] === substr($big['file'], 0, -4) . '.source.mov' && file_get_contents("{$data}/videos/{$done['original']}") === file_get_contents("{$tmp}/big.mov"), $done);
|
||||
|
||||
$probe = json_decode((string) shell_exec('ffprobe -v error -print_format json -show_streams ' . escapeshellarg("{$data}/videos/{$big['file']}")), true);
|
||||
$codecs = array_column($probe['streams'], 'codec_name');
|
||||
@@ -208,7 +211,25 @@ check('the picker lists ready and failed ones', $listed[$big['file']]['status']
|
||||
$fakeAgain = $store->store($fake, 'holiday.mov', $folder);
|
||||
check('a failed upload sent again is tried again', $fakeAgain['status'] === 'queued', $fakeAgain);
|
||||
|
||||
check('deleting a converted video takes poster and details with it', $store->delete($big['file'])
|
||||
// An upload kept without being converted, converted later.
|
||||
$kept = $store->store((string) file_get_contents("{$tmp}/small.mov"), 'kept.mkv', $folder, false);
|
||||
check('without converting the upload is the converted file it already is', $kept['status'] === 'ready', $kept);
|
||||
makeVideo("{$tmp}/later.mov", '320x180', 30, 0.5, false);
|
||||
$later = $store->store((string) file_get_contents("{$tmp}/later.mov"), 'later.mkv', $folder, false);
|
||||
$laterHash = basename($later['file'], '.mp4');
|
||||
check('a new upload without converting is only kept', $later['status'] === 'unconverted' && $later['original'] === "{$folder}/{$laterHash}.source.mkv" && $later['bytes'] === filesize("{$tmp}/later.mov"), $later);
|
||||
check('no job waits for it', $store->queue()->job($folder, $laterHash) === null && $worker->runOnce() === true && $store->record($later['file'])['status'] === 'unconverted');
|
||||
$listed = array_column($store->list($folder, false, [$folder => 'ann']), null, 'file');
|
||||
check('the picker lists it once, as not converted, with its owner', ($listed[$later['file']]['status'] ?? '') === 'unconverted' && $listed[$later['file']]['owner'] === 'ann' && $listed[$later['file']]['deletable'] === true, $listed[$later['file']] ?? null);
|
||||
check('but not for another account', !in_array($later['file'], array_column($store->list('ffffffffffff', false, []), 'file'), true));
|
||||
check('it counts as there for deleting', $store->exists($later['file']));
|
||||
$asked = $store->convert($later['file']);
|
||||
check('asked to, it is queued, under its name', $asked['status'] === 'queued' && $store->queue()->job($folder, $laterHash)['name'] === 'later.mkv', $asked);
|
||||
check('asking again queues it once', $store->convert($later['file'])['status'] === 'queued' && count(array_filter($store->queue()->jobs(), static fn(array $j): bool => $j['hash'] === $laterHash)) === 1);
|
||||
check('the worker converts it from the kept upload', $worker->runOnce() && $store->record($later['file'])['status'] === 'ready' && $store->record($later['file'])['original'] === $later['original']);
|
||||
check('a video not there cannot be converted', $store->convert("{$folder}/" . str_repeat('0', 64) . '.mp4') === null && $store->convert('../x.mp4') === null);
|
||||
|
||||
check('deleting a converted video takes poster, details and the upload with it', $store->delete($big['file'])
|
||||
&& glob("{$data}/videos/{$folder}/" . basename($big['file'], '.mp4') . '*') === []);
|
||||
check('deleting a file that is not there says so', $store->delete($big['file']) === false);
|
||||
check('a path out of the store is no file to delete', $store->delete('../queue/x.mp4') === false);
|
||||
|
||||
@@ -61,7 +61,7 @@ export async function topbar(t) {
|
||||
'Master routing',
|
||||
'Clear saved data',
|
||||
null,
|
||||
'Start recording',
|
||||
'Start recording…',
|
||||
null,
|
||||
'General settings…',
|
||||
'Plugins',
|
||||
|
||||
+122
-6
@@ -1,4 +1,4 @@
|
||||
import { MAKE_OBJECT } from './lib/scaffold.mjs';
|
||||
import { MAKE_OBJECT, pickAssetType } from './lib/scaffold.mjs';
|
||||
|
||||
/**
|
||||
* Recording the game view (#405). A behavior starts a recording at 1080p and 30 fps when the run
|
||||
@@ -177,10 +177,30 @@ export async function recording(t) {
|
||||
// 67e. The editor records itself from the main menu: the whole canvas at 60 fps, the mouse pointer
|
||||
// drawn in where the system draws it over the canvas, and the red dot beside the menu on
|
||||
// screen only. The frame is read where the pointer rested on the empty middle of the top bar.
|
||||
const { mouse, cdp, clickToolbar, clickText } = t;
|
||||
const { mouse, cdp, click, clickToolbar, clickText } = t;
|
||||
// Downloads are caught rather than saved: what counts is which file and under which name.
|
||||
await evaluate(`window.__downloads = [];
|
||||
HTMLAnchorElement.prototype.click = function () { window.__downloads.push({ name: this.download, href: this.href }); };`);
|
||||
const startDialog = async (change) => {
|
||||
await clickToolbar('menu');
|
||||
const idle = await json('__gm.menuRows()');
|
||||
await clickText('Start recording');
|
||||
const rows = await json('__gm.menuRows()');
|
||||
await clickText('Start recording…');
|
||||
await waitUntil('__gm.recordingDialog() !== null', { label: 'the recording dialog opens' });
|
||||
await evaluate(`__gm.recordingDialogChoose(${JSON.stringify(change)})`);
|
||||
return rows;
|
||||
};
|
||||
const DEFAULTS = {
|
||||
name: '',
|
||||
resolution: 'screen',
|
||||
fps: 60,
|
||||
pointer: true,
|
||||
sound: true,
|
||||
convert: true,
|
||||
adopt: true,
|
||||
};
|
||||
const idle = await startDialog(DEFAULTS);
|
||||
const start = (await json('__gm.recordingDialog()')).start;
|
||||
await click(start.x, start.y);
|
||||
await waitUntil(`__gm.recording().editor.takes[0]?.state === 'recording'`, { label: 'the editor records' });
|
||||
const redo = await json('__gm.toolbarAt("redo")');
|
||||
const playAt = await json('__gm.toolbarAt("play")');
|
||||
@@ -289,8 +309,8 @@ export async function recording(t) {
|
||||
}).length
|
||||
: -1;
|
||||
check(
|
||||
'Start recording in the main menu records the whole editor at 60 fps with the pointer drawn in, the red dot on screen only, and Stop recording saves it',
|
||||
idle.includes('Start recording') &&
|
||||
'Start recording… in the main menu records the whole editor at 60 fps with the pointer drawn in, the red dot on screen only, and Stop recording saves it',
|
||||
idle.includes('Start recording…') &&
|
||||
busy.includes('Stop recording') &&
|
||||
take.width === canvas.w - (canvas.w % 2) &&
|
||||
take.height === canvas.h - (canvas.h % 2) &&
|
||||
@@ -327,6 +347,102 @@ export async function recording(t) {
|
||||
}),
|
||||
);
|
||||
|
||||
// 67e-ii. The video tab's Download saves the recording as it was recorded – the Matroska file the
|
||||
// editor uploaded, kept beside the MP4 the server made of it.
|
||||
const firstBytes = (href) =>
|
||||
evaluate(
|
||||
`fetch(${JSON.stringify(href)}).then((r) => r.arrayBuffer()).then((b) => [...new Uint8Array(b.slice(0, 4))].map((v) => v.toString(16).padStart(2, '0')).join(''))`,
|
||||
);
|
||||
await evaluate(`__gm.openDocument(${JSON.stringify(`asset:${upload.assetId}`)})`);
|
||||
await waitUntil(`__gm.videoTab.current() === ${JSON.stringify(upload.assetId)}`, {
|
||||
label: 'the recording opens in the video tab',
|
||||
});
|
||||
const downloadAt = await json('__gm.videoTab.downloadButton()');
|
||||
await click(downloadAt.x, downloadAt.y);
|
||||
await waitUntil('__gm.videoTab.lastDownload() !== null', { label: 'the video tab downloads' });
|
||||
const tabDownload = await json('__gm.videoTab.lastDownload()');
|
||||
const tabHead = await firstBytes(tabDownload.href);
|
||||
check(
|
||||
"the video tab's Download saves the recording as it was recorded, not the MP4",
|
||||
tabDownload.href === `/game-maker/data/videos/${file.replace(/\.mp4$/, '.source.mkv')}` &&
|
||||
tabDownload.name === `${take.name}.mkv` &&
|
||||
(await json('window.__downloads')).some((d) => d.name === tabDownload.name) &&
|
||||
tabHead === '1a45dfa3',
|
||||
JSON.stringify({ tabDownload, tabHead, file }),
|
||||
);
|
||||
|
||||
// 67f. "Start recording…" with its options. 1440p from the 1280×800 window is drawn sharper while
|
||||
// it records (resolution 1.8) rather than scaled up, here at 30 fps without sound. Without
|
||||
// Convert, Import goes grey, the file is only kept on the server and nothing comes into the
|
||||
// project. The video picker downloads it as it is, and converts it on asking at its full size,
|
||||
// above the 1080p the server used to shrink every video to.
|
||||
const assetsBefore = await json('__gm.state.project.assets.length');
|
||||
await startDialog({ resolution: '1440p', fps: 30, pointer: false, sound: false });
|
||||
const convertAt = (await json('__gm.recordingDialog()')).switches.convert;
|
||||
await click(convertAt.x, convertAt.y);
|
||||
const asked = await json('__gm.recordingDialog()');
|
||||
await click(asked.start.x, asked.start.y);
|
||||
await waitUntil(`__gm.recording().editor.takes[1]?.state === 'recording'`, {
|
||||
label: 'the second editor take records',
|
||||
});
|
||||
const raised = (await json('__gm.recording().editor')).resolution;
|
||||
await sleep(1000);
|
||||
await clickToolbar('menu');
|
||||
await clickText('Stop recording');
|
||||
await waitUntil(`__gm.recording().editor.takes[1]?.state === 'done'`, {
|
||||
label: 'the second editor take is saved',
|
||||
});
|
||||
const sharp = (await json('__gm.recording().editor')).takes[1];
|
||||
const back = (await json('__gm.recording().editor')).resolution;
|
||||
await waitUntil(
|
||||
`__gm.recording().uploads.some((u) => u.name === ${JSON.stringify(sharp.name)} && (u.state === 'kept' || u.state === 'failed'))`,
|
||||
{ timeout: 60_000, label: 'the second editor recording is uploaded' },
|
||||
);
|
||||
const kept = (await recordings()).uploads.find((u) => u.name === sharp.name);
|
||||
await showTab('scene');
|
||||
await clickText('+');
|
||||
await pickAssetType(t, 'Video');
|
||||
await waitUntil(`__gm.videoPicker()?.files.includes(${JSON.stringify(kept.file)})`, {
|
||||
label: 'the picker lists the kept recording',
|
||||
});
|
||||
const keptRow = await json(`__gm.videoPickerRow(${JSON.stringify(kept.file)})`);
|
||||
await click(keptRow.x, keptRow.y);
|
||||
const keptPick = await json('__gm.videoPicker()');
|
||||
const [pickerDownload, pickerConvert] = keptPick.extras;
|
||||
await click(pickerDownload.x, pickerDownload.y);
|
||||
const pickerSaved = (await json('__gm.videoPicker()')).lastDownload;
|
||||
const pickerHead = pickerSaved ? await firstBytes(pickerSaved.href) : '';
|
||||
await click(pickerConvert.x, pickerConvert.y);
|
||||
await waitUntil(`__gm.videoPicker()?.detail.includes('2304 × 1440')`, {
|
||||
timeout: 60_000,
|
||||
label: 'the kept recording is converted on asking',
|
||||
});
|
||||
const converted = await json('__gm.videoPicker()');
|
||||
await press('Escape');
|
||||
check(
|
||||
'Start recording… records 1440p sharper at 30 fps without sound; without Convert it is only kept, the picker downloads it as it is and converts it on asking',
|
||||
asked.adoptEnabled === false &&
|
||||
asked.values.convert === false &&
|
||||
asked.size === '2304 × 1440 at 30 fps, from this window' &&
|
||||
raised === 1.8 &&
|
||||
back === 1 &&
|
||||
sharp.width === 2304 &&
|
||||
sharp.height === 1440 &&
|
||||
sharp.fps === 30 &&
|
||||
sharp.sound === false &&
|
||||
kept.state === 'kept' &&
|
||||
keptPick.detail.includes('Not converted') &&
|
||||
pickerDownload.enabled &&
|
||||
pickerConvert.enabled &&
|
||||
pickerSaved?.name === `${sharp.name}.mkv` &&
|
||||
pickerSaved.href === `/game-maker/data/videos/${kept.file.replace(/\.mp4$/, '.source.mkv')}` &&
|
||||
pickerHead === '1a45dfa3' &&
|
||||
converted.detail.includes('2304 × 1440') &&
|
||||
converted.extras[1].enabled === false &&
|
||||
(await json('__gm.state.project.assets.length')) === assetsBefore,
|
||||
JSON.stringify({ asked, raised, back, sharp, kept, keptPick, pickerSaved, pickerHead, converted }),
|
||||
);
|
||||
|
||||
await mutate(`
|
||||
const p = __gm.state.project;
|
||||
const made = ${JSON.stringify([...assets.map((a) => a.id), upload.assetId])};
|
||||
|
||||
Reference in new issue
Block a user