Bun.sleep threw in a browser or Node the first time a piece was retried;
setTimeout does the same everywhere. The browser bundle has no Bun.* left.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
A chunk of 0 looped forever, a huge chunk held the film in memory and a huge
window opened a request (a thread on Kotlin) per piece. statusProblem checks
chunk, window, received and landed; the client window is capped at 16. Same
in MediaUploader, with tests on both sides.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
A piece at an offset is idempotent, which is what PUT means. Java's
HttpURLConnection, which the Kotlin port uses, refuses PATCH outright. nginx
also retries PUT on the next upstream by default but never PATCH, so the docs
now only ask for non_idempotent on the start/status POST. The protocol is
unreleased, so nothing else depends on the old method.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
When a piece failed through a proxy whose backend was down, the CLI printed
Bun's whole HTML error page. Answers that are HTML are now left out of error
messages, and the rest is cut at 300 characters.
Found in an end-to-end run: two S3+Postgres relays behind a load balancer,
`media put` of 300 MiB, one relay killed with SIGKILL mid-upload. The test
balancer went strictly round robin with no failover, so every retry's PATCH
hit the dead relay and the run stopped, saying to run it again. Run again
with failover to the next backend (like nginx proxy_next_upstream), the same
command resumed from the first run's job at 31%. Relay 3921 was killed again
after 4 pieces, 2 pieces failed over, and relay 3922 took 9. The file came
back byte-identical and shade_media_uploads was left empty.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
`live record <link> [-o base] [--put --server URL]` writes what a channel
carries until the channel ends or Ctrl-C:
- text goes to base.txt;
- video and sound go to base.webm or base.mp4: the init, then every chunk in
the order sent. A chunk that arrives late is left out and counted. A new
init continues in base-2.…;
- pictures go to base-images/.
ffmpeg then rewrites each recording with -c copy, which adds an index for
seeking and starts the clock at 0:00. `--put` seals and uploads the recording
under the channel's name (several files become an album). LiveRecorder is
exported from @shade/media/node.
`live video` now sends a sticky meta frame like text and picture channels do.
The browser and Android players ignore it.
Verified against a real relay:
- A 30 s VP8/Opus broadcast was recorded and is 29–32 s long, starting at 0.
- It was uploaded as "Kveldssending.webm" and plays in Chromium, with a seek
to 22 s (frame 14).
- Live playback with the meta frame still plays, with 2.4 s latency.
Tests:
- object-store's memory test now runs in its own process. RSS is process-wide,
and other test files in the same `bun test` made it flaky (192 MiB). It now
compares memory held after a collection at 128 MiB and 512 MiB, ~85 vs
~103 MiB, instead of using a magic number.
- The sweep test has its own prefix.
- tests/live-record.test.ts (4).
- media 122 green, 3 runs in a row. All 27 packages type-check.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
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>
Bun.serve reads a request body as fast as the client sends it, whether the
handler takes it or not. Whenever the store was slower than the client, one
PUT of a film put the whole film in the relay's memory: a 512 MiB upload
peaked at 762 MiB (disk) and 1011 MiB (S3).
A sealed file over 16 MiB now goes up as POST /v1/media/:id/upload plus
16 MiB PATCH pieces, each signed over its offset and length, up to 4 in
flight and landing in any order. Uploads under way are durable: on disk
uploads/<id>.part + .json + .log (the log names a piece only after fsync),
and in S3 a row in shade_media_uploads beside the multipart upload, where
piece n is part n+1. A dropped connection, a relay restart or the next piece
landing on another instance costs only the pieces in flight. The client asks
how far the upload got and sends the rest. Uploads count against quota and
are swept after 24 h without a piece. An upload still receiving pieces is
never swept, however old its multipart upload is.
The sweep is now part of every MediaStore and runs from createMediaService
(onSweep) instead of two copies of the timer. No route takes more than
64 MiB, so Bun's 128 MiB cap stays and the container's body limit covers
every route. `media put` shows progress.
bench/media-store.ts: the relay's peak RSS is 330–369 MiB at both 512 MiB
and 1.5 GiB (worst of 3 runs, both stores).
Also found:
- Bun 1.3.5 fetch never finishes sending a Bun.file().slice() body, so the
client reads each piece itself.
- postgres.js reads a NULL element of a TEXT[] as the string "NULL", so etags
are selected as JSON.
Tests:
- tests/upload.test.ts (11).
- S3 across two instances (+2).
- PG index (+1).
- media 114, storage-postgres 21, server 55, cli 15.
- All 27 packages type-check.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
LiveRelay.stop() fired the claim releases and forgot them, and nothing
closed the shared backend's Postgres pool: on a redeploy the process could
exit first, leaving the other instances to follow a dead relay until the
claim went stale (30 s). stop() is now async and resolves once the
releases are written; MediaService.stop() passes it through; the
container awaits it and closes the backend on SIGTERM, and `media serve`
gained SIGINT/SIGTERM handling that does the same and closes open sockets
so publishers and viewers reconnect elsewhere.
Verified: a test that a stopped relay's claim is gone at once; a real
`media serve --s3 --pg --advertise` with a live publisher: SIGTERM →
exit in ~0.4 s, its shade_live_publishers row 1 → 0, the publisher
reconnecting. Suites green (media 101, storage-postgres 20, server 55,
cli 15).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
`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>
Pictures were a live content type the watch page could show but nothing
could publish. `shade live images`:
- stdin: back-to-back JPEG/PNG, e.g.
`ffmpeg -f v4l2 -i /dev/video0 -r 1 -c:v mjpeg -f image2pipe -`;
- files/directories: a slideshow, one picture every --every seconds;
- --watch DIR: each new picture once its size holds still (cameras
write in pieces).
Each picture is a keyframe, so a late viewer opens on the latest. The meta
carries the first picture's type (MIME_RE rightly refuses image/*).
ImageStreamSplitter walks JPEG markers (lengths to SOS, then the
entropy-coded data, where every 0xFF is stuffed) and PNG chunks to IEND,
so an EXIF thumbnail — a whole JPEG inside APP1 — does not end a picture.
Bounded at 16 MiB per picture, junk refused at its first bytes.
The Android demo shows live picture channels and sealed pictures
(decoded off the UI thread, downsampled to the screen).
Verified: splitter on real ffmpeg MJPEG/PNG under random pipe chunking,
the thumbnail case, truncation, junk and the size cap (4 tests); in
Chromium a 2 fps MJPEG "webcam" through the relay (8 → 14 pictures in 3 s,
960×540); a watched folder with a PNG written in two halves (sent once,
whole) and a .txt ignored; slideshow; error paths. Demo APK builds; not
run on a device (none connected).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
`shade live video` wrote meta.mime from the container alone (video/webm,
video/mp4) before the init segment was seen, so an audio-only stream
(Opus/WebM, AAC/fMP4) played sound in a black 120 px video box. It now
reads until the splitter yields the init and uses its type
(audio/webm; codecs="opus"); the watch page then builds an <audio>, and
sound gets a player bar on the panel instead of a black stage.
Verified in Chromium, unmuted, through the relay: Opus/WebM and AAC/fMP4
radio both play (currentTime advancing, readyState 4) with measured
output (WebAudio RMS 0.044). Media suite 93/0.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
With several relays sharing pins, a viewer and the publisher could land on
different instances and never meet. LiveRelayOptions.mesh: each relay
claims the channels whose publisher it holds (LivePublisherLocator,
Postgres table shade_live_publishers, heartbeat 10 s). A relay whose
viewers want a channel published elsewhere subscribes to that relay once,
with a viewer's own read token, and fans out locally, verifying every
frame against the pin (a peer or a poisoned locator row cannot forge
one). Re-following replays a backlog; frames are passed on once (seq).
Viewers follow a publisher that moves. A token that fails the in-memory
pin is checked against the shared pin before refusal, so a publisher
back with a new read token is honoured on every instance.
SHADE_MEDIA_RELAY_URL / `media serve --advertise`.
Relays now send {"type":"state","live"} when a channel goes live or quiet
after a viewer joined; handled by the TS client (browser) and Android's
LiveWatcher.
Fixed on the way:
- The relay never saw its publisher leave: Hono gives each event its own
WSContext and the close handler compared identity. Channels stayed
"live" with nobody publishing; a replaced publisher was never closed.
- FileMediaStore on an unusable directory raised an unhandled rejection
at start; now each call fails with the reason.
Verified: 5 mesh tests (follow, late join, publisher moving A→B with
dedupe, forging peer refused, new read token) + state test, each fix
mutation-checked; Postgres locator + two media services over Postgres;
CLI relays with --advertise behind a round-robin HTTP+WS balancer:
publisher on A, Chromium viewer on B, "live", 208 lines. Suites: media
93, storage-postgres 20, server 55; Kotlin 92 (1 skipped), 0 failures.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
FileMediaStore ties a library to one disk on one machine. SHADE_MEDIA_S3_URL
+ SHADE_MEDIA_PG_URL (or `media serve --s3 --pg`) put sealed bytes in any
S3 bucket and the records every instance must agree on in Postgres.
- ObjectMediaStore: each upload streams as multipart to its own object
key; the commit is an INSERT whose primary key admits one record per id,
so racing uploads on any instances are decided once and the loser
deletes its object. Delete drops the record first. sweep() reclaims
unreferenced objects and dead multipart uploads past a 24 h grace.
- S3Bucket: Shade's own SigV4 client. Bun 1.3.5's S3Client buffers a
whole upload (512 MiB in, 543 MiB RSS), end(error) does not abort, and
slice(0, n).stream() returned the whole object. Here: at most three parts
in memory (512 MiB through, 11 MiB RSS), payload-hashed signatures,
AbortMultipartUpload, ranged reads checked for length.
- PostgresMediaIndex, PostgresLivePinStore, createSharedMediaBackend in
@shade/storage-postgres. LivePinStore.put now refuses a key change
(LivePinTakenError) in every store, atomically in Postgres.
- The container logs a backend it cannot use and runs on without media.
Verified: SigV4 reproduces AWS's published example signature; SeaweedFS
with signature checking accepts it and refuses a wrong secret (403);
Postgres 16: racing inserts over 8 pools (1 of 24 wins), racing pins,
BIGINT sizes; two relays over one backend; CLI relays behind a
round-robin proxy: upload, bit-identical download, Chromium playback
seeked to 24 s with ranges served by both; the bucket holds no
plaintext, name or MP4 marker. Suites: media 87, storage-postgres 18,
server 55, cli 15, all green.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The relay never knows names and a link is printed once, so a lost link
made an owned film unreachable. media put now appends each upload and its
grant to $XDG_CONFIG_HOME/shade/media-library.jsonl (0600, one JSON line
per change: concurrent uploads cannot lose entries, a torn line costs only
itself). media ls names uploads from it; media link <name|id> prints the
link again; media rm forgets it.
encodeGrant now writes meta in canonical (validateMeta) order, so one
grant is always one link; media.json vectors regenerated (album and
subtitle vectors only), Kotlin 82/0.
Verified: 82 TS tests (library: fold, find, 0600, torn line, 200
concurrent appends, stable encoding); CLI put → ls → link gives back the
identical link.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
ffprobe decides per stream: H.264/VP8/VP9/AV1 and AAC/MP3/Opus are
copied, anything else becomes H.264 (CRF 20) / AAC with every audio track
and its language kept; embedded text subtitles come out of the same
ffmpeg pass as subtitle tracks; picture subtitles are reported. Output is
an MP4 with the index first. Without --web, put warns when ffprobe sees
streams browsers will not play.
Verified: an HEVC + AC-3 5.1 MKV with embedded Norwegian/English SubRip:
Chromium refuses the original (DEMUXER_ERROR_NO_SUPPORTED_STREAMS); the
--web upload plays with audio decoded and the Norwegian track showing.
78 TS tests.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
`shade media put Film.mkv` seals Film.srt / Film.no.srt / Film.en.vtt
found beside it and carries their grants in the film's sealed meta
(extra["shade.subtitles"]), so they follow the film alone or in an album
and the relay sees unrelated objects. /watch/ adds them as <track>s (SRT
to VTT, labels in the viewer's language, the viewer's language on, one at
a time); `media get` writes them back; Android opens them with
ShadeMedia.openFilm and gives them to ExoPlayer as side-loaded tracks
(ShadeMediaDataSource now resolves readers by URI).
Verified: 76 TS tests; Chromium nb-NO shows the Norwegian track only, en-US
the English one; film + subtitles round-trip bit-identical; Robolectric
ExoPlayer sees both text tracks with the Norwegian one default; a shared
vector checks the meta field in Kotlin (82/0).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
An album is a sealed file (shade.album/v1) listing grants, so the relay
cannot tell it from a film. `shade media put dir/` uploads every file and
the album (subdirectories nest, natural order); `media get` brings an
album back as a directory; /watch/ shows a grid with decrypted previews
and Back returns to the album without putting grants in history. Kotlin
reads albums (Albums.read) against a new shared vector.
Fixed: `media get` used the sealer-chosen meta.name as the output path.
Fixed a relay test race (flush() is sent, not received); the relay now
reports framesIn.
Verified: 64 TS tests x3, Kotlin 81/0, a 6-file album with a nested album
uploaded, browsed, played and downloaded back bit-identical.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Fmp4Splitter cuts ftyp+moov into the sticky init and moof+mdat into frames,
reading sync samples from trun/tfhd/trex flags so fragments shorter than a
GOP still mark where late joiners may start. Codec strings come from the
sample entries. MediaSplitter sniffs WebM vs fMP4; the CLI's new
`live video` uses it (`live webm` stays as the pinned form).
Verified: 9 new tests on real ffmpeg output; H.264/AAC live in headless
Chromium (49/49 fragments appended, late join, 3.2 s latency) and a sealed
H.264 film seeking to 24 s.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Bun.serve refuses request bodies over 128 MiB by default, so every film
larger than that got a 413 from both `shade media serve` and the container.
The cap is now raised to the media object limit only when media is
mounted, and every other route gets an explicit 128 MiB bodyLimit — several
read the whole body before checking its size, so Bun's default was their
only guard. Verified on the standalone process: 300 MiB sealed film round
trip identical; a 200 MiB POST to a prekey route still 413.
docs/media.md: formats (SMF1, SLF1, grants) as the cross-language contract,
key schedule, what the relay learns, design notes, limits.
bench/media.ts: throughput, seek latency, live fan-out → media.chart.json.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
- createMediaService: sealed store + live relay + /watch in one mount, used
by both `shade media serve` and standalone.ts
- SHADE_MEDIA_DIR enables it (no in-memory fallback, like the vault);
SHADE_MEDIA_OWNERS lists who may upload and open live channels
- live publishers co-sign their hello with an owner key; a relay with an
owner list refuses everyone else, and the client stops on that refusal
instead of reconnecting forever
- relay caps live channels held at once; `shade media whoami`
Verified against the real standalone process: film round trip identical,
stranger gets 403 / refused channel, live logs and browser playback.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
test-vectors/media.json pins SMF1 files (empty, partial, exact boundary,
multi-segment with full metadata) and SLF1 live frames in link mode across
a rotation. Kotlin reads them and reproduces every sealed file and every
signed frame byte for byte; TS locks the same file.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
- Service Worker plays sealed files in native <video>/<audio>/<img> with
Range seeking; watch page served by the relay itself (#shade= fragment
links, grant never sent to a server)
- MSE live player with keyframe-aware joining, gap detection, latency control
- WebM splitter (init + clusters, keyframe detection) that puts blocks in
timecode order — Chrome rejects ffmpeg's interleaved Opus/VP8 otherwise
- Link mode for live channels: epoch seeds from a channel secret, so a
link survives publisher restarts and scheduled rotations
- File store streams byte ranges itself (Bun.file().slice() in a Response
sent whole files to Range requests)
- shade media serve|put|get|ls|rm, shade live text|webm|watch
Verified end to end in headless Chromium: VP9/Opus film plays and seeks,
live VP8/Opus at 2.9 s latency, live logs, sealed JPEG and Opus audio.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
SMF1 seals a film, video, image or song once into a file any Range-capable
store can serve; the reader fetches only segments under the playhead and
checks each against a digest table pinned by the grant's root digest.
Live channels use a sender-key chain with per-frame Ed25519 signatures,
sticky init frames and keyframe snapshots for late joiners, and epoch
rotation to remove a viewer. Server side: a disk-backed media store with
signed owner uploads and a WebSocket relay with bounded backlog.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>