feat(media): shade live record — a broadcast to files, or to a sealed film with its own link

`live record <link> [-o base] [--put --server URL]` writes what a channel
carries until the channel ends or Ctrl-C:
- text goes to base.txt;
- video and sound go to base.webm or base.mp4: the init, then every chunk in
  the order sent. A chunk that arrives late is left out and counted. A new
  init continues in base-2.…;
- pictures go to base-images/.

ffmpeg then rewrites each recording with -c copy, which adds an index for
seeking and starts the clock at 0:00. `--put` seals and uploads the recording
under the channel's name (several files become an album). LiveRecorder is
exported from @shade/media/node.

`live video` now sends a sticky meta frame like text and picture channels do.
The browser and Android players ignore it.

Verified against a real relay:
- A 30 s VP8/Opus broadcast was recorded and is 29–32 s long, starting at 0.
- It was uploaded as "Kveldssending.webm" and plays in Chromium, with a seek
  to 22 s (frame 14).
- Live playback with the meta frame still plays, with 2.4 s latency.

Tests:
- object-store's memory test now runs in its own process. RSS is process-wide,
  and other test files in the same `bun test` made it flaky (192 MiB). It now
  compares memory held after a collection at 128 MiB and 512 MiB, ~85 vs
  ~103 MiB, instead of using a magic number.
- The sweep test has its own prefix.
- tests/live-record.test.ts (4).
- media 122 green, 3 runs in a row. All 27 packages type-check.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-10-19 00:01:55 +02:00
parent ee93dee8db
commit 5cc9133b3c
10 changed files with 462 additions and 26 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 165 KiB

View File

@@ -11,3 +11,4 @@
11 — Live-radio uten bilde (Opus/WebM og AAC/fMP4): spilleren får strømmens ekte type fra init-segmentet og blir en lydspiller, ikke en svart videoboks; lyd målt i Chromium (RMS 0,044) 11 — Live-radio uten bilde (Opus/WebM og AAC/fMP4): spilleren får strømmens ekte type fra init-segmentet og blir en lydspiller, ikke en svart videoboks; lyd målt i Chromium (RMS 0,044)
12 — Bilder live: ffmpeg-«webkamera» (MJPEG, 2 bilder/s) → shade live images → nettleser; hvert bilde er en keyframe, så en sen seer åpner på det siste. Også lysbildeserie og overvåket mappe 12 — Bilder live: ffmpeg-«webkamera» (MJPEG, 2 bilder/s) → shade live images → nettleser; hvert bilde er en keyframe, så en sen seer åpner på det siste. Også lysbildeserie og overvåket mappe
13 — shade live video --input film.webm: CLI-en kjører ffmpeg selv, VP9/Opus kodes til H.264/AAC med keyframe hvert 2. s, live i Chromium med 0,96 s forsinkelse (H.264/AAC-kilder kopieres uten omkoding) 13 — shade live video --input film.webm: CLI-en kjører ffmpeg selv, VP9/Opus kodes til H.264/AAC med keyframe hvert 2. s, live i Chromium med 0,96 s forsinkelse (H.264/AAC-kilder kopieres uten omkoding)
14 — Et live-opptak («shade live record --put») spilles av som forseglet film: 30 s sending, opptatt, ryddet med ffmpeg -c copy, forseglet og lastet opp under kanalens navn; spolt til 22 s

View File

@@ -78,6 +78,11 @@ New package **`@shade/media`** — see `docs/media.md`.
media id (sealed copy and job under `$XDG_CONFIG_HOME/shade/media-pending/`), media id (sealed copy and job under `$XDG_CONFIG_HOME/shade/media-pending/`),
and a file already up gives its link again instead of a second copy. Above all, a relay's and a file already up gives its link again instead of a second copy. Above all, a relay's
memory no longer grows with the film (see Fixed). memory no longer grows with the film (see Fixed).
- **`shade live record <link>`**: a channel to files until it ends: text,
seekable WebM/MP4 (ffmpeg `-c copy`, clock from 0:00), pictures. `--put`
seals and uploads the recording under the channel's name, so a broadcast
can be watched later (`LiveRecorder` in `@shade/media/node`). `live
video` now sends its name as a sticky `meta` frame like the other kinds.
- **`shade live video --input`** a film, `/dev/video0` or `rtsp://…`: ffmpeg is - **`shade live video --input`** a film, `/dev/video0` or `rtsp://…`: ffmpeg is
run for you, H.264/AAC copied (a camera's own encoder) and anything else run for you, H.264/AAC copied (a camera's own encoder) and anything else
encoded to H.264 (keyframe every 2 s) and AAC, as low-latency fMP4. encoded to H.264 (keyframe every 2 s) and AAC, as low-latency fMP4.

