feat(media): browser playback, live WebM and log streaming, shade media/live CLI

- Service Worker plays sealed files in native <video>/<audio>/<img> with
  Range seeking; watch page served by the relay itself (#shade= fragment
  links, grant never sent to a server)
- MSE live player with keyframe-aware joining, gap detection, latency control
- WebM splitter (init + clusters, keyframe detection) that puts blocks in
  timecode order — Chrome rejects ffmpeg's interleaved Opus/VP8 otherwise
- Link mode for live channels: epoch seeds from a channel secret, so a
  link survives publisher restarts and scheduled rotations
- File store streams byte ranges itself (Bun.file().slice() in a Response
  sent whole files to Range requests)
- shade media serve|put|get|ls|rm, shade live text|webm|watch

Verified end to end in headless Chromium: VP9/Opus film plays and seeks,
live VP8/Opus at 2.9 s latency, live logs, sealed JPEG and Opus audio.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-10-18 21:01:52 +02:00
parent 9e64ec87be
commit f359cbd9ad
28 changed files with 1796 additions and 40 deletions

View File

@@ -131,3 +131,44 @@ describe('live channel', () => {
for (const k of kinds) expect((await sub.open(await pub.frame(k)))?.content).toEqual(k);
});
});
describe('link mode', () => {
test('a link grant follows rotations and a publisher restart on its own', async () => {
const secret = new Uint8Array(32).fill(9);
const pub = new LivePublisher({ channelSecret: secret, rotateEvery: 5 });
const g = parseGrant(encodeGrant(pub.grant({ link: true }))) as LiveGrant;
expect(g.channelSecret).toEqual(secret);
const sub = new LiveSubscriber(g);
const seen: string[] = [];
for (let i = 0; i < 12; i++) {
if (pub.rotationDue) await pub.rotate();
const r = await sub.open(await pub.frame(text(`a${i}`)));
if (r?.content.type === 'text') seen.push(r.content.text);
}
expect(seen.length).toBe(12);
expect(pub.epoch).toBe(2);
// The publisher process restarts with the same identity, one epoch on.
const restarted = new LivePublisher({
channelId: pub.channelId,
signingSecret: (pub as unknown as { signingSecret: Uint8Array }).signingSecret,
channelSecret: secret,
epoch: pub.epoch + 1,
});
// A late viewer joins mid-epoch: it derives forward from seq 0.
for (let i = 0; i < 40; i++) await restarted.frame(text(`skip${i}`));
const r = await sub.open(await restarted.frame(text('after restart')));
expect(r?.content).toEqual(text('after restart'));
expect(r?.epoch).toBe(3);
});
test('a session grant does not carry the secret, and cannot read later epochs', async () => {
const pub = new LivePublisher({ channelSecret: new Uint8Array(32).fill(1) });
const g = pub.grant({ from: 'now' });
expect(g.channelSecret).toBeUndefined();
const sub = new LiveSubscriber(g);
await pub.rotate();
await expect(sub.open(await pub.frame(text('x')))).rejects.toBeInstanceOf(LiveKeyError);
expect(() => new LivePublisher().grant({ link: true })).toThrow();
});
});

View File

