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

@@ -10,6 +10,7 @@
* 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 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
* `$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 { LivePublisher } from './live/channel.js';
import { LivePublishClient, LiveWatchClient } from './live/client.js';
import { LiveRecorder } from './live/record.js';
import { sealFile } from './node.js';
import { OwnerKey } from './owner.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 { 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;
const send = async (batch: ReturnType<MediaSplitter['push']>) => {
for (const p of batch) {
@@ -839,6 +843,99 @@ async function liveWatch(pos: string[]): Promise<number> {
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 = `
media serve [--port 3910] [--dir ./shade-media-data] [--owners k1,k2] [--open]
[--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
new picture landing in a directory
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. */
@@ -929,6 +1031,8 @@ export async function runMediaCli(group: 'media' | 'live', argv: string[], hooks
return await liveImages(pos, flags);
case 'watch':
return await liveWatch(pos);
case 'record':
return await liveRecord(pos, flags);
}
}
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;
return result;
}
export { LiveRecorder, mediaExtension } from './live/record.js';
export type { RecordedFile, RecordStats } from './live/record.js';