Files
Shade/packages/shade-media/tests/image-stream.test.ts
Sterister d87db5f4dc 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>
2026-10-18 22:53:37 +02:00

81 lines
3.3 KiB
TypeScript

import { describe, test, expect } from 'bun:test';
import { ImageStreamSplitter } from '../src/image-stream.js';
import { MediaFormatError } from '../src/errors.js';
const hasFfmpeg = Bun.which('ffmpeg') !== null;
async function ffmpegImages(codec: 'mjpeg' | 'png', frames: number): Promise<Uint8Array> {
const p = Bun.spawn(
['ffmpeg', '-hide_banner', '-loglevel', 'error', '-f', 'lavfi', '-i', 'testsrc2=size=320x240:rate=10', '-frames:v', String(frames), '-c:v', codec, '-f', 'image2pipe', '-'],
{ stdout: 'pipe' },
);
const out = new Uint8Array(await new Response(p.stdout).arrayBuffer());
if ((await p.exited) !== 0) throw new Error('ffmpeg failed');
return out;
}
/** Feed in random-sized pieces, as a pipe does. */
function feed(bytes: Uint8Array, seed = 7) {
const s = new ImageStreamSplitter();
const got = [];
let x = seed;
for (let i = 0; i < bytes.length; ) {
x = (x * 1103515245 + 12345) & 0x7fffffff;
const n = 1 + (x % 9000);
got.push(...s.push(bytes.subarray(i, i + n)));
i += n;
}
s.finish();
return got;
}
const concat = (...parts: Uint8Array[]) => {
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
let o = 0;
for (const p of parts) {
out.set(p, o);
o += p.length;
}
return out;
};
describe.skipIf(!hasFfmpeg)('ImageStreamSplitter on ffmpeg image2pipe output', () => {
test('MJPEG: every frame whole, in order, whatever the pipe chunking', async () => {
const stream = await ffmpegImages('mjpeg', 12);
for (const seed of [1, 2, 3]) {
const imgs = feed(stream, seed);
expect(imgs.length).toBe(12);
expect(imgs.every((i) => i.mime === 'image/jpeg' && i.bytes[0] === 0xff && i.bytes[1] === 0xd8)).toBe(true);
expect(concat(...imgs.map((i) => i.bytes))).toEqual(stream);
}
});
test('PNG: every frame whole', async () => {
const stream = await ffmpegImages('png', 5);
const imgs = feed(stream);
expect(imgs.map((i) => i.mime)).toEqual(Array(5).fill('image/png'));
expect(concat(...imgs.map((i) => i.bytes))).toEqual(stream);
});
test('a JPEG carrying a whole JPEG thumbnail in APP1 is one image, not two', async () => {
const [thumb] = feed(await ffmpegImages('mjpeg', 1));
const [main] = feed(await ffmpegImages('mjpeg', 1));
const exif = concat(new TextEncoder().encode('Exif\0\0'), thumb!.bytes);
const app1 = concat(new Uint8Array([0xff, 0xe1, (exif.length + 2) >> 8, (exif.length + 2) & 0xff]), exif);
// SOI, APP1(thumbnail), then the rest of the main image.
const withThumb = concat(main!.bytes.subarray(0, 2), app1, main!.bytes.subarray(2));
const imgs = feed(concat(withThumb, withThumb));
expect(imgs.length).toBe(2);
expect(imgs[0]!.bytes).toEqual(withThumb);
});
test('a truncated stream and junk are refused', async () => {
const stream = await ffmpegImages('mjpeg', 2);
expect(() => feed(stream.subarray(0, stream.length - 10))).toThrow(MediaFormatError);
expect(() => new ImageStreamSplitter().push(new TextEncoder().encode('hello, not an image'))).toThrow(/JPEG or PNG/);
expect(() => new ImageStreamSplitter().push(new TextEncoder().encode('junk'))).toThrow(/JPEG or PNG/);
const tiny = new ImageStreamSplitter(1000);
expect(() => tiny.push(stream)).toThrow(/larger than/);
});
});