@@ -47,7 +47,7 @@ function pattern(n: number): Uint8Array {
return out;
}
const until = async (cond: () => boolean, ms = 3000) => {
const until = async (cond: () => boolean, ms = 10_000) => {
const t = Date.now();
while (!cond()) {
if (Date.now() - t > ms) throw new Error('timed out');
@@ -122,6 +122,26 @@ describe('media routes over real HTTP', () => {
}
});
test('a Range request on a multi-MiB file returns exactly that range', async () => {
// Regression: Bun.file().slice() in a Response sent the whole file.
const dir = await tempDir();
const app = new Hono();
app.route('/', createMediaRoutes(new FileMediaStore(dir)));
const { server, base } = serve(app);
try {
const client = new MediaClient(base, OwnerKey.generate());
const plain = pattern(3 * 1024 * 1024 + 5);
const grant = await client.uploadBytes(plain, { readToken: null });
const res = await fetch(grant.url!, { headers: { Range: 'bytes=100-1048675' } });
expect(res.status).toBe(206);
expect((await res.arrayBuffer()).byteLength).toBe(1048576);
const r = await openGrant(grant);
expect(await r.read(0, plain.length)).toEqual(plain);
} finally {
server.stop(true);
}
});
test('refuses what is not a sealed file, bad signatures, and owners not on the list', async () => {
const dir = await tempDir();
const allowed = OwnerKey.generate();

View File

@@ -0,0 +1,89 @@
import { describe, test, expect } from 'bun:test';
import { WebmSplitter } from '../src/webm.js';
import type { WebmPiece } from '../src/webm.js';
const hasFfmpeg = Bun.which('ffmpeg') !== null;
async function ffmpegWebm(args: string[]): Promise<Uint8Array> {
const p = Bun.spawn(['ffmpeg', '-hide_banner', '-loglevel', 'error', ...args, '-f', 'webm', 'pipe:1'], {
stdout: 'pipe',
stderr: 'inherit',
});
const out = new Uint8Array(await new Response(p.stdout).arrayBuffer());
await p.exited;
return out;
}
/** Relative timecodes of the SimpleBlocks in one cluster, in file order. */
function clusterTimecodes(c: Uint8Array): number[] {
const vint = (at: number) => {
let len = 1;
while ((c[at]! & (0x80 >> (len - 1))) === 0) len++;
let v = c[at]! & (0xff >> len);
for (let i = 1; i < len; i++) v = v * 256 + c[at + i]!;
return { v, len };
};
const idLen = (at: number) => {
let len = 1;
while ((c[at]! & (0x80 >> (len - 1))) === 0) len++;
return len;
};
let at = idLen(0);
at += vint(at).len;
const out: number[] = [];
while (at < c.length) {
const il = idLen(at);
const isSimple = c[at] === 0xa3;
const sz = vint(at + il);
const body = at + il + sz.len;
if (isSimple) {
const tr = vint(body);
out.push(new DataView(c.buffer, c.byteOffset).getInt16(body + tr.len, false));
}
at = body + sz.v;
}
return out;
}
function split(bytes: Uint8Array, chunk: number): WebmPiece[] {
const s = new WebmSplitter();
const out: WebmPiece[] = [];
for (let i = 0; i < bytes.length; i += chunk) out.push(...s.push(bytes.subarray(i, i + chunk)));
out.push(...s.finish());
return out;
}
describe.skipIf(!hasFfmpeg)('WebM splitter on real ffmpeg output', () => {
test('VP8+Opus live stream: init, then keyframe clusters, bytes preserved', async () => {
const webm = await ffmpegWebm([
'-f', 'lavfi', '-i', 'testsrc=size=320x240:rate=30',
'-f', 'lavfi', '-i', 'sine=frequency=440:sample_rate=48000',
'-t', '4', '-c:v', 'libvpx', '-b:v', '300k', '-g', '30', '-deadline', 'realtime',
'-c:a', 'libopus', '-live', '1', '-cluster_time_limit', '1000',
]);
for (const chunk of [1, 777, 65536, webm.length]) {
const pieces = split(webm, chunk);
expect(pieces[0]!.type).toBe('init');
expect((pieces[0] as { mime: string }).mime).toBe('video/webm; codecs="vp8,opus"');
const clusters = pieces.slice(1);
expect(clusters.length).toBeGreaterThan(2);
expect(clusters.every((p) => p.type === 'cluster')).toBe(true);
// ffmpeg starts a cluster on each keyframe; with -g 30 at 30 fps that is one a second.
expect(clusters.filter((p) => p.type === 'cluster' && p.keyframe).length).toBeGreaterThanOrEqual(3);
expect(clusters[0]!.type === 'cluster' && clusters[0]!.keyframe).toBe(true);
// Same length and same bytes, give or take the block order inside a cluster.
const joined = Buffer.concat(pieces.map((p) => p.bytes));
expect(joined.length).toBe(webm.length);
expect(Buffer.from(joined).sort().equals(Buffer.from(webm).sort())).toBe(true);
// What Chrome's MSE demands: block timecodes never go backwards inside a cluster.
for (const p of clusters) expect(clusterTimecodes(p.bytes)).toEqual([...clusterTimecodes(p.bytes)].sort((a, b) => a - b));
}
}, 30_000);
test('audio-only Opus: every cluster is a starting point', async () => {
const webm = await ffmpegWebm(['-f', 'lavfi', '-i', 'sine=frequency=220', '-t', '3', '-c:a', 'libopus', '-live', '1', '-cluster_time_limit', '500']);
const pieces = split(webm, 4096);
expect((pieces[0] as { mime: string }).mime).toBe('audio/webm; codecs="opus"');
expect(pieces.slice(1).every((p) => p.type === 'cluster' && p.keyframe)).toBe(true);
}, 30_000);
});