diff --git a/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/14-live-opptak-som-film.png b/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/14-live-opptak-som-film.png new file mode 100644 index 0000000..d91ab9f Binary files /dev/null and b/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/14-live-opptak-som-film.png differ diff --git a/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/captions.txt b/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/captions.txt index 346cbb5..af8f747 100644 --- a/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/captions.txt +++ b/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/captions.txt @@ -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) 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) +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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 6851348..d590a73 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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/`), 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). +- **`shade live record `**: 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 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. diff --git a/docs/media.md b/docs/media.md index e906842..b602741 100644 --- a/docs/media.md +++ b/docs/media.md @@ -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. shade live images Ferie/ --every 5 --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 '' -o Kveldssending --put --server https://relay.example ``` `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 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 ` keeps a live channel's identity across restarts: the link keeps working, and each run starts a new epoch. diff --git a/packages/shade-media/src/cli.ts b/packages/shade-media/src/cli.ts index 880f999..1382bcf 100644 --- a/packages/shade-media/src/cli.ts +++ b/packages/shade-media/src/cli.ts @@ -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 a live text channel in the terminal + * shade live record --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 } 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) => { for (const p of batch) { @@ -839,6 +843,99 @@ async function liveWatch(pos: string[]): Promise { return 0; } +/** + * `live record [-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 { + const link = pos[0]; + if (link === undefined) throw new UsageError('usage: shade live record [-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((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 { + 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 Follow a live text channel in the terminal + live record [-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}`); diff --git a/packages/shade-media/src/live/record.ts b/packages/shade-media/src/live/record.ts new file mode 100644 index 0000000..a91ac7e --- /dev/null +++ b/packages/shade-media/src/live/record.ts @@ -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 = { + '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 { + return new Sink(path, await open(path, 'w', 0o600)); + } + async write(b: Uint8Array): Promise { + await this.fh.write(b); + this.bytes += b.length; + } + close(): Promise { + 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 = { late: 0, beforeInit: 0 }; + /** Where the recording stands: the last (epoch, seq) written. */ + private last: { epoch: number; seq: number } | null = null; + private queue: Promise = 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 { + 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 { + 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 { + 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 { + 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 }; + } +} diff --git a/packages/shade-media/src/node.ts b/packages/shade-media/src/node.ts index 1d56af4..736569d 100644 --- a/packages/shade-media/src/node.ts +++ b/packages/shade-media/src/node.ts @@ -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'; diff --git a/packages/shade-media/tests/fixtures/object-upload-rss.ts b/packages/shade-media/tests/fixtures/object-upload-rss.ts new file mode 100644 index 0000000..9c8245c --- /dev/null +++ b/packages/shade-media/tests/fixtures/object-upload-rss.ts @@ -0,0 +1,40 @@ +/** + * For object-store.test.ts: 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 + */ +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() })); diff --git a/packages/shade-media/tests/live-record.test.ts b/packages/shade-media/tests/live-record.test.ts new file mode 100644 index 0000000..efa4ca7 --- /dev/null +++ b/packages/shade-media/tests/live-record.test.ts @@ -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 { + 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'); + }); +}); diff --git a/packages/shade-media/tests/object-store.test.ts b/packages/shade-media/tests/object-store.test.ts index 3f927a0..b57abac 100644 --- a/packages/shade-media/tests/object-store.test.ts +++ b/packages/shade-media/tests/object-store.test.ts @@ -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); });