Files
Shade/docs/media.md
Sterister 0bbeb5682b 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>
2026-10-18 22:56:19 +02:00

493 lines
27 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# `@shade/media` — streaming under Shade
V4.15. Films, videos, songs, images, and live streams of logs, text, video and
audio, all end-to-end encrypted. Whoever stores or relays the bytes cannot read
them, and whoever holds a key cannot forge them for anyone else.
There are two shapes, because "a film" and "a log" are different problems:
| | Sealed media (SMF1) | Live channel (SLF1) |
|---|---|---|
| What | a file that exists in full: film, episode, photo, song, document | a stream that is still being made: `tail -f`, a camera, a broadcast |
| Read how | random access over HTTP Range, so you can seek | in order over a WebSocket, joining late from a backlog |
| Stored where | any dumb store: the relay, nginx, S3, a USB disk | the relay holds minutes of ciphertext for late joiners, then lets it go |
| Keys | one random key per file | Sender Keys: a hash chain per epoch, every frame signed |
| Plays in | `<video>`/`<audio>`/`<img>` through a Service Worker; ExoPlayer via `MediaReader.inputStream` | `<video>` through Media Source Extensions; a log view; the terminal |
Both hand their keys to a viewer as a **grant**: a small JSON message sent over an
existing Shade session (Double Ratchet, so it is authenticated and forward-secret),
or carried in the `#shade=` fragment of a link for a device with no session.
## Quick start
```bash
# A relay: sealed store + live relay + the /watch page, on one port.
shade media serve --port 3910 --dir /srv/shade-media
# A film. Seals in one streaming pass, uploads, prints a watch link.
shade media put Film.mkv --server https://relay.example
# → https://relay.example/watch/#shade=eyJraW5kIjoic2hhZGUubWVkaWEtZ3JhbnQ…
# Back on disk, decrypted and verified.
shade media get '<link>' -o Film.mkv
# A season, a photo album: every file, plus one link that opens them all.
shade media put "Sesong 1/" --server https://relay.example
shade media get '<album link>' -o "Sesong 1" # the whole directory back
# Live logs.
tail -f /var/log/app.log | shade live text --server https://relay.example --name "api logs" --channel ~/.config/shade/api-logs.json
shade live watch '<link>' # in a terminal — or open the link in a browser
# Live video (and audio) from anything ffmpeg can read: WebM (VP8/VP9/AV1 + Opus) …
ffmpeg -re -i camera.mp4 -c:v libvpx -deadline realtime -g 30 -c:a libopus \
-f webm -live 1 -cluster_time_limit 1000 - \
| shade live video --server https://relay.example --name "Kamera 1"
# … or fragmented MP4 (H.264/HEVC/AV1 + AAC/Opus), what cameras, OBS and Safari speak.
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"
# 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`
pins it). A fragment is a starting point for late joiners when the first sample of its
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 <file>` keeps a live channel's identity across restarts: the link keeps
working, and each run starts a new epoch.
The owner key (who may upload, delete and open live channels) is created the first
time it is needed, under `$XDG_CONFIG_HOME/shade/media-owner.key` (mode 0600).
`shade media whoami` prints its public half.
The relay knows ids and sizes, never names, and a link is printed once. So `media put`
also writes every upload, with its grant, to `$XDG_CONFIG_HOME/shade/media-library.jsonl`
(mode 0600: a grant is a key). `shade media ls` names your uploads from it, and
`shade media link <name or id>` prints a link again. The file is append-only, one JSON
line per change, so two uploads at once cannot lose each other's entries. A grant
always encodes to the same link: its meta is written in canonical order.
### In the Shade container
```
SHADE_MEDIA_DIR=/data/media # enables media; required (no in-memory fallback)
SHADE_MEDIA_OWNERS=<key>,<key> # who may upload / open channels (`shade media whoami`)
SHADE_DISABLE_MEDIA=1 # optional: off entirely
```
Routes: `/v1/media/:id`, `/v1/live/:channelId` (WebSocket), `/watch/`.
**There is no in-memory fallback**, for the vault's reason: a library that lives in
RAM accepts every upload and loses all of it on the next redeploy, without anything
failing. With `SHADE_MEDIA_DIR` unset the routes are not mounted, and the log says so.
With `SHADE_MEDIA_OWNERS` empty, the relay serves what it has and accepts nothing new.
`*` admits every key, which is only safe on a private network.
### Several instances, one library (S3 + Postgres)
```
SHADE_MEDIA_S3_URL=https://<key>:<secret>@s3.eu-north-1.amazonaws.com/<bucket>[/<prefix>]
SHADE_MEDIA_PG_URL=postgres://… # falls back to SHADE_PREKEY_PG_URL
SHADE_MEDIA_RELAY_URL=http://10.0.0.5:3000 # this instance, as the others reach it (live channels)
```
(`shade media serve --s3 … --pg … --advertise URL` does the same outside the container.) Sealed
bytes go to the bucket, records and live-channel pins to Postgres, and any number of
instances behind one hostname serve one library. Any S3 API works (AWS, R2, MinIO,
SeaweedFS, Garage, B2); credentials left out of the URL come from
`AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY`, the region from an `amazonaws.com` host
or `?region=`. A bucket the credentials cannot use is reported at start; media stays
off and the rest of the server runs.
- **Uploads stream.** A film goes up as an S3 multipart upload, part by part, with at
most three 16 MiB parts in memory (512 MiB through: 11 MiB of RSS). Every part's
payload is hashed into its signature, so a part damaged in transit is refused.
- **Racing uploads of one id** (on any instances) each go to their own object key;
the primary key in Postgres admits one record, and the loser deletes its object.
Delete removes the record first, so a crash never brings a film back.
- **Sweeping.** Objects no record points at and multipart uploads never completed
(a crash mid-upload) are reclaimed after 24 hours, a minute after start and every
6 hours. Every instance may sweep at once.
- **Live channels** are pinned in Postgres, so a channel cannot be pinned to two keys
by two instances. Each instance records which channels' publishers are connected to
it (`shade_live_publishers`, refreshed every 10 s). An instance whose viewers want a
channel published elsewhere subscribes to that instance once, with a viewer's own
read token, and fans the frames out locally. It verifies every frame against the pin
as if the publisher were its own, so a peer, or a poisoned locator row, cannot forge
one. Following an instance again replays its backlog; frames already passed on (by
`seq`) are not passed on twice. If the publisher moves (a deploy), viewers on every
instance follow it within a poll (2 s). What is sent while they look for it reaches
them the way a late joiner gets it, from a keyframe. A token that does not match the
pin held in memory is checked against the shared pin before it is refused, so a
publisher that comes back with a new read token is honoured everywhere. Without
`SHADE_MEDIA_RELAY_URL` an instance cannot be followed, and `/v1/live/*` must go to
one instance.
- Viewers now hear when a channel goes live or quiet after they joined: a
`{"type":"state","live":…}` message, in the browser, the TS client and Android.
- The bucket holds only sealed SMF1 bytes. No key, name or plaintext is in it or in
Postgres.
`S3Bucket` is Shade's own small S3 client (SigV4, checked against AWS's published
signature example and a server that validates signatures), not `Bun.S3Client`: in
Bun 1.3.5 its writer buffers everything written to it (512 MiB in, 543 MiB of RSS),
`end(error)` does not abort, and `slice(0, n).stream()` returned the whole object.
## In code
```ts
import { MediaClient, OwnerKey, openGrant, encodeGrant, parseGrant } from '@shade/media';
import { sealFile } from '@shade/media/node';
// Owner side: seal and upload, then grant a peer over the Shade session.
const sealed = await sealFile('Film.mkv', '/tmp/film.smf', { meta: { mime: 'video/x-matroska', name: 'Film' } });
const grant = await new MediaClient(relay, owner).putSealed(sealed, Bun.file('/tmp/film.smf'));
await shade.send('bob', encodeGrant(grant));
// Viewer side: open what was granted and read any range.
const g = parseGrant(await shade.receive('alice', envelope));
const film = await openGrant(g); // fetches the footer + trailer only
const bytes = await film.read(3_000_000_000, 1 << 20); // 1 MiB from 3 GB in
```
Live:
```ts
import { LivePublisher, LivePublishClient, LiveWatchClient } from '@shade/media';
const pub = new LivePublishClient({ relay, publisher: new LivePublisher({ meta: { name: 'logs' } }), readToken, owner });
await pub.whenReady();
await shade.send('bob', encodeGrant(pub.grant('oldest'))); // backlog from the oldest kept keyframe
await pub.send({ type: 'text', text: 'line\n' }, { keyframe: true });
// bob
new LiveWatchClient(grant, { onFrame: (f) => console.log(f.content) });
```
In a page, `installMediaWorker('/sw.js')` registers the decrypting worker, and
`keyring.add(grant)` returns a URL to put in `<video src>`. `new LivePlayer(video, grant)`
plays a live WebM or fragmented-MP4 channel; `MediaSplitter` cuts either container into
the frames a publisher sends (init once, sticky; then one frame per cluster or fragment). The relay serves a ready-made page at `/watch/` that does
both from a link.
On Android/JVM, `no.zyon.shade.media`: `Grants.fromCapabilityUrl(link)`,
`(grant as MediaGrant).open()` returns a `MediaReader` with `read(offset, len)` and
`inputStream()`. `LiveSubscriber(grant).open(frame)` handles live frames, and
`MediaSealer` and `LivePublisher` write both formats byte for byte the way TS does.
For playback, `:shade-android-media` hands a reader to Media3/ExoPlayer, so any
container ExoPlayer understands plays and seeks from a sealed file:
```kotlin
val reader = ShadeMedia.open(link) // blocking: footer + trailer over HTTP
player.setMediaSource(ShadeMedia.mediaSource(reader))
player.prepare()
```
`ShadeMediaDataSource` serves the plaintext ranges ExoPlayer asks for; a tampered
segment fails the read with a `DataSourceException` instead of reaching the decoder.
Live channels play too: `ShadeMedia.liveMediaSource(liveGrant)` connects a
`LiveWatcher` (OkHttp WebSocket, reconnects with backoff, the relay's backlog
deduplicated) and turns the frames into one endless WebM or fMP4 stream for
ExoPlayer's own extractors: the init, then media from the first keyframe, and after
any gap (a reconnect, the relay shedding a slow viewer) nothing until the next
keyframe. A late joiner's timeline starts at 0:00: fMP4 through a per-join
`TimestampAdjuster`, WebM by rewriting each cluster's Timecode in place. Otherwise a
viewer arriving an hour in would wait an hour for the first sample. A different init
mid-stream fails playback with a `ParserException`, which is not retried, rather than
feeding the decoder a spliced stream. `LiveWatcher` on its own follows text and image
channels.
`:shade-media-demo` is a small player app for the dev phone: share a watch link to it,
or start it with `adb shell am start -n no.zyon.shade.mediademo/.PlayerActivity --es link '<link>'`.
Against `shade media serve` on the PC, `adb reverse tcp:3910 tcp:3910` makes a
`http://localhost:3910/…` link work on the phone.
## SMF1 — the sealed file (cross-language contract)
All integers are big-endian.
```
segment[0] … segment[n-1] AES-256-GCM(segKey) of `segmentSize` plaintext bytes each;
the last holds the rest (0 … segmentSize). n ≥ 1.
meta AES-256-GCM(metaKey) of UTF-8 JSON (MediaMeta)
table n × SHA-256(sealed segment i)
footer (64 bytes) "SMF1" | 0x01 | flags=0 | 0 0 | segmentSize u32 |
plaintextSize u64 | metaLen u32 | mediaId (16) |
20 × 0 | "SMF1"
```
```
mediaKey 32 random bytes, fresh for every seal (never caller-chosen)
mediaId 16 random bytes
segKey = HKDF-SHA256(ikm = mediaKey, salt = mediaId, info = "shade-media/v1\0segment", 32)
metaKey = HKDF-SHA256(ikm = mediaKey, salt = mediaId, info = "shade-media/v1\0meta", 32)
nonce_i = u32(0) ‖ u64(i) aad_i = "SMF1" ‖ mediaId ‖ u64(i) ‖ u8(i == n-1)
nonce_meta = u32(1) ‖ u64(0) aad_meta = "SMF1-meta" ‖ mediaId
rootDigest = SHA-256(meta ‖ table ‖ footer)
```
- **The trailer is at the end** so a writer can seal a stream of unknown length in one
pass with one segment of memory, and upload as it goes. A reader fetches the last 64
bytes, then the trailer, which is about 130 KiB for a 4 GB film.
- **Deterministic nonces are safe** because no key is ever used for two files. The
sealer draws the key itself; the only way to pin one is `@shade/media/testing`, for
vectors.
- **`last` is in the AAD**, so truncation fails closed. Cutting the file makes a
segment that was not the last one claim to be.
- **Two layers of integrity.** AEAD protects against the store. The table, pinned by
`rootDigest` in the grant, also protects against *other key holders*. Without it,
a viewer who holds the key could re-encrypt forged segments and serve them to a
third viewer through a store it controls. The reader checks every segment's hash
before decrypting it.
- **Strict parsing.** Unknown flags, non-zero reserved bytes, a size that does not
match the footer, or a `metaLen` over 64 KiB are all refused, never guessed at.
- Default segment size is 1 MiB (allowed: 4 KiB to 16 MiB). The overhead is 48 bytes
per segment plus the trailer, about 0.005 %.
`MediaMeta` holds `mime`, `name`, `durationMs`, `width`, `height`, `createdAt` and
`extra` (string → string). It is validated on both sides, and a writer serialises it
in that key order so two languages produce the same bytes.
## SLF1 — the live frame (cross-language contract)
```
0..4 "SLF1"
4 version = 1
5 flags: 0x01 sticky · 0x02 keyframe · 0x04 end (other bits refused)
6..8 0
8..24 channelId
24..28 epoch u32
28..36 seq u64
36..44 timestamp ms u64 (publisher clock)
44..48 ctLen u32
48.. AES-256-GCM ciphertext ‖ tag (aad = bytes 0..48)
+64 Ed25519 signature over everything before it
```
Payload (inside the ciphertext): one kind byte, then `1` text (UTF-8), `2` binary,
`3` init (u8 mimeLen, mime, bytes), `4` media chunk, `5` image (mime-prefixed like
init), `6` meta (JSON), or `7` end.
Keys follow Signal's Sender Keys, per epoch:
```
ck[0] = HKDF(epochSeed, salt = channelId ‖ u32(epoch), "shade-live/v1\0chain")
stickyKey = HKDF(epochSeed, salt = channelId ‖ u32(epoch), "shade-live/v1\0sticky")
mk[i] = HMAC-SHA256(ck[i], 0x01) used for exactly one frame, then wiped
ck[i+1] = HMAC-SHA256(ck[i], 0x02) one-way: ck[i] cannot be recovered
nonce = u32(epoch) ‖ u64(seq)
```
- **Every frame is signed** with the channel's Ed25519 key. All viewers hold the
same chain, so without a signature any of them could forge frames to the others
through the relay. The signing key's public half travels in the grant, and the
grant travels over an authenticated Shade session; that is what ties a channel
to a person. The relay checks signatures too, against the key the channel was
pinned to on first use, so it never stores or forwards anything a viewer would
reject.
- **Sticky frames** (codec init, the channel's own description) are sealed under
`stickyKey`, not the chain. The relay keeps them for the whole epoch, so a viewer
who joins an hour in can still decode the init segment sent at second zero.
- **Joining late.** The publisher keeps chain snapshots at recent keyframes (64 by
default). A grant carries the chain key at one of them: `oldest` (the most backlog
the relay still has), `latest`, or `now`. A viewer can never derive anything before
its grant's point.
- **Out of order and gaps.** A subscriber derives forward up to 100 000 frames and
keeps keys for up to 2 000 skipped ones, evicting the oldest first. Replays are
dropped quietly.
- **Removing a viewer** means a new epoch: fresh seed, `seq` back to 0, and the sticky
frames resealed. Everyone who stays gets a new grant; anyone left out is out.
- **Link mode** (`channelSecret`): `epochSeed(e) = HKDF(channelSecret, salt =
channelId, "shade-live/v1\0epoch" ‖ u32(e))`. A grant made with `{ link: true }`
carries the secret, so its holder can follow every later epoch without a new grant.
That is how a link survives publisher restarts and the CLI's scheduled rotation
(every 20 000 frames, so catching up stays cheap). The trade-off is that there is
no forward secrecy against a link holder and no way to remove one short of a new
channel. Session grants never carry the secret, so they stay per-epoch either way.
## Grants
```jsonc
// sealed file
{ "kind": "shade.media-grant/v1", "mediaId": "<b64u 16>", "key": "<b64u 32>",
"root": "<hex 32>", "url": "https://…/v1/media/<hex id>", "token": "<b64u>", "meta": { … } }
// live channel
{ "kind": "shade.live-grant/v1", "channelId": "<b64u 16>", "signingKey": "<b64u 32>",
"epoch": 0, "seq": 1234, "chainKey": "<b64u 32>", "stickyKey": "<b64u 32>",
"channelSecret": "<b64u 32, link grants only>", "url": "wss://…", "token": "<b64u>" }
```
`token` is the relay's read token. It is a door, not a key: the relay stores only its
SHA-256 and answers a wrong token and a missing id with the same 404, so a prober
cannot tell which ids exist. A link is `…/watch/#shade=<b64u(grant JSON)>`. The
fragment is never sent to a server, and the page removes it from the address bar
once it has read it.
## Albums
An album is a sealed file like any other, with meta `mime`
`application/vnd.shade.album+json` and this plaintext:
```jsonc
{ "kind": "shade.album/v1", "title": "Sesong 1",
"items": [ { "kind": "shade.media-grant/v1", … }, { "kind": "shade.live-grant/v1", … }, … ] }
```
Items are grants in their wire form, so an album can hold films, pictures, live
channels and other albums (`shade media put dir/` turns subdirectories into nested
albums, in natural order). Parsing is strict on both sides: every item must be a
valid grant, at most 10 000 items, a title of at most 512 characters.
The relay stores an album as one more opaque object. It cannot tell an album from a
film, see its title, count its items or link it to them. Holding the album link means
holding every item's keys: deleting the album does not take them back from someone who
has already opened it. To revoke, delete the items.
Names in an album (and in any sealed file's meta) come from whoever sealed it, so
`shade media get` never uses them as paths: only the last path segment is kept,
without control characters or leading dots, and duplicates get a ` (2)` suffix.
`MediaClient.uploadAlbum`, `openAlbum` / `readAlbum` and `encodeAlbum` / `parseAlbum`
in TS, `Albums.parse` / `Albums.read` in Kotlin. The `/watch/` page shows an album as a
grid with decrypted previews, and Back returns from an item to its album. History
entries hold only a depth, never a grant.
## Films that play in any browser (`--web`)
Real films are often MKV with AC-3, E-AC-3 or DTS audio, or HEVC video. Browsers decode
none of those: Chromium refuses such a file outright ("no supported streams"). Since
sealing happens on the uploader's machine and the relay never sees the content, that is
the only place to fix it. `shade media put Film.mkv --web` runs ffmpeg first:
| In the file | Becomes |
|---|---|
| H.264, VP8, VP9, AV1 video | copied |
| other video (HEVC, MPEG-2, …) | H.264 (CRF 20), which takes a while |
| AAC, MP3, Opus audio | copied |
| other audio (AC-3, E-AC-3, DTS, TrueHD) | AAC, all tracks kept with their languages |
| text subtitles (SubRip, ASS, mov_text) | subtitle tracks (below), in the same pass |
| picture subtitles (PGS, DVD) | reported and skipped: they cannot become text |
The result is an MP4 with its index first. Without `--web`, `media put` uses ffprobe
(when it is installed) to say which streams browsers will not play.
## Subtitles
`shade media put Film.mkv` also seals and uploads the subtitle files next to it, named
the usual way: `Film.srt`, `Film.no.srt`, `Film.en-GB.vtt`. Their grants go into the
film's own sealed meta, under `extra["shade.subtitles"]`:
```jsonc
[{ "lang": "no", "label": "Norsk", "grant": { "kind": "shade.media-grant/v1", … } }, …]
```
So the subtitles travel with the film, shared alone or inside an album, and the relay
sees unrelated objects. In a directory, subtitles that belong to a video are not listed
as album items of their own. `shade media get` writes them back next to the film as
`Film.<lang>.srt`.
The `/watch/` page decrypts them through the worker, turns SubRip into WebVTT, and adds
them as `<track>`s with names in the viewer's language. The track in the browser's
language is on (Bokmål and Nynorsk match a `no` file), and only one is shown at a time.
On Android, `ShadeMedia.openFilm(grant)` opens the film and its subtitle files, and
`ShadeMedia.mediaSource(film)` gives them to ExoPlayer as side-loaded text tracks, the
one in the device's language marked default. A subtitle that cannot be opened is
skipped; the film plays without it. `withSubtitles` / `subtitlesOf` (TS) and
`Subtitles.of` (Kotlin) read and write the field, checked against a shared vector.
## What the relay learns
- **Sealed:** that an opaque id exists, its size (to within a segment), when it was
uploaded, which owner key uploaded it, and which ranges get fetched when. Range
patterns reveal viewing behaviour such as seeking and how far someone watched,
but not content.
- **Live:** that a channel is active, the frame sizes and timing (the bitrate
envelope of a video, the burstiness of a log), keyframe and sticky flags, epoch and
seq, and how many viewers are connected.
- **Never:** content, file names, titles, MIME types, or who a viewer is. Viewers
present a token, not an identity.
Padding sizes or frame timing would hide more, at a real cost in bandwidth. It is not
done in v1. A deployment that needs it can pad above this layer.
## Testing and vectors
- `packages/shade-media/tests/`: format round trips at every boundary, tamper
(flipped bytes, swapped segments, forged table, truncation), live chains (late
join, reordering, replay, forged frames from a key holder, rotation lock-out, link
mode across restarts), the HTTP routes and relay over real sockets, and the WebM
and fMP4 splitters on real ffmpeg output (keyframes inside a GOP, codec strings
for H.264, HEVC, AV1, VP9, AAC and Opus, CMAF `styp`/`prft` prefixes).
- `tests/object-store.test.ts` and `shade-storage-postgres/tests/postgres-media.test.ts`
run against a real S3 API and Postgres when `SHADE_TEST_S3_URL` /
`SHADE_TEST_PG_URL` are set (commands in the files): two relays over one bucket,
racing uploads and pins, sweeping, bounded memory.
- `test-vectors/media.json` (`bun run scripts/generate-vectors.ts media.json`): the
Kotlin port reads every vector and reproduces every sealed file and signed frame
byte for byte (`MediaVectorTest`).
- `bench/media.ts`: throughput, seek latency and live fan-out, written as
`bench/media.chart.json`.
## Design notes
- **Why not HLS/DASH with AES-128?** Their key delivery is a URL the player fetches,
so whoever runs the key server can read everything, and segments are not
authenticated. SMF1 needs only a Range-capable store and puts the key in a grant.
Because the Service Worker presents the decrypted file as an ordinary one, the
browser's native player handles seeking, buffering and codecs.
- **Why not `ShadeStream` (V4.11) for broadcast?** ShadeStream is a pairwise Double
Ratchet, ideal for one server streaming a console to one client. A broadcast to N
viewers through a relay would need N encryptions per frame, and the relay could not
keep one backlog for late joiners. Sender Keys encrypt once and sign once. The
signature restores what the pairwise ratchet gave for free: only the publisher can
speak.
- **Chrome's WebM rule.** Chrome's MSE demuxer rejects a cluster in which any block,
on any track, has an earlier timecode than the block before it. ffmpeg's live
muxer writes exactly that when Opus timestamps round a millisecond below an
interleaved video frame. The splitter sorts blocks within each cluster (stable, so
each track keeps its order). The cluster keeps its size and every block keeps its
bytes.
- **fMP4 keyframes.** The splitter reads sync-ness the way MSE does:
`trun` first-sample flags, else per-sample flags, else `tfhd` defaults, else the
`trex` defaults from the init. The codec string comes from the sample entry
(`avcC`, `hvcC`, `av1C`, `vpcC`, `esds`), so the browser is asked for exactly what
the encoder wrote. CENC-encrypted tracks (`encv`/`enca`) are refused; Shade already
encrypts, and a second DRM layer would leave the viewer without keys.
- **Bun 1.3.5.** `new Response(Bun.file(p).slice(a, b))` sent the whole file in
answer to a Range request when the file was large. The store therefore reads the
range itself.
## Limits (defaults)
| | |
|---|---|
| sealed file | 64 GiB per object, 256 GiB per owner (`MediaRoutesOptions`) |
| metadata | 64 KiB |
| live frame payload | 16 MiB |
| live backlog | 3 keyframes, at most 32 MiB / 5000 frames per channel |
| slow viewer | over 8 MiB buffered: frames dropped until it drains and a keyframe comes |
| channels held | 1000 live channels per relay; pins idle for 30 days are dropped |