diff --git a/.scaffold/branches/streaming.md b/.scaffold/branches/streaming.md index bceb02d..1bea2df 100644 --- a/.scaffold/branches/streaming.md +++ b/.scaffold/branches/streaming.md @@ -34,6 +34,7 @@ decided: "2026-10-18 — Cardwell: neste steg er Shade-streaming av tekst, video - [x] Live på tvers av relay-instanser: relayene sier hvor publisererne er (Postgres), en relay med seere følger den som har publisereren og verifiserer hver ramme; seere får `state` når kanalen går live/stille (nettleser, TS, Android). To feil rettet underveis: relayen merket aldri at publisereren gikk (Hono-WSContext), og ubrukelig mediekatalog ga uhåndtert avvisning - [x] Live-lyd alene (radio/podkast): Opus/WebM og AAC/fMP4 gir lydspiller med målt lyd i Chromium (meta fikk init-segmentets ekte type) - [x] Bilder live: `shade live images` (webkamera via ffmpeg image2pipe, lysbildeserie, overvåket mappe); JPEG-/PNG-splitter med markørparsing; Android-demoen viser live og forseglede bilder (bygget, ikke kjørt på enhet) +- [x] `shade live video --input `: ffmpeg kjøres for deg, H.264/AAC kopieres, resten kodes (keyframe hvert 2. s); live i Chromium fra både VP9/Opus (omkodet, 0,96 s) og H.264/AAC (kopiert) ## Neste - Kjør `:shade-media-demo` på dev-telefonen (RFCN504DWJF var ikke tilkoblet 2026-10-18) diff --git a/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/13-live-input-transcode.png b/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/13-live-input-transcode.png new file mode 100644 index 0000000..04b633e Binary files /dev/null and b/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/13-live-input-transcode.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 640673f..346cbb5 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 @@ -10,3 +10,4 @@ 10 — Live-logg på tvers av relayer: publisereren landet på instans A og seeren på B bak lastbalansereren; B følger A, verifiserer hver ramme mot pinnen og viser «live» 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) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2232e28..381e69c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,6 +66,9 @@ New package **`@shade/media`** — see `docs/media.md`. `PostgresLivePinStore`, `createSharedMediaBackend` in `@shade/storage-postgres`. A live pin can no longer change key, even between instances (`LivePinTakenError`). +- **`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. - **`shade live images`.** A channel of pictures: JPEG/PNG piped in (a webcam through `ffmpeg -f image2pipe`), a slideshow of files, or each new picture landing in a watched folder. `ImageStreamSplitter` walks JPEG diff --git a/docs/media.md b/docs/media.md index 268ffee..ac63a13 100644 --- a/docs/media.md +++ b/docs/media.md @@ -49,6 +49,11 @@ ffmpeg -re -i camera.mp4 -c:v libx264 -tune zerolatency -g 30 -c:a aac \ -f mp4 -movflags frag_keyframe+empty_moov+default_base_moof -frag_duration 250000 - \ | shade live video --server https://relay.example --name "Kamera 1" +# Or let shade run ffmpeg: a film, a webcam, an IP camera. H.264/AAC is copied, +# anything else encoded (H.264 with a keyframe every 2 s, AAC); a file plays at its own pace. +shade live video --input rtsp://camera.local/stream1 --server https://relay.example --name "Inngang" +shade live video --input Film.mkv --server https://relay.example --name "Filmkveld" + # Live radio: the same, with sound only — the page and the app give it an audio player. ffmpeg -re -i radio.mp3 -c:a libopus -f webm -live 1 -cluster_time_limit 1000 - \ | shade live video --server https://relay.example --name "Radio" diff --git a/packages/shade-media/src/cli.ts b/packages/shade-media/src/cli.ts index 74a589c..befaaf1 100644 --- a/packages/shade-media/src/cli.ts +++ b/packages/shade-media/src/cli.ts @@ -33,7 +33,7 @@ import type { MediaMeta } from './sealed.js'; import { MediaSplitter } from './splitter.js'; import { IMAGE_MIME, ImageStreamSplitter } from './image-stream.js'; import { SUBTITLE_EXTENSIONS, subtitleFor, subtitlesOf, withSubtitles } from './subtitles.js'; -import { prepareForWeb, webIssues } from './web-prep.js'; +import { liveEncodePlan, prepareForWeb, probeLive, webIssues } from './web-prep.js'; import { MediaLibrary } from './library.js'; import type { SubtitleTrack } from './subtitles.js'; import type { LiveContainer } from './splitter.js'; @@ -557,8 +557,23 @@ async function liveText(flags: Flags): Promise { async function liveVideo(flags: Flags, pinned?: LiveContainer): Promise { const format = pinned ?? str(flags, 'format'); if (format !== undefined && format !== 'webm' && format !== 'fmp4') throw new UsageError('--format must be webm or fmp4'); - const splitter = new MediaSplitter(format); - const stdin = Bun.stdin.stream().getReader(); + const input = str(flags, 'input'); + let source: ReadableStream = Bun.stdin.stream(); + let encoder: ReturnType | null = null; + let encoderErr: Promise = Promise.resolve(''); + if (input !== undefined) { + if (Bun.which('ffmpeg') === null || Bun.which('ffprobe') === null) throw new UsageError('--input needs ffmpeg and ffprobe on PATH'); + if (format === 'webm') throw new UsageError('--input sends fragmented MP4; leave out --format webm'); + const st = await stat(input).catch(() => null); + const plan = liveEncodePlan(input, await probeLive(input), { realtime: st?.isFile() === true }); + for (const n of plan.notes) err(n); + const proc = Bun.spawn(plan.args, { stdout: 'pipe', stderr: 'pipe', stdin: 'ignore' }); + encoder = proc; + encoderErr = new Response(proc.stderr).text(); + source = proc.stdout; + } + const splitter = new MediaSplitter(input !== undefined ? 'fmp4' : format); + const stdin = source.getReader(); // Read until the init segment is out, so the meta carries the stream's real // type: a radio stream is audio/webm, and a viewer should get a player for // sound, not a black video box. @@ -566,7 +581,10 @@ async function liveVideo(flags: Flags, pinned?: LiveContainer): Promise let init: { mime: string } | undefined; while (init === undefined) { const { value, done } = await stdin.read(); - if (done) throw new UsageError(splitter.container === null ? 'no input on stdin' : 'the stream ended before its init segment'); + if (done) { + if (encoder !== null && (await encoder.exited) !== 0) throw new UsageError(`ffmpeg failed: ${(await encoderErr).trim().split('\n').slice(-3).join(' / ')}`); + throw new UsageError(splitter.container === null ? 'no input on stdin' : 'the stream ended before its init segment'); + } first = first.concat(splitter.push(value)); init = first.find((p) => p.type === 'init'); } @@ -591,6 +609,7 @@ async function liveVideo(flags: Flags, pinned?: LiveContainer): Promise await send(splitter.push(value)); } await send(splitter.finish()); + if (encoder !== null && (await encoder.exited) !== 0) err(`! ffmpeg: ${(await encoderErr).trim().split('\n').slice(-3).join(' / ')}`); err(`${pieces} ${splitter.container === 'webm' ? 'clusters' : 'fragments'} sent`); await client.end(); return 0; @@ -744,11 +763,13 @@ export const MEDIA_HELP = ` media rm --server URL live text --server URL [--name N] [--channel file.json] Publish stdin as a live log (tail -f app.log | shade live text …) - live video --server URL [--name N] [--channel file.json] [--format webm|fmp4] + live video --server URL [--name N] [--channel file.json] [--format webm|fmp4] [--input SRC] Publish a live WebM or fragmented MP4 from stdin: ffmpeg … -f webm - | … ffmpeg … -c:v libx264 -c:a aac -f mp4 \\ -movflags frag_keyframe+empty_moov+default_base_moof - | … + or --input a film, /dev/video0, rtsp://camera: ffmpeg is run + for you, copying H.264/AAC and encoding the rest live webm … The same, pinned to WebM live images --server URL [--name N] [… [--every 5]] [--watch DIR] [--mime M] A channel of pictures: JPEG/PNG piped in (a webcam via diff --git a/packages/shade-media/src/web-prep.ts b/packages/shade-media/src/web-prep.ts index 9bf7c01..9e79733 100644 --- a/packages/shade-media/src/web-prep.ts +++ b/packages/shade-media/src/web-prep.ts @@ -29,7 +29,7 @@ export interface WebPrepared { notes: string[]; } -interface ProbeStream { +export interface ProbeStream { index: number; codec_type: 'video' | 'audio' | 'subtitle' | 'data' | 'attachment'; codec_name?: string; @@ -145,3 +145,70 @@ export async function prepareForWeb(input: string, workdir: string, opts: { onPr await run(args); return { file, mime: video !== undefined ? 'video/mp4' : 'audio/mp4', subtitles, notes }; } + +export interface LiveEncodePlan { + /** The ffmpeg command, output on stdout as fragmented MP4. */ + args: string[]; + /** What is copied and what is encoded, in plain words. */ + notes: string[]; +} + +/** + * The ffmpeg command for `shade live video --input`: a film, a camera + * (`/dev/video0`), an IP camera (`rtsp://…`) or anything ffmpeg reads, as + * low-latency fragmented MP4 every browser and ExoPlayer plays. H.264 and + * AAC are copied (a camera's own encoder, no CPU spent); anything else is + * encoded to H.264 with a keyframe every 2 s (where late joiners can start) + * and AAC. A file is read at its own pace (`-re`), as if it were live. + */ +export function liveEncodePlan(input: string, streams: ProbeStream[], opts: { realtime: boolean }): LiveEncodePlan { + const video = streams.find((s) => s.codec_type === 'video' && s.disposition?.attached_pic !== 1); + const audio = streams.find((s) => s.codec_type === 'audio'); + if (video === undefined && audio === undefined) throw new Error('no audio or video stream in the input'); + const notes: string[] = []; + const args = ['ffmpeg', '-hide_banner', '-loglevel', 'error', '-nostdin']; + if (opts.realtime) args.push('-re'); + args.push(...inputArgs(input), '-i', input); + if (video !== undefined) { + args.push('-map', `0:${video.index}`); + if (video.codec_name === 'h264') { + args.push('-c:v', 'copy'); + notes.push('video h264: copied (late joiners start at its own keyframes)'); + } else { + args.push( + '-c:v', 'libx264', '-preset', 'veryfast', '-tune', 'zerolatency', '-pix_fmt', 'yuv420p', + '-crf', '23', '-maxrate', '6M', '-bufsize', '12M', + // A keyframe every 2 s whatever the frame rate: where a late viewer can start. + '-force_key_frames', 'expr:gte(t,n_forced*2)', + ); + notes.push(`video ${video.codec_name} → H.264 (a keyframe every 2 s)`); + } + } + if (audio !== undefined) { + args.push('-map', `0:${audio.index}`); + if (audio.codec_name === 'aac') { + args.push('-c:a', 'copy'); + notes.push('audio aac: copied'); + } else { + args.push('-c:a', 'aac', '-b:a', (audio.channels ?? 2) > 2 ? '384k' : '160k'); + if ((audio.channels ?? 2) > 6) args.push('-ac', '6'); + notes.push(`audio ${audio.codec_name} → AAC`); + } + } + args.push('-sn', '-dn', '-f', 'mp4', '-movflags', 'frag_keyframe+empty_moov+default_base_moof', '-frag_duration', '500000', 'pipe:1'); + return { args, notes }; +} + +/** How ffmpeg must open what is not a plain file or URL it recognises by itself. */ +function inputArgs(input: string): string[] { + if (/^\/dev\/video\d+$/.test(input)) return ['-f', 'v4l2']; + // UDP drops and reorders on a busy network; a camera's RTSP over TCP does not. + if (/^rtsps?:\/\//i.test(input)) return ['-rtsp_transport', 'tcp']; + return []; +} + +/** Probe a live input (devices and RTSP need their input options). */ +export async function probeLive(input: string): Promise { + const out = await run(['ffprobe', '-v', 'error', ...inputArgs(input), '-show_streams', '-of', 'json', input]); + return (JSON.parse(out) as { streams?: ProbeStream[] }).streams ?? []; +} diff --git a/packages/shade-media/tests/web-prep.test.ts b/packages/shade-media/tests/web-prep.test.ts index e8c2ff5..a8c6181 100644 --- a/packages/shade-media/tests/web-prep.test.ts +++ b/packages/shade-media/tests/web-prep.test.ts @@ -2,7 +2,8 @@ import { describe, test, expect, afterAll } from 'bun:test'; import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { prepareForWeb, probe } from '../src/web-prep.js'; +import { liveEncodePlan, prepareForWeb, probe } from '../src/web-prep.js'; +import type { ProbeStream } from '../src/web-prep.js'; const hasFfmpeg = Bun.which('ffmpeg') !== null && Bun.which('ffprobe') !== null; const dirs: string[] = []; @@ -70,3 +71,37 @@ describe.skipIf(!hasFfmpeg)('prepareForWeb (media put --web)', () => { expect((await probe(prep.file)).map((s) => s.codec_name)).toEqual(['h264', 'aac']); }, 30_000); }); + +describe('liveEncodePlan (live video --input)', () => { + const v = (codec: string): ProbeStream => ({ index: 0, codec_type: 'video', codec_name: codec }); + const a = (codec: string, channels = 2): ProbeStream => ({ index: 1, codec_type: 'audio', codec_name: codec, channels }); + const after = (args: string[], flag: string) => args[args.indexOf(flag) + 1]; + + test("a camera's H.264/AAC is copied; RTSP goes over TCP; not paced", () => { + const p = liveEncodePlan('rtsp://cam.local/stream1', [v('h264'), a('aac')], { realtime: false }); + expect(after(p.args, '-c:v')).toBe('copy'); + expect(after(p.args, '-c:a')).toBe('copy'); + expect(after(p.args, '-rtsp_transport')).toBe('tcp'); + expect(p.args).not.toContain('-re'); + expect(p.args.slice(-1)).toEqual(['pipe:1']); + expect(after(p.args, '-movflags')).toBe('frag_keyframe+empty_moov+default_base_moof'); + }); + + test('a film in HEVC with 7.1 DTS is encoded, paced, with a keyframe every 2 s', () => { + const p = liveEncodePlan('/films/x.mkv', [v('hevc'), a('dts', 8), { index: 2, codec_type: 'subtitle', codec_name: 'subrip' }], { realtime: true }); + expect(p.args).toContain('-re'); + expect(after(p.args, '-c:v')).toBe('libx264'); + expect(after(p.args, '-force_key_frames')).toBe('expr:gte(t,n_forced*2)'); + expect(after(p.args, '-c:a')).toBe('aac'); + expect(after(p.args, '-ac')).toBe('6'); + expect(p.args).toContain('-sn'); + expect(p.notes).toEqual(['video hevc → H.264 (a keyframe every 2 s)', 'audio dts → AAC']); + }); + + test('a webcam device is opened as v4l2; sound alone is fine; nothing at all is refused', () => { + expect(after(liveEncodePlan('/dev/video0', [v('mjpeg')], { realtime: false }).args, '-f')).toBe('v4l2'); + const radio = liveEncodePlan('http://radio.example/stream.mp3', [a('mp3')], { realtime: false }); + expect(radio.args).not.toContain('-c:v'); + expect(() => liveEncodePlan('x', [], { realtime: false })).toThrow(/no audio or video/); + }); +});