Files
Shade/docs/media.md
Sterister 9efe1bcfd3 feat(media,android): live channels in ExoPlayer — LiveWatcher, ShadeLiveDataSource
LiveWatcher is the Android LiveWatchClient (OkHttp WebSocket, subscribe
with the read token, reconnect with backoff, backlog deduplicated by the
subscriber). ShadeLiveDataSource turns frames into one endless WebM/fMP4
stream for ExoPlayer's extractors: init, then media from the first
keyframe, and after a gap nothing until the next keyframe. Late joiners
start at 0:00 (fMP4: per-join TimestampAdjuster; WebM: cluster Timecode
rewritten in place). A changed init fails with a ParserException (not
retried). The demo app plays live video and follows log channels.
LiveSubscriber.close() wipes keys, as in TS.

Verified (Robolectric): late join on H.264/AAC fMP4 and VP8/Opus WebM cut
by the TS splitter (fixtures from scripts/make-live-fixtures.ts) plays
from the keyframe, rebased (mutation check: without the rebase the WebM
test fails, 5020 vs 4250 ms); gap recovery; format change; LiveWatcher
against MockWebServer with a dropped connection and backlog replay.
Kotlin 81/0. Not yet run on a device.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 21:53:17 +02:00

19 KiB
Raw Blame History

@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

# 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"

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.

--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.

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.

In code

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:

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:

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

// 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:

{ "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.

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).
  • 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