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

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);
test('a film streams through: memory is bounded by the parts in flight, not the film', async () => {
const partSize = 8 * 1024 * 1024;
const store = new ObjectMediaStore(s3, new MemoryMediaIndex(), { prefix, partSize });
const chunk = new Uint8Array(1024 * 1024);
const total = 512 * 1024 * 1024;
Bun.gc(true);
const before = process.memoryUsage().rss;
let peak = 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);
}
await up.commit({ id, owner: 'o', size: total, readTokenHash: null, createdAt: Date.now() });
// Three parts (one filling, two uploading) and the HTTP machinery — not 512 MiB.
const grewMiB = (peak - before) / 1024 / 1024;
console.log(`object upload of 512 MiB: RSS grew ${grewMiB.toFixed(0)} MiB`);
expect(grewMiB).toBeLessThan(120);
const body = await store.body(id, 300 * 1024 * 1024 - 1, 300 * 1024 * 1024 + 1);
expect(new Uint8Array(await new Response(body).arrayBuffer())).toEqual(new Uint8Array([299 & 0xff, 300 & 0xff]));
expect(await store.delete(id)).toBe(true);
// Each size in a process of its own: RSS is process-wide, and other test
// files in this one leave garbage the collector has not returned yet.
const grew = async (mib: number) => {
const proc = Bun.spawn(['bun', `${import.meta.dir}/fixtures/object-upload-rss.ts`, URL_!, prefix, String(mib)], { stdout: 'pipe', stderr: 'inherit' });
const out = await new Response(proc.stdout).text();
expect(await proc.exited).toBe(0);
const r = JSON.parse(out) as { retainedMiB: number; peakMiB: number; readBack: boolean };
expect(r.readBack).toBe(true);
return r;
};
const small = await grew(128);
const large = await grew(512);
const f = (n: number) => n.toFixed(0);
console.log(
`object upload: RSS held ${f(small.retainedMiB)} MiB for 128 MiB, ${f(large.retainedMiB)} MiB for 512 MiB ` +
`(peaks before collection ${f(small.peakMiB)} / ${f(large.peakMiB)})`,
);
// Three parts (one filling, two uploading) and the HTTP machinery: four
// times the film is not four times the memory, nor anywhere near the film.
expect(large.retainedMiB).toBeLessThan(small.retainedMiB + 48);
expect(large.retainedMiB).toBeLessThan(128);
}, 180_000);
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 () => {
const index = new MemoryMediaIndex();
const grace = 2000;
const a = new ObjectMediaStore(s3, index, { prefix, sweepGraceMs: grace });
const b = new ObjectMediaStore(s3, index, { prefix, sweepGraceMs: grace });
// A prefix of its own: with a grace period this short, a sweep over the
// 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 id = toHex(result.mediaId);
const terms = { id, owner: 'o', size: bytes.length, readTokenHash: null, chunk: DEFAULT_CHUNK_BYTES, createdAt: Date.now() };
await a.openUpload(terms);
// B starting the same upload finds A's, rather than a second multipart upload.
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.
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);
expect(await b.sweep()).toEqual({ objects: 0, uploads: 1 });
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);
});