Files
Shade/docs/media.md
Sterister 20c5ec07ab feat(media): media put resumes across runs, and a file already up gives its link again
A run already survives a dropped connection by retrying. This covers what one
run cannot survive: Ctrl-C, a laptop that sleeps, a relay that is gone for
longer than the retries wait.

Each file being put has a job under $XDG_CONFIG_HOME/shade/media-pending/,
keyed by server, path, size, mtime and options. The job holds:
- the sealed copy;
- job.json (0600: the seal result with the file key, the read token, and the
  meta including subtitle grants);
- a lock with the pid of the run working on it. A lock left by a dead run is
  taken over.

Running the same command again resumes with the same media id, so the relay
already has most of the file. Once the relay has stored it, the copy goes and
the grant stays. Putting the file again gives the same link while the relay
still serves it, so a season's put run again after it stopped re-sends only
what is missing. Jobs untouched for 30 days are removed.

Verified with real processes, a 300 MiB file and a file-store relay:
- Run 1 was SIGKILLed after 8 of 19 pieces.
- Run 2 resumed at 42% and finished.
- Run 3 printed "already on the relay, same link".
- `media get` returned the file byte-identical, and the library has one item.

tests/put-jobs.test.ts (4). media 118, cli 15. All 27 packages type-check.

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

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

# 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/media/:id/upload, /v1/live/:channelId (WebSocket), /watch/.

Uploads go up in pieces

A sealed file larger than 16 MiB is not one request. shade media put (and MediaClient.putSealed) starts an upload (POST /v1/media/:id/upload, signed over id, size and read-token hash) and sends it in pieces of 16 MiB (PATCH, each signed over its offset and length), up to 4 at once. The relay keeps what landed on disk or in the bucket, so:

  • A dropped connection costs the pieces in flight, not the film. After a failure the client asks the relay how far the upload got and sends only what is missing, with backoff, for up to 8 tries in a row. A piece sent twice is the same bytes twice, and the second is a no-op.
  • A relay restart, or the next piece landing on another instance, changes nothing. The upload is uploads/<id>.part + .json + .log on disk, or a row in shade_media_uploads beside its S3 multipart upload. The log (or the row) names only pieces already on stable storage, so a piece cut off by a crash is sent again.
  • The relay's memory is bounded by the window, not the film. This is the reason the protocol exists. Bun.serve does not hold back a request body the handler reads slowly: one PUT of a 512 MiB film put 762 MiB (disk) and 1011 MiB (S3) into the relay. In pieces, it stays around 350 MiB at 512 MiB and at 1.5 GiB alike (bench/media-store.ts). Every route now takes at most 64 MiB per request, so Bun's own 128 MiB cap stays in place.
  • An upload counts against the owner's quota from its start. One with no new piece for 24 hours is dropped by the sweep.

Across runs, too. Ctrl-C, a laptop that sleeps, or a relay gone for longer than the retries wait: run the same shade media put again and it goes on with the same media id. Each file being put has a job under $XDG_CONFIG_HOME/shade/media-pending/ (keyed by server, path, size, mtime and options) holding the sealed copy and what a rerun needs (job.json, 0600: it holds the file key, like the library). Once the relay has the file, the copy is removed and the grant is kept: putting the same file again gives the same link while the relay still serves it. So running a season's put again after it stopped at episode 7 sends only episodes 7 to 10. Jobs untouched for 30 days are removed.

A file of at most one piece still goes up as one PUT /v1/media/:id. The full exchange is described in packages/shade-media/src/upload.ts.

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. Each piece of an upload is one part of an S3 multipart upload, and any instance may take the next one. Every part's payload is hashed into its signature, so a part damaged in transit is refused. A file sent in one PUT goes up part by part as it arrives, with at most three 16 MiB parts in memory.
  • 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. Three kinds of leftovers are reclaimed after 24 hours: objects no record points at, uploads with no new piece in that time, and multipart uploads no upload owns (a crash mid-PUT). An upload still receiving pieces is spared, however old its multipart upload is. The sweep runs a minute after start and then hourly, for the disk store too, and 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

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.

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"]:

[{ "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.
  • bench/media-store.ts: disk store against S3 (+ Postgres) through the real routes, each relay in its own process. Upload and read speed, seek latency, and the relay's peak memory at two film sizes, median or worst of 3 runs (bench/media-store.chart.json).
  • tests/upload.test.ts: uploads in pieces on the memory and disk stores. Covers dropped connections before and after the relay stored a piece, a restart with a piece cut off mid-write, pieces out of order and twice at once, the window, signatures per offset, a bad footer at the last piece, quota and sweep. object-store.test.ts covers the same over S3 across two instances.

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, so the store reads the range itself. fetch(url, { body: Bun.file(p).slice(a, b) }) never finishes sending, so the client reads each piece itself. And Bun.serve buffers a request body without limit when the handler reads it slower than the client sends, which is why uploads go up in pieces.

Limits (defaults)

sealed file 64 GiB per object, 256 GiB per owner, uploads under way included (MediaRoutesOptions)
one request 64 MiB (MAX_PIECE_BYTES): a file larger than that goes up in pieces of 16 MiB (more for files over 156 GiB), 4 in flight
abandoned upload dropped after 24 h without a new piece
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