diff --git a/.scaffold/branches/streaming.md b/.scaffold/branches/streaming.md index 6d98141..bceb02d 100644 --- a/.scaffold/branches/streaming.md +++ b/.scaffold/branches/streaming.md @@ -33,6 +33,7 @@ decided: "2026-10-18 — Cardwell: neste steg er Shade-streaming av tekst, video - [x] Delt mediebibliotek for flere relay-instanser: filmer i S3 (egen SigV4-klient, multipart med begrenset minne), poster og live-pinner i Postgres, feiing av foreldreløse objekter; verifisert mot SeaweedFS med signaturkontroll + Postgres 16, to relayer bak round-robin - [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) ## 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/12-live-webcam-images.png b/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/12-live-webcam-images.png new file mode 100644 index 0000000..7fa10e7 Binary files /dev/null and b/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/12-live-webcam-images.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 5b8f6ff..640673f 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 @@ -9,3 +9,4 @@ 09 — To relay-instanser bak en round-robin-lastbalanserer deler ett bibliotek (filmbytes i S3, poster i Postgres): opplastet via den ene, spilt og spolt til 24 s med Range-lesinger fra begge 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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e6a8e0..2232e28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,6 +66,10 @@ 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 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 + markers and PNG chunks. The Android demo shows live and sealed pictures. - **Live channels across relay instances.** `LiveRelayOptions.mesh` with a `LivePublisherLocator` (`PostgresLivePublisherLocator`; `SHADE_MEDIA_RELAY_URL` / `media serve --advertise`): a relay with viewers diff --git a/android/shade-media-demo/src/main/kotlin/no/zyon/shade/mediademo/PlayerActivity.kt b/android/shade-media-demo/src/main/kotlin/no/zyon/shade/mediademo/PlayerActivity.kt index 4e7e599..2d69a31 100644 --- a/android/shade-media-demo/src/main/kotlin/no/zyon/shade/mediademo/PlayerActivity.kt +++ b/android/shade-media-demo/src/main/kotlin/no/zyon/shade/mediademo/PlayerActivity.kt @@ -2,6 +2,8 @@ package no.zyon.shade.mediademo import android.app.Activity import android.content.Intent +import android.graphics.Bitmap +import android.graphics.BitmapFactory import android.graphics.Color import android.os.Bundle import android.view.Gravity @@ -9,6 +11,7 @@ import android.view.ViewGroup.LayoutParams.MATCH_PARENT import android.view.ViewGroup.LayoutParams.WRAP_CONTENT import android.widget.Button import android.widget.EditText +import android.widget.ImageView import android.widget.LinearLayout import android.widget.ScrollView import android.widget.TextView @@ -28,8 +31,9 @@ import no.zyon.shade.media.android.ShadeMedia import java.util.concurrent.Executors /** - * Plays a sealed Shade film, video or song, or watches a live channel: - * live video/audio through ExoPlayer, a live log as scrolling text. + * Plays a sealed Shade film, video, song or picture, or watches a live + * channel: live video/audio through ExoPlayer, a live log as scrolling text, + * live pictures (a webcam, a watched folder) one after another. * * The link comes from a share (`ACTION_SEND` text), from * `adb shell am start -n no.zyon.shade.mediademo/.PlayerActivity --es link ''`, @@ -46,6 +50,7 @@ class PlayerActivity : Activity() { private lateinit var view: PlayerView private lateinit var log: TextView private lateinit var logScroll: ScrollView + private lateinit var picture: ImageView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -72,6 +77,11 @@ class PlayerActivity : Activity() { addView(log) visibility = android.view.View.GONE } + picture = ImageView(this).apply { + scaleType = ImageView.ScaleType.FIT_CENTER + setBackgroundColor(Color.BLACK) + visibility = android.view.View.GONE + } val bar = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL gravity = Gravity.CENTER_VERTICAL @@ -86,6 +96,7 @@ class PlayerActivity : Activity() { addView(status, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT)) addView(view, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f)) addView(logScroll, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f)) + addView(picture, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f)) }, ) linkFrom(intent)?.let { @@ -132,7 +143,7 @@ class PlayerActivity : Activity() { val name = g.meta?.name ?: "live channel" val mime = g.meta?.mime ?: "" if (mime.startsWith("video/") || mime.startsWith("audio/")) { - showPlayer(true) + show(View.PLAYER) val p = newPlayer() status.text = "$name · live · end-to-end encrypted" p.setMediaSource(ShadeMedia.liveMediaSource(g)) @@ -141,7 +152,7 @@ class PlayerActivity : Activity() { return } // Text and images: follow the channel directly. - showPlayer(false) + show(if (mime.startsWith("image/")) View.PICTURE else View.LOG) log.text = "" status.text = "$name · connecting…" watcher = LiveWatcher(g, object : LiveWatcher.Listener { @@ -149,7 +160,11 @@ class PlayerActivity : Activity() { val c = frame.content runOnUiThread { when (c) { - is LiveContent.Text -> appendLog(c.text) + is LiveContent.Text -> { + show(View.LOG) + appendLog(c.text) + } + is LiveContent.Image -> showPicture(c.bytes) is LiveContent.End -> status.text = "$name · the broadcast has ended" else -> Unit } @@ -170,9 +185,33 @@ class PlayerActivity : Activity() { if (atBottom) logScroll.post { logScroll.fullScroll(android.view.View.FOCUS_DOWN) } } - private fun showPlayer(video: Boolean) { - view.visibility = if (video) android.view.View.VISIBLE else android.view.View.GONE - logScroll.visibility = if (video) android.view.View.GONE else android.view.View.VISIBLE + private enum class View { PLAYER, LOG, PICTURE } + + private fun show(which: View) { + fun vis(on: Boolean) = if (on) android.view.View.VISIBLE else android.view.View.GONE + view.visibility = vis(which == View.PLAYER) + logScroll.visibility = vis(which == View.LOG) + picture.visibility = vis(which == View.PICTURE) + } + + /** + * Decode off the UI thread, scaled to the screen: a 40-megapixel photo + * decoded whole is 160 MB of bitmap. A picture that will not decode is + * reported and skipped — the next one may. + */ + private fun showPicture(bytes: ByteArray) { + show(View.PICTURE) + val target = maxOf(resources.displayMetrics.widthPixels, resources.displayMetrics.heightPixels) + io.execute { + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) + var sample = 1 + while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= target) sample *= 2 + val bmp: Bitmap? = BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample }) + runOnUiThread { + if (bmp == null) status.text = "${status.text} · a picture could not be decoded" else picture.setImageBitmap(bmp) + } + } } private fun newPlayer(): ExoPlayer { @@ -189,7 +228,21 @@ class PlayerActivity : Activity() { private fun start(f: ShadeFilm) { film = f - showPlayer(true) + val meta0 = f.reader.meta + if (meta0.mime?.startsWith("image/") == true) { + status.text = "${meta0.name ?: "picture"} · ${meta0.mime} · ${f.reader.size / 1024} KiB · end-to-end encrypted" + if (f.reader.size > MAX_PICTURE_BYTES) { + status.text = "${status.text} · too large to show here" + return + } + show(View.PICTURE) + io.execute { + val bytes = runCatching { f.reader.read(0, f.reader.size.toInt()) } + runOnUiThread { bytes.fold(onSuccess = { showPicture(it) }, onFailure = { status.text = "Cannot read: ${it.message}" }) } + } + return + } + show(View.PLAYER) val p = newPlayer() val meta = f.reader.meta val subs = if (f.subtitles.isEmpty()) "" else " · ${f.subtitles.size} subtitle track(s)" @@ -200,6 +253,7 @@ class PlayerActivity : Activity() { } private fun stop() { + picture.setImageDrawable(null) watcher?.close() watcher = null view.player = null @@ -222,5 +276,6 @@ class PlayerActivity : Activity() { private companion object { const val MAX_LOG_CHARS = 200_000 + const val MAX_PICTURE_BYTES = 64L * 1024 * 1024 } } diff --git a/docs/media.md b/docs/media.md index 1a31f4e..268ffee 100644 --- a/docs/media.md +++ b/docs/media.md @@ -48,6 +48,17 @@ ffmpeg -re -i camera.mp4 -c:v libvpx -deadline realtime -g 30 -c:a libopus \ 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" + +# 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" + +# Live pictures: a webcam at one picture a second … +ffmpeg -f v4l2 -i /dev/video0 -r 1 -c:v mjpeg -f image2pipe - \ + | shade live images --server https://relay.example --name "Hytta" +# … a slideshow, or every new picture that lands in a folder. +shade live images Ferie/ --every 5 --server https://relay.example +shade live images --watch ~/Pictures/Screenshots --server https://relay.example ``` `shade live video` recognises the container from the first bytes (`--format webm|fmp4` @@ -55,6 +66,11 @@ pins it). A fragment is a starting point for late joiners when the first sample video track is a sync sample, so fragments shorter than a GOP keep latency down without breaking late joining. +`shade live images` splits a piped stream into whole JPEG/PNG pictures by walking +their markers and chunks (a JPEG's EXIF thumbnail is a whole JPEG and does not end the +picture). Each picture is a keyframe, so a late viewer opens on the latest. A watched +folder sends a file once its size has held still, because cameras write in pieces. + `--channel ` keeps a live channel's identity across restarts: the link keeps working, and each run starts a new epoch. diff --git a/packages/shade-media/src/cli.ts b/packages/shade-media/src/cli.ts index d5ee6f0..74a589c 100644 --- a/packages/shade-media/src/cli.ts +++ b/packages/shade-media/src/cli.ts @@ -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 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 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 { + 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 => { + 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>(); + 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 { const link = pos[0]; if (link === undefined) throw new UsageError('usage: shade live watch '); @@ -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] [… [--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 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); } diff --git a/packages/shade-media/src/image-stream.ts b/packages/shade-media/src/image-stream.ts new file mode 100644 index 0000000..148a83c --- /dev/null +++ b/packages/shade-media/src/image-stream.ts @@ -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 = { + '.jpg': 'image/jpeg', + '.jpeg': 'image/jpeg', + '.png': 'image/png', + '.webp': 'image/webp', + '.gif': 'image/gif', + '.avif': 'image/avif', +}; diff --git a/packages/shade-media/tests/image-stream.test.ts b/packages/shade-media/tests/image-stream.test.ts new file mode 100644 index 0000000..cfc7e39 --- /dev/null +++ b/packages/shade-media/tests/image-stream.test.ts @@ -0,0 +1,80 @@ +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 { + 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/); + }); +});