feat(media): live video --input — a film, a webcam or an IP camera without writing the ffmpeg line
`shade live video` needed a hand-written ffmpeg pipeline. --input <file | /dev/video0 | rtsp://…> probes the source and runs ffmpeg itself: H.264 and AAC are copied (a camera's own encoder, no CPU), anything else becomes H.264 with a keyframe every 2 s whatever the frame rate (where late joiners start) and AAC (>6 channels downmixed to 5.1), out as low-latency fragmented MP4. A file is paced (-re) as if live; RTSP goes over TCP; /dev/videoN opens as v4l2. ffmpeg's failure is reported with its own last lines. Verified: liveEncodePlan unit tests (copy, encode, pacing, RTSP/v4l2, audio-only, nothing-to-send); Chromium through the relay: VP9/Opus WebM encoded → live H.264/AAC, keyframe every 4th 0.5 s fragment, 0.96 s latency; H.264/AAC MKV copied, 1.8 s latency. Media suite 97/0. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -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<number> {
|
||||
async function liveVideo(flags: Flags, pinned?: LiveContainer): Promise<number> {
|
||||
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<Uint8Array> = Bun.stdin.stream();
|
||||
let encoder: ReturnType<typeof Bun.spawn> | null = null;
|
||||
let encoderErr: Promise<string> = 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<number>
|
||||
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<number>
|
||||
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 <link|id> --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] [<file|dir>… [--every 5]] [--watch DIR] [--mime M]
|
||||
A channel of pictures: JPEG/PNG piped in (a webcam via
|
||||
|
||||
@@ -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<ProbeStream[]> {
|
||||
const out = await run(['ffprobe', '-v', 'error', ...inputArgs(input), '-show_streams', '-of', 'json', input]);
|
||||
return (JSON.parse(out) as { streams?: ProbeStream[] }).streams ?? [];
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user