View File

@@ -64,6 +64,9 @@ ffmpeg -f v4l2 -i /dev/video0 -r 1 -c:v mjpeg -f image2pipe - \
# … a slideshow, or every new picture that lands in a folder. # … a slideshow, or every new picture that lands in a folder.
shade live images Ferie/ --every 5 --server https://relay.example shade live images Ferie/ --every 5 --server https://relay.example
shade live images --watch ~/Pictures/Screenshots --server https://relay.example shade live images --watch ~/Pictures/Screenshots --server https://relay.example
# Record a channel until it ends, and keep it as a sealed film with its own link.
shade live record '<link>' -o Kveldssending --put --server https://relay.example
``` ```
`shade live video` recognises the container from the first bytes (`--format webm|fmp4` `shade live video` recognises the container from the first bytes (`--format webm|fmp4`
@@ -76,6 +79,16 @@ their markers and chunks (a JPEG's EXIF thumbnail is a whole JPEG and does not e
picture). Each picture is a keyframe, so a late viewer opens on the latest. A watched picture). Each picture is a keyframe, so a late viewer opens on the latest. A watched
folder sends a file once its size has held still, because cameras write in pieces. folder sends a file once its size has held still, because cameras write in pieces.
`shade live record` writes what the channel carries: text to `base.txt`, video or
sound to `base.webm`/`base.mp4` (the init segment, then every chunk, in the order they
were sent; a chunk that arrives after newer ones is left out and counted), pictures
to `base-images/`. If the publisher starts over with a different init, the recording
goes on in `base-2.…`. When the channel ends (or on Ctrl-C), ffmpeg, if present,
rewrites each recording without re-encoding: an index for seeking, the clock from
0:00. `--put` then seals and uploads it like `media put`, under the channel's name; a
recording of several files becomes an album. Every channel kind now sends its name as
a sticky `meta` frame, so a viewer without the grant's meta learns it too.
`--channel <file>` keeps a live channel's identity across restarts: the link keeps `--channel <file>` keeps a live channel's identity across restarts: the link keeps
working, and each run starts a new epoch. working, and each run starts a new epoch.

View File

@@ -10,6 +10,7 @@
* ffmpeg … -f webm - | shade live video --server URL --name "Camera" (or fragmented MP4) * ffmpeg … -f webm - | shade live video --server URL --name "Camera" (or fragmented MP4)
* shade live images --server URL … pictures: piped JPEG/PNG, a slideshow, a watched folder * shade live images --server URL … pictures: piped JPEG/PNG, a slideshow, a watched folder
* shade live watch <link> a live text channel in the terminal * shade live watch <link> a live text channel in the terminal
* shade live record <link> --put a broadcast, to watch later
* *
* The owner key (who may upload and delete) is created on first use under * The owner key (who may upload and delete) is created on first use under
* `$XDG_CONFIG_HOME/shade/` and reused; nothing to configure. * `$XDG_CONFIG_HOME/shade/` and reused; nothing to configure.
@@ -27,6 +28,7 @@ import { encodeGrant, fromCapabilityUrl, toCapabilityUrl } from './grant.js';
import type { Grant, MediaGrant } from './grant.js'; import type { Grant, MediaGrant } from './grant.js';
import { LivePublisher } from './live/channel.js'; import { LivePublisher } from './live/channel.js';
import { LivePublishClient, LiveWatchClient } from './live/client.js'; import { LivePublishClient, LiveWatchClient } from './live/client.js';
import { LiveRecorder } from './live/record.js';
import { sealFile } from './node.js'; import { sealFile } from './node.js';
import { OwnerKey } from './owner.js'; import { OwnerKey } from './owner.js';
import type { MediaMeta } from './sealed.js'; import type { MediaMeta } from './sealed.js';
@@ -690,6 +692,8 @@ async function liveVideo(flags: Flags, pinned?: LiveContainer): Promise<number>
} }
const meta: MediaMeta = { name: str(flags, 'name') ?? 'Live', mime: str(flags, 'mime') ?? init.mime }; const meta: MediaMeta = { name: str(flags, 'name') ?? 'Live', mime: str(flags, 'mime') ?? init.mime };
const { client } = await startPublishing(flags, meta); const { client } = await startPublishing(flags, meta);
// Like text and picture channels: whoever joins learns what the channel is, grant meta or not.
await client.send({ type: 'meta', meta }, { sticky: true });
let pieces = 0; let pieces = 0;
const send = async (batch: ReturnType<MediaSplitter['push']>) => { const send = async (batch: ReturnType<MediaSplitter['push']>) => {
for (const p of batch) { for (const p of batch) {
@@ -839,6 +843,99 @@ async function liveWatch(pos: string[]): Promise<number> {
return 0; return 0;
} }
/**
* `live record <link> [-o base] [--put --server URL]`: a channel to files
* (see `live/record.ts`) until the publisher ends it or Ctrl-C. Recorded
* video and sound are rewritten by ffmpeg, if it is there, without
* re-encoding: an index for seeking, the clock from 0:00. `--put` seals and
* uploads what was recorded, so the broadcast can be watched later.
*/
async function liveRecord(pos: string[], flags: Flags): Promise<number> {
const link = pos[0];
if (link === undefined) throw new UsageError('usage: shade live record <link> [-o base] [--put --server URL]');
const g = fromCapabilityUrl(link);
if (g.kind !== 'shade.live-grant/v1') throw new UsageError('that link is a sealed file — use `shade media get`');
if (flags.put === true && str(flags, 'server') === undefined && process.env.SHADE_MEDIA_SERVER === undefined) {
throw new UsageError('--put needs --server URL (or SHADE_MEDIA_SERVER): where the recording goes');
}
const stamp = new Date().toISOString().slice(0, 19).replace(/[-:]/g, '').replace('T', '-');
const base = str(flags, 'out') ?? `live-${stamp}`;
await mkdir(dirname(base) === '' ? '.' : dirname(base), { recursive: true });
const rec = new LiveRecorder(base);
let frames = 0;
await new Promise<void>((resolve) => {
const stop = () => {
w.close();
resolve();
};
const w = new LiveWatchClient(g, {
onFrame: (f) => {
if (f.content.type === 'end') {
err('the publisher ended the channel');
stop();
return;
}
frames++;
if (frames === 1) err(`recording to ${base}.* (Ctrl-C to stop)`);
return rec.frame(f);
},
onState: (st) => {
if (st === 'waiting') err('(waiting for the publisher)');
},
onError: (e) => err(`! ${e.message}`),
});
process.once('SIGINT', stop);
process.once('SIGTERM', stop);
});
const stats = await rec.close();
if (stats.late > 0) err(` ${stats.late} frame(s) arrived after newer ones and were left out`);
if (stats.beforeInit > 0) err(` ${stats.beforeInit} chunk(s) came before the stream's start and were skipped`);
if (stats.files.length === 0) {
err('nothing was recorded');
return 1;
}
const paths: string[] = [];
for (const f of stats.files) {
if (f.kind === 'media') await tidyRecording(f.path);
const size = f.kind === 'images' ? `${f.count} pictures` : `${(f.bytes / 1048576).toFixed(1)} MiB`;
err(` ${f.path} (${size})`);
paths.push(f.path);
}
if (flags.put !== true) return 0;
// One recording, one link; video and its log or pictures together, an album.
const named = stats.meta?.name ?? g.meta?.name;
const title = named ?? basename(base);
if (paths.length > 1 || stats.files[0]!.kind === 'images') return mediaPut(paths, { ...flags, album: title });
// A single recording is named after the channel, if it named itself.
const only = stats.files[0]!;
return mediaPut(paths, named !== undefined ? { ...flags, name: `${named}${extname(only.path)}` } : flags);
}
/**
* Rewrite a recorded stream as an ordinary file, without re-encoding: a
* fragmented stream joined mid-way starts at its sender's clock and has no
* index, so players cannot seek in it. Left as it is without ffmpeg.
*/
async function tidyRecording(path: string): Promise<void> {
if (Bun.which('ffmpeg') === null) {
err(` (no ffmpeg: ${basename(path)} plays, but seeking in it may not work)`);
return;
}
const ext = extname(path);
const tmp = `${path.slice(0, -ext.length)}.tidy${ext}`;
const proc = Bun.spawn(
['ffmpeg', '-v', 'error', '-y', '-i', path, '-map', '0', '-c', 'copy', ...(ext === '.mp4' ? ['-movflags', '+faststart'] : []), tmp],
{ stdout: 'ignore', stderr: 'pipe', stdin: 'ignore' },
);
const why = await new Response(proc.stderr).text();
if ((await proc.exited) !== 0) {
await rm(tmp, { force: true });
err(` (ffmpeg could not tidy ${basename(path)}; kept as recorded: ${why.trim().split('\n').at(-1) ?? ''})`);
return;
}
await rename(tmp, path);
}
export const MEDIA_HELP = ` export const MEDIA_HELP = `
media serve [--port 3910] [--dir ./shade-media-data] [--owners k1,k2] [--open] media serve [--port 3910] [--dir ./shade-media-data] [--owners k1,k2] [--open]
[--s3 https://key:secret@host/bucket[/prefix] --pg postgres://… [--advertise URL]] [--s3 https://key:secret@host/bucket[/prefix] --pg postgres://… [--advertise URL]]
@@ -877,6 +974,11 @@ export const MEDIA_HELP = `
ffmpeg -f image2pipe), a slideshow of files, or each ffmpeg -f image2pipe), a slideshow of files, or each
new picture landing in a directory new picture landing in a directory
live watch <link> Follow a live text channel in the terminal live watch <link> Follow a live text channel in the terminal
live record <link> [-o base] [--put --server URL]
Record a channel to files until it ends (or Ctrl-C):
text → base.txt, video/sound → base.webm|mp4 (seekable,
via ffmpeg -c copy), pictures → base-images/.
--put: seal and upload the recording, print its link.
`; `;
/** Entry for `shade media …` / `shade live …`. Returns the exit code. */ /** Entry for `shade media …` / `shade live …`. Returns the exit code. */
@@ -929,6 +1031,8 @@ export async function runMediaCli(group: 'media' | 'live', argv: string[], hooks
return await liveImages(pos, flags); return await liveImages(pos, flags);
case 'watch': case 'watch':
return await liveWatch(pos); return await liveWatch(pos);
case 'record':
return await liveRecord(pos, flags);
} }
} }
err(`Usage:${MEDIA_HELP}`); err(`Usage:${MEDIA_HELP}`);

View File

@@ -0,0 +1,190 @@
/**
* Recording a live channel to files, for `shade live record`.
*
* What a channel carries decides what is written, next to `base`:
*
* text `base.txt`, as it arrives (a log, a chat)
* init+chunk `base.webm` / `base.mp4`: the init segment, then every media
* chunk after it, a file that plays as it is. If the publisher
* starts over with a different init (another encoder, another
* resolution), the recording goes on in `base-2.…`, since one file
* cannot hold two inits.
* image `base-images/00001.jpg`, … in the order they were sent
* binary `base.bin`, appended
*
* The subscriber hands over each frame once, but a frame that arrives late
* comes after newer ones. Text and media must keep the order they were sent
* in, so a chunk older than the last one written is dropped (and counted)
* rather than spliced in at the wrong place. Chunks before the first init
* cannot be decoded and are skipped. Across epochs (a key rotation), order
* is by epoch, then sequence.
*/
import { mkdir, open } from 'node:fs/promises';
import type { FileHandle } from 'node:fs/promises';
import { join } from 'node:path';
import type { ReceivedFrame } from './channel.js';
import type { MediaMeta } from '../sealed.js';
export interface RecordedFile {
path: string;
kind: 'text' | 'media' | 'images' | 'binary';
/** Media: the init segment's type, e.g. `video/webm; codecs="vp9,opus"`. */
mime?: string;
bytes: number;
/** Images: how many pictures. */
count?: number;
}
export interface RecordStats {
files: RecordedFile[];
/** Frames that arrived after newer ones and were left out. */
late: number;
/** Chunks before any init, which nothing could decode. */
beforeInit: number;
/** The channel's own description, if it sent one. */
meta?: MediaMeta;
}
const IMAGE_EXT: Record<string, string> = {
'image/jpeg': 'jpg',
'image/png': 'png',
'image/webp': 'webp',
'image/gif': 'gif',
'image/avif': 'avif',
};
/** The file extension a media init's type plays as. */
export function mediaExtension(mime: string): string {
const base = mime.split(';')[0]!.trim().toLowerCase();
if (base.endsWith('/webm')) return 'webm';
if (base.endsWith('/mp4')) return 'mp4';
return 'bin';
}
const sameBytes = (a: Uint8Array, b: Uint8Array) => a.length === b.length && a.every((x, i) => x === b[i]);
class Sink {
bytes = 0;
private constructor(
readonly path: string,
private readonly fh: FileHandle,
) {}
static async create(path: string): Promise<Sink> {
return new Sink(path, await open(path, 'w', 0o600));
}
async write(b: Uint8Array): Promise<void> {
await this.fh.write(b);
this.bytes += b.length;
}
close(): Promise<void> {
return this.fh.close();
}
}
export class LiveRecorder {
private text: Sink | null = null;
private binary: Sink | null = null;
private media: { sink: Sink; init: Uint8Array; mime: string } | null = null;
private imagesDir: string | null = null;
private images = 0;
private imageBytes = 0;
private part = 0;
private readonly done: RecordedFile[] = [];
private readonly stats: Omit<RecordStats, 'files'> = { late: 0, beforeInit: 0 };
/** Where the recording stands: the last (epoch, seq) written. */
private last: { epoch: number; seq: number } | null = null;
private queue: Promise<void> = Promise.resolve();
/** @param base path without extension, e.g. `rec/Kveldssending` */
constructor(private readonly base: string) {}
/** Frames are written in the order this is called; safe to call without awaiting. */
frame(f: ReceivedFrame): Promise<void> {
this.queue = this.queue.then(() => this.write(f));
return this.queue;
}
private isLate(f: ReceivedFrame): boolean {
if (this.last === null) return false;
return f.epoch < this.last.epoch || (f.epoch === this.last.epoch && f.seq < this.last.seq);
}
private async write(f: ReceivedFrame): Promise<void> {
const c = f.content;
if (c.type === 'meta') {
this.stats.meta = c.meta;
return;
}
if (c.type === 'end') return;
// An init is sticky: the relay sends it again to whoever joins or rejoins.
// It is judged by its bytes, not by when it came.
if (c.type === 'init') {
if (this.media !== null && sameBytes(this.media.init, c.bytes)) return;
await this.closeMedia();
this.part++;
const suffix = this.part === 1 ? '' : `-${this.part}`;
const sink = await Sink.create(`${this.base}${suffix}.${mediaExtension(c.mime)}`);
await sink.write(c.bytes);
this.media = { sink, init: c.bytes.slice(), mime: c.mime };
return;
}
if (this.isLate(f)) {
this.stats.late++;
return;
}
switch (c.type) {
case 'chunk':
if (this.media === null) {
this.stats.beforeInit++;
return;
}
await this.media.sink.write(c.bytes);
break;
case 'text':
this.text ??= await Sink.create(`${this.base}.txt`);
await this.text.write(new TextEncoder().encode(c.text));
break;
case 'binary':
this.binary ??= await Sink.create(`${this.base}.bin`);
await this.binary.write(c.bytes);
break;
case 'image': {
if (this.imagesDir === null) {
this.imagesDir = `${this.base}-images`;
await mkdir(this.imagesDir, { recursive: true, mode: 0o700 });
}
this.images++;
const sink = await Sink.create(join(this.imagesDir, `${String(this.images).padStart(5, '0')}.${IMAGE_EXT[c.mime] ?? 'img'}`));
await sink.write(c.bytes);
await sink.close();
this.imageBytes += c.bytes.length;
break;
}
}
this.last = { epoch: f.epoch, seq: f.seq };
}
private async closeMedia(): Promise<void> {
if (this.media === null) return;
await this.media.sink.close();
this.done.push({ path: this.media.sink.path, kind: 'media', mime: this.media.mime, bytes: this.media.sink.bytes });
this.media = null;
}
/** Finish every file; what was written, and what was left out. */
async close(): Promise<RecordStats> {
await this.queue;
await this.closeMedia();
for (const [sink, kind] of [
[this.text, 'text'],
[this.binary, 'binary'],
] as const) {
if (sink === null) continue;
await sink.close();
this.done.push({ path: sink.path, kind, bytes: sink.bytes });
}
if (this.imagesDir !== null) this.done.push({ path: this.imagesDir, kind: 'images', bytes: this.imageBytes, count: this.images });
return { files: this.done, ...this.stats };
}
}

View File

@@ -68,3 +68,5 @@ export async function sealFile(
await done; await done;
return result; return result;
} }
export { LiveRecorder, mediaExtension } from './live/record.js';
export type { RecordedFile, RecordStats } from './live/record.js';

View File

@@ -0,0 +1,40 @@
/**
* For object-store.test.ts: <mib> MiB through ObjectMediaStore.begin() in a
* process of its own, so the RSS it reports is this upload's alone and not
* whatever other test files left for the collector. `retainedMiB` is RSS
* after a full collection at every 32 MiB written: what the upload holds,
* not how lazily garbage is returned (`peakMiB`). Prints JSON.
*
* bun tests/fixtures/object-upload-rss.ts <s3 url> <prefix> <mib>
*/
import { MemoryMediaIndex, ObjectMediaStore, S3Bucket } from '../../src/server.js';
import { toHex } from '../../src/bytes.js';
const [url, prefix, mib] = process.argv.slice(2) as [string, string, string];
const { bucket: s3 } = S3Bucket.fromUrl(url);
const store = new ObjectMediaStore(s3, new MemoryMediaIndex(), { prefix, partSize: 8 * 1024 * 1024 });
const chunk = new Uint8Array(1024 * 1024);
const total = Number(mib) * 1024 * 1024;
Bun.gc(true);
const before = process.memoryUsage().rss;
let peak = before;
let retained = before;
const id = toHex(new Uint8Array(16).fill(0x5a));
const up = await store.begin(id);
for (let off = 0; off < total; off += chunk.length) {
chunk.fill((off / chunk.length) & 0xff);
await up.write(chunk);
peak = Math.max(peak, process.memoryUsage().rss);
if ((off / chunk.length) % 32 === 31) {
Bun.gc(true);
retained = Math.max(retained, process.memoryUsage().rss);
}
}
await up.commit({ id, owner: 'o', size: total, readTokenHash: null, createdAt: Date.now() });
const at = Math.floor(total / 2);
const body = await store.body(id, at - 1, at + 1);
const probe = [...new Uint8Array(await new Response(body).arrayBuffer())];
await store.delete(id);
const expect = [((at - 1) / chunk.length) & 0xff, (at / chunk.length) & 0xff];
const MiB = 1024 * 1024;
console.log(JSON.stringify({ retainedMiB: (retained - before) / MiB, peakMiB: (peak - before) / MiB, readBack: probe.join() === expect.join() }));

View File

@@ -0,0 +1,79 @@
import { describe, test, expect, afterAll } from 'bun:test';
import { mkdtemp, readdir, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { LiveRecorder, mediaExtension } from '../src/node.js';
import type { ReceivedFrame, LiveContent } from '../src/index.js';
const dirs: string[] = [];
afterAll(async () => {
for (const d of dirs) await rm(d, { recursive: true, force: true });
});
async function base(): Promise<string> {
const d = await mkdtemp(join(tmpdir(), 'shade-record-'));
dirs.push(d);
return join(d, 'rec');
}
const b = (...xs: number[]) => new Uint8Array(xs);
const frame = (seq: number, content: LiveContent, epoch = 0): ReceivedFrame => ({
epoch,
seq,
timestamp: seq,
sticky: content.type === 'init' || content.type === 'meta',
keyframe: false,
content,
});
describe('LiveRecorder', () => {
test('media: the init, then chunks in order; the init again is not news; a late chunk is left out', async () => {
const at = await base();
const r = new LiveRecorder(at);
const init: LiveContent = { type: 'init', mime: 'video/webm; codecs="vp9,opus"', bytes: b(1, 2, 3) };
await r.frame(frame(1, { type: 'chunk', bytes: b(9) })); // before any init: undecodable
await r.frame(frame(0, init));
await r.frame(frame(2, { type: 'chunk', bytes: b(4) }));
await r.frame(frame(4, { type: 'chunk', bytes: b(6) }));
await r.frame(frame(3, { type: 'chunk', bytes: b(5) })); // late: after 4
await r.frame(frame(0, init)); // a reconnect replays the sticky init
await r.frame(frame(5, { type: 'chunk', bytes: b(7) }));
await r.frame(frame(0, { type: 'chunk', bytes: b(8) }, 1)); // next epoch starts over at 0
const stats = await r.close();
expect(stats.late).toBe(1);
expect(stats.beforeInit).toBe(1);
expect(stats.files).toEqual([{ path: `${at}.webm`, kind: 'media', mime: 'video/webm; codecs="vp9,opus"', bytes: 7 }]);
expect(new Uint8Array(await readFile(`${at}.webm`))).toEqual(b(1, 2, 3, 4, 6, 7, 8));
});
test('a different init (the publisher started over) goes on in a second file', async () => {
const at = await base();
const r = new LiveRecorder(at);
await r.frame(frame(0, { type: 'init', mime: 'video/mp4; codecs="avc1.64001f"', bytes: b(1) }));
await r.frame(frame(1, { type: 'chunk', bytes: b(2) }));
await r.frame(frame(2, { type: 'init', mime: 'video/mp4; codecs="avc1.640028"', bytes: b(3) }));
await r.frame(frame(3, { type: 'chunk', bytes: b(4) }));
const { files } = await r.close();
expect(files.map((f) => f.path)).toEqual([`${at}.mp4`, `${at}-2.mp4`]);
expect(new Uint8Array(await readFile(`${at}-2.mp4`))).toEqual(b(3, 4));
});
test('text to .txt, pictures to a folder in order, the channel meta kept', async () => {
const at = await base();
const r = new LiveRecorder(at);
await r.frame(frame(0, { type: 'meta', meta: { name: 'Kveldssending' } }));
await r.frame(frame(1, { type: 'text', text: 'linje 1\n' }));
await r.frame(frame(2, { type: 'image', mime: 'image/jpeg', bytes: b(0xff, 0xd8) }));
await r.frame(frame(3, { type: 'text', text: 'linje 2\n' }));
await r.frame(frame(4, { type: 'image', mime: 'image/png', bytes: b(0x89) }));
const stats = await r.close();
expect(stats.meta).toEqual({ name: 'Kveldssending' });
expect(await readFile(`${at}.txt`, 'utf8')).toBe('linje 1\nlinje 2\n');
expect((await readdir(`${at}-images`)).sort()).toEqual(['00001.jpg', '00002.png']);
expect(stats.files.find((f) => f.kind === 'images')).toMatchObject({ count: 2, bytes: 3 });
});
test('extensions from the init type', () => {
expect(mediaExtension('audio/webm; codecs="opus"')).toBe('webm');
expect(mediaExtension('audio/mp4; codecs="mp4a.40.2"')).toBe('mp4');
expect(mediaExtension('application/x-weird')).toBe('bin');
});
});

View File

@@ -111,28 +111,27 @@ describe.skipIf(URL_ === undefined)('ObjectMediaStore (S3)', () => {
}, 60_000); }, 60_000);
test('a film streams through: memory is bounded by the parts in flight, not the film', async () => { test('a film streams through: memory is bounded by the parts in flight, not the film', async () => {
const partSize = 8 * 1024 * 1024; // Each size in a process of its own: RSS is process-wide, and other test
const store = new ObjectMediaStore(s3, new MemoryMediaIndex(), { prefix, partSize }); // files in this one leave garbage the collector has not returned yet.
const chunk = new Uint8Array(1024 * 1024); const grew = async (mib: number) => {
const total = 512 * 1024 * 1024; const proc = Bun.spawn(['bun', `${import.meta.dir}/fixtures/object-upload-rss.ts`, URL_!, prefix, String(mib)], { stdout: 'pipe', stderr: 'inherit' });
Bun.gc(true); const out = await new Response(proc.stdout).text();
const before = process.memoryUsage().rss; expect(await proc.exited).toBe(0);
let peak = before; const r = JSON.parse(out) as { retainedMiB: number; peakMiB: number; readBack: boolean };
const id = toHex(new Uint8Array(16).fill(0x5a)); expect(r.readBack).toBe(true);
const up = await store.begin(id); return r;
for (let off = 0; off < total; off += chunk.length) { };
chunk.fill((off / chunk.length) & 0xff); const small = await grew(128);
await up.write(chunk); const large = await grew(512);
peak = Math.max(peak, process.memoryUsage().rss); const f = (n: number) => n.toFixed(0);
} console.log(
await up.commit({ id, owner: 'o', size: total, readTokenHash: null, createdAt: Date.now() }); `object upload: RSS held ${f(small.retainedMiB)} MiB for 128 MiB, ${f(large.retainedMiB)} MiB for 512 MiB ` +
// Three parts (one filling, two uploading) and the HTTP machinery — not 512 MiB. `(peaks before collection ${f(small.peakMiB)} / ${f(large.peakMiB)})`,
const grewMiB = (peak - before) / 1024 / 1024; );
console.log(`object upload of 512 MiB: RSS grew ${grewMiB.toFixed(0)} MiB`); // Three parts (one filling, two uploading) and the HTTP machinery: four
expect(grewMiB).toBeLessThan(120); // times the film is not four times the memory, nor anywhere near the film.
const body = await store.body(id, 300 * 1024 * 1024 - 1, 300 * 1024 * 1024 + 1); expect(large.retainedMiB).toBeLessThan(small.retainedMiB + 48);
expect(new Uint8Array(await new Response(body).arrayBuffer())).toEqual(new Uint8Array([299 & 0xff, 300 & 0xff])); expect(large.retainedMiB).toBeLessThan(128);
expect(await store.delete(id)).toBe(true);
}, 180_000); }, 180_000);
test('a film in pieces across two instances: each piece lands where it lands, one multipart upload, one object', async () => { test('a film in pieces across two instances: each piece lands where it lands, one multipart upload, one object', async () => {
@@ -164,15 +163,18 @@ describe.skipIf(URL_ === undefined)('ObjectMediaStore (S3)', () => {
test('pieces out of order and twice at once on two instances; sweep spares an old upload still being sent', async () => { test('pieces out of order and twice at once on two instances; sweep spares an old upload still being sent', async () => {
const index = new MemoryMediaIndex(); const index = new MemoryMediaIndex();
const grace = 2000; const grace = 2000;
const a = new ObjectMediaStore(s3, index, { prefix, sweepGraceMs: grace }); // A prefix of its own: with a grace period this short, a sweep over the
const b = new ObjectMediaStore(s3, index, { prefix, sweepGraceMs: grace }); // shared one would take other tests' objects for orphans.
const own = `${prefix}sweep/`;
const a = new ObjectMediaStore(s3, index, { prefix: own, sweepGraceMs: grace });
const b = new ObjectMediaStore(s3, index, { prefix: own, sweepGraceMs: grace });
const { bytes, result } = await sealMediaBytes(pattern(DEFAULT_CHUNK_BYTES + 1024 * 1024)); const { bytes, result } = await sealMediaBytes(pattern(DEFAULT_CHUNK_BYTES + 1024 * 1024));
const id = toHex(result.mediaId); const id = toHex(result.mediaId);
const terms = { id, owner: 'o', size: bytes.length, readTokenHash: null, chunk: DEFAULT_CHUNK_BYTES, createdAt: Date.now() }; const terms = { id, owner: 'o', size: bytes.length, readTokenHash: null, chunk: DEFAULT_CHUNK_BYTES, createdAt: Date.now() };
await a.openUpload(terms); await a.openUpload(terms);
// B starting the same upload finds A's, rather than a second multipart upload. // B starting the same upload finds A's, rather than a second multipart upload.
await b.openUpload(terms); await b.openUpload(terms);
expect((await s3.listMultipart(prefix)).filter((u) => u.key.includes(id)).length).toBe(1); expect((await s3.listMultipart(own)).filter((u) => u.key.includes(id)).length).toBe(1);
// The last piece first; then, past the grace period, the first one on both instances at once. // The last piece first; then, past the grace period, the first one on both instances at once.
expect(await b.appendUpload(id, DEFAULT_CHUNK_BYTES, bytes.slice(DEFAULT_CHUNK_BYTES))).toBe(0); expect(await b.appendUpload(id, DEFAULT_CHUNK_BYTES, bytes.slice(DEFAULT_CHUNK_BYTES))).toBe(0);
@@ -187,6 +189,6 @@ describe.skipIf(URL_ === undefined)('ObjectMediaStore (S3)', () => {
await Bun.sleep(grace + 1200); await Bun.sleep(grace + 1200);
expect(await b.sweep()).toEqual({ objects: 0, uploads: 1 }); expect(await b.sweep()).toEqual({ objects: 0, uploads: 1 });
expect(await index.getPending(id)).toBeNull(); expect(await index.getPending(id)).toBeNull();
expect((await s3.listMultipart(prefix)).filter((u) => u.key.includes(id))).toEqual([]); expect((await s3.listMultipart(own)).filter((u) => u.key.includes(id))).toEqual([]);
}, 60_000); }, 60_000);
}); });