feat(media): shade live images — a webcam, a slideshow or a watched folder, end to end

Pictures were a live content type the watch page could show but nothing
could publish. `shade live images`:
- stdin: back-to-back JPEG/PNG, e.g.
  `ffmpeg -f v4l2 -i /dev/video0 -r 1 -c:v mjpeg -f image2pipe -`;
- files/directories: a slideshow, one picture every --every seconds;
- --watch DIR: each new picture once its size holds still (cameras
  write in pieces).
Each picture is a keyframe, so a late viewer opens on the latest. The meta
carries the first picture's type (MIME_RE rightly refuses image/*).

ImageStreamSplitter walks JPEG markers (lengths to SOS, then the
entropy-coded data, where every 0xFF is stuffed) and PNG chunks to IEND,
so an EXIF thumbnail — a whole JPEG inside APP1 — does not end a picture.
Bounded at 16 MiB per picture, junk refused at its first bytes.

The Android demo shows live picture channels and sealed pictures
(decoded off the UI thread, downsampled to the screen).

Verified: splitter on real ffmpeg MJPEG/PNG under random pipe chunking,
the thumbnail case, truncation, junk and the size cap (4 tests); in
Chromium a 2 fps MJPEG "webcam" through the relay (8 → 14 pictures in 3 s,
960×540); a watched folder with a PNG written in two halves (sent once,
whole) and a .txt ignored; slideshow; error paths. Demo APK builds; not
run on a device (none connected).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-10-18 22:53:37 +02:00
parent 1653060494
commit d87db5f4dc
9 changed files with 436 additions and 10 deletions

View File

@@ -8,13 +8,14 @@
* shade media ls|rm --server URL
* tail -f app.log | shade live text --server URL --name "app logs"
* 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
*
* The owner key (who may upload and delete) is created on first use under
* `$XDG_CONFIG_HOME/shade/` and reused; nothing to configure.
*/
import { chmod, mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
import { chmod, mkdir, mkdtemp, readdir, readFile, rm, stat, watch, writeFile } from 'node:fs/promises';
import { createWriteStream } from 'node:fs';
import { homedir, tmpdir } from 'node:os';
import { basename, dirname, extname, join } from 'node:path';
@@ -30,6 +31,7 @@ import { sealFile } from './node.js';
import { OwnerKey } from './owner.js';
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 { MediaLibrary } from './library.js';
@@ -594,6 +596,106 @@ async function liveVideo(flags: Flags, pinned?: LiveContainer): Promise<number>
return 0;
}
/**
* `live images`: a channel of pictures, each a keyframe, so a late viewer
* opens on the latest. Three sources:
* - stdin: back-to-back JPEG/PNG (`ffmpeg -f v4l2 -i /dev/video0 -r 1 -c:v mjpeg -f image2pipe - | …`);
* - files and directories: a slideshow, one picture every `--every` seconds;
* - `--watch DIR`: each new picture in DIR as it lands (a camera, a screenshot folder).
*/
async function liveImages(pos: string[], flags: Flags): Promise<number> {
const watchDir = str(flags, 'watch');
const everyMs = Math.round(Number(str(flags, 'every') ?? 5) * 1000);
if (!Number.isFinite(everyMs) || everyMs < 0) throw new UsageError('--every must be seconds, 0 or more');
const maxBytes = 16 * 1024 * 1024;
const isImage = (p: string) => IMAGE_MIME[extname(p).toLowerCase()] !== undefined;
// Resolve the slideshow before going live: a typo should fail before a link is printed.
const files: string[] = [];
for (const p of pos) {
const st = await stat(p).catch(() => null);
if (st === null) throw new UsageError(`no such file or directory: ${p}`);
if (st.isDirectory()) {
const names = (await readdir(p)).filter((n) => !n.startsWith('.') && isImage(n)).sort(naturally.compare);
files.push(...names.map((n) => join(p, n)));
} else if (isImage(p)) {
files.push(p);
} else {
throw new UsageError(`not a picture (by its extension): ${p}`);
}
}
// The meta names the pictures' type (each picture still carries its own):
// the first file's, or the first piped picture's — read before going live,
// as `live video` reads its init. A watched folder alone has none yet.
const splitter = new ImageStreamSplitter(maxBytes);
const stdin = Bun.stdin.stream().getReader();
let firstPiped: { mime: string; bytes: Uint8Array }[] = [];
if (files.length === 0 && watchDir === undefined) {
while (firstPiped.length === 0) {
const { value, done } = await stdin.read();
if (done) throw new UsageError('no pictures: pipe JPEG/PNG in, or name files, a directory or --watch DIR');
firstPiped = splitter.push(value);
}
}
const firstType = files.length > 0 ? IMAGE_MIME[extname(files[0]!).toLowerCase()] : firstPiped[0]?.mime;
const meta: MediaMeta = { name: str(flags, 'name') ?? 'Live pictures', mime: str(flags, 'mime') ?? firstType ?? 'image/jpeg' };
const { client } = await startPublishing(flags, meta);
await client.send({ type: 'meta', meta }, { sticky: true });
let sent = 0;
const sendFile = async (path: string): Promise<void> => {
const bytes = new Uint8Array(await readFile(path));
if (bytes.length > maxBytes) {
err(`skipped ${basename(path)}: over ${maxBytes / 1024 / 1024} MiB`);
return;
}
await client.send({ type: 'image', mime: IMAGE_MIME[extname(path).toLowerCase()]!, bytes }, { keyframe: true });
sent++;
};
if (files.length > 0) {
for (const [i, f] of files.entries()) {
await sendFile(f);
if (i < files.length - 1 || watchDir !== undefined) await Bun.sleep(everyMs);
}
}
if (watchDir !== undefined) {
err(`watching ${watchDir} for new pictures (Ctrl-C to stop)`);
// A file is sent once its size has held still: a camera writes in pieces.
const pending = new Map<string, ReturnType<typeof setTimeout>>();
const settle = (path: string, lastSize = -1) => {
clearTimeout(pending.get(path));
pending.set(
path,
setTimeout(async () => {
const st = await stat(path).catch(() => null);
if (st === null || !st.isFile()) return void pending.delete(path);
if (st.size !== lastSize) return settle(path, st.size);
pending.delete(path);
await sendFile(path).catch((e: unknown) => err(`! ${basename(path)}: ${(e as Error).message}`));
}, 300),
);
};
for await (const ev of watch(watchDir)) {
if (ev.filename !== null && !ev.filename.startsWith('.') && isImage(ev.filename)) settle(join(watchDir, ev.filename));
}
} else if (files.length === 0) {
let batch = firstPiped;
for (;;) {
for (const img of batch) {
await client.send({ type: 'image', mime: img.mime, bytes: img.bytes }, { keyframe: true });
sent++;
}
const { value, done } = await stdin.read();
if (done) break;
batch = splitter.push(value);
}
splitter.finish();
}
err(`${sent} pictures sent`);
await client.end();
return 0;
}
async function liveWatch(pos: string[]): Promise<number> {
const link = pos[0];
if (link === undefined) throw new UsageError('usage: shade live watch <link>');
@@ -648,6 +750,10 @@ export const MEDIA_HELP = `
ffmpeg … -c:v libx264 -c:a aac -f mp4 \\
-movflags frag_keyframe+empty_moov+default_base_moof - | …
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
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
`;
@@ -696,6 +802,8 @@ export async function runMediaCli(group: 'media' | 'live', argv: string[], hooks
return await liveVideo(flags);
case 'webm':
return await liveVideo(flags, 'webm');
case 'images':
return await liveImages(pos, flags);
case 'watch':
return await liveWatch(pos);
}

View File

@@ -0,0 +1,161 @@
/**
* Split a byte stream of back-to-back images into whole images: what
* `ffmpeg … -f image2pipe -c:v mjpeg -` (a webcam, a screen grab) or
* `-c:v png` writes, for `shade live images`.
*
* JPEG is walked marker by marker, not searched for FFD9: an EXIF APP1
* segment can hold a whole thumbnail JPEG, end marker included. Segments up
* to SOS carry their length; after SOS, entropy-coded data stuffs every
* 0xFF with 0x00, so the next 0xFF followed by anything but 0x00 or a
* restart marker is the next real marker. PNG is walked chunk by chunk to
* IEND.
*/
import { MediaFormatError } from './errors.js';
export interface StreamImage {
mime: 'image/jpeg' | 'image/png';
bytes: Uint8Array;
}
const PNG_SIG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
export class ImageStreamSplitter {
private buf = new Uint8Array(0);
/** Where scanning resumes inside the current image (bytes before are known to be one image's). */
private scan = 0;
private inEntropy = false;
/** @param maxImageBytes an image larger than this is refused, not buffered without end. */
constructor(private readonly maxImageBytes = 16 * 1024 * 1024) {}
push(chunk: Uint8Array): StreamImage[] {
const next = new Uint8Array(this.buf.length + chunk.length);
next.set(this.buf);
next.set(chunk, this.buf.length);
this.buf = next;
const out: StreamImage[] = [];
for (;;) {
const img = this.take();
if (img === null) break;
out.push(img);
}
if (this.buf.length > this.maxImageBytes) {
throw new MediaFormatError(`an image in the stream is larger than ${this.maxImageBytes} bytes`);
}
return out;
}
/** Call at end of input: leftover bytes are a truncated image. */
finish(): void {
if (this.buf.length > 0) throw new MediaFormatError(`the stream ended inside an image (${this.buf.length} bytes left)`);
}
private take(): StreamImage | null {
const b = this.buf;
if (b.length === 0) return null;
// Judge the start as soon as it can be judged: junk is refused, not waited on.
const jpeg = b[0] === 0xff && (b.length < 2 || b[1] === 0xd8);
const png = PNG_SIG.every((x, i) => i >= b.length || b[i] === x);
if (!jpeg && !png) throw new MediaFormatError('not a stream of JPEG or PNG images');
if (b.length < 8) return null;
let end: number | null;
let mime: StreamImage['mime'];
if (b[0] === 0xff && b[1] === 0xd8) {
mime = 'image/jpeg';
end = this.jpegEnd();
} else if (PNG_SIG.every((x, i) => b[i] === x)) {
mime = 'image/png';
end = this.pngEnd();
} else {
throw new MediaFormatError('not a stream of JPEG or PNG images');
}
if (end === null) return null;
if (end > this.maxImageBytes) throw new MediaFormatError(`an image in the stream is larger than ${this.maxImageBytes} bytes`);
const bytes = b.slice(0, end);
this.buf = b.slice(end);
this.scan = 0;
this.inEntropy = false;
return { mime, bytes };
}
private jpegEnd(): number | null {
const b = this.buf;
let i = this.scan === 0 ? 2 : this.scan;
for (;;) {
if (this.inEntropy) {
// Find the marker that ends the scan.
for (; i + 1 < b.length; i++) {
if (b[i] !== 0xff) continue;
const m = b[i + 1]!;
if (m === 0x00 || (m >= 0xd0 && m <= 0xd7) || m === 0xff) continue;
break;
}
if (i + 1 >= b.length) {
this.scan = i;
return null;
}
this.inEntropy = false;
}
if (i + 2 > b.length) {
this.scan = i;
return null;
}
if (b[i] !== 0xff) throw new MediaFormatError(`JPEG: expected a marker at byte ${i}`);
const m = b[i + 1]!;
if (m === 0xff) {
i++; // fill byte
continue;
}
if (m === 0xd9) return i + 2; // EOI
if ((m >= 0xd0 && m <= 0xd7) || m === 0x01) {
i += 2; // no length
continue;
}
if (i + 4 > b.length) {
this.scan = i;
return null;
}
const len = (b[i + 2]! << 8) | b[i + 3]!;
if (len < 2) throw new MediaFormatError('JPEG: bad segment length');
if (i + 2 + len > b.length) {
this.scan = i;
return null;
}
i += 2 + len;
if (m === 0xda) this.inEntropy = true; // SOS: entropy-coded data follows its header
}
}
private pngEnd(): number | null {
const b = this.buf;
let i = this.scan === 0 ? 8 : this.scan;
const v = new DataView(b.buffer, b.byteOffset, b.byteLength);
for (;;) {
if (i + 8 > b.length) {
this.scan = i;
return null;
}
const len = v.getUint32(i);
const type = String.fromCharCode(b[i + 4]!, b[i + 5]!, b[i + 6]!, b[i + 7]!);
if (!/^[A-Za-z]{4}$/.test(type)) throw new MediaFormatError('PNG: bad chunk type');
const next = i + 12 + len;
if (next > b.length) {
this.scan = i;
return null;
}
i = next;
if (type === 'IEND') return i;
}
}
}
/** Image files `live images` publishes, by extension. */
export const IMAGE_MIME: Record<string, string> = {
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.png': 'image/png',
'.webp': 'image/webp',
'.gif': 'image/gif',
'.avif': 'image/avif',
};