Compare commits
43 Commits
fb7f2e55c0
...
v4.15.1
| Author | SHA1 | Date | |
|---|---|---|---|
| 200d5ad831 | |||
| 6852e09cb4 | |||
| 579d2730e0 | |||
| bc7cb85682 | |||
| 6f67bad97e | |||
| 8c7b8800fa | |||
| 98f54952b5 | |||
| 8d6f1fb8a6 | |||
| 65d7a0646f | |||
| 7d45be8712 | |||
| 0a706cdb47 | |||
| b53dcd7813 | |||
| f5125b8f66 | |||
| f42a9bbe5e | |||
| 441f26f814 | |||
| 6ee9ccc18a | |||
| 6e97329a58 | |||
| 5cc9133b3c | |||
| ee93dee8db | |||
| 20c5ec07ab | |||
| 0dc89e6cba | |||
| bd4882e1b8 | |||
| 5f7c6ff4b4 | |||
| 0bbeb5682b | |||
| d87db5f4dc | |||
| 1653060494 | |||
| f1b4c1ade1 | |||
| aaec92429d | |||
| 01f8471fb5 | |||
| d784e47ab3 | |||
| 422a37e830 | |||
| 9efe1bcfd3 | |||
| 8c7300fa51 | |||
| e696d83283 | |||
| 75dbf530ce | |||
| c5b897b924 | |||
| 4703140683 | |||
| 8fd1b19902 | |||
| e9ae5bd28e | |||
| df3ca685c5 | |||
| d117397b36 | |||
| f359cbd9ad | |||
| 9e64ec87be |
3
.gitignore
vendored
@@ -5,6 +5,3 @@ dist/
|
||||
**/.tmp-*.db
|
||||
**/.tmp-*.db-shm
|
||||
**/.tmp-*.db-wal
|
||||
|
||||
# Byggeartefakt fra @shade/observer (outDir-avviket i G0)
|
||||
dist-build/
|
||||
|
||||
51
.scaffold/branches/streaming.md
Normal file
@@ -0,0 +1,51 @@
|
||||
---
|
||||
branch: Streaming
|
||||
status: active
|
||||
order: 10
|
||||
updated: 2026-10-19
|
||||
started: 2026-10-18
|
||||
decided: "2026-10-18 — Cardwell: neste steg er Shade-streaming av tekst, video, bilder og lyd under Shade-kappen (filmer, videoer, bilder, logger). Bygges som ny pakke @shade/media oppå den låste stacken — kjernekrypto (ratchet, X3DH, proto) røres ikke, så G0–G4-revisjonen påvirkes ikke."
|
||||
---
|
||||
|
||||
## Mål
|
||||
- Filmer, videoer, bilder og lyd som spilles av E2E-kryptert, med spoling, uten at relayen ser innholdet.
|
||||
- Live-strømmer (logger, tekst, live video/lyd) fra én avsender til mange mottakere, E2E-kryptert, med sen innstigning.
|
||||
- Samme format i TS og Kotlin (delte test-vektorer), og avspilling rett i nettleseren (`<video>`, `<audio>`, `<img>`).
|
||||
|
||||
## Nå
|
||||
- [x] `@shade/media` SMF1: streaming-forsegling, tilfeldig tilgang, integritet mot nøkkelholdere, vektorer + tester
|
||||
- [x] Live-kanal: kjede, signaturer, epokerotasjon, sen innstigning, grants over Shade-sesjoner + tester
|
||||
- [x] Server: diskbasert medielager med Range-GET + live-relay over WebSocket med backlog + tester
|
||||
- [x] Klienter: HTTP Range-kilde, live-klient, CLI (`shade media …`, `shade live …`)
|
||||
- [x] Nettleser: Service Worker som spiller forseglede filer i `<video>`/`<img>`, MSE-spiller for live WebM; headless-test + film
|
||||
- [x] Kotlin: SMF1-leser + live-mottaker, verifisert mot vektorene
|
||||
- [x] Design + docs: `docs/media.md` (SMF1, live-kanal, trusselmodell), CHANGELOG, versjon, loggpost, commit
|
||||
|
||||
- [x] fMP4 (H.264/HEVC/AV1 + AAC/Opus) i live-splitteren ved siden av WebM, `shade live video` autodetekterer
|
||||
|
||||
- [x] Android: `:shade-android-media` (Media3 `ShadeMediaDataSource`, Robolectric-test med ExoPlayer som spiller og spoler) + `:shade-media-demo`-APK
|
||||
- [x] Album: én lenke for en sesong/et fotoalbum (forseglet liste av grants), `shade media put dir/`, rutenett i `/watch/`, Kotlin-leser + vektor
|
||||
- [x] Sikkerhet: `shade media get` brukte `meta.name` som filsti (sti-traversering) — rettet
|
||||
- [x] Android live: `LiveWatcher` + `ShadeLiveDataSource` (WebM/fMP4 i ExoPlayer, sen innstigning, hull, tidslinje fra 0), demo-appen spiller live video og følger loggkanaler
|
||||
- [x] Undertekster: `Film.no.srt` ved siden av filmen forsegles og følger filmen i dens meta; `<track>` i nettleseren (språkvalg, SRT→VTT), ExoPlayer på Android, `media get` skriver dem tilbake
|
||||
- [x] `media put --web`: HEVC/AC3/DTS-filmer (som Chromium nekter) konverteres før forsegling, innebygde tekstundertekster blir spor; advarsel uten flagget
|
||||
- [x] Lokalt bibliotek: `media ls` med navn, `media link <navn>` gir lenken igjen; kanonisk grant-koding (én grant = én lenke)
|
||||
- [x] Delt mediebibliotek for flere relay-instanser: filmer i S3 (egen SigV4-klient, multipart med begrenset minne), poster og live-pinner i Postgres, feiing av foreldreløse objekter; verifisert mot SeaweedFS med signaturkontroll + Postgres 16, to relayer bak round-robin
|
||||
- [x] Live på tvers av relay-instanser: relayene sier hvor publisererne er (Postgres), en relay med seere følger den som har publisereren og verifiserer hver ramme; seere får `state` når kanalen går live/stille (nettleser, TS, Android). To feil rettet underveis: relayen merket aldri at publisereren gikk (Hono-WSContext), og ubrukelig mediekatalog ga uhåndtert avvisning
|
||||
- [x] Live-lyd alene (radio/podkast): Opus/WebM og AAC/fMP4 gir lydspiller med målt lyd i Chromium (meta fikk init-segmentets ekte type)
|
||||
- [x] Bilder live: `shade live images` (webkamera via ffmpeg image2pipe, lysbildeserie, overvåket mappe); JPEG-/PNG-splitter med markørparsing; Android-demoen viser live og forseglede bilder (bygget, ikke kjørt på enhet)
|
||||
- [x] `shade live video --input <fil|rtsp://|/dev/video0>`: ffmpeg kjøres for deg, H.264/AAC kopieres, resten kodes (keyframe hvert 2. s); live i Chromium fra både VP9/Opus (omkodet, 0,96 s) og H.264/AAC (kopiert)
|
||||
- [x] Opplasting i stykker, gjenopptakbar: Bun.serve buffret hele filmen i relayens minne når lageret var tregere enn klienten (512 MiB-PUT → 762/1011 MiB RSS). Nå 16 MiB-stykker, 4 i flyt, i vilkårlig rekkefølge; brudd/omstart/annen instans koster bare stykkene i flyt; relay-RSS 330–369 MiB både ved 512 MiB og 1,5 GiB. Verifisert: relay drept med SIGKILL midt i `media put` av 300 MiB, startet igjen etter 4 s, opplastingen fullførte selv, byte-identisk
|
||||
- [x] `media put` gjenopptar på tvers av kjøringer (Ctrl-C, sovende laptop, lang nedetid): samme kommando fortsetter med samme media-id fra en forseglet kopi under `media-pending/`; en fil som allerede er oppe gir samme lenke igjen. Verifisert med SIGKILL etter 8/19 stykker → run 2 fortsatte fra 42 %, run 3 «already on the relay», byte-identisk
|
||||
- [x] `shade live record <link> [--put]`: en sending til filer (tekst, spolbar WebM/MP4 via ffmpeg -c copy, bilder) og med `--put` en forseglet film med egen lenke under kanalens navn. Verifisert: 30 s VP8/Opus-sending tatt opp, lastet opp som «Kveldssending.webm», spilt og spolt i Chromium (bilde 14)
|
||||
|
||||
- [x] Kotlin-opplaster: `MediaUploader` + `MediaOwner` (samme stykkeprotokoll, vindu, resync), `MediaSealer.sealStream`, `MediaGrant.encode/capabilityUrl`; eier-signaturer og grant-koding som nye vektorer; `scripts/media-live-kotlin.ts` mot ekte TS-relay med tapt svar + avvist stykke → TS leser 40 MiB-filmen tilbake byte for byte
|
||||
- [x] Demo-appen: «Del til Shade» — video/bilde/lyd/dokument fra galleriet forsegles på telefonen og lastes opp i en forgrunnstjeneste med fremdrift; flere filer på én gang blir ett album; varselet spiller av eller deler lenken. `UploadJobs` gjør at et drept opplastingsløp fortsetter med samme media-id; eiernøkkelen ligger under en Keystore-nøkkel (`KeystoreSecretFile`). Verifisert uten enhet: Robolectric-deling av `content://`-video mot ekte relay, album TS åpner, lint/bygg grønt
|
||||
- [x] Herding: opplasteren (TS + Kotlin) stolte blindt på relayens status — `chunk: 0` ga evig løkke, stort vindu ga en tråd per stykke; nå sjekket (`statusProblem`), vindu ≤ 16
|
||||
|
||||
## Neste
|
||||
- Kjør `:shade-media-demo` på dev-telefonen (RFCN504DWJF var ikke tilkoblet 2026-10-18/19): avspilling, live, og «Del til Shade» med en ekte galleri-video
|
||||
- Live fra telefonkameraet (`LivePublisher` finnes i Kotlin; mangler MediaCodec → fMP4-muxing)
|
||||
|
||||
## Senere
|
||||
- Sanntidssamtaler (V5.0): SFrame-nøkler fra samme kjede over WebRTC Insertable Streams
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
title: "media put forsegler lengde og bildestørrelse"
|
||||
date: 2026-10-20
|
||||
created: 2026-10-20T00:03:38+02:00
|
||||
author: "Claude"
|
||||
---
|
||||
|
||||
`media put` måler nå lengde og bildestørrelse med ffprobe og forsegler dem i meta (`durationMs`, `width`, `height`), målt på filen som faktisk forsegles (etter `--web`). Feltene fantes i `MediaMeta` og ble lest av Iris og `/watch/`, men ble aldri fylt ut. Derfor viste Iris på Android filmfliser uten lengde.
|
||||
|
||||
Verifisert: ny test i `tests/web-prep.test.ts` (film har lengde og størrelse, lyd bare lengde, bilde bare størrelse, manglende fil gir tomt). Hele `shade-media` er grønn: 119 bestått og 6 hoppet over. `tsc` er ren.
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
title: "Mediaworkeren kan bygges inn i en apps egen Service Worker"
|
||||
date: 2026-10-20
|
||||
created: 2026-10-20T00:13:40+02:00
|
||||
author: "Claude"
|
||||
---
|
||||
|
||||
Shade sin mediaworker kan nå bygges inn i en apps egen Service Worker via `@shade/media/worker`: `installShadeMedia(self)`, `isShadeMediaRequest` og `shadeMediaResponse`. Bakgrunnen er at en worker svarer på alle forespørslene fra sidene den kontrollerer. En installert PWA med worker på `/` slapp derfor aldri `media/<id>` videre til Shade-workeren ved siden av. Den frittstående `browser/sw.ts` er nå et tynt skall rundt samme modul.
|
||||
|
||||
Verifisert i Iris: `tests/shade.spec.ts` kjører både en app-worker med Shade bygd inn og den frittstående workeren mot en lokal relay (album, filmbilde, lengde, avspilling og spoling). På dev-telefonen er Iris-demoen installert fra Chrome som WebAPK og spiller forseglede filmer gjennom appens egen worker. `tsc` er ren, og `shade-media`-testene er grønne.
|
||||
@@ -0,0 +1,255 @@
|
||||
---
|
||||
title: "Shade-streaming: film, video, bilder, lyd og logger under Shade-kappen"
|
||||
date: 2026-10-18
|
||||
updated: 2026-10-19
|
||||
created: 2026-10-18T21:20:41+02:00
|
||||
author: "Claude"
|
||||
cover: "media/2026-10-18-shade-streaming/14-live-opptak-som-film.png"
|
||||
---
|
||||
|
||||
Shade kan nå strømme filmer, video, bilder, lyd og logger ende-til-ende-kryptert. Relayen lagrer og videresender bare chiffertekst, og den som har en grant, spiller av rett i nettleseren, i terminalen eller på Android.
|
||||
|
||||
**Oppdatert natt til 2026-10-19.** Siden kvelden har streamingen fått et delt bibliotek for flere relayer (S3 og Postgres), live på tvers av relayer, radio, bilder live og `--input`. Store filmer lastes nå opp i stykker som kan gjenopptas, også fra en ny kjøring, og en sending kan tas opp med `live record`. På telefonen er det kommet «Del til Shade»: en video eller bilder fra galleriet forsegles på telefonen og blir én lenke. Ingenting er publisert eller deployet.
|
||||
|
||||

|
||||

|
||||
|
||||

|
||||
|
||||
1. En forseglet VP9/Opus-film spilles av i Chromium gjennom Service Worker-en, spolt til 24 s; relayen ser bare chiffertekst
|
||||
2. Live VP8/Opus fra ffmpeg → shade live webm → relay → Chromium (MSE), 2,9 s forsinkelse; etter fiksen som sorterer blokkene i hvert kluster
|
||||
3. tail -f-aktig logg → shade live text → nettleser; den gamle lenken virker fortsatt etter at kanalen er startet på nytt (epoke 1)
|
||||
4. Et forseglet JPEG-bilde vist via Service Worker; lyd (Opus) spiller og spoler på samme måte
|
||||
5. Live H.264/AAC som fragmentert MP4 (ffmpeg → shade live video → relay → Chromium), sen innstigning på keyframe-fragment, 3,2 s forsinkelse
|
||||
6. Et album («Ferie 2026»): én lenke åpner film, video, lyd, bilde og et nøstet album; forhåndsvisningene dekrypteres i nettleseren, relayen ser bare én ugjennomsiktig fil til
|
||||
7. En forseglet film med Testfilm.no.srt og Testfilm.en.srt ved siden av: undertekstene følger filmen kryptert, og nettleseren velger norsk fordi den er satt til bokmål
|
||||
8. En ekte MKV-film med HEVC-video og AC3 5.1-lyd: Chromium nekter originalen («no supported streams»); med media put --web spiller den med lyd og den innebygde norske underteksten
|
||||
9. To relay-instanser bak en round-robin-lastbalanserer deler ett bibliotek (filmbytes i S3, poster i Postgres): opplastet via den ene, spilt og spolt til 24 s med Range-lesinger fra begge
|
||||
10. Live-logg på tvers av relayer: publisereren landet på instans A og seeren på B bak lastbalansereren; B følger A, verifiserer hver ramme mot pinnen og viser «live»
|
||||
11. Live-radio uten bilde (Opus/WebM og AAC/fMP4): spilleren får strømmens ekte type fra init-segmentet og blir en lydspiller, ikke en svart videoboks; lyd målt i Chromium (RMS 0,044)
|
||||
12. Bilder live: ffmpeg-«webkamera» (MJPEG, 2 bilder/s) → shade live images → nettleser; hvert bilde er en keyframe, så en sen seer åpner på det siste. Også lysbildeserie og overvåket mappe
|
||||
13. shade live video --input film.webm: CLI-en kjører ffmpeg selv, VP9/Opus kodes til H.264/AAC med keyframe hvert 2. s, live i Chromium med 0,96 s forsinkelse (H.264/AAC-kilder kopieres uten omkoding)
|
||||
14. Et live-opptak («shade live record --put») spilles av som forseglet film: 30 s sending, opptatt, ryddet med ffmpeg -c copy, forseglet og lastet opp under kanalens navn; spolt til 22 s
|
||||
|
||||
## Hva det er
|
||||
|
||||
Ny pakke **`@shade/media`** (4.15.0) som legger all streaming under Shade-kappen. To formater:
|
||||
|
||||
- **SMF1 — forseglede filer** (film, video, bilde, lyd). Fila deles i segmenter på 1 MiB, hver forseglet med AES-256-GCM og en nonce som er utledet fra segmentnummeret. AAD-en binder `mediaId`, indeksen og et siste-segment-flagg, så segmenter kan verken byttes om, flyttes mellom filer eller kuttes bort. En hale med kryptert metadata og SHA-256 av alle segmenter, pluss en `rootDigest` i grant-en, gjør at relayen ikke kan bytte innhold uten at det oppdages. Relayen serverer vanlige HTTP Range-forespørsler og ser bare chiffertekst.
|
||||
- **SLF1 — live-strømmer** (logger, tekst, live video/lyd). Én avsender, mange seere. Nøklene ruller fremover i en Sender Keys-kjede, og hver ramme signeres med Ed25519. Sene seere kommer inn på siste keyframe. Epokerotasjon kaster ut en seer. I lenkemodus overlever en delt lenke at kanalen startes på nytt.
|
||||
|
||||
Grants (`shade.media-grant/v1` / `shade.live-grant/v1`) sendes over en vanlig Shade-sesjon (`shade.shareMedia()` / `onMediaGrant()`) eller som en lenke med nøkkelen i `#shade=`-fragmentet. Fragmentet sendes aldri til serveren.
|
||||
|
||||
Fullt design, formatkontrakt og trusselmodell står i `docs/media.md`.
|
||||
|
||||
## Fullført
|
||||
|
||||
### Økt 2–4 (natt til 2026-10-19)
|
||||
|
||||
| Del | Verifisert slik |
|
||||
|---|---|
|
||||
| **Delt mediebibliotek**: filmer i S3 (egen SigV4-klient, multipart med begrenset minne), poster og live-pinner i Postgres, feiing av foreldreløse objekter | `tests/object-store.test.ts` + `postgres-media.test.ts` mot SeaweedFS (med signaturkontroll) og Postgres 16; to relayer bak round-robin |
|
||||
| **Live på tvers av relayer**: relayen med seere følger relayen som har publisereren, og verifiserer hver ramme; seere får `state` live/stille | servertester med to relayer; nettleser, TS og Android viser tilstanden |
|
||||
| **Radio/podkast** (bare lyd live: Opus/WebM, AAC/fMP4) | lydspiller med målt lyd i Chromium (bilde 11) |
|
||||
| **Bilder live**: `shade live images` (webkamera, lysbildeserie, overvåket mappe) | JPEG-/PNG-splitter med tester; Chromium viser bildene (bilde 12) |
|
||||
| **`shade live video --input <fil, rtsp:// eller /dev/video0>`**: ffmpeg kjøres for deg | live i Chromium både omkodet fra VP9/Opus og kopiert fra H.264/AAC (bilde 13) |
|
||||
| **Opplasting i stykker, gjenopptakbar**: 16 MiB per stykke, 4 i flyt, i vilkårlig rekkefølge | `tests/upload.test.ts` (12 tester); relay drept med SIGKILL midt i en `media put` av 300 MiB, startet igjen etter 4 s, filen ble byte-identisk; en lastbalanserer med S3+PG fortsatte fra 31 % da en instans ble drept |
|
||||
| **`media put` gjenopptar på tvers av kjøringer** (`media-pending/`) | drept etter 8 av 19 stykker; kjøring 2 fortsatte fra 42 %, kjøring 3 sa «already on the relay» og ga samme lenke |
|
||||
| **`shade live record <lenke> [--put]`** | 30 s VP8/Opus tatt opp, lastet opp som «Kveldssending.webm», spilt og spolt til 22 s i Chromium (bilde 14) |
|
||||
| **Kotlin-opplaster** `MediaUploader` + `MediaOwner` (samme stykkeprotokoll), `MediaSealer.sealStream`, grant-koding til lenke | nye vektorer for eier-signaturer og grant-koding (byte for byte); `scripts/media-live-kotlin.ts` mot ekte TS-relay med et tapt svar og et avvist stykke lagt inn, og TS leser 40 MiB-filmen tilbake byte for byte |
|
||||
| **`UploadJobs`**: et drept opplastingsløp fortsetter med samme media-id | `UploadJobsTest` (4); i live-kjøringen «drepes» jobben etter første stykke og fortsetter, og en tredje deling sender ingenting og gir samme lenke |
|
||||
| **«Del til Shade» i demo-appen**: forgrunnstjeneste med fremdrift; eiernøkkel under en Keystore-nøkkel (`KeystoreSecretFile`); flere filer gir ett album; spilleren viser album | Robolectric `ShadeUploadTest` deler en `content://`-video mot den ekte relayen; Kotlin lager et album som TS åpner; albumvektoren forsegles på nytt byte for byte fra Kotlin; bygg og lint grønt. **Ikke kjørt på enhet** |
|
||||
| **Herding**: opplasteren stolte på relayens status | se «Feil» nedenfor; tester på begge sider |
|
||||
|
||||
Suiter ved slutt: `@shade/media` 124 grønne, typecheck rent i alle 27 pakker, `:shade-android:test` og `:shade-android-media:testDebugUnitTest` grønne, `:shade-media-demo` bygger og passerer lint.
|
||||
|
||||
### Økt 1 (kveld 2026-10-18)
|
||||
|
||||
| Del | Verifisert slik |
|
||||
|---|---|
|
||||
| SMF1-forsegling og -leser (streaming, tilfeldig tilgang, LRU, samlede range-kall) | `tests/sealed.test.ts`: tukling, ombytting, avkutting, feil nøkkel |
|
||||
| Live-kanal (kjede, signaturer, sticky init/meta, keyframe-snapshot, rotasjon, lenkemodus) | `tests/live.test.ts` |
|
||||
| Medielager på disk (atomisk commit, sidecar, indeks), Range-ruter, kvoter, eiere | `tests/server.test.ts`, inkludert en regresjonstest for Bun-slice-feilen |
|
||||
| Live-relay over WebSocket (pinning, backlog, avlasting av trege seere) | `tests/server.test.ts` |
|
||||
| WebM-splitter (init og klustre, keyframes, sortering av blokker) | `tests/webm.test.ts` |
|
||||
| CLI: `shade media serve/put/get/ls/rm/whoami`, `shade live text/webm/watch` | Kjørt ende til ende mot ekte server |
|
||||
| Nettleser: Service Worker med Range til `<video>`/`<audio>`/`<img>`, MSE-spiller for live | Headless Chromium: film spolt til 24 s, live-video 44/44 rammer med 2,9 s forsinkelse, logger, bilde og lyd |
|
||||
| Kotlin: SMF1-leser og -forsegler, live-mottaker, grants | 9 vektortester (byte-identisk forsegling); hele Kotlin-suiten har 80 tester, 0 feil |
|
||||
| Delte test-vektorer | `test-vectors/media.json`, 15 vektorer |
|
||||
| `shade-server standalone` | Media monteres når `SHADE_MEDIA_DIR` er satt; 300 MiB rundtur bit-identisk; 200 MiB mot `/v1/bundles` gir fortsatt 413 |
|
||||
| SDK | `shareMedia`/`onMediaGrant`; hele SDK-suiten grønn (111) |
|
||||
|
||||
Totalt 43 tester i `@shade/media`, og tsc er rent. Kjernekryptoen (ratchet, X3DH, proto) er ikke rørt, så G0–G4-revisjonen påvirkes ikke.
|
||||
|
||||
## Tall
|
||||
|
||||
Fra `bench/media.ts`, med 1 GiB tilfeldige data:
|
||||
|
||||
```chart
|
||||
{
|
||||
"type": "bar",
|
||||
"title": "Sealed media throughput (MiB/s)",
|
||||
"subtitle": "1024 MiB of incompressible data, 1 MiB segments, one core",
|
||||
"y": {"label":"MiB/s","min":0},
|
||||
"note": "Bun 1.3.5; HTTP is localhost through the real media routes; size overhead 0.0046 %",
|
||||
"source": {"path":"bench/media-results.json","sha256":"6db8fb2955253753371ca00b6f1d6a2ec32a3c0c3000ad5204f9b8a19e22c06c"},
|
||||
"series": [
|
||||
{"name":"MiB/s","data":[["seal (disk → disk)",259.1],["read + verify (disk)",480.2],["upload (HTTP PUT)",50.9],["read + verify (HTTP Range)",209.5]]}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
```chart
|
||||
{
|
||||
"type": "bar",
|
||||
"title": "Seeking in a sealed film over HTTP (ms)",
|
||||
"subtitle": "open = footer + trailer + root check; seek = first 64 KiB at a random offset, no cache",
|
||||
"y": {"label":"ms","min":0},
|
||||
"note": "n = 10 opens, 100 seeks; localhost",
|
||||
"source": {"path":"bench/media-results.json","sha256":"6db8fb2955253753371ca00b6f1d6a2ec32a3c0c3000ad5204f9b8a19e22c06c"},
|
||||
"series": [
|
||||
{"name":"p50","data":[["open",3.28],["seek",3.98]]},
|
||||
{"name":"p95","data":[["open",6.58],["seek",8.21]]}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
```chart
|
||||
{
|
||||
"type": "line",
|
||||
"title": "Live fan-out: latency publish → decrypted, by viewers",
|
||||
"subtitle": "10 fps × 32 KiB frames (≈ 2.6 Mbit/s) for 6 s; relay in its own process, all viewers in one",
|
||||
"x": {"label":"viewers"},
|
||||
"y": {"label":"ms","min":0},
|
||||
"note": "delivered: 1 → 100 %, 10 → 100 %, 50 → 100 %, 100 → 100 %, 200 → 100 %. Every viewer verifies every signature and decrypts every frame, in one process, so the curve is mostly the viewers' CPU, not the relay's.",
|
||||
"source": {"path":"bench/media-results.json","sha256":"6db8fb2955253753371ca00b6f1d6a2ec32a3c0c3000ad5204f9b8a19e22c06c"},
|
||||
"series": [
|
||||
{"name":"p50","data":[[1,3],[10,6],[50,22],[100,15],[200,28]]},
|
||||
{"name":"p95","data":[[1,12],[10,20],[50,58],[100,72],[200,151]]}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> Opplastingen (51 MiB/s for 1 GiB) er begrenset av disken, ikke av koden. Samme opplasting går i 373 MiB/s på tmpfs. Det som skjer er writeback og fsync av temp-fila før `link()`.
|
||||
|
||||
Relayens minne ved opplasting av store filmer, før og etter stykkene: en enkelt PUT på 512 MiB fikk relayen opp i 762 MiB (disk) og 1011 MiB (S3). Med stykker ligger den på rundt 330–370 MiB både ved 512 MiB og 1,5 GiB, altså uavhengig av filmens størrelse. Målt av `bench/media-store.ts`, der hver relay går i sin egen prosess, med median eller verste av 3 kjøringer:
|
||||
|
||||
```chart
|
||||
{
|
||||
"type": "bar",
|
||||
"title": "Sealed film store: disk vs S3 (MiB/s)",
|
||||
"subtitle": "1536 MiB film through the real media routes, median of 3 runs; relay in its own process; S3 = local SeaweedFS",
|
||||
"y": {"label":"MiB/s","min":0},
|
||||
"note": "Bun 1.3.5. Uploads go up in 16 MiB pieces, up to 4 in flight. Disk: each piece fsynced before it is acknowledged. S3: each piece is one SHA-256-signed multipart part.",
|
||||
"source": {"path":"bench/media-store-results.json","sha256":"c44122ed2c11654de9268e7dbcaa766c433890fe8eae3ab9f52c51ce35f3cbf3"},
|
||||
"series": [
|
||||
{"name":"disk (FileMediaStore)","data":[["upload (pieces)",286.6],["read + verify (Range)",199.6]]},
|
||||
{"name":"S3 + Postgres (ObjectMediaStore)","data":[["upload (pieces)",79.3],["read + verify (Range)",107.4]]}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
```chart
|
||||
{
|
||||
"type": "bar",
|
||||
"title": "Relay memory does not grow with the film",
|
||||
"subtitle": "Peak relay RSS growth during one upload (VmHWM − RSS before), worst of 3 runs, per film size",
|
||||
"y": {"label":"MiB","min":0},
|
||||
"note": "Bounded by the upload window (4 pieces of 16 MiB) and garbage not yet collected. Before pieces, one PUT of a 512 MiB film put 762 MiB (disk) and 1011 MiB (S3) in the relay: Bun.serve reads a request body as fast as the client sends.",
|
||||
"source": {"path":"bench/media-store-results.json","sha256":"c44122ed2c11654de9268e7dbcaa766c433890fe8eae3ab9f52c51ce35f3cbf3"},
|
||||
"series": [
|
||||
{"name":"disk (FileMediaStore)","data":[["512 MiB film",330],["1536 MiB film",369]]},
|
||||
{"name":"S3 + Postgres (ObjectMediaStore)","data":[["512 MiB film",360],["1536 MiB film",358]]}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
```chart
|
||||
{
|
||||
"type": "bar",
|
||||
"title": "Seek latency, disk vs S3 (ms)",
|
||||
"subtitle": "64 KiB at a random offset of the 1536 MiB film, fresh reader each (n = 50 per run, median of 3 runs)",
|
||||
"y": {"label":"ms","min":0},
|
||||
"note": "Includes opening: footer + trailer + root check, then the range.",
|
||||
"source": {"path":"bench/media-store-results.json","sha256":"c44122ed2c11654de9268e7dbcaa766c433890fe8eae3ab9f52c51ce35f3cbf3"},
|
||||
"series": [
|
||||
{"name":"disk (FileMediaStore)","data":[["p50",9.05],["p95",19.37]]},
|
||||
{"name":"S3 + Postgres (ObjectMediaStore)","data":[["p50",20.37],["p95",31.89]]}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Feil funnet underveis
|
||||
|
||||
- **Bun 1.3.5 sendte hele fila** når `Bun.file().slice()` ble brukt som svar på en Range-forespørsel. Lageret strømmer nå selve byteområdet, og det finnes en regresjonstest.
|
||||
- **Bun avviser kropper over 128 MiB** som standard, så filmer over 128 MiB fikk 413. Grensen er hevet bare for `/v1/media/`. Alle andre ruter fikk en eksplisitt `bodyLimit`, fordi prekey-rutene leser hele kroppen før de sjekker størrelsen.
|
||||
- **ffmpeg fletter Opus- og VP8-blokker ute av tidsrekkefølge**, og Chrome sin MSE avviser det. Splitteren sorterer nå blokkene stabilt innen hvert kluster.
|
||||
- **En publisher som ble avvist, koblet seg til på nytt i det uendelige.** Lukkekode 1008 er nå endelig.
|
||||
- **Bun.serve buffret hele filmen** i relayens minne når lageret var tregere enn klienten. Det var grunnen til de høye RSS-tallene, og grunnen til at opplasting nå går i stykker.
|
||||
- **`fetch` med en `Bun.file().slice()` som kropp ble aldri ferdig** (Bun 1.3.5). Klienten leser derfor hvert stykke inn i minnet først, maks 4 × 16 MiB.
|
||||
- **postgres.js leste NULL i en TEXT[] som strengen «NULL»**, og PG-subscript i en tom array flyttet nedre grense. Løst med `array_fill` ved innsetting og `array_to_json` ved lesing.
|
||||
- **Et tapt svar på siste stykke ga EXISTS** ved gjenopptak. POST svarer nå `complete: true` til samme eier.
|
||||
- **Java sin HttpURLConnection kan ikke PATCH**, så stykkene er nå PUT. Den endringen kom før Kotlin-opplasteren.
|
||||
- **Opplasteren (TS og Kotlin) stolte blindt på relayens status.** `chunk: 0` ga en evig løkke, en stor `chunk` holdt hele filmen i minnet, og et stort `window` ga én forespørsel (på Kotlin: én tråd) per stykke. Status sjekkes nå (`statusProblem`), og vinduet er maks 16.
|
||||
- **`MediaClient` brukte `Bun.sleep`** før nye forsøk, så et nytt forsøk kastet i nettleser og Node. Bruker nå `setTimeout`.
|
||||
|
||||
## Beslutninger
|
||||
|
||||
- **Stykker i stedet for én stor PUT.** En enkelt PUT er begrenset til 64 MiB; over det svarer relayen `413 USE_UPLOAD`. Stykkene er PUT, så nginx kan prøve dem på nytt; POST-en trenger `non_idempotent` (står i `docs/media.md`).
|
||||
- **Demo-appen krever nå minSdk 28**, fordi eiernøkkelen ligger i Keystore-modulen. Det er en demo, ikke et produkt, og dev-telefonen er nyere.
|
||||
- **Eiernøkkelen på telefonen er ikke biometri-låst.** Den signerer hvert stykke, og et fingeravtrykk per stykke ville gjort opplasting umulig. Mister appen Keystore-nøkkelen (data gjenopprettet på en annen telefon), lages en ny eier, og relayen må få den nye id-en.
|
||||
- **Bare navn, type, størrelse, varighet og bildestørrelse** følger med i meta fra telefonen; ingen posisjon og ingen sti.
|
||||
- **Opplasting fra nettleseren ble ikke bygget i natt.** Den trenger et lagringsvalg for eiernøkkelen i nettleseren, og forsegling som strømmer rett inn i opplastingen. Det er beskrevet under «Neste».
|
||||
- **Ny pakke i stedet for endringer i kjernen.** Dermed holdes G0–G4-revisjonen ren.
|
||||
- **`shade media serve` er lukket som standard.** Bare din egen nøkkel og eventuelle `--owners` kan laste opp; `--open` slipper inn alle.
|
||||
- **Ingen `SHADE_MEDIA_DIR`-standard i Dockerfile**, slik det er gjort for vault. Det er stilt som spørsmål nedenfor.
|
||||
- **Lenkemodus er bevisst svakere.** Den som har lenken, kan lese alle epoker. Avveiningen er dokumentert i `docs/media.md`, og vanlig modus (grants per seer over Shade) har ekte utkasting.
|
||||
- **CLI-en roterer hver 20 000. ramme.**
|
||||
|
||||
> [!QUESTION] id=media-dockerfile-default · default: A · asked-by=06aacd12
|
||||
> Skal Docker-imaget slå på media som standard (SHADE_MEDIA_DIR=/data/media), eller bare når det settes eksplisitt?
|
||||
> - [x] A — Bare eksplisitt, som vault (ingen overraskende diskbruk)
|
||||
> - [ ] B — Standard /data/media i Dockerfile
|
||||
> - [ ] Annet: ___
|
||||
> answered: 2026-10-18 21:33 · A063
|
||||
|
||||
## Blokkert / trenger deg
|
||||
|
||||
- **Kjøring på enhet:** dev-telefonen (RFCN504DWJF) var ikke tilkoblet (`adb devices` tom) verken 18. eller 19. oktober. Du må plugge den i, så kan neste økt installere `:shade-media-demo` og kjøre avspilling, live og «Del til Shade» med en ekte galleri-video. Ingen emulator er startet.
|
||||
- Publisering og deploy av 4.15.0 er ikke gjort, med vilje.
|
||||
|
||||
## Endret
|
||||
|
||||
- `packages/shade-media/`: `src/upload.ts` (ny), `owner.ts`, `client.ts`, `put-jobs.ts` (ny), `live/record.ts` (ny), `cli.ts`, `server/{file-store,object-store,media-routes,service}.ts`, tester (`upload`, `put-jobs`, `live-record`, `object-store`)
|
||||
- `packages/shade-storage-postgres/` (`shade_media_uploads`), `packages/shade-server/src/standalone.ts`
|
||||
- `android/shade-android/…/media/`: `MediaOwner.kt`, `MediaUploader.kt`, `UploadJobs.kt` (nye), `MediaGrant.kt`, `Album.kt`, `MediaFormat.kt`, `MediaReader.kt`; tester `MediaLiveTest`, `MediaUploaderTest`, `UploadJobsTest`, `MediaVectorTest`
|
||||
- `android/shade-android-keystore/…/KeystoreSecretFile.kt` (ny), `android/shade-android-media/…/ShadeUpload.kt` (ny) + `ShadeUploadTest`
|
||||
- `android/shade-media-demo/`: `ShareActivity`, `UploadService`, `Uploads` (nye), `PlayerActivity` (del-knapp, album), manifest, gradle
|
||||
- `scripts/media-live-kotlin.ts` (ny), `scripts/generate-vectors.ts`, `test-vectors/media.json` (19 vektorer)
|
||||
- `bench/media-store*.ts` + `bench/media-store.chart.json`, `docs/media.md`, `CHANGELOG.md` (4.15.0)
|
||||
- Ikke committet med vilje: `.cursor/`, `.serena/`, `docs/ECOSYSTEM.md`, endringen i `CLAUDE.md` (ikke mine)
|
||||
|
||||
<details><summary>Endret i økt 1</summary>
|
||||
|
||||
- `packages/shade-media/` (ny)
|
||||
- `docs/media.md`
|
||||
- `test-vectors/media.json`, `scripts/generate-vectors.ts`
|
||||
- `android/shade-android/src/main/kotlin/no/zyon/shade/media/` og `MediaVectorTest.kt`
|
||||
- `packages/shade-server/src/standalone.ts`, `packages/shade-sdk/src/shade.ts`, `packages/shade-cli/src/cli.ts`
|
||||
- `bench/media*.ts`, `bench/media.chart.json`
|
||||
- CHANGELOG og versjon 4.15.0
|
||||
- Commits fra `9e64ec8` til `4703140` på `main`
|
||||
|
||||
</details>
|
||||
|
||||
## Budsjett
|
||||
|
||||
Ved slutt (00:39): økt 34 % (nullstilles 03:00), uke 57 % (nullstilles om 3 d 13 t). Konteksten er 24 % brukt. Økten ble komprimert 4 ganger; sporet (plan, gren, captions, git) dekket alt, og ingenting kjent gikk tapt.
|
||||
|
||||
## Neste
|
||||
|
||||
- **Plugg inn dev-telefonen:** kjør `:shade-media-demo`, del en ekte video og et par bilder fra galleriet, og spill av lenkene.
|
||||
- **Opplasting fra nettleseren** (iPhone uten app): eiernøkkel i nettleseren og forsegling som strømmer rett inn i stykkene.
|
||||
- **Live fra telefonkameraet:** `LivePublisher` finnes i Kotlin; det som mangler er muxing fra MediaCodec til fMP4.
|
||||
- Publiser og deploy 4.15.0 når G0-publiseringssakene er løst.
|
||||
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 152 KiB |
|
After Width: | Height: | Size: 127 KiB |
|
After Width: | Height: | Size: 101 KiB |
|
After Width: | Height: | Size: 151 KiB |
|
After Width: | Height: | Size: 53 KiB |
|
After Width: | Height: | Size: 162 KiB |
|
After Width: | Height: | Size: 195 KiB |
|
After Width: | Height: | Size: 156 KiB |
|
After Width: | Height: | Size: 124 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 211 KiB |
|
After Width: | Height: | Size: 66 KiB |
|
After Width: | Height: | Size: 165 KiB |
@@ -0,0 +1,14 @@
|
||||
01 — En forseglet VP9/Opus-film spilles av i Chromium gjennom Service Worker-en, spolt til 24 s; relayen ser bare chiffertekst
|
||||
02 — Live VP8/Opus fra ffmpeg → shade live webm → relay → Chromium (MSE), 2,9 s forsinkelse; etter fiksen som sorterer blokkene i hvert kluster
|
||||
03 — tail -f-aktig logg → shade live text → nettleser; den gamle lenken virker fortsatt etter at kanalen er startet på nytt (epoke 1)
|
||||
04 — Et forseglet JPEG-bilde vist via Service Worker; lyd (Opus) spiller og spoler på samme måte
|
||||
05 — Live H.264/AAC som fragmentert MP4 (ffmpeg → shade live video → relay → Chromium), sen innstigning på keyframe-fragment, 3,2 s forsinkelse
|
||||
06 — Et album («Ferie 2026»): én lenke åpner film, video, lyd, bilde og et nøstet album; forhåndsvisningene dekrypteres i nettleseren, relayen ser bare én ugjennomsiktig fil til
|
||||
07 — En forseglet film med Testfilm.no.srt og Testfilm.en.srt ved siden av: undertekstene følger filmen kryptert, og nettleseren velger norsk fordi den er satt til bokmål
|
||||
08 — En ekte MKV-film med HEVC-video og AC3 5.1-lyd: Chromium nekter originalen («no supported streams»); med media put --web spiller den med lyd og den innebygde norske underteksten
|
||||
09 — To relay-instanser bak en round-robin-lastbalanserer deler ett bibliotek (filmbytes i S3, poster i Postgres): opplastet via den ene, spilt og spolt til 24 s med Range-lesinger fra begge
|
||||
10 — Live-logg på tvers av relayer: publisereren landet på instans A og seeren på B bak lastbalansereren; B følger A, verifiserer hver ramme mot pinnen og viser «live»
|
||||
11 — Live-radio uten bilde (Opus/WebM og AAC/fMP4): spilleren får strømmens ekte type fra init-segmentet og blir en lydspiller, ikke en svart videoboks; lyd målt i Chromium (RMS 0,044)
|
||||
12 — Bilder live: ffmpeg-«webkamera» (MJPEG, 2 bilder/s) → shade live images → nettleser; hvert bilde er en keyframe, så en sen seer åpner på det siste. Også lysbildeserie og overvåket mappe
|
||||
13 — shade live video --input film.webm: CLI-en kjører ffmpeg selv, VP9/Opus kodes til H.264/AAC med keyframe hvert 2. s, live i Chromium med 0,96 s forsinkelse (H.264/AAC-kilder kopieres uten omkoding)
|
||||
14 — Et live-opptak («shade live record --put») spilles av som forseglet film: 30 s sending, opptatt, ryddet med ffmpeg -c copy, forseglet og lastet opp under kanalens navn; spolt til 22 s
|
||||
@@ -1,11 +1,9 @@
|
||||
---
|
||||
project: "Shade"
|
||||
phase: "Post-4.x GA — hardening til revisjonsklar (G0–G4) før V5.0-design"
|
||||
updated: 2026-10-15
|
||||
focus: "GCM-nonce-fiksen er levert (2026-08-13) og @shade/vault står ferdig og testet (2026-08-14), men er IKKE deployet eller publisert. De tre gjenstående G0-P0-ene er publiserings- og CI-saker. Historikk: G0 fikk en andre bestiller: @shade/vault (server-side kryptert fillager, bestilt 2026-08-13 av Scaffold-backupen) bygger på at-rest-stacken, og skal ikke reise seg på en kjent GCM-svakhet. Nonce-fiksens migreringssti er verifisert gratis — aeadOpen leser alltid nonce fra prefiks, så eksisterende blobber åpnes uendret."
|
||||
blockers:
|
||||
- "P0: @shade/observer@4.11.1 tomt på registry (outDir=dist-build, publish shipper dist/)"
|
||||
- "P0: @shade/cli bin dingler etter publish (bin ikke omskrevet til dist/)"
|
||||
updated: 2026-10-20
|
||||
focus: "GCM-nonce-fiksen er levert (2026-08-13) og @shade/vault står ferdig og testet (2026-08-14), men er IKKE deployet eller publisert. 4.15.0 er publisert (2026-10-20) med observer- og cli-P0-ene fikset i publiseringsskriptet; G0 har CI-gaten igjen. Historikk: G0 fikk en andre bestiller: @shade/vault (server-side kryptert fillager, bestilt 2026-08-13 av Scaffold-backupen) bygger på at-rest-stacken, og skal ikke reise seg på en kjent GCM-svakhet. Nonce-fiksens migreringssti er verifisert gratis — aeadOpen leser alltid nonce fra prefiks, så eksisterende blobber åpnes uendret."
|
||||
blockers: []
|
||||
---
|
||||
|
||||
# Plan — Shade
|
||||
@@ -20,7 +18,7 @@ Gated hardening — hard utgangsport per steg (full plan + funn: helsesjekk-arti
|
||||
- [ ] **Publiser 4.13.2** (register med tidsgrense + ekte retry + `registration: 'background'`,
|
||||
gjort 2026-10-15, se `logs/2026-10-15-register-venter-ikke-lenger-pa-en-server-som-ikke-svarer.md`).
|
||||
Venter på at `gt.zyon.no` er oppe. UNCOMMITTED.
|
||||
- [ ] **G0 — Stopp blødningen (P0):** ~~tilfeldig nonce per skriving i
|
||||
- [x] **G0 — Stopp blødningen (P0):** ~~tilfeldig nonce per skriving i
|
||||
storage-encrypted~~ (gjort 2026-08-13 — 9 nye tester, ingen migrering nødvendig,
|
||||
Android var aldri rammet; se `logs/2026-08-13-gcm-nonce-reuse-fikset.md`.
|
||||
**Ikke publisert** — Prism er pinnet på 4.12.0); observer `outDir→dist` +
|
||||
@@ -30,10 +28,14 @@ Gated hardening — hard utgangsport per steg (full plan + funn: helsesjekk-arti
|
||||
borte og alle 26 pakker er grønne); fiks `bin`-omskriving + tarball-verifisering i publish.
|
||||
Port: typecheck grønn i CI, nonce-negativtest grønn, `bun pm pack` inneholder
|
||||
main-fil for alle pakker.
|
||||
Resten gjort 2026-10-20: observer bygger til `dist/`, `bin` omskrives til `dist/*.js`, og
|
||||
`publish-all.ts` avviser en tarball som mangler en fil `main`/`types`/`bin`/`exports` peker på
|
||||
(bevist mot den gamle observer-feilen). 4.15.0 publisert med alle 27 pakker.
|
||||
- [ ] **G1 — Revisjonsklar kjerne (P1):** peer-signeringsnøkkel per sesjon → symmetrisk safety-number; argon2id i backup-KDF (TS+Kotlin); hono ≥4.12.18; håndhevende §4 at-rest-tuklingstest; bestill ekstern krypto-review + pentest. Port: `alice.verify(bob, bob.getIdentityFingerprint())`===true, `bun audit` ren.
|
||||
- [ ] **G2 — CI som mur:** biome + coverage-terskel + soak:smoke i CI; fjern/synk `.github/workflows`; publish kjører `prepublish:check`; bryt server↔inbox-server-syklus; rydd sdk/cli/files-deps; `dashboard: private`; pin bun. Port: PR blokkeres ved brudd, alle 8 examples grønne i CI.
|
||||
|
||||
## Neste
|
||||
- **Streaming (`@shade/media`, 4.15.0)** — levert 2026-10-18, se `branches/streaming.md`: forseglede filmer/bilder/lyd (SMF1) og live-strømmer (SLF1) E2E, TS + Kotlin; fMP4 + WebM live, ExoPlayer (Android), album, undertekster, `--web`, delt S3/Postgres-lager. Delte relay-instanser med live på tvers, gjenopptakbar opplasting i stykker, `live record`, og «Del til Shade» fra Android (album av flere filer). Gjenstår: demo-APK på enhet. Ikke publisert eller deployet.
|
||||
- **V4.13 — `@shade/vault`: server-side kryptert fillager.** Klient, ruter,
|
||||
`MemoryVaultStore`, `SqliteVaultStore`, ruting i `standalone.ts` og
|
||||
`docs/vault.md` er levert natt til 2026-08-14 (auto-mode); 16 + 7 tester
|
||||
|
||||
@@ -326,3 +326,96 @@ tasks:
|
||||
created: 2026-08-13
|
||||
updated: 2026-08-14
|
||||
completed_at: null
|
||||
|
||||
# ─────────────── Streaming — @shade/media ───────────────
|
||||
- id: media-smf1-live
|
||||
title: "@shade/media: forseglede filer (SMF1) + live-kanal (SLF1), server, CLI, nettleser, Kotlin"
|
||||
description: >
|
||||
E2E-kryptert streaming av filmer, video, bilder, lyd og logger. SMF1 for filer
|
||||
med tilfeldig tilgang (Range), SLF1 for live-strømmer med sen innstigning og
|
||||
epokerotasjon. Relay ser bare chiffertekst.
|
||||
status: done
|
||||
column: done
|
||||
priority: high
|
||||
assignee: claude
|
||||
branch: streaming
|
||||
context: "packages/shade-media, docs/media.md, test-vectors/media.json, android/.../no/zyon/shade/media/"
|
||||
acceptance: "43 TS-tester + 9 Kotlin-vektortester grønne; film/live/bilde/lyd spilt i headless Chromium; benchmark i bench/media.chart.json."
|
||||
created: 2026-10-18
|
||||
updated: 2026-10-18
|
||||
completed_at: 2026-10-18
|
||||
- id: media-fmp4-live
|
||||
title: "fMP4 (H.264/AAC) i live-splitteren"
|
||||
description: "Live-splitteren forstår i dag bare WebM; fMP4 gir H.264/AAC fra kameraer og OBS, og Safari."
|
||||
status: done
|
||||
column: done
|
||||
priority: medium
|
||||
assignee: claude
|
||||
branch: streaming
|
||||
created: 2026-10-18
|
||||
updated: 2026-10-18
|
||||
completed_at: 2026-10-18
|
||||
- id: media-android-exoplayer
|
||||
title: "Android-demo: ExoPlayer DataSource for forseglede filmer"
|
||||
description: "Avspilling (Media3 DataSource), live og opplasting fra telefonen er bygget og testet uten enhet; gjenstår kjøring på dev-telefonen (RFCN504DWJF)."
|
||||
status: doing
|
||||
column: doing
|
||||
priority: medium
|
||||
assignee: claude
|
||||
branch: streaming
|
||||
todos:
|
||||
- text: "ShadeMediaDataSource + ShadeMedia (Media3), Robolectric: ExoPlayer spiller og spoler forseglet H.264/AAC"
|
||||
done: true
|
||||
- text: "Demo-app :shade-media-demo bygger (debug-APK)"
|
||||
done: true
|
||||
- text: "«Del til Shade»: forsegling + opplasting fra telefonen (MediaUploader, UploadJobs, forgrunnstjeneste, album) — Robolectric mot ekte relay"
|
||||
done: true
|
||||
- text: "Installer og spill på dev-telefonen RFCN504DWJF, og del en ekte galleri-video — ikke tilkoblet 2026-10-18/19"
|
||||
done: false
|
||||
created: 2026-10-18
|
||||
updated: 2026-10-19
|
||||
completed_at: null
|
||||
- id: media-durable-store
|
||||
title: "Postgres/S3-medielager for flere relay-instanser"
|
||||
description: "Gjort: ObjectMediaStore (S3, egen SigV4-klient, multipart med begrenset minne) + PostgresMediaIndex/PostgresLivePinStore; SHADE_MEDIA_S3_URL/SHADE_MEDIA_PG_URL og media serve --s3 --pg. Gjenstår utenfor kortet: live-fan-out på tvers av instanser, og selve deployen (ikke bedt om)."
|
||||
status: done
|
||||
column: done
|
||||
priority: low
|
||||
assignee: any
|
||||
branch: streaming
|
||||
created: 2026-10-18
|
||||
updated: 2026-10-18
|
||||
completed_at: 2026-10-18
|
||||
- id: media-resumable-upload
|
||||
title: "Opplasting i stykker, gjenopptakbar (TS + Kotlin), media put på tvers av kjøringer, live record"
|
||||
description: "16 MiB-stykker, 4 i flyt; relay-RSS uavhengig av filmstørrelse; media put fortsetter etter Ctrl-C/SIGKILL; shade live record [--put]; Kotlin MediaUploader med samme protokoll."
|
||||
status: done
|
||||
column: done
|
||||
priority: high
|
||||
assignee: claude
|
||||
branch: streaming
|
||||
created: 2026-10-18
|
||||
updated: 2026-10-19
|
||||
completed_at: 2026-10-19
|
||||
- id: media-browser-upload
|
||||
title: "Opplasting fra nettleseren (iPhone uten app)"
|
||||
description: "Eiernøkkel i nettleseren og forsegling som strømmer rett inn i stykkene (MediaClient kjører allerede i nettleseren)."
|
||||
status: todo
|
||||
column: todo
|
||||
priority: medium
|
||||
assignee: any
|
||||
branch: streaming
|
||||
created: 2026-10-19
|
||||
updated: 2026-10-19
|
||||
completed_at: null
|
||||
- id: media-android-camera-live
|
||||
title: "Live fra telefonkameraet"
|
||||
description: "LivePublisher finnes i Kotlin; mangler MediaCodec → fMP4-muxing og en publiseringsskjerm. Krever enhet for å verifiseres."
|
||||
status: todo
|
||||
column: todo
|
||||
priority: low
|
||||
assignee: any
|
||||
branch: streaming
|
||||
created: 2026-10-19
|
||||
updated: 2026-10-19
|
||||
completed_at: null
|
||||
|
||||
202
CHANGELOG.md
@@ -5,6 +5,208 @@ All notable changes to Shade are documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [4.15.1] — 2026-10-20 — Media: a relay no longer dies when a player walks away
|
||||
|
||||
### Fixed
|
||||
|
||||
- **`@shade/media`: `FileMediaStore.body()` held a file handle for the whole
|
||||
response.** It was closed only when the client read to the end or the runtime
|
||||
called `cancel`. A player that seeks or closes mid-film often does neither, so
|
||||
the handle was left to the garbage collector — which Bun 1.4 treats as fatal.
|
||||
The Prism relay restarted five times in four hours this way. Each piece now
|
||||
opens and closes the file itself; nothing is held between reads. Regression
|
||||
test: `tests/fixtures/abandoned-body.ts`, run in its own process, checks that
|
||||
no descriptor is open between reads (fails on 4.15.0 under any Bun).
|
||||
|
||||
## [4.15.0] — 2026-10-18 — Media: films, video, images, audio and live streams, end to end
|
||||
|
||||
New package **`@shade/media`** — see `docs/media.md`.
|
||||
|
||||
- **Sealed media (SMF1).** A film, video, song or image is sealed once
|
||||
(streaming, constant memory, ~300 MiB/s) into a file any Range-capable
|
||||
store can serve. Readers fetch only the segments under the playhead; every
|
||||
segment is checked against a digest table pinned by the grant's root
|
||||
digest, so neither the store nor another key holder can substitute bytes.
|
||||
Seek over HTTP: ~4 ms to the first decrypted byte (localhost).
|
||||
- **Live channels (SLF1).** Logs, text, live video/audio and images from one
|
||||
publisher to many viewers through a relay. Sender-Keys hash chain (each
|
||||
frame key used once), every frame Ed25519-signed, sticky init frames and
|
||||
keyframe snapshots so a viewer can join late, epoch rotation to remove a
|
||||
viewer, and link mode so a capability link survives publisher restarts.
|
||||
200 viewers: 100 % delivered, p50 28 ms.
|
||||
- **Grants** carry the keys over an existing Shade session —
|
||||
`shade.shareMedia(peer, grant)` / `shade.onMediaGrant(handler)` in the SDK —
|
||||
or in a `#shade=` link fragment that never reaches a server.
|
||||
- **Browser.** A Service Worker plays sealed files in native
|
||||
`<video>`/`<audio>`/`<img>` with seeking; `LivePlayer` plays live WebM or
|
||||
fragmented MP4 (H.264/HEVC/AV1 + AAC/Opus) via MSE; the relay serves a `/watch/` page that opens any link.
|
||||
- **Server.** `createMediaService`: disk-backed sealed store with signed
|
||||
owner uploads and immutable objects, a WebSocket live relay with bounded
|
||||
backlog and slow-viewer shedding, and the watch page. Mounted by the
|
||||
container when `SHADE_MEDIA_DIR` is set (no in-memory fallback);
|
||||
`SHADE_MEDIA_OWNERS` lists who may upload and open channels.
|
||||
- **CLI.** `shade media serve|put|get|ls|rm|whoami`,
|
||||
`shade live text|video|watch` (`tail -f … | shade live text`,
|
||||
`ffmpeg … -f webm - | shade live video`, or `-f mp4 -movflags
|
||||
frag_keyframe+empty_moov` for H.264/AAC; the container is detected).
|
||||
`MediaSplitter`, `WebmSplitter` and `Fmp4Splitter` are exported for apps
|
||||
that publish from their own source.
|
||||
- **Albums.** One link for a season, a photo album or a camera wall: an
|
||||
album is a sealed file listing grants (`shade.album/v1`), so the relay
|
||||
cannot tell it from a film. `shade media put dir/` uploads every file
|
||||
and prints the album's link (subdirectories become nested albums, in
|
||||
natural order); `shade media get` downloads an album back into a
|
||||
directory; `/watch/` shows it as a grid with decrypted previews.
|
||||
`uploadAlbum`, `openAlbum`, `Albums.read` (Kotlin), and a shared vector.
|
||||
- **Subtitles.** `shade media put Film.mkv` seals `Film.srt`,
|
||||
`Film.no.srt`, `Film.en.vtt` … beside it and carries their grants in the
|
||||
film's sealed meta; `/watch/` shows them as `<track>`s (SRT converted to
|
||||
VTT, the viewer's language on), `media get` writes them back, and
|
||||
Android plays them as side-loaded ExoPlayer text tracks
|
||||
(`ShadeMedia.openFilm`).
|
||||
- **`media put --web`.** Films with AC-3/DTS audio or HEVC video (Chromium
|
||||
refuses them outright) are converted before sealing: what browsers play
|
||||
is copied, the rest becomes H.264/AAC, embedded text subtitles become
|
||||
subtitle tracks, all in one ffmpeg pass. Without the flag, `put` warns
|
||||
when ffprobe sees streams browsers will not play.
|
||||
- **Shared media library.** `SHADE_MEDIA_S3_URL` + `SHADE_MEDIA_PG_URL` (or
|
||||
`media serve --s3 --pg`): sealed films in any S3 bucket, records and live
|
||||
pins in Postgres, so several relay instances serve one library.
|
||||
`ObjectMediaStore` streams uploads as multipart with bounded memory, decides
|
||||
racing uploads by the Postgres primary key, and sweeps orphaned objects and
|
||||
dead multipart uploads. `S3Bucket` is a small SigV4 client of Shade's own
|
||||
(Bun 1.3.5's `S3Client` buffers whole uploads). `PostgresMediaIndex`,
|
||||
`PostgresLivePinStore`, `createSharedMediaBackend` in
|
||||
`@shade/storage-postgres`. A live pin can no longer change key, even between
|
||||
instances (`LivePinTakenError`).
|
||||
- **Uploads in pieces, resumable.** A sealed file over 16 MiB goes up as
|
||||
`POST /v1/media/:id/upload` + 16 MiB `PUT` pieces (each signed over its
|
||||
offset), up to 4 in flight and landing in any order. 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 under way survive restarts (`uploads/` on disk, `shade_media_uploads`
|
||||
beside the S3 multipart upload), count against quota and are swept after
|
||||
24 h without a piece. `media put` shows progress, and resumes across runs:
|
||||
after Ctrl-C or a long outage the same command goes on with the same
|
||||
media id (sealed copy and job under `$XDG_CONFIG_HOME/shade/media-pending/`),
|
||||
and a file already up gives its link again instead of a second copy. Above all, a relay's
|
||||
memory no longer grows with the film (see Fixed).
|
||||
- **`shade live record <link>`**: a channel to files until it ends: text,
|
||||
seekable WebM/MP4 (ffmpeg `-c copy`, clock from 0:00), pictures. `--put`
|
||||
seals and uploads the recording under the channel's name, so a broadcast
|
||||
can be watched later (`LiveRecorder` in `@shade/media/node`). `live
|
||||
video` now sends its name as a sticky `meta` frame like the other kinds.
|
||||
- **`shade live video --input`** a film, `/dev/video0` or `rtsp://…`: ffmpeg is
|
||||
run for you, H.264/AAC copied (a camera's own encoder) and anything else
|
||||
encoded to H.264 (keyframe every 2 s) and AAC, as low-latency fMP4.
|
||||
- **`shade live images`.** A channel of pictures: JPEG/PNG piped in (a
|
||||
webcam through `ffmpeg -f image2pipe`), a slideshow of files, or each new
|
||||
picture landing in a watched folder. `ImageStreamSplitter` walks JPEG
|
||||
markers and PNG chunks. The Android demo shows live and sealed pictures.
|
||||
- **Live channels across relay instances.** `LiveRelayOptions.mesh` with a
|
||||
`LivePublisherLocator` (`PostgresLivePublisherLocator`;
|
||||
`SHADE_MEDIA_RELAY_URL` / `media serve --advertise`): a relay with viewers
|
||||
of a channel published elsewhere follows the relay that has the publisher,
|
||||
verifying every frame against the pin, and viewers follow a publisher that
|
||||
moves. Viewers get a `state` message when a channel goes live or quiet.
|
||||
`LiveRelay.stop()` / `MediaService.stop()` now resolve once the relay's
|
||||
claims are released; the container and `media serve` (SIGINT/SIGTERM) wait
|
||||
for it and close the Postgres pool, so a redeploy does not leave other
|
||||
instances pointing at a relay that is gone.
|
||||
- **Library.** `media put` records each upload and its grant in
|
||||
`$XDG_CONFIG_HOME/shade/media-library.jsonl` (0600, append-only); `media
|
||||
ls` shows names, `media link <name|id>` prints a link again. Grants now
|
||||
encode their meta canonically, so one grant is always one link.
|
||||
- **Kotlin.** `no.zyon.shade.media`: SMF1 reader and sealer, grants, live
|
||||
subscriber and publisher — byte-for-byte against `test-vectors/media.json`.
|
||||
`:shade-android-media` plays sealed files in Media3/ExoPlayer
|
||||
(`ShadeMediaDataSource`, `ShadeMedia.mediaSource(reader)`), and
|
||||
`:shade-media-demo` is a player app that opens a shared watch link.
|
||||
Live channels on Android: `LiveWatcher` (OkHttp) and
|
||||
`ShadeMedia.liveMediaSource(grant)` play live WebM/fMP4 in ExoPlayer,
|
||||
with late joining from a keyframe, gap recovery and the timeline rebased
|
||||
to 0:00.
|
||||
- **Uploads from Kotlin.** `MediaUploader` puts sealed files on a relay from
|
||||
a phone: one PUT up to 16 MiB, larger ones in pieces with the relay's
|
||||
window, retries and a resync after a lost answer — the same protocol as
|
||||
`media put`. `MediaOwner` signs owner requests (byte for byte against the
|
||||
new owner vector), `MediaSealer.sealStream` seals a film to a file, and
|
||||
`MediaGrant.encode()` / `capabilityUrl(page)` make the link to share
|
||||
(against a new grant-encode vector). `scripts/media-live-kotlin.ts` runs it
|
||||
against a real TS relay with a lost answer and a refused piece injected;
|
||||
TS reads the film back byte for byte.
|
||||
- **Share to Shade (Android).** `UploadJobs` lets an upload survive the app
|
||||
being killed (sealed once, resumed with the same media id, one link per
|
||||
shared file); `ShadeUpload` seals a shared `content://` URI with its name,
|
||||
type, duration and picture size; `KeystoreSecretFile` keeps the owner seed
|
||||
under a Keystore key. The demo app takes shares from the gallery, uploads
|
||||
them in a foreground service with progress, and offers the link to play or
|
||||
share. Several files shared at once become one album link
|
||||
(`MediaUploader.uploadAlbum`, `Albums.encode`, `Grant.encode` for live
|
||||
grants too — the album vector now resealed byte for byte from Kotlin), and
|
||||
the demo player lists an album's items and opens them in place.
|
||||
Its minSdk is now 28.
|
||||
|
||||
### Fixed
|
||||
|
||||
- An uploader (TS and Kotlin) trusted the relay's upload status: a `chunk` of
|
||||
0 looped forever, a huge one held the film in memory, a huge `window` opened
|
||||
a request (a thread, on Kotlin) per piece. The status is now checked
|
||||
(`statusProblem`) and the window capped at 16.
|
||||
- `MediaClient` waited between retries with `Bun.sleep`, so a retry threw in
|
||||
a browser or Node; it uses `setTimeout` now (the browser bundle of
|
||||
`@shade/media` has no `Bun.*` left).
|
||||
- `shade media get` used the sealed file's `meta.name` as the output path,
|
||||
so whoever sealed a file chose where it was written (`../../.bashrc`).
|
||||
Names are now reduced to one safe path component.
|
||||
- A relay test raced: `flush()` means sent, not received, so a viewer could
|
||||
join mid-burst and (correctly) get an older backlog. The relay now counts
|
||||
`framesIn` in `stats()`, and the test waits on it.
|
||||
- The live relay never noticed its publisher leave: Hono hands each event its
|
||||
own `WSContext`, and the close handler compared them by identity. A channel
|
||||
stayed "live" with nobody publishing, and a replaced publisher's socket was
|
||||
never closed. They are compared by the socket underneath now.
|
||||
- `shade live video` labelled every stream `video/…`, so a live radio stream
|
||||
(Opus or AAC alone) played sound in a black video box. The meta now carries
|
||||
the init segment's type, and the page gives sound an audio player.
|
||||
- `FileMediaStore` on a directory it could not use rejected at start with no
|
||||
handler (an unhandled rejection). Now every call fails with the reason.
|
||||
|
||||
- The container refused every request body over 128 MiB (Bun's default),
|
||||
which would have made every film a 413. Films now go up in pieces of at
|
||||
most 64 MiB, so the cap stays, and every route has an explicit 128 MiB
|
||||
body limit.
|
||||
- An upload put the whole film in the relay's memory whenever the store was
|
||||
slower than the client: Bun.serve reads a request body as fast as it
|
||||
arrives, whether the handler takes it or not. One `PUT` of a 512 MiB film
|
||||
peaked at 762 MiB (disk) and 1011 MiB (S3). In pieces it stays the same at
|
||||
512 MiB and 1.5 GiB (`bench/media-store.ts`).
|
||||
- The media sweep ran only for the S3 store, from two copies of the timer
|
||||
(container and `media serve`). It is now part of every store and of
|
||||
`createMediaService` (`onSweep` reports it), hourly.
|
||||
|
||||
### Also in 4.15.0
|
||||
|
||||
- **`@shade/media/worker`: Shade's media handler inside an app's own Service
|
||||
Worker.** A worker answers every request of the pages it controls, so an
|
||||
installed PWA with a worker at `/` never let `media/<id>` reach Shade's
|
||||
worker beside it. `installShadeMedia(self)`, `isShadeMediaRequest(req)` and
|
||||
`shadeMediaResponse(req)` put it in the app's worker instead. The standalone
|
||||
`browser/sw.ts` is now a thin wrapper around the same module.
|
||||
- **`media put` records length and picture size.** Video, audio and images
|
||||
are measured with ffprobe (after `--web`, so the numbers match the sealed
|
||||
file) and sealed with `durationMs`, `width` and `height` in their meta. A
|
||||
viewer can show a film's length on a tile and reserve its shape without
|
||||
fetching a byte. Without ffprobe the fields are left out, as before.
|
||||
- **Publishing.** `@shade/media` is in the publish order (first: it depends on
|
||||
no other Shade package), so `@shade/server`, `@shade/sdk` and `@shade/cli`
|
||||
no longer point at a package the registry does not have. `@shade/observer`
|
||||
builds to `dist/` like the rest and is no longer published empty, and a
|
||||
`bin` on `src/*.ts` is rewritten to `dist/*.js`, so `shade` runs after
|
||||
install instead of failing on its first import.
|
||||
|
||||
## [4.14.1] — 2026-10-16 — Vault: `edit` for vaults two devices write
|
||||
|
||||
- `VaultClient.edit(change, at)` changes a few files against the head that
|
||||
|
||||
@@ -2,4 +2,5 @@ plugins {
|
||||
kotlin("jvm") version "2.0.20" apply false
|
||||
kotlin("android") version "2.0.20" apply false
|
||||
id("com.android.library") version "8.7.3" apply false
|
||||
id("com.android.application") version "8.7.3" apply false
|
||||
}
|
||||
|
||||
@@ -21,3 +21,7 @@ project(":shade-android").projectDir = file("shade-android")
|
||||
|
||||
include(":shade-android-keystore")
|
||||
project(":shade-android-keystore").projectDir = file("shade-android-keystore")
|
||||
include(":shade-android-media")
|
||||
project(":shade-android-media").projectDir = file("shade-android-media")
|
||||
include(":shade-media-demo")
|
||||
project(":shade-media-demo").projectDir = file("shade-media-demo")
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package no.zyon.shade.keystore
|
||||
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.security.GeneralSecurityException
|
||||
import java.security.SecureRandom
|
||||
|
||||
/**
|
||||
* A small secret (a signing seed, a token) kept in a file, encrypted under a
|
||||
* hardware-backed Android Keystore key that never leaves the secure element.
|
||||
* For secrets the app uses without asking the user each time — a media owner
|
||||
* key that signs every upload piece — so the key is not biometric-gated;
|
||||
* use [KeystoreMasterKey] with `requireBiometric` for those that should be.
|
||||
*
|
||||
* File: `"SKS1" || nonce(12) || AES-256-GCM(secret)`, with the alias as AAD
|
||||
* so a file cannot be swapped in under another alias. A backup restored to
|
||||
* another phone carries the file but not the key: [read] then throws
|
||||
* [SecretLostException] rather than handing back garbage.
|
||||
*/
|
||||
class KeystoreSecretFile(private val file: File, private val alias: String) {
|
||||
private val key = KeystoreMasterKey(alias, requireBiometric = false)
|
||||
|
||||
class SecretLostException(message: String, cause: Throwable? = null) : IOException(message, cause)
|
||||
|
||||
/** The secret, or null if none was written. */
|
||||
fun read(): ByteArray? {
|
||||
if (!file.exists()) return null
|
||||
val b = file.readBytes()
|
||||
if (b.size < HEADER + 16 || !b.copyOfRange(0, 4).contentEquals(MAGIC)) throw SecretLostException("${file.name} is not a Keystore secret")
|
||||
if (!key.exists()) throw SecretLostException("the Keystore key for ${file.name} is gone (restored from a backup, or the app's keys were cleared)")
|
||||
return try {
|
||||
val c = key.cipherForDecrypt(b.copyOfRange(4, HEADER))
|
||||
c.updateAAD(alias.toByteArray(Charsets.UTF_8))
|
||||
c.doFinal(b, HEADER, b.size - HEADER)
|
||||
} catch (e: GeneralSecurityException) {
|
||||
throw SecretLostException("${file.name} does not open under its Keystore key", e)
|
||||
}
|
||||
}
|
||||
|
||||
fun write(secret: ByteArray) {
|
||||
val c = key.cipherForEncrypt()
|
||||
c.updateAAD(alias.toByteArray(Charsets.UTF_8))
|
||||
val ct = c.doFinal(secret)
|
||||
val nonce = c.iv
|
||||
check(nonce.size == 12) { "unexpected GCM nonce size ${nonce.size}" }
|
||||
file.parentFile?.mkdirs()
|
||||
val tmp = File(file.path + ".tmp")
|
||||
tmp.writeBytes(MAGIC + nonce + ct)
|
||||
if (!tmp.renameTo(file)) throw IOException("cannot write ${file.name}")
|
||||
}
|
||||
|
||||
/** The secret, made with `size` random bytes on first use. */
|
||||
fun getOrCreate(size: Int): ByteArray = read() ?: ByteArray(size).also {
|
||||
SecureRandom().nextBytes(it)
|
||||
write(it)
|
||||
}
|
||||
|
||||
/** Remove the file and its key: the secret is gone for good. */
|
||||
fun destroy() {
|
||||
file.delete()
|
||||
key.deleteKey()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
val MAGIC = "SKS1".toByteArray(Charsets.US_ASCII)
|
||||
const val HEADER = 4 + 12
|
||||
}
|
||||
}
|
||||
54
android/shade-android-media/build.gradle.kts
Normal file
@@ -0,0 +1,54 @@
|
||||
plugins {
|
||||
id("com.android.library")
|
||||
kotlin("android")
|
||||
}
|
||||
|
||||
// Sealed Shade media (SMF1) in Media3/ExoPlayer.
|
||||
//
|
||||
// `:shade-android` reads and verifies sealed files on the JVM; this module
|
||||
// hands that reader to ExoPlayer as a DataSource, so any container the
|
||||
// player understands (MP4, WebM, MKV, MP3, …) plays and seeks from a sealed
|
||||
// file without the plaintext ever touching disk or the network.
|
||||
|
||||
android {
|
||||
namespace = "no.zyon.shade.media.android"
|
||||
compileSdk = 35
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 24
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
kotlinOptions {
|
||||
jvmTarget = "17"
|
||||
}
|
||||
|
||||
testOptions {
|
||||
unitTests.isIncludeAndroidResources = true
|
||||
unitTests.all {
|
||||
// ShadeUploadTest's live half is gated on this; as an input, a new relay reruns it.
|
||||
it.inputs.property("shadeMediaLiveSpec", System.getenv("SHADE_MEDIA_LIVE_SPEC") ?: "")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val media3 = "1.5.1"
|
||||
|
||||
dependencies {
|
||||
api(project(":shade-android"))
|
||||
api("androidx.media3:media3-exoplayer:$media3")
|
||||
api("androidx.media3:media3-datasource:$media3")
|
||||
// Live channels: the relay speaks WebSocket. `api`: LiveWatcher takes an OkHttpClient.
|
||||
api("com.squareup.okhttp3:okhttp:4.12.0")
|
||||
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
testImplementation("org.robolectric:robolectric:4.14.1")
|
||||
testImplementation("androidx.test:core:1.6.1")
|
||||
testImplementation("androidx.media3:media3-test-utils:$media3")
|
||||
testImplementation("androidx.media3:media3-test-utils-robolectric:$media3")
|
||||
testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0")
|
||||
}
|
||||
2
android/shade-android-media/src/main/AndroidManifest.xml
Normal file
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
|
||||
@@ -0,0 +1,149 @@
|
||||
package no.zyon.shade.media.android
|
||||
|
||||
import no.zyon.shade.media.LiveGrant
|
||||
import no.zyon.shade.media.LiveSubscriber
|
||||
import no.zyon.shade.media.ReceivedFrame
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.Response
|
||||
import okhttp3.WebSocket
|
||||
import okhttp3.WebSocketListener
|
||||
import okio.ByteString
|
||||
import org.json.JSONObject
|
||||
import java.io.Closeable
|
||||
import java.util.Base64
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.ScheduledExecutorService
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* Watch a live channel: the Android side of the TS `LiveWatchClient`.
|
||||
*
|
||||
* Connects to the relay named in the grant, subscribes with the read token,
|
||||
* and hands every frame that verifies and decrypts to [Listener.onFrame], in
|
||||
* arrival order. A dropped connection is retried with backoff; the relay's
|
||||
* backlog on reconnect is deduplicated by the subscriber, so the listener
|
||||
* sees each frame once.
|
||||
*/
|
||||
class LiveWatcher(
|
||||
grant: LiveGrant,
|
||||
private val listener: Listener,
|
||||
private val client: OkHttpClient = sharedClient,
|
||||
url: String? = null,
|
||||
) : Closeable {
|
||||
enum class State { CONNECTING, WAITING, LIVE, RECONNECTING, CLOSED }
|
||||
|
||||
interface Listener {
|
||||
fun onFrame(frame: ReceivedFrame)
|
||||
fun onState(state: State) {}
|
||||
/** A frame failed to verify or decrypt, or the relay refused us. The stream continues. */
|
||||
fun onError(error: Exception) {}
|
||||
}
|
||||
|
||||
private val url: String = url ?: grant.url ?: throw IllegalArgumentException("grant has no relay URL")
|
||||
private val token: String = grant.readToken?.let { Base64.getUrlEncoder().withoutPadding().encodeToString(it) }
|
||||
?: throw IllegalArgumentException("grant has no read token")
|
||||
/** Not thread-safe; every use is under `lock`. */
|
||||
private val subscriber = LiveSubscriber(grant)
|
||||
private val lock = Any()
|
||||
private val timer: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor { r ->
|
||||
Thread(r, "shade-live-reconnect").apply { isDaemon = true }
|
||||
}
|
||||
@Volatile private var closed = false
|
||||
private var socket: WebSocket? = null
|
||||
private var delayMs = INITIAL_DELAY_MS
|
||||
private var everConnected = false
|
||||
|
||||
init {
|
||||
connect()
|
||||
}
|
||||
|
||||
/** Hand over the grant for a new epoch (it arrives over the Shade session). */
|
||||
fun addGrant(g: LiveGrant) = synchronized(lock) {
|
||||
subscriber.addGrant(g)
|
||||
subscriber.forgetBefore(g.epoch)
|
||||
}
|
||||
|
||||
private fun connect() {
|
||||
if (closed) return
|
||||
listener.onState(if (everConnected) State.RECONNECTING else State.CONNECTING)
|
||||
val request = Request.Builder().url(url).build()
|
||||
val ws = client.newWebSocket(request, Handler())
|
||||
synchronized(lock) { socket = ws }
|
||||
}
|
||||
|
||||
private inner class Handler : WebSocketListener() {
|
||||
override fun onOpen(webSocket: WebSocket, response: Response) {
|
||||
webSocket.send(JSONObject().put("type", "subscribe").put("token", token).toString())
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, text: String) {
|
||||
val msg = runCatching { JSONObject(text) }.getOrNull() ?: return
|
||||
when (msg.optString("type")) {
|
||||
"ready" -> {
|
||||
synchronized(lock) {
|
||||
delayMs = INITIAL_DELAY_MS
|
||||
everConnected = true
|
||||
}
|
||||
listener.onState(if (msg.optBoolean("live")) State.LIVE else State.WAITING)
|
||||
}
|
||||
// The publisher arrived or left after we joined.
|
||||
"state" -> listener.onState(if (msg.optBoolean("live")) State.LIVE else State.WAITING)
|
||||
"error" -> listener.onError(LiveRelayException(msg.optString("message", "relay error")))
|
||||
}
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
|
||||
// OkHttp calls this on the socket's reader thread, one message at
|
||||
// a time — frames are opened in arrival order, as the chain needs.
|
||||
val frame = try {
|
||||
synchronized(lock) { if (closed) return else subscriber.open(bytes.toByteArray()) }
|
||||
} catch (e: Exception) {
|
||||
listener.onError(e)
|
||||
return
|
||||
}
|
||||
if (frame != null) listener.onFrame(frame)
|
||||
}
|
||||
|
||||
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
|
||||
webSocket.close(1000, null)
|
||||
}
|
||||
|
||||
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) = retry(webSocket)
|
||||
|
||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) = retry(webSocket)
|
||||
}
|
||||
|
||||
private fun retry(ws: WebSocket) {
|
||||
val delay = synchronized(lock) {
|
||||
if (closed || socket !== ws) return
|
||||
socket = null
|
||||
delayMs.also { delayMs = minOf(delayMs * 2, MAX_DELAY_MS) }
|
||||
}
|
||||
listener.onState(State.RECONNECTING)
|
||||
timer.schedule({ connect() }, delay, TimeUnit.MILLISECONDS)
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
val ws = synchronized(lock) {
|
||||
if (closed) return
|
||||
closed = true
|
||||
socket.also { socket = null }
|
||||
}
|
||||
ws?.close(1000, null)
|
||||
timer.shutdownNow()
|
||||
synchronized(lock) { subscriber.close() }
|
||||
listener.onState(State.CLOSED)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val INITIAL_DELAY_MS = 250L
|
||||
const val MAX_DELAY_MS = 10_000L
|
||||
/** One client for every watcher: OkHttp shares its pools and threads. */
|
||||
val sharedClient: OkHttpClient by lazy {
|
||||
OkHttpClient.Builder().pingInterval(20, TimeUnit.SECONDS).readTimeout(0, TimeUnit.MILLISECONDS).build()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class LiveRelayException(message: String) : Exception(message)
|
||||
@@ -0,0 +1,253 @@
|
||||
package no.zyon.shade.media.android
|
||||
|
||||
import android.net.Uri
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.ParserException
|
||||
import androidx.media3.common.PlaybackException
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.datasource.BaseDataSource
|
||||
import androidx.media3.datasource.DataSource
|
||||
import androidx.media3.datasource.DataSourceException
|
||||
import androidx.media3.datasource.DataSpec
|
||||
import no.zyon.shade.media.LiveContent
|
||||
import no.zyon.shade.media.ReceivedFrame
|
||||
import java.io.Closeable
|
||||
import java.io.InterruptedIOException
|
||||
import java.util.ArrayDeque
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.locks.ReentrantLock
|
||||
import kotlin.concurrent.withLock
|
||||
|
||||
/**
|
||||
* A live Shade channel (WebM or fragmented MP4) as one endless byte stream
|
||||
* for ExoPlayer's progressive extractors.
|
||||
*
|
||||
* The stream is what a demuxer expects from a live muxer: the channel's
|
||||
* init (sticky), then media pieces from the first keyframe on. Where frames
|
||||
* are missing — a reconnect, the relay shedding a slow viewer — it skips to
|
||||
* the next keyframe, so the decoder never sees a piece that depends on one
|
||||
* it did not get. A late joiner's timeline is rebased to start at zero (see
|
||||
* [ShadeMedia.liveMediaSource] for fMP4; WebM cluster timecodes here), or a
|
||||
* player would wait out the minutes it missed.
|
||||
*
|
||||
* `connect` opens the frame feed: [LiveWatcher] by default, a fake in tests.
|
||||
*/
|
||||
@UnstableApi
|
||||
class ShadeLiveDataSource(
|
||||
private val connect: (LiveWatcher.Listener) -> Closeable,
|
||||
) : BaseDataSource(/* isNetwork = */ true) {
|
||||
private val lock = ReentrantLock()
|
||||
private val ready = lock.newCondition()
|
||||
private val queue = ArrayDeque<ByteArray>()
|
||||
private var head: ByteArray? = null
|
||||
private var headPos = 0
|
||||
private var init: ByteArray? = null
|
||||
private var webm = false
|
||||
private var needKeyframe = true
|
||||
private var lastEpoch = -1L
|
||||
private var lastSeq = -1L
|
||||
/** WebM: the first delivered cluster's timecode, subtracted from every cluster. */
|
||||
private var webmBase = -1L
|
||||
private var ended = false
|
||||
private var failure: Exception? = null
|
||||
private var feed: Closeable? = null
|
||||
private var uri: Uri? = null
|
||||
|
||||
/** Frames skipped while waiting for a keyframe, for diagnostics. */
|
||||
@Volatile var droppedFrames = 0L
|
||||
private set
|
||||
|
||||
override fun open(dataSpec: DataSpec): Long {
|
||||
// A live stream cannot resume mid-byte; ExoPlayer reopens an
|
||||
// unseekable source from the start, which is a fresh join.
|
||||
if (dataSpec.position != 0L) throw DataSourceException(PlaybackException.ERROR_CODE_IO_READ_POSITION_OUT_OF_RANGE)
|
||||
uri = dataSpec.uri
|
||||
transferInitializing(dataSpec)
|
||||
lock.withLock { resetLocked() }
|
||||
feed = connect(Feed())
|
||||
transferStarted(dataSpec)
|
||||
return C.LENGTH_UNSET.toLong()
|
||||
}
|
||||
|
||||
override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
|
||||
if (length == 0) return 0
|
||||
val n = lock.withLock {
|
||||
while (head == null) {
|
||||
failure?.let { throw it as? java.io.IOException ?: DataSourceException(it, PlaybackException.ERROR_CODE_IO_UNSPECIFIED) }
|
||||
val next = queue.pollFirst()
|
||||
if (next != null) {
|
||||
head = next
|
||||
headPos = 0
|
||||
break
|
||||
}
|
||||
if (ended) return C.RESULT_END_OF_INPUT
|
||||
// Wake now and then: ExoPlayer cancels a load by interrupting.
|
||||
ready.await(250, TimeUnit.MILLISECONDS)
|
||||
if (Thread.interrupted()) throw InterruptedIOException()
|
||||
}
|
||||
val h = head!!
|
||||
val n = minOf(length, h.size - headPos)
|
||||
System.arraycopy(h, headPos, buffer, offset, n)
|
||||
headPos += n
|
||||
if (headPos == h.size) head = null
|
||||
n
|
||||
}
|
||||
bytesTransferred(n)
|
||||
return n
|
||||
}
|
||||
|
||||
override fun getUri(): Uri? = uri
|
||||
|
||||
override fun close() {
|
||||
val f = feed
|
||||
feed = null
|
||||
f?.close()
|
||||
lock.withLock {
|
||||
resetLocked()
|
||||
ended = true
|
||||
ready.signalAll()
|
||||
}
|
||||
if (uri != null) {
|
||||
uri = null
|
||||
transferEnded()
|
||||
}
|
||||
}
|
||||
|
||||
private fun resetLocked() {
|
||||
queue.clear()
|
||||
head = null
|
||||
init = null
|
||||
webm = false
|
||||
needKeyframe = true
|
||||
lastEpoch = -1
|
||||
lastSeq = -1
|
||||
webmBase = -1
|
||||
ended = false
|
||||
failure = null
|
||||
}
|
||||
|
||||
/** Frames in arrival order (from the watcher's thread) → bytes for the extractor. */
|
||||
private inner class Feed : LiveWatcher.Listener {
|
||||
override fun onFrame(frame: ReceivedFrame) {
|
||||
lock.withLock { accept(frame) }
|
||||
}
|
||||
|
||||
private fun accept(frame: ReceivedFrame) {
|
||||
if (ended || failure != null) return
|
||||
// Contiguous: the next seq in this epoch, or seq 0 of the next
|
||||
// epoch (a rotation reseals the sticky frames first, numbered from 0).
|
||||
val contiguous = (frame.epoch == lastEpoch && frame.seq == lastSeq + 1) ||
|
||||
(frame.epoch == lastEpoch + 1 && frame.seq == 0L)
|
||||
if (!contiguous && lastEpoch >= 0) needKeyframe = true
|
||||
lastEpoch = frame.epoch
|
||||
lastSeq = frame.seq
|
||||
when (val c = frame.content) {
|
||||
is LiveContent.Init -> {
|
||||
val known = init
|
||||
if (known == null) {
|
||||
init = c.bytes
|
||||
webm = c.mime.contains("webm")
|
||||
queue.addLast(c.bytes)
|
||||
ready.signalAll()
|
||||
} else if (!known.contentEquals(c.bytes)) {
|
||||
// A new init mid-stream is a new stream; the demuxer cannot
|
||||
// splice it. A ParserException, because retrying cannot help
|
||||
// and ExoPlayer's load policy does not retry those.
|
||||
failure = ParserException.createForMalformedContainer(
|
||||
"the live stream changed its format",
|
||||
LiveFormatChangedException(),
|
||||
)
|
||||
ready.signalAll()
|
||||
}
|
||||
}
|
||||
is LiveContent.Chunk -> {
|
||||
if (init == null || (needKeyframe && !frame.keyframe)) {
|
||||
droppedFrames++
|
||||
return
|
||||
}
|
||||
needKeyframe = false
|
||||
queue.addLast(if (webm) rebaseCluster(c.bytes) else c.bytes)
|
||||
ready.signalAll()
|
||||
}
|
||||
is LiveContent.End -> {
|
||||
ended = true
|
||||
ready.signalAll()
|
||||
}
|
||||
else -> Unit // text, images and meta are not part of the media stream
|
||||
}
|
||||
}
|
||||
|
||||
override fun onError(error: Exception) {
|
||||
// A frame that failed to verify is dropped by the watcher; the gap
|
||||
// check above then waits for the next keyframe. Nothing to do here.
|
||||
}
|
||||
}
|
||||
|
||||
/** WebM: rewrite the cluster's Timecode so the first cluster delivered is at 0. */
|
||||
private fun rebaseCluster(cluster: ByteArray): ByteArray {
|
||||
val tc = Ebml.clusterTimecode(cluster) ?: return cluster
|
||||
if (webmBase < 0) webmBase = tc.value
|
||||
val v = tc.value - webmBase
|
||||
if (v < 0) return cluster
|
||||
val out = cluster.copyOf()
|
||||
var x = v
|
||||
for (i in tc.length - 1 downTo 0) {
|
||||
out[tc.offset + i] = (x and 0xff).toByte()
|
||||
x = x ushr 8
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
class Factory(private val connect: (LiveWatcher.Listener) -> Closeable) : DataSource.Factory {
|
||||
override fun createDataSource(): DataSource = ShadeLiveDataSource(connect)
|
||||
}
|
||||
}
|
||||
|
||||
class LiveFormatChangedException : Exception("the live stream changed its format; reopen it")
|
||||
|
||||
/** Just enough EBML to find a Cluster's Timecode. */
|
||||
internal object Ebml {
|
||||
class Field(val offset: Int, val length: Int, val value: Long)
|
||||
|
||||
private const val ID_CLUSTER = 0x1f43b675L
|
||||
private const val ID_TIMECODE = 0xe7L
|
||||
|
||||
private fun vintLength(first: Int, max: Int): Int {
|
||||
var len = 1
|
||||
while (len <= max && (first and (0x80 shr (len - 1))) == 0) len++
|
||||
return if (len > max) -1 else len
|
||||
}
|
||||
|
||||
fun clusterTimecode(b: ByteArray): Field? {
|
||||
val idLen = vintLength(b.getOrNull(0)?.toInt()?.and(0xff) ?: return null, 4)
|
||||
if (idLen < 0 || readUInt(b, 0, idLen) != ID_CLUSTER) return null
|
||||
val sizeLen = vintLength(b.getOrNull(idLen)?.toInt()?.and(0xff) ?: return null, 8)
|
||||
if (sizeLen < 0) return null
|
||||
var at = idLen + sizeLen
|
||||
// The Timecode is the first child in practice; look a few elements in.
|
||||
repeat(4) {
|
||||
val first = b.getOrNull(at)?.toInt()?.and(0xff) ?: return null
|
||||
val cl = vintLength(first, 4)
|
||||
if (cl < 0) return null
|
||||
val id = readUInt(b, at, cl)
|
||||
val szFirst = b.getOrNull(at + cl)?.toInt()?.and(0xff) ?: return null
|
||||
val sl = vintLength(szFirst, 8)
|
||||
if (sl < 0) return null
|
||||
var size = (szFirst and (0xff shr sl)).toLong()
|
||||
for (i in 1 until sl) size = (size shl 8) or (b[at + cl + i].toLong() and 0xff)
|
||||
val body = at + cl + sl
|
||||
if (id == ID_TIMECODE) {
|
||||
if (size !in 1..8 || body + size > b.size) return null
|
||||
return Field(body, size.toInt(), readUInt(b, body, size.toInt()))
|
||||
}
|
||||
at = body + size.toInt()
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun readUInt(b: ByteArray, at: Int, len: Int): Long {
|
||||
var v = 0L
|
||||
for (i in 0 until len) v = (v shl 8) or (b[at + i].toLong() and 0xff)
|
||||
return v
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package no.zyon.shade.media.android
|
||||
|
||||
import android.net.Uri
|
||||
import androidx.media3.common.MediaItem
|
||||
import androidx.media3.common.MediaMetadata
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.MimeTypes
|
||||
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
|
||||
import androidx.media3.exoplayer.source.MediaSource
|
||||
import androidx.media3.common.util.TimestampAdjuster
|
||||
import androidx.media3.exoplayer.source.ProgressiveMediaSource
|
||||
import androidx.media3.extractor.Extractor
|
||||
import androidx.media3.extractor.ExtractorsFactory
|
||||
import androidx.media3.extractor.mkv.MatroskaExtractor
|
||||
import androidx.media3.extractor.mp4.FragmentedMp4Extractor
|
||||
import androidx.media3.extractor.text.SubtitleParser
|
||||
import no.zyon.shade.media.Grant
|
||||
import no.zyon.shade.media.Grants
|
||||
import no.zyon.shade.media.LiveGrant
|
||||
import no.zyon.shade.media.MediaFormatException
|
||||
import no.zyon.shade.media.MediaGrant
|
||||
import no.zyon.shade.media.MediaReader
|
||||
import no.zyon.shade.media.SubtitleTrack
|
||||
import no.zyon.shade.media.Subtitles
|
||||
|
||||
/**
|
||||
* Sealed Shade media for ExoPlayer, from a link or grant to a [MediaSource].
|
||||
*
|
||||
* ```
|
||||
* val reader = ShadeMedia.open(link) // network: off the main thread
|
||||
* player.setMediaSource(ShadeMedia.mediaSource(reader))
|
||||
* player.prepare()
|
||||
*
|
||||
* player.setMediaSource(ShadeMedia.liveMediaSource(liveGrant)) // a live channel
|
||||
* ```
|
||||
*/
|
||||
@UnstableApi
|
||||
object ShadeMedia {
|
||||
/** The grant in a capability link (`…#shade=…`). */
|
||||
fun grant(link: String): Grant = Grants.fromCapabilityUrl(link)
|
||||
|
||||
/** Open the sealed file a capability link grants. Blocking. */
|
||||
fun open(link: String): MediaReader {
|
||||
val grant = grant(link)
|
||||
if (grant !is MediaGrant) throw MediaFormatException("that link is a live channel, not a sealed file")
|
||||
return grant.open()
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a sealed film and the subtitle files its meta names. Blocking. A
|
||||
* subtitle that cannot be opened is skipped; the film plays without it.
|
||||
*/
|
||||
fun openFilm(grant: MediaGrant): ShadeFilm {
|
||||
val reader = grant.open()
|
||||
val tracks = runCatching { Subtitles.of(reader.meta) }.getOrDefault(emptyList())
|
||||
val subs = tracks.mapNotNull { t -> runCatching { t to t.grant.open() }.getOrNull() }
|
||||
return ShadeFilm(grant, reader, subs)
|
||||
}
|
||||
|
||||
/**
|
||||
* A film with its subtitles as side-loaded text tracks. ExoPlayer parses
|
||||
* SubRip and WebVTT itself; each file is read through its own reader.
|
||||
*/
|
||||
fun mediaSource(film: ShadeFilm, locale: java.util.Locale = java.util.Locale.getDefault()): MediaSource {
|
||||
// The track in the viewer's language is on by default (Bokmål and
|
||||
// Nynorsk match a `no` file); otherwise none is.
|
||||
val base = { tag: String -> tag.substringBefore('-').lowercase().let { if (it == "nb" || it == "nn") "no" else it } }
|
||||
val preferred = film.subtitles.indexOfFirst { (t, _) -> t.lang != null && base(t.lang!!) == base(locale.language) }
|
||||
val readers = HashMap<Uri, MediaReader>()
|
||||
val filmUri = uriOf(film.grant).also { readers[it] = film.reader }
|
||||
val configs = film.subtitles.mapIndexed { i, (track, reader) ->
|
||||
val uri = uriOf(track.grant).also { readers[it] = reader }
|
||||
val vtt = reader.meta.name?.lowercase()?.endsWith(".vtt") == true || reader.meta.mime == "text/vtt"
|
||||
MediaItem.SubtitleConfiguration.Builder(uri)
|
||||
.setMimeType(if (vtt) MimeTypes.TEXT_VTT else MimeTypes.APPLICATION_SUBRIP)
|
||||
.apply { track.lang?.let { setLanguage(it) } }
|
||||
.apply { (track.label ?: track.lang)?.let { setLabel(it) } }
|
||||
.setSelectionFlags(if (i == preferred) C.SELECTION_FLAG_DEFAULT else 0)
|
||||
.build()
|
||||
}
|
||||
val item = MediaItem.Builder()
|
||||
.setUri(filmUri)
|
||||
.apply { film.reader.meta.mime?.let { setMimeType(it) } }
|
||||
.setMediaMetadata(MediaMetadata.Builder().setTitle(film.reader.meta.name).build())
|
||||
.setSubtitleConfigurations(configs)
|
||||
.build()
|
||||
return DefaultMediaSourceFactory(ShadeMediaDataSource.Factory { u -> readers[u] }).createMediaSource(item)
|
||||
}
|
||||
|
||||
private fun uriOf(g: MediaGrant): Uri =
|
||||
Uri.parse("shade-media://" + g.mediaId.joinToString("") { "%02x".format(it) })
|
||||
|
||||
/** A progressive media source playing the reader's plaintext. */
|
||||
fun mediaSource(reader: MediaReader): MediaSource {
|
||||
val item = MediaItem.Builder()
|
||||
.setUri(Uri.parse("shade-media://sealed"))
|
||||
.apply { reader.meta.mime?.let { setMimeType(it) } }
|
||||
.setMediaMetadata(MediaMetadata.Builder().setTitle(reader.meta.name).build())
|
||||
.build()
|
||||
return ProgressiveMediaSource.Factory(ShadeMediaDataSource.Factory(reader)).createMediaSource(item)
|
||||
}
|
||||
|
||||
/**
|
||||
* A live channel carrying WebM or fragmented MP4 (`shade live video`).
|
||||
*
|
||||
* `connect` opens the frame feed; the default is a [LiveWatcher] on the
|
||||
* grant's relay. The fMP4 extractor gets a fresh [TimestampAdjuster] per
|
||||
* join, so a viewer who arrives an hour in starts at 0:00 rather than
|
||||
* waiting an hour for the first sample; WebM is rebased by the data source.
|
||||
*/
|
||||
fun liveMediaSource(
|
||||
grant: LiveGrant,
|
||||
connect: (LiveWatcher.Listener) -> java.io.Closeable = { l -> LiveWatcher(grant, l) },
|
||||
): MediaSource {
|
||||
val item = MediaItem.Builder()
|
||||
.setUri(Uri.parse("shade-live://channel"))
|
||||
.setMediaMetadata(MediaMetadata.Builder().setTitle(grant.meta?.name).build())
|
||||
.build()
|
||||
val extractors = ExtractorsFactory {
|
||||
arrayOf<Extractor>(
|
||||
FragmentedMp4Extractor(SubtitleParser.Factory.UNSUPPORTED, 0, TimestampAdjuster(0), null, emptyList(), null),
|
||||
MatroskaExtractor(SubtitleParser.Factory.UNSUPPORTED),
|
||||
)
|
||||
}
|
||||
return ProgressiveMediaSource.Factory(ShadeLiveDataSource.Factory(connect), extractors).createMediaSource(item)
|
||||
}
|
||||
}
|
||||
|
||||
/** A sealed film and its opened subtitle files. Close it when done. */
|
||||
class ShadeFilm(
|
||||
val grant: MediaGrant,
|
||||
val reader: MediaReader,
|
||||
val subtitles: List<Pair<SubtitleTrack, MediaReader>>,
|
||||
) : java.io.Closeable {
|
||||
override fun close() {
|
||||
reader.close()
|
||||
subtitles.forEach { it.second.close() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package no.zyon.shade.media.android
|
||||
|
||||
import android.net.Uri
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.PlaybackException
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.datasource.BaseDataSource
|
||||
import androidx.media3.datasource.DataSource
|
||||
import androidx.media3.datasource.DataSourceException
|
||||
import androidx.media3.datasource.DataSpec
|
||||
import no.zyon.shade.media.MediaReader
|
||||
import java.io.IOException
|
||||
|
||||
/**
|
||||
* A Media3 [DataSource] over a sealed Shade file.
|
||||
*
|
||||
* ExoPlayer asks for byte ranges of the plaintext (the container's header,
|
||||
* then wherever a seek lands); [MediaReader] fetches only the sealed segments
|
||||
* under each range, checks them against the digest table and decrypts them.
|
||||
* The plaintext lives in the reader's small segment cache and the player's
|
||||
* buffers, never on disk.
|
||||
*
|
||||
* The URI picks the reader (`resolve`): a film and its subtitle files are
|
||||
* separate sealed files, each with its own `shade-media://<id>`. Readers are
|
||||
* thread-safe, so one may back many data sources, which is what [Factory]
|
||||
* does.
|
||||
*/
|
||||
@UnstableApi
|
||||
class ShadeMediaDataSource(private val resolve: (Uri) -> MediaReader?) : BaseDataSource(/* isNetwork = */ true) {
|
||||
/** Every URI reads this one file. */
|
||||
constructor(reader: MediaReader) : this({ _: Uri -> reader })
|
||||
|
||||
private lateinit var reader: MediaReader
|
||||
private var uri: Uri? = null
|
||||
private var position = 0L
|
||||
private var remaining = 0L
|
||||
private var opened = false
|
||||
|
||||
override fun open(dataSpec: DataSpec): Long {
|
||||
reader = resolve(dataSpec.uri)
|
||||
?: throw DataSourceException(PlaybackException.ERROR_CODE_IO_FILE_NOT_FOUND)
|
||||
uri = dataSpec.uri
|
||||
transferInitializing(dataSpec)
|
||||
if (dataSpec.position > reader.size) {
|
||||
throw DataSourceException(PlaybackException.ERROR_CODE_IO_READ_POSITION_OUT_OF_RANGE)
|
||||
}
|
||||
position = dataSpec.position
|
||||
val left = reader.size - position
|
||||
remaining = if (dataSpec.length == C.LENGTH_UNSET.toLong()) left else minOf(dataSpec.length, left)
|
||||
opened = true
|
||||
transferStarted(dataSpec)
|
||||
return remaining
|
||||
}
|
||||
|
||||
override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
|
||||
if (length == 0) return 0
|
||||
if (remaining == 0L) return C.RESULT_END_OF_INPUT
|
||||
val n = minOf(length.toLong(), remaining, MAX_READ).toInt()
|
||||
val bytes = try {
|
||||
reader.read(position, n)
|
||||
} catch (e: IOException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
// Tampered, truncated or foreign data: the file cannot be trusted
|
||||
// from here on, and retrying will not change that.
|
||||
throw DataSourceException(e, PlaybackException.ERROR_CODE_IO_UNSPECIFIED)
|
||||
}
|
||||
if (bytes.isEmpty()) return C.RESULT_END_OF_INPUT
|
||||
System.arraycopy(bytes, 0, buffer, offset, bytes.size)
|
||||
position += bytes.size
|
||||
remaining -= bytes.size
|
||||
bytesTransferred(bytes.size)
|
||||
return bytes.size
|
||||
}
|
||||
|
||||
override fun getUri(): Uri? = uri
|
||||
|
||||
override fun close() {
|
||||
uri = null
|
||||
if (opened) {
|
||||
opened = false
|
||||
transferEnded()
|
||||
}
|
||||
}
|
||||
|
||||
/** Data sources sharing opened readers, chosen by URI. */
|
||||
class Factory(private val resolve: (Uri) -> MediaReader?) : DataSource.Factory {
|
||||
/** Every URI reads this one file. */
|
||||
constructor(reader: MediaReader) : this({ _: Uri -> reader })
|
||||
|
||||
override fun createDataSource(): DataSource = ShadeMediaDataSource(resolve)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
/** One segment: the reader decrypts whole segments, so larger reads gain nothing. */
|
||||
const val MAX_READ = 1L shl 20
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package no.zyon.shade.media.android
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.BitmapFactory
|
||||
import android.media.MediaMetadataRetriever
|
||||
import android.net.Uri
|
||||
import android.provider.OpenableColumns
|
||||
import no.zyon.shade.media.MediaGrant
|
||||
import no.zyon.shade.media.MediaMeta
|
||||
import no.zyon.shade.media.MediaUploader
|
||||
import no.zyon.shade.media.UploadJobs
|
||||
import java.io.FileNotFoundException
|
||||
|
||||
/**
|
||||
* Sealing and uploading what the phone has — a video from the gallery, a
|
||||
* photo, a recording, any document a share hands over as a `content://` URI.
|
||||
* Blocking: run it off the main thread (in a foreground service for a film).
|
||||
*/
|
||||
object ShadeUpload {
|
||||
|
||||
/** What a share is: the URI, and the meta it will be sealed with. */
|
||||
class Item(val uri: Uri, val size: Long, val meta: MediaMeta)
|
||||
|
||||
/**
|
||||
* Name, type and size from the content resolver; duration and picture size
|
||||
* read from the file itself (video, audio, images), so a library can show
|
||||
* them without opening it. Nothing else — no location, no path — goes in.
|
||||
*/
|
||||
fun describe(context: Context, uri: Uri): Item {
|
||||
val cr = context.contentResolver
|
||||
var name: String? = null
|
||||
var size = -1L
|
||||
cr.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null)?.use { c ->
|
||||
if (c.moveToFirst()) {
|
||||
c.getColumnIndex(OpenableColumns.DISPLAY_NAME).takeIf { it >= 0 && !c.isNull(it) }?.let { name = c.getString(it) }
|
||||
c.getColumnIndex(OpenableColumns.SIZE).takeIf { it >= 0 && !c.isNull(it) }?.let { size = c.getLong(it) }
|
||||
}
|
||||
}
|
||||
val mime = cr.getType(uri)?.takeIf { MIME_RE.matches(it) }
|
||||
var durationMs: Long? = null
|
||||
var width: Long? = null
|
||||
var height: Long? = null
|
||||
when {
|
||||
mime?.startsWith("video/") == true || mime?.startsWith("audio/") == true -> runCatching {
|
||||
MediaMetadataRetriever().apply { setDataSource(context, uri) }.let { r ->
|
||||
try {
|
||||
durationMs = r.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull()
|
||||
val w = r.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)?.toLongOrNull()
|
||||
val h = r.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)?.toLongOrNull()
|
||||
val turned = r.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION)?.toIntOrNull()?.let { it % 180 != 0 } ?: false
|
||||
// As it is shown: a portrait phone video is stored sideways.
|
||||
width = if (turned) h else w
|
||||
height = if (turned) w else h
|
||||
} finally {
|
||||
r.release()
|
||||
}
|
||||
}
|
||||
}
|
||||
mime?.startsWith("image/") == true -> runCatching {
|
||||
val o = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
cr.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, o) }
|
||||
if (o.outWidth > 0) {
|
||||
width = o.outWidth.toLong()
|
||||
height = o.outHeight.toLong()
|
||||
}
|
||||
}
|
||||
}
|
||||
val meta = MediaMeta(
|
||||
mime = mime,
|
||||
name = name?.let(::cleanName),
|
||||
durationMs = durationMs,
|
||||
width = width,
|
||||
height = height,
|
||||
)
|
||||
return Item(uri, size, MediaMeta.validate(meta))
|
||||
}
|
||||
|
||||
/**
|
||||
* Seal and upload `item` as a job in `jobs` (see [MediaUploader.upload]):
|
||||
* killed half-way, the same call resumes it; shared again, it gives the
|
||||
* same link while the relay has the file.
|
||||
*/
|
||||
fun upload(
|
||||
context: Context,
|
||||
uploader: MediaUploader,
|
||||
jobs: UploadJobs,
|
||||
item: Item,
|
||||
onProgress: ((Long, Long) -> Unit)? = null,
|
||||
): MediaGrant {
|
||||
return uploader.upload(jobs, jobKey(jobs, uploader, item), item.meta.name ?: item.uri.toString(), item.meta, {
|
||||
context.contentResolver.openInputStream(item.uri) ?: throw FileNotFoundException("cannot open ${item.uri}")
|
||||
}, onProgress = onProgress)
|
||||
}
|
||||
|
||||
/** The job `item` is in `jobs` when uploaded with `uploader`: the relay, the URI, its size and name. */
|
||||
fun jobKey(jobs: UploadJobs, uploader: MediaUploader, item: Item): String =
|
||||
jobs.key(uploader.server, item.uri.toString(), item.size.toString(), item.meta.name ?: "")
|
||||
|
||||
private val MIME_RE = Regex("""^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$""", RegexOption.IGNORE_CASE)
|
||||
|
||||
/** A display name, not a path; control characters out (the meta refuses them). */
|
||||
private fun cleanName(n: String): String? =
|
||||
n.substringAfterLast('/').filter { it.code >= 0x20 && it.code != 0x7f }.take(1024).ifEmpty { null }
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
package no.zyon.shade.media.android
|
||||
|
||||
import androidx.media3.common.MimeTypes
|
||||
import androidx.media3.common.PlaybackException
|
||||
import androidx.media3.common.Player
|
||||
import androidx.media3.test.utils.TestExoPlayerBuilder
|
||||
import androidx.media3.test.utils.robolectric.TestPlayerRunHelper
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import no.zyon.shade.media.LiveContent
|
||||
import no.zyon.shade.media.LiveGrant
|
||||
import no.zyon.shade.media.LivePublisher
|
||||
import no.zyon.shade.media.LiveSubscriber
|
||||
import no.zyon.shade.media.ReceivedFrame
|
||||
import okhttp3.Response
|
||||
import okhttp3.WebSocket
|
||||
import okhttp3.WebSocketListener
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import okio.ByteString.Companion.toByteString
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import java.io.Closeable
|
||||
import java.nio.ByteBuffer
|
||||
import java.security.SecureRandom
|
||||
import java.util.Base64
|
||||
import java.util.Collections
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class ShadeLiveTest {
|
||||
/** A piece cut by the TS splitter (scripts/make-live-fixtures.ts). */
|
||||
class Piece(val init: Boolean, val keyframe: Boolean, val bytes: ByteArray)
|
||||
|
||||
private fun pieces(name: String): List<Piece> {
|
||||
val b = ByteBuffer.wrap(javaClass.getResourceAsStream("/$name")!!.readBytes())
|
||||
val out = ArrayList<Piece>()
|
||||
while (b.hasRemaining()) {
|
||||
val kind = b.get().toInt()
|
||||
val bytes = ByteArray(b.getInt()).also { b.get(it) }
|
||||
out += Piece(kind == 0, kind == 1, bytes)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private fun random(n: Int) = ByteArray(n).also { SecureRandom().nextBytes(it) }
|
||||
|
||||
/** A channel: the grant a viewer holds, and every frame the publisher sent, sealed and signed. */
|
||||
private class Channel(val grant: LiveGrant, val frames: List<ByteArray>)
|
||||
|
||||
private fun channel(pieces: List<Piece>, mime: String, extra: (LivePublisher) -> List<ByteArray> = { emptyList() }): Channel {
|
||||
val pub = LivePublisher(random(16), random(32), null)
|
||||
val grant = pub.grant(from = "now", url = "ws://relay.invalid/v1/live/x", readToken = random(32))
|
||||
val frames = ArrayList<ByteArray>()
|
||||
for (p in pieces) {
|
||||
frames += if (p.init) pub.frame(LiveContent.Init(mime, p.bytes), sticky = true) else pub.frame(LiveContent.Chunk(p.bytes), keyframe = p.keyframe)
|
||||
}
|
||||
frames += extra(pub)
|
||||
frames += pub.frame(LiveContent.End)
|
||||
return Channel(grant, frames)
|
||||
}
|
||||
|
||||
/** A feed that opens and delivers the chosen frames on its own thread, as the watcher would. */
|
||||
private fun feed(ch: Channel, pick: (Int) -> Boolean = { true }): (LiveWatcher.Listener) -> Closeable = { listener ->
|
||||
val t = Thread {
|
||||
val sub = LiveSubscriber(ch.grant)
|
||||
ch.frames.forEachIndexed { i, f -> if (pick(i)) sub.open(f)?.let(listener::onFrame) }
|
||||
}
|
||||
t.start()
|
||||
Closeable { t.join() }
|
||||
}
|
||||
|
||||
private class Played(val mimes: List<String?>, val endPositionMs: Long)
|
||||
|
||||
private fun play(ch: Channel, connect: (LiveWatcher.Listener) -> Closeable): Played {
|
||||
val player = TestExoPlayerBuilder(ApplicationProvider.getApplicationContext()).build()
|
||||
player.setMediaSource(ShadeMedia.liveMediaSource(ch.grant, connect))
|
||||
player.prepare()
|
||||
TestPlayerRunHelper.run(player).untilState(Player.STATE_READY)
|
||||
val mimes = player.currentTracks.groups.map { it.getTrackFormat(0).sampleMimeType }
|
||||
player.play()
|
||||
TestPlayerRunHelper.run(player).untilState(Player.STATE_ENDED)
|
||||
val end = player.currentPosition
|
||||
player.release()
|
||||
return Played(mimes, end)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun lateJoinOnFragmentedMp4StartsAtTheNextKeyframeAndAtZero() {
|
||||
val pieces = pieces("live-h264.pieces")
|
||||
val ch = channel(pieces, "video/mp4")
|
||||
// Frame 0 is the init; a viewer joining mid-GOP sees media from frame 3.
|
||||
val firstKey = (3 until pieces.size).first { pieces[it].keyframe }
|
||||
val played = play(ch, feed(ch) { it == 0 || it >= 3 })
|
||||
assertTrue("tracks: ${played.mimes}", MimeTypes.VIDEO_H264 in played.mimes && MimeTypes.AUDIO_AAC in played.mimes)
|
||||
// 20 pieces of 250 ms; from the keyframe on that is what plays, from 0:00.
|
||||
val expectMs = (pieces.size - firstKey) * 250L
|
||||
assertEquals("rebased to zero, not ${firstKey * 250} ms in", expectMs.toDouble(), played.endPositionMs.toDouble(), 300.0)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun lateJoinOnWebmIsRebasedToo() {
|
||||
val pieces = pieces("live-vp8.pieces")
|
||||
val ch = channel(pieces, "video/webm")
|
||||
val firstKey = (3 until pieces.size).first { pieces[it].keyframe }
|
||||
val played = play(ch, feed(ch) { it == 0 || it >= 3 })
|
||||
assertTrue("tracks: ${played.mimes}", MimeTypes.VIDEO_VP8 in played.mimes && MimeTypes.AUDIO_OPUS in played.mimes)
|
||||
val expectMs = (pieces.size - firstKey) * 250L
|
||||
assertEquals(expectMs.toDouble(), played.endPositionMs.toDouble(), 350.0)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aGapWaitsForTheNextKeyframe() {
|
||||
val pieces = pieces("live-h264.pieces")
|
||||
val ch = channel(pieces, "video/mp4")
|
||||
// Lose one frame inside a GOP: the rest of that GOP must not reach the decoder.
|
||||
val lost = (2 until pieces.size).first { !pieces[it].keyframe && !pieces[it - 1].keyframe }
|
||||
val ds = ShadeLiveDataSource(feed(ch) { it != lost })
|
||||
val read = drain(ds)
|
||||
val nextKey = (lost + 1 until pieces.size).first { pieces[it].keyframe }
|
||||
val expected = pieces.filterIndexed { i, _ -> i < lost || i >= nextKey }.map { it.bytes }
|
||||
assertEquals(expected.sumOf { it.size }, read.size)
|
||||
assertEquals((nextKey - lost - 1).toLong(), ds.droppedFrames)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aDifferentInitMidStreamFailsPlaybackInsteadOfCorruptingIt() {
|
||||
val pieces = pieces("live-h264.pieces")
|
||||
val ch = channel(pieces.take(8), "video/mp4") { pub ->
|
||||
listOf(pub.frame(LiveContent.Init("video/mp4", byteArrayOf(1, 2, 3)), sticky = true))
|
||||
}
|
||||
val player = TestExoPlayerBuilder(ApplicationProvider.getApplicationContext()).build()
|
||||
player.setMediaSource(ShadeMedia.liveMediaSource(ch.grant, feed(ch)))
|
||||
player.prepare()
|
||||
player.play()
|
||||
val error: PlaybackException = TestPlayerRunHelper.runUntilError(player)
|
||||
var cause: Throwable? = error
|
||||
while (cause != null && cause !is LiveFormatChangedException) cause = cause.cause
|
||||
val chain = generateSequence(error as Throwable) { it.cause }.joinToString(" <- ") { "${it.javaClass.simpleName}(${it.message})" }
|
||||
assertTrue("error: $chain", cause is LiveFormatChangedException)
|
||||
player.release()
|
||||
}
|
||||
|
||||
/** Read a data source to its end, as an extractor would. */
|
||||
private fun drain(ds: ShadeLiveDataSource): ByteArray {
|
||||
val out = java.io.ByteArrayOutputStream()
|
||||
ds.open(androidx.media3.datasource.DataSpec(android.net.Uri.parse("shade-live://x")))
|
||||
val buf = ByteArray(4096)
|
||||
while (true) {
|
||||
val n = ds.read(buf, 0, buf.size)
|
||||
if (n < 0) break
|
||||
out.write(buf, 0, n)
|
||||
}
|
||||
ds.close()
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun watcherSubscribesReconnectsAndDeliversEachFrameOnce() {
|
||||
val pieces = pieces("live-h264.pieces").take(6)
|
||||
val server = MockWebServer()
|
||||
server.start()
|
||||
val pub = LivePublisher(random(16), random(32), null)
|
||||
val token = random(32)
|
||||
val grant = pub.grant(from = "now", url = server.url("/v1/live/x").toString().replace("http", "ws"), readToken = token)
|
||||
val frames = pieces.map {
|
||||
if (it.init) pub.frame(LiveContent.Init("video/mp4", it.bytes), sticky = true) else pub.frame(LiveContent.Chunk(it.bytes), keyframe = it.keyframe)
|
||||
} + pub.frame(LiveContent.End)
|
||||
val subscribes = Collections.synchronizedList(ArrayList<String>())
|
||||
// First connection: half the frames, then the relay drops us.
|
||||
// Second: the backlog again from the start (as a relay does), then the rest.
|
||||
for (attempt in 0..1) {
|
||||
server.enqueue(
|
||||
MockResponse().withWebSocketUpgrade(object : WebSocketListener() {
|
||||
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
|
||||
webSocket.close(1000, null)
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, text: String) {
|
||||
subscribes += text
|
||||
webSocket.send("""{"type":"ready","live":true}""")
|
||||
val upTo = if (attempt == 0) 4 else frames.size
|
||||
for (f in frames.take(upTo)) webSocket.send(f.toByteString())
|
||||
if (attempt == 0) webSocket.close(1001, "going away")
|
||||
}
|
||||
}),
|
||||
)
|
||||
}
|
||||
val got = Collections.synchronizedList(ArrayList<ReceivedFrame>())
|
||||
val states = Collections.synchronizedList(ArrayList<LiveWatcher.State>())
|
||||
val done = CountDownLatch(1)
|
||||
val watcher = LiveWatcher(grant, object : LiveWatcher.Listener {
|
||||
override fun onFrame(frame: ReceivedFrame) {
|
||||
got += frame
|
||||
if (frame.content is LiveContent.End) done.countDown()
|
||||
}
|
||||
override fun onState(state: LiveWatcher.State) {
|
||||
states += state
|
||||
}
|
||||
})
|
||||
assertTrue("timed out; states $states, frames ${got.size}", done.await(10, TimeUnit.SECONDS))
|
||||
watcher.close()
|
||||
server.shutdown()
|
||||
|
||||
assertEquals(2, subscribes.size)
|
||||
for (s in subscribes) {
|
||||
val o = JSONObject(s)
|
||||
assertEquals("subscribe", o.getString("type"))
|
||||
assertEquals(Base64.getUrlEncoder().withoutPadding().encodeToString(token), o.getString("token"))
|
||||
}
|
||||
assertEquals((0L until frames.size).toList(), got.map { it.seq })
|
||||
assertTrue("states: $states", states.count { it == LiveWatcher.State.LIVE } == 2 && LiveWatcher.State.RECONNECTING in states)
|
||||
assertEquals(LiveWatcher.State.CLOSED, states.last())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun watcherFollowsThePublisherArrivingAndLeavingAfterItJoined() {
|
||||
val server = MockWebServer()
|
||||
server.start()
|
||||
val pub = LivePublisher(random(16), random(32), null)
|
||||
val grant = pub.grant(from = "now", url = server.url("/v1/live/x").toString().replace("http", "ws"), readToken = random(32))
|
||||
val first = pub.frame(LiveContent.Chunk(byteArrayOf(1)), keyframe = true)
|
||||
server.enqueue(
|
||||
MockResponse().withWebSocketUpgrade(object : WebSocketListener() {
|
||||
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
|
||||
webSocket.close(1000, null)
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, text: String) {
|
||||
// Joins an empty channel; the publisher arrives, sends, leaves.
|
||||
webSocket.send("""{"type":"ready","live":false}""")
|
||||
webSocket.send("""{"type":"state","live":true}""")
|
||||
webSocket.send(first.toByteString())
|
||||
webSocket.send("""{"type":"state","live":false}""")
|
||||
}
|
||||
}),
|
||||
)
|
||||
val states = Collections.synchronizedList(ArrayList<LiveWatcher.State>())
|
||||
val left = CountDownLatch(1)
|
||||
val watcher = LiveWatcher(grant, object : LiveWatcher.Listener {
|
||||
override fun onFrame(frame: ReceivedFrame) {}
|
||||
override fun onState(state: LiveWatcher.State) {
|
||||
states += state
|
||||
if (state == LiveWatcher.State.WAITING && LiveWatcher.State.LIVE in states) left.countDown()
|
||||
}
|
||||
})
|
||||
assertTrue("states: $states", left.await(10, TimeUnit.SECONDS))
|
||||
watcher.close()
|
||||
server.shutdown()
|
||||
val seen = states.filter { it == LiveWatcher.State.WAITING || it == LiveWatcher.State.LIVE }
|
||||
assertEquals(listOf(LiveWatcher.State.WAITING, LiveWatcher.State.LIVE, LiveWatcher.State.WAITING), seen)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package no.zyon.shade.media.android
|
||||
|
||||
import android.net.Uri
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.MimeTypes
|
||||
import androidx.media3.common.Player
|
||||
import androidx.media3.datasource.DataSource
|
||||
import androidx.media3.datasource.DataSourceException
|
||||
import androidx.media3.datasource.DataSpec
|
||||
import androidx.media3.exoplayer.source.ProgressiveMediaSource
|
||||
import androidx.media3.test.utils.TestExoPlayerBuilder
|
||||
import androidx.media3.test.utils.robolectric.TestPlayerRunHelper
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import no.zyon.shade.media.ByteArraySource
|
||||
import no.zyon.shade.media.MediaKeys
|
||||
import no.zyon.shade.media.MediaMeta
|
||||
import no.zyon.shade.media.MediaReader
|
||||
import no.zyon.shade.media.MediaGrant
|
||||
import no.zyon.shade.media.MediaSealer
|
||||
import no.zyon.shade.media.SubtitleTrack
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class ShadeMediaDataSourceTest {
|
||||
/** A 2 s H.264/AAC MP4, sealed in 4 KiB segments so every read crosses several. */
|
||||
private val clip: ByteArray = javaClass.getResourceAsStream("/clip.mp4")!!.readBytes()
|
||||
|
||||
private fun sealed(plain: ByteArray = clip): Pair<ByteArray, MediaKeys> {
|
||||
val (bytes, r) = MediaSealer.sealBytes(plain, MediaMeta(mime = "video/mp4", name = "clip.mp4"), segmentSize = 4096)
|
||||
return bytes to MediaKeys(r.mediaId, r.mediaKey, r.rootDigest)
|
||||
}
|
||||
|
||||
private fun reader(): MediaReader {
|
||||
val (bytes, keys) = sealed()
|
||||
return MediaReader.open(ByteArraySource(bytes), keys)
|
||||
}
|
||||
|
||||
private fun readAll(ds: DataSource, spec: DataSpec): ByteArray {
|
||||
val out = ByteArrayOutputStream()
|
||||
val buf = ByteArray(3000) // not a divisor of the segment size
|
||||
ds.open(spec)
|
||||
while (true) {
|
||||
val n = ds.read(buf, 0, buf.size)
|
||||
if (n == C.RESULT_END_OF_INPUT) break
|
||||
out.write(buf, 0, n)
|
||||
}
|
||||
ds.close()
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun readsThePlaintextWholeAndInRanges() {
|
||||
val ds = ShadeMediaDataSource(reader())
|
||||
val uri = Uri.parse("shade-media://sealed")
|
||||
assertArrayEquals(clip, readAll(ds, DataSpec(uri)))
|
||||
// Mid-file windows, as a seek produces: unbounded and bounded.
|
||||
assertArrayEquals(clip.copyOfRange(9999, clip.size), readAll(ds, DataSpec.Builder().setUri(uri).setPosition(9999).build()))
|
||||
assertArrayEquals(
|
||||
clip.copyOfRange(4095, 4095 + 5000),
|
||||
readAll(ds, DataSpec.Builder().setUri(uri).setPosition(4095).setLength(5000).build()),
|
||||
)
|
||||
// open() reports the length it will deliver.
|
||||
assertEquals((clip.size - 100).toLong(), ds.open(DataSpec.Builder().setUri(uri).setPosition(100).build()))
|
||||
ds.close()
|
||||
assertEquals(0L, ds.open(DataSpec.Builder().setUri(uri).setPosition(clip.size.toLong()).build()))
|
||||
assertEquals(C.RESULT_END_OF_INPUT, ds.read(ByteArray(10), 0, 10))
|
||||
ds.close()
|
||||
assertThrows(DataSourceException::class.java) {
|
||||
ds.open(DataSpec.Builder().setUri(uri).setPosition(clip.size + 1L).build())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aTamperedSegmentFailsTheRead() {
|
||||
val (bytes, keys) = sealed()
|
||||
bytes[2 * 4096 + 100] = (bytes[2 * 4096 + 100].toInt() xor 1).toByte()
|
||||
val ds = ShadeMediaDataSource(MediaReader.open(ByteArraySource(bytes), keys))
|
||||
val e = assertThrows(DataSourceException::class.java) { readAll(ds, DataSpec(Uri.parse("shade-media://sealed"))) }
|
||||
assertTrue(e.cause!!.message!!.contains("does not match its digest"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun exoPlayerPlaysAndSeeksASealedFilm() {
|
||||
val reader = reader()
|
||||
val opens = mutableListOf<Long>()
|
||||
val counting = DataSource.Factory {
|
||||
val inner = ShadeMediaDataSource(reader)
|
||||
object : DataSource by inner {
|
||||
override fun open(dataSpec: DataSpec): Long {
|
||||
opens += dataSpec.position
|
||||
return inner.open(dataSpec)
|
||||
}
|
||||
}
|
||||
}
|
||||
val player = TestExoPlayerBuilder(ApplicationProvider.getApplicationContext()).build()
|
||||
val item = ShadeMedia.mediaSource(reader).mediaItem
|
||||
player.setMediaSource(ProgressiveMediaSource.Factory(counting).createMediaSource(item))
|
||||
player.prepare()
|
||||
TestPlayerRunHelper.run(player).untilState(Player.STATE_READY)
|
||||
|
||||
val mimes = player.currentTracks.groups.map { it.getTrackFormat(0).sampleMimeType }
|
||||
assertTrue("tracks: $mimes", MimeTypes.VIDEO_H264 in mimes)
|
||||
assertTrue("tracks: $mimes", MimeTypes.AUDIO_AAC in mimes)
|
||||
assertEquals(2000.0, player.duration.toDouble(), 100.0)
|
||||
assertEquals("clip.mp4", player.mediaMetadata.title)
|
||||
|
||||
player.play()
|
||||
TestPlayerRunHelper.run(player).untilState(Player.STATE_ENDED)
|
||||
|
||||
// A seek back into the film reopens the source mid-file.
|
||||
opens.clear()
|
||||
player.seekTo(1200)
|
||||
TestPlayerRunHelper.run(player).untilState(Player.STATE_READY)
|
||||
assertTrue("opened at $opens", opens.any { it > 0 })
|
||||
assertTrue(player.currentPosition >= 1000)
|
||||
player.play()
|
||||
TestPlayerRunHelper.run(player).untilState(Player.STATE_ENDED)
|
||||
player.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFilmPlaysWithItsSubtitlesAndPicksTheViewersLanguage() {
|
||||
fun sealedFile(bytes: ByteArray, meta: MediaMeta): Pair<MediaGrant, MediaReader> {
|
||||
val (sealed, r) = MediaSealer.sealBytes(bytes, meta, segmentSize = 4096)
|
||||
val grant = MediaGrant(r.mediaId, r.mediaKey, r.rootDigest, url = "https://relay.invalid/x")
|
||||
return grant to MediaReader.open(ByteArraySource(sealed), MediaKeys(r.mediaId, r.mediaKey, r.rootDigest))
|
||||
}
|
||||
val no = sealedFile("1\r\n00:00:00,100 --> 00:00:01,900\r\nHei, æøå!\r\n".toByteArray(), MediaMeta(name = "clip.no.srt"))
|
||||
val en = sealedFile("WEBVTT\n\n00:00.100 --> 00:01.900\nHello!\n".toByteArray(), MediaMeta(name = "clip.en.vtt", mime = "text/vtt"))
|
||||
val film = sealedFile(clip, MediaMeta(mime = "video/mp4", name = "clip.mp4"))
|
||||
val shadeFilm = ShadeFilm(
|
||||
film.first,
|
||||
film.second,
|
||||
listOf(SubtitleTrack(en.first, "en") to en.second, SubtitleTrack(no.first, "no", "Norsk") to no.second),
|
||||
)
|
||||
val player = TestExoPlayerBuilder(ApplicationProvider.getApplicationContext()).build()
|
||||
player.setMediaSource(ShadeMedia.mediaSource(shadeFilm, java.util.Locale.forLanguageTag("nb-NO")))
|
||||
player.prepare()
|
||||
TestPlayerRunHelper.run(player).untilState(Player.STATE_READY)
|
||||
val text = player.currentTracks.groups.filter { it.type == C.TRACK_TYPE_TEXT }
|
||||
assertEquals("text tracks: ${text.map { it.getTrackFormat(0) }}", 2, text.size)
|
||||
// The test player has no text renderer to select with; what we decide
|
||||
// is which track is the default, and the player reports that flag.
|
||||
val defaults = text.filter { it.getTrackFormat(0).selectionFlags and C.SELECTION_FLAG_DEFAULT != 0 }.map { it.getTrackFormat(0).language }
|
||||
assertEquals(listOf("no"), defaults)
|
||||
assertTrue(text.any { it.getTrackFormat(0).label == "Norsk" })
|
||||
player.play()
|
||||
TestPlayerRunHelper.run(player).untilState(Player.STATE_ENDED)
|
||||
player.release()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package no.zyon.shade.media.android
|
||||
|
||||
import android.content.ContentProvider
|
||||
import android.content.ContentValues
|
||||
import android.database.Cursor
|
||||
import android.database.MatrixCursor
|
||||
import android.net.Uri
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.provider.OpenableColumns
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import no.zyon.shade.media.MediaOwner
|
||||
import no.zyon.shade.media.MediaUploader
|
||||
import no.zyon.shade.media.UploadJobs
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.Robolectric
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
import java.security.SecureRandom
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class ShadeUploadTest {
|
||||
/** A gallery: one video, served the way a share hands it over. */
|
||||
class Gallery : ContentProvider() {
|
||||
override fun onCreate() = true
|
||||
override fun query(uri: Uri, projection: Array<out String>?, selection: String?, args: Array<out String>?, sort: String?): Cursor =
|
||||
MatrixCursor(arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE)).apply { addRow(arrayOf<Any>(name, file!!.length())) }
|
||||
override fun getType(uri: Uri) = "video/mp4"
|
||||
override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor = ParcelFileDescriptor.open(file!!, ParcelFileDescriptor.MODE_READ_ONLY)
|
||||
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
|
||||
override fun delete(uri: Uri, selection: String?, args: Array<out String>?) = 0
|
||||
override fun update(uri: Uri, values: ContentValues?, selection: String?, args: Array<out String>?) = 0
|
||||
|
||||
companion object {
|
||||
var file: File? = null
|
||||
var name = "VID_0042.mp4"
|
||||
}
|
||||
}
|
||||
|
||||
private val context = ApplicationProvider.getApplicationContext<android.app.Application>()
|
||||
private val uri = Uri.parse("content://test.gallery/video/42")
|
||||
|
||||
private fun video(bytes: ByteArray): File {
|
||||
Robolectric.setupContentProvider(Gallery::class.java, "test.gallery")
|
||||
return File.createTempFile("vid", ".mp4").also {
|
||||
it.writeBytes(bytes)
|
||||
it.deleteOnExit()
|
||||
Gallery.file = it
|
||||
}
|
||||
}
|
||||
|
||||
private fun sha256(b: ByteArray) = MessageDigest.getInstance("SHA-256").digest(b).joinToString("") { "%02x".format(it) }
|
||||
|
||||
@Test
|
||||
fun describeTakesTheNameTypeAndSizeAndNothingElse() {
|
||||
video(ByteArray(5000))
|
||||
Gallery.name = "Kveld\u0007 på hytta.mp4"
|
||||
val item = ShadeUpload.describe(context, uri)
|
||||
assertEquals("Kveld på hytta.mp4", item.meta.name)
|
||||
assertEquals("video/mp4", item.meta.mime)
|
||||
assertEquals(5000L, item.size)
|
||||
assertEquals(null, item.meta.createdAt)
|
||||
assertEquals(null, item.meta.extra)
|
||||
Gallery.name = "VID_0042.mp4"
|
||||
}
|
||||
|
||||
/** Against a real TS relay — run by `bun run scripts/media-live-kotlin.ts`, skipped without it. */
|
||||
@Test
|
||||
fun aSharedVideoIsSealedFromItsUriAndUploaded() {
|
||||
val specPath = System.getenv("SHADE_MEDIA_LIVE_SPEC")
|
||||
assumeTrue("SHADE_MEDIA_LIVE_SPEC not set — live upload skipped", !specPath.isNullOrEmpty())
|
||||
val spec = JSONObject(File(specPath!!).readText())
|
||||
val seed = spec.getString("seed").chunked(2).map { it.toInt(16).toByte() }.toByteArray()
|
||||
val uploader = MediaUploader(spec.getString("url"), MediaOwner(seed))
|
||||
val jobs = UploadJobs(File(spec.getString("scratch"), "android-jobs"))
|
||||
val bytes = ByteArray(20 * 1024 * 1024).also { SecureRandom().nextBytes(it) }
|
||||
video(bytes)
|
||||
val item = ShadeUpload.describe(context, uri)
|
||||
val grant = ShadeUpload.upload(context, uploader, jobs, item)
|
||||
grant.open().use { r ->
|
||||
assertEquals("VID_0042.mp4", r.meta.name)
|
||||
assertEquals(sha256(bytes), sha256(r.read(0, r.size.toInt())))
|
||||
}
|
||||
// Shared again: the same job, the same link.
|
||||
assertEquals(grant.encode(), ShadeUpload.upload(context, uploader, jobs, ShadeUpload.describe(context, uri)).encode())
|
||||
File(spec.getString("scratch"), "android-out.txt").writeText(grant.capabilityUrl("https://watch.example/"))
|
||||
}
|
||||
}
|
||||
BIN
android/shade-android-media/src/test/resources/clip.mp4
Normal file
BIN
android/shade-android-media/src/test/resources/live-h264.pieces
Normal file
BIN
android/shade-android-media/src/test/resources/live-vp8.pieces
Normal file
@@ -49,9 +49,10 @@ dependencies {
|
||||
|
||||
tasks.withType<Test>().configureEach {
|
||||
useJUnit()
|
||||
// VaultLiveTest is gated on this; as an input, a new spec (a new live
|
||||
// VaultLiveTest and MediaLiveTest are gated on these; as an input, a new spec (a new live
|
||||
// relay) reruns the tests instead of reporting a stale UP-TO-DATE.
|
||||
inputs.property("shadeVaultLiveSpec", System.getenv("SHADE_VAULT_LIVE_SPEC") ?: "")
|
||||
inputs.property("shadeMediaLiveSpec", System.getenv("SHADE_MEDIA_LIVE_SPEC") ?: "")
|
||||
testLogging {
|
||||
events("passed", "failed", "skipped")
|
||||
showStandardStreams = false
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package no.zyon.shade.media
|
||||
|
||||
import no.zyon.shade.serialization.stringifyJson
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONException
|
||||
import org.json.JSONObject
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.charset.CharacterCodingException
|
||||
import java.nio.charset.CodingErrorAction
|
||||
|
||||
/**
|
||||
* Albums — mirror of `@shade/media/src/album.ts`. An album is a sealed file
|
||||
* whose plaintext lists grants (films, pictures, nested albums, live
|
||||
* channels), so one link opens them all and the relay cannot tell it from
|
||||
* any other file.
|
||||
*/
|
||||
|
||||
const val ALBUM_KIND = "shade.album/v1"
|
||||
const val ALBUM_MIME = "application/vnd.shade.album+json"
|
||||
const val MAX_ALBUM_ITEMS = 10_000
|
||||
private const val MAX_TITLE = 512
|
||||
private const val MAX_ALBUM_BYTES = 16L * 1024 * 1024
|
||||
|
||||
class Album(val title: String, val items: List<Grant>)
|
||||
|
||||
object Albums {
|
||||
/** An album's plaintext, byte for byte what TS `encodeAlbum` writes. */
|
||||
fun encode(album: Album): ByteArray {
|
||||
if (album.title.length > MAX_TITLE) throw MediaFormatException("album title longer than $MAX_TITLE characters")
|
||||
if (album.items.size > MAX_ALBUM_ITEMS) throw MediaFormatException("album holds more than $MAX_ALBUM_ITEMS items")
|
||||
val o = LinkedHashMap<String, Any>()
|
||||
o["kind"] = ALBUM_KIND
|
||||
o["title"] = album.title
|
||||
o["items"] = album.items.map { it.toJsonMap() }
|
||||
return stringifyJson(o).toByteArray(Charsets.UTF_8)
|
||||
}
|
||||
|
||||
/** The meta an album is sealed with: its type, and the title as its name. */
|
||||
fun meta(title: String) = MediaMeta(mime = ALBUM_MIME, name = title)
|
||||
|
||||
/** Parse an album's plaintext, strictly: every item must be a valid grant. */
|
||||
fun parse(bytes: ByteArray): Album {
|
||||
val text = try {
|
||||
Charsets.UTF_8.newDecoder()
|
||||
.onMalformedInput(CodingErrorAction.REPORT)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPORT)
|
||||
.decode(ByteBuffer.wrap(bytes)).toString()
|
||||
} catch (e: CharacterCodingException) {
|
||||
throw MediaFormatException("album is not UTF-8")
|
||||
}
|
||||
val o = try { JSONObject(text) } catch (e: JSONException) { throw MediaFormatException("album is not a JSON object") }
|
||||
if (o.opt("kind") != ALBUM_KIND) throw MediaFormatException("not an album (kind ${o.opt("kind")})")
|
||||
val title = o.opt("title") as? String ?: throw MediaFormatException("album.title must be a string")
|
||||
if (title.length > MAX_TITLE) throw MediaFormatException("album title longer than $MAX_TITLE characters")
|
||||
val items = o.opt("items") as? JSONArray ?: throw MediaFormatException("album.items must be an array")
|
||||
if (items.length() > MAX_ALBUM_ITEMS) throw MediaFormatException("album holds more than $MAX_ALBUM_ITEMS items")
|
||||
return Album(
|
||||
title,
|
||||
(0 until items.length()).map { i ->
|
||||
val item = items.opt(i) as? JSONObject ?: throw MediaFormatException("album item $i is not a grant")
|
||||
try {
|
||||
Grants.parse(item.toString())
|
||||
} catch (e: MediaFormatException) {
|
||||
throw MediaFormatException("album item $i: ${e.message}")
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/** The items of an album already opened as a reader. */
|
||||
fun read(reader: MediaReader): Album {
|
||||
if (reader.meta.mime != ALBUM_MIME) throw MediaFormatException("not an album (${reader.meta.mime ?: "no type"})")
|
||||
if (reader.size > MAX_ALBUM_BYTES) throw MediaFormatException("album larger than 16 MiB")
|
||||
return parse(reader.read(0, reader.size.toInt()))
|
||||
}
|
||||
|
||||
/** Does this grant's meta preview name an album? */
|
||||
fun isAlbum(grant: Grant): Boolean = when (grant) {
|
||||
is MediaGrant -> grant.meta?.mime == ALBUM_MIME
|
||||
is LiveGrant -> false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
package no.zyon.shade.media
|
||||
|
||||
import com.google.crypto.tink.subtle.Ed25519Sign
|
||||
import com.google.crypto.tink.subtle.Ed25519Verify
|
||||
import com.google.crypto.tink.subtle.Hkdf
|
||||
import java.nio.ByteBuffer
|
||||
import java.security.GeneralSecurityException
|
||||
import javax.crypto.Mac
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
/**
|
||||
* Live channels — mirror of `@shade/media/src/live/{frame,channel}.ts`.
|
||||
*
|
||||
* SLF1 frame: 48-byte header ("SLF1", ver, flags, 0 0, channelId(16),
|
||||
* epoch u32, seq u64, timestamp u64, ctLen u32) ‖ AES-256-GCM(ct‖tag, aad =
|
||||
* header) ‖ Ed25519 signature over everything before it.
|
||||
*
|
||||
* Keys: Sender Keys. ck[0]/stickyKey from the epoch seed; mk[i] = HMAC(ck[i],
|
||||
* 01) used once; ck[i+1] = HMAC(ck[i], 02). Every frame is signed by the
|
||||
* channel key, so a viewer (who holds the chain) cannot forge to another.
|
||||
*/
|
||||
|
||||
class LiveKeyException(message: String) : Exception(message)
|
||||
|
||||
const val SLF_HEADER_BYTES = 48
|
||||
const val SLF_SIGNATURE_BYTES = 64
|
||||
const val FLAG_STICKY = 0x01
|
||||
const val FLAG_KEYFRAME = 0x02
|
||||
const val FLAG_END = 0x04
|
||||
const val LIVE_MAX_SKIP = 100_000L
|
||||
const val LIVE_MAX_SKIPPED_KEYS = 2_000
|
||||
const val LIVE_MAX_FRAME_PAYLOAD = 16 * 1024 * 1024
|
||||
|
||||
private val SLF_MAGIC = byteArrayOf(0x53, 0x4c, 0x46, 0x31)
|
||||
private val INFO_CHAIN = "shade-live/v1\u0000chain".toByteArray(Charsets.UTF_8)
|
||||
private val INFO_STICKY = "shade-live/v1\u0000sticky".toByteArray(Charsets.UTF_8)
|
||||
private val INFO_EPOCH = "shade-live/v1\u0000epoch".toByteArray(Charsets.UTF_8)
|
||||
|
||||
class EpochKeys(val chainKey: ByteArray, val stickyKey: ByteArray)
|
||||
|
||||
fun epochKeys(epochSeed: ByteArray, channelId: ByteArray, epoch: Long): EpochKeys {
|
||||
val salt = channelId + u32(epoch)
|
||||
return EpochKeys(
|
||||
Hkdf.computeHkdf("HMACSHA256", epochSeed, salt, INFO_CHAIN, 32),
|
||||
Hkdf.computeHkdf("HMACSHA256", epochSeed, salt, INFO_STICKY, 32),
|
||||
)
|
||||
}
|
||||
|
||||
fun linkEpochSeed(channelSecret: ByteArray, channelId: ByteArray, epoch: Long): ByteArray =
|
||||
Hkdf.computeHkdf("HMACSHA256", channelSecret, channelId, INFO_EPOCH + u32(epoch), 32)
|
||||
|
||||
private fun hmac(key: ByteArray, data: ByteArray): ByteArray =
|
||||
Mac.getInstance("HmacSHA256").apply { init(SecretKeySpec(key, "HmacSHA256")) }.doFinal(data)
|
||||
|
||||
/** One chain step: (message key for this seq, chain key for the next). */
|
||||
fun chainStep(ck: ByteArray): Pair<ByteArray, ByteArray> = hmac(ck, byteArrayOf(1)) to hmac(ck, byteArrayOf(2))
|
||||
|
||||
fun frameNonce(epoch: Long, seq: Long): ByteArray = u32(epoch) + u64(seq)
|
||||
|
||||
/** What a frame carries — mirror of the TS `LiveContent` union. */
|
||||
sealed class LiveContent {
|
||||
data class Text(val text: String) : LiveContent()
|
||||
class Binary(val bytes: ByteArray) : LiveContent()
|
||||
class Init(val mime: String, val bytes: ByteArray) : LiveContent()
|
||||
class Chunk(val bytes: ByteArray) : LiveContent()
|
||||
class Image(val mime: String, val bytes: ByteArray) : LiveContent()
|
||||
data class Meta(val meta: MediaMeta) : LiveContent()
|
||||
object End : LiveContent()
|
||||
|
||||
fun encode(): ByteArray = when (this) {
|
||||
is Text -> byteArrayOf(1) + text.toByteArray(Charsets.UTF_8)
|
||||
is Binary -> byteArrayOf(2) + bytes
|
||||
is Init -> withMime(3, mime, bytes)
|
||||
is Chunk -> byteArrayOf(4) + bytes
|
||||
is Image -> withMime(5, mime, bytes)
|
||||
is Meta -> byteArrayOf(6) + MediaMeta.validate(meta).toJson().toByteArray(Charsets.UTF_8)
|
||||
End -> byteArrayOf(7)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private fun withMime(kind: Int, mime: String, bytes: ByteArray): ByteArray {
|
||||
val m = mime.toByteArray(Charsets.UTF_8)
|
||||
if (m.isEmpty() || m.size > 255) throw MediaFormatException("mime must be 1–255 bytes")
|
||||
return byteArrayOf(kind.toByte(), m.size.toByte()) + m + bytes
|
||||
}
|
||||
|
||||
fun decode(p: ByteArray): LiveContent {
|
||||
if (p.isEmpty()) throw MediaFormatException("empty live payload")
|
||||
val body = p.copyOfRange(1, p.size)
|
||||
fun mimeBody(): Pair<String, ByteArray> {
|
||||
val n = body.firstOrNull()?.toInt()?.and(0xff) ?: throw MediaFormatException("bad mime prefix")
|
||||
if (n == 0 || body.size < 1 + n) throw MediaFormatException("bad mime prefix")
|
||||
return String(body, 1, n, Charsets.UTF_8) to body.copyOfRange(1 + n, body.size)
|
||||
}
|
||||
return when (p[0].toInt()) {
|
||||
1 -> Text(String(body, Charsets.UTF_8))
|
||||
2 -> Binary(body)
|
||||
3 -> mimeBody().let { Init(it.first, it.second) }
|
||||
4 -> Chunk(body)
|
||||
5 -> mimeBody().let { Image(it.first, it.second) }
|
||||
6 -> Meta(MediaMeta.fromJson(String(body, Charsets.UTF_8)))
|
||||
7 -> End
|
||||
else -> throw MediaFormatException("unknown live content kind ${p[0]}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class FrameHeader(val flags: Int, val channelId: ByteArray, val epoch: Long, val seq: Long, val timestamp: Long, val ctLen: Int) {
|
||||
fun encode(): ByteArray = ByteBuffer.allocate(SLF_HEADER_BYTES)
|
||||
.put(SLF_MAGIC).put(1).put(flags.toByte()).put(0).put(0)
|
||||
.put(channelId).putInt(epoch.toInt()).putLong(seq).putLong(timestamp).putInt(ctLen)
|
||||
.array()
|
||||
}
|
||||
|
||||
class DecodedFrame(val header: FrameHeader, val headerBytes: ByteArray, val ciphertext: ByteArray, val signed: ByteArray, val signature: ByteArray)
|
||||
|
||||
fun decodeFrame(frame: ByteArray): DecodedFrame {
|
||||
if (frame.size < SLF_HEADER_BYTES + TAG_BYTES + SLF_SIGNATURE_BYTES) throw MediaFormatException("live frame too short")
|
||||
if (!frame.copyOfRange(0, 4).contentEquals(SLF_MAGIC)) throw MediaFormatException("not an SLF1 frame")
|
||||
if (frame[4].toInt() != 1) throw MediaFormatException("unsupported SLF version ${frame[4]}")
|
||||
val flags = frame[5].toInt() and 0xff
|
||||
if (flags and (FLAG_STICKY or FLAG_KEYFRAME or FLAG_END).inv() != 0 || frame[6].toInt() != 0 || frame[7].toInt() != 0) {
|
||||
throw MediaFormatException("unknown SLF flags or reserved bytes")
|
||||
}
|
||||
val bb = ByteBuffer.wrap(frame)
|
||||
val ctLen = bb.getInt(44)
|
||||
if (ctLen < TAG_BYTES || ctLen > LIVE_MAX_FRAME_PAYLOAD + 17) throw MediaFormatException("bad ctLen")
|
||||
if (frame.size != SLF_HEADER_BYTES + ctLen + SLF_SIGNATURE_BYTES) throw MediaFormatException("live frame length does not match its header")
|
||||
val seq = bb.getLong(28)
|
||||
val ts = bb.getLong(36)
|
||||
if (seq < 0 || seq > (1L shl 53) || ts < 0) throw MediaFormatException("u64 field exceeds 2^53")
|
||||
return DecodedFrame(
|
||||
FrameHeader(flags, frame.copyOfRange(8, 24), bb.getInt(24).toLong() and 0xffff_ffffL, seq, ts, ctLen),
|
||||
frame.copyOfRange(0, SLF_HEADER_BYTES),
|
||||
frame.copyOfRange(SLF_HEADER_BYTES, SLF_HEADER_BYTES + ctLen),
|
||||
frame.copyOfRange(0, SLF_HEADER_BYTES + ctLen),
|
||||
frame.copyOfRange(SLF_HEADER_BYTES + ctLen, frame.size),
|
||||
)
|
||||
}
|
||||
|
||||
class ReceivedFrame(val epoch: Long, val seq: Long, val timestamp: Long, val sticky: Boolean, val keyframe: Boolean, val content: LiveContent)
|
||||
|
||||
/**
|
||||
* Viewing side. Feed frames in any order; each is returned once, or `null`
|
||||
* for a harmless drop (a duplicate, or backlog before the grant's start).
|
||||
* Throws on a forgery. Not thread-safe: call from one thread (the socket's).
|
||||
*/
|
||||
class LiveSubscriber(grant: LiveGrant) {
|
||||
val channelId: ByteArray = grant.channelId
|
||||
val signingKey: ByteArray = grant.signingKey
|
||||
private val verifier = Ed25519Verify(grant.signingKey)
|
||||
|
||||
private class EpochState(val stickyKey: ByteArray, var nextSeq: Long, var chainKey: ByteArray) {
|
||||
val skipped = LinkedHashMap<Long, ByteArray>()
|
||||
val stickySeen = HashSet<Long>()
|
||||
}
|
||||
|
||||
private val epochs = HashMap<Long, EpochState>()
|
||||
private var link: Pair<ByteArray, Long>? = null
|
||||
|
||||
init {
|
||||
addGrant(grant)
|
||||
}
|
||||
|
||||
fun addGrant(g: LiveGrant) {
|
||||
if (!g.channelId.contentEquals(channelId)) throw MediaFormatException("grant is for another channel")
|
||||
if (!g.signingKey.contentEquals(signingKey)) throw MediaIntegrityException("grant changes the channel signing key")
|
||||
g.channelSecret?.let { s -> if (link == null || g.epoch < link!!.second) link = s.copyOf() to g.epoch }
|
||||
val existing = epochs[g.epoch]
|
||||
if (existing != null && existing.nextSeq <= g.seq) return
|
||||
epochs[g.epoch] = EpochState(g.stickyKey.copyOf(), g.seq, g.chainKey.copyOf())
|
||||
}
|
||||
|
||||
fun forgetBefore(epoch: Long) {
|
||||
val it = epochs.entries.iterator()
|
||||
while (it.hasNext()) {
|
||||
val (e, st) = it.next()
|
||||
if (e < epoch) {
|
||||
st.chainKey.fill(0)
|
||||
st.stickyKey.fill(0)
|
||||
st.skipped.values.forEach { k -> k.fill(0) }
|
||||
it.remove()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Wipe every key held; the subscriber opens nothing afterwards. */
|
||||
fun close() {
|
||||
forgetBefore(Long.MAX_VALUE)
|
||||
link?.first?.fill(0)
|
||||
link = null
|
||||
}
|
||||
|
||||
private fun epochState(epoch: Long): EpochState? {
|
||||
epochs[epoch]?.let { return it }
|
||||
val (secret, from) = link ?: return null
|
||||
if (epoch < from) return null
|
||||
val k = epochKeys(linkEpochSeed(secret, channelId, epoch), channelId, epoch)
|
||||
val st = EpochState(k.stickyKey, 0, k.chainKey)
|
||||
epochs[epoch] = st
|
||||
forgetBefore(epoch)
|
||||
return st
|
||||
}
|
||||
|
||||
fun open(frame: ByteArray): ReceivedFrame? {
|
||||
val f = decodeFrame(frame)
|
||||
val h = f.header
|
||||
if (!h.channelId.contentEquals(channelId)) throw MediaFormatException("frame is for another channel")
|
||||
try {
|
||||
verifier.verify(f.signature, f.signed)
|
||||
} catch (e: GeneralSecurityException) {
|
||||
throw MediaIntegrityException("live frame signature does not verify")
|
||||
}
|
||||
val st = epochState(h.epoch) ?: throw LiveKeyException("no grant for epoch ${h.epoch}")
|
||||
val sticky = h.flags and FLAG_STICKY != 0
|
||||
val nonce = frameNonce(h.epoch, h.seq)
|
||||
val plain = if (sticky) {
|
||||
if (!st.stickySeen.add(h.seq)) return null
|
||||
gcmOpen(st.stickyKey, nonce, f.ciphertext, f.headerBytes)
|
||||
} else {
|
||||
val mk = messageKey(st, h.seq) ?: return null
|
||||
try {
|
||||
gcmOpen(mk, nonce, f.ciphertext, f.headerBytes)
|
||||
} finally {
|
||||
mk.fill(0)
|
||||
}
|
||||
}
|
||||
return ReceivedFrame(h.epoch, h.seq, h.timestamp, sticky, h.flags and FLAG_KEYFRAME != 0, LiveContent.decode(plain))
|
||||
}
|
||||
|
||||
private fun messageKey(st: EpochState, seq: Long): ByteArray? {
|
||||
if (seq < st.nextSeq) return st.skipped.remove(seq)
|
||||
if (seq - st.nextSeq > LIVE_MAX_SKIP) throw LiveKeyException("frame $seq is ${seq - st.nextSeq} ahead — beyond MAX_SKIP")
|
||||
var ck = st.chainKey
|
||||
for (s in st.nextSeq until seq) {
|
||||
val (mk, next) = chainStep(ck)
|
||||
ck.fill(0)
|
||||
ck = next
|
||||
if (seq - s <= LIVE_MAX_SKIPPED_KEYS) {
|
||||
st.skipped[s] = mk
|
||||
if (st.skipped.size > LIVE_MAX_SKIPPED_KEYS) {
|
||||
val oldest = st.skipped.keys.first()
|
||||
st.skipped.remove(oldest)?.fill(0)
|
||||
}
|
||||
} else {
|
||||
mk.fill(0)
|
||||
}
|
||||
}
|
||||
val (mk, next) = chainStep(ck)
|
||||
ck.fill(0)
|
||||
st.chainKey = next
|
||||
st.nextSeq = seq + 1
|
||||
return mk
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sending side — a phone streaming its camera or its own logs. Mirror of the
|
||||
* TS `LivePublisher` (link mode supported). Not thread-safe; frames are
|
||||
* numbered in call order.
|
||||
*/
|
||||
class LivePublisher(
|
||||
val channelId: ByteArray,
|
||||
private val signingSeed: ByteArray,
|
||||
private val channelSecret: ByteArray?,
|
||||
startEpoch: Long = 0,
|
||||
private val snapshotLimit: Int = 64,
|
||||
) {
|
||||
private val signer = Ed25519Sign(signingSeed)
|
||||
val signingKey: ByteArray = Ed25519Sign.KeyPair.newKeyPairFromSeed(signingSeed).publicKey
|
||||
var epoch: Long = startEpoch
|
||||
private set
|
||||
private var seq = 0L
|
||||
private var chainKey: ByteArray
|
||||
private var stickyKey: ByteArray
|
||||
private val snapshots = ArrayDeque<Pair<Long, ByteArray>>()
|
||||
private val stickyContent = ArrayList<Pair<LiveContent, Boolean>>()
|
||||
|
||||
init {
|
||||
require(channelId.size == 16) { "channelId must be 16 bytes" }
|
||||
val k = epochKeys(seedFor(epoch), channelId, epoch)
|
||||
chainKey = k.chainKey
|
||||
stickyKey = k.stickyKey
|
||||
}
|
||||
|
||||
private fun seedFor(e: Long): ByteArray =
|
||||
channelSecret?.let { linkEpochSeed(it, channelId, e) } ?: ByteArray(32).also { java.security.SecureRandom().nextBytes(it) }
|
||||
|
||||
fun frame(content: LiveContent, keyframe: Boolean = false, sticky: Boolean = false, timestamp: Long = System.currentTimeMillis()): ByteArray {
|
||||
val plain = content.encode()
|
||||
if (plain.size > LIVE_MAX_FRAME_PAYLOAD) throw MediaFormatException("live frame payload too large")
|
||||
val s = seq++
|
||||
var flags = 0
|
||||
if (sticky) flags = flags or FLAG_STICKY
|
||||
if (keyframe) flags = flags or FLAG_KEYFRAME
|
||||
if (content is LiveContent.End) flags = flags or FLAG_END
|
||||
if (keyframe && !sticky) {
|
||||
snapshots.addLast(s to chainKey.copyOf())
|
||||
while (snapshots.size > snapshotLimit) snapshots.removeFirst().second.fill(0)
|
||||
}
|
||||
val (mk, next) = chainStep(chainKey)
|
||||
chainKey.fill(0)
|
||||
chainKey = next
|
||||
val header = FrameHeader(flags, channelId, epoch, s, timestamp, plain.size + TAG_BYTES).encode()
|
||||
val ct = gcmSeal(if (sticky) stickyKey else mk, frameNonce(epoch, s), plain, header)
|
||||
mk.fill(0)
|
||||
val signed = header + ct
|
||||
if (sticky) stickyContent += content to keyframe
|
||||
return signed + signer.sign(signed)
|
||||
}
|
||||
|
||||
fun grant(from: String = "oldest", link: Boolean = false, url: String? = null, readToken: ByteArray? = null): LiveGrant {
|
||||
val (s, ck) = when {
|
||||
from == "now" || snapshots.isEmpty() -> seq to chainKey
|
||||
from == "latest" -> snapshots.last()
|
||||
else -> snapshots.first()
|
||||
}
|
||||
if (link && channelSecret == null) throw IllegalStateException("link grants need a channelSecret")
|
||||
return LiveGrant(channelId, signingKey, epoch, s, ck.copyOf(), stickyKey.copyOf(), url, readToken, null, if (link) channelSecret!!.copyOf() else null)
|
||||
}
|
||||
|
||||
/** New epoch; returns the sticky frames resealed for it — send them first. */
|
||||
fun rotate(timestamp: Long = System.currentTimeMillis()): List<ByteArray> {
|
||||
epoch++
|
||||
seq = 0
|
||||
snapshots.forEach { it.second.fill(0) }
|
||||
snapshots.clear()
|
||||
chainKey.fill(0)
|
||||
stickyKey.fill(0)
|
||||
val k = epochKeys(seedFor(epoch), channelId, epoch)
|
||||
chainKey = k.chainKey
|
||||
stickyKey = k.stickyKey
|
||||
val content = stickyContent.toList()
|
||||
stickyContent.clear()
|
||||
return content.map { (c, kf) -> frame(c, keyframe = kf, sticky = true, timestamp = timestamp) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
package no.zyon.shade.media
|
||||
|
||||
import com.google.crypto.tink.subtle.Hkdf
|
||||
import no.zyon.shade.serialization.stringifyJson
|
||||
import org.json.JSONException
|
||||
import org.json.JSONObject
|
||||
import java.nio.ByteBuffer
|
||||
import java.security.MessageDigest
|
||||
import java.security.SecureRandom
|
||||
import javax.crypto.AEADBadTagException
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
/**
|
||||
* SMF1 — Shade Media Format v1, mirror of `@shade/media/src/sealed.ts`.
|
||||
* The cross-language contract is `docs/media.md`; vectors in
|
||||
* `test-vectors/media.json`.
|
||||
*
|
||||
* segment[0] … segment[n-1] AES-256-GCM, `segmentSize` plaintext each
|
||||
* meta AES-256-GCM over UTF-8 JSON
|
||||
* table n × SHA-256(segment bytes)
|
||||
* footer (64) "SMF1" · ver · flags · 0 0 · segSize u32 ·
|
||||
* plainSize u64 · metaLen u32 · mediaId(16) ·
|
||||
* 20 × 0 · "SMF1"
|
||||
*/
|
||||
|
||||
class MediaFormatException(message: String) : Exception(message)
|
||||
|
||||
/** Bytes failed authentication — a store or another key holder changed them. */
|
||||
class MediaIntegrityException(message: String) : Exception(message)
|
||||
|
||||
val SMF_MAGIC = byteArrayOf(0x53, 0x4d, 0x46, 0x31)
|
||||
const val SMF_VERSION = 1
|
||||
const val FOOTER_BYTES = 64
|
||||
const val DIGEST_BYTES = 32
|
||||
const val TAG_BYTES = 16
|
||||
const val MEDIA_ID_BYTES = 16
|
||||
const val MEDIA_KEY_BYTES = 32
|
||||
const val DEFAULT_SEGMENT_SIZE = 1024 * 1024
|
||||
const val MIN_SEGMENT_SIZE = 4 * 1024
|
||||
const val MAX_SEGMENT_SIZE = 16 * 1024 * 1024
|
||||
const val MAX_META_BYTES = 64 * 1024
|
||||
|
||||
private val INFO_SEGMENT = "shade-media/v1\u0000segment".toByteArray(Charsets.UTF_8)
|
||||
private val INFO_META = "shade-media/v1\u0000meta".toByteArray(Charsets.UTF_8)
|
||||
private val AAD_META_PREFIX = "SMF1-meta".toByteArray(Charsets.UTF_8)
|
||||
|
||||
/**
|
||||
* Sealed metadata. Numbers are whole (milliseconds, pixels): the TS writer
|
||||
* would accept a fraction, but JSON number formatting is not something two
|
||||
* languages agree on byte for byte, and nothing here needs one.
|
||||
*/
|
||||
data class MediaMeta(
|
||||
val mime: String? = null,
|
||||
val name: String? = null,
|
||||
val durationMs: Long? = null,
|
||||
val width: Long? = null,
|
||||
val height: Long? = null,
|
||||
val createdAt: Long? = null,
|
||||
val extra: Map<String, String>? = null,
|
||||
) {
|
||||
/** `JSON.stringify` of the TS-validated object — same key order, same bytes. */
|
||||
fun toJson(): String = stringifyJson(toJsonMap())
|
||||
|
||||
/** The fields in `toJson`'s order, for embedding in a larger JSON (a grant). */
|
||||
internal fun toJsonMap(): Map<String, Any> {
|
||||
val m = LinkedHashMap<String, Any>()
|
||||
mime?.let { m["mime"] = it }
|
||||
name?.let { m["name"] = it }
|
||||
durationMs?.let { m["durationMs"] = it }
|
||||
width?.let { m["width"] = it }
|
||||
height?.let { m["height"] = it }
|
||||
createdAt?.let { m["createdAt"] = it }
|
||||
extra?.let { m["extra"] = LinkedHashMap(it) }
|
||||
return m
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val MIME_RE = Regex("""^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}(?:;[ -~]{0,200})?$""", RegexOption.IGNORE_CASE)
|
||||
|
||||
fun validate(m: MediaMeta): MediaMeta {
|
||||
m.mime?.let { if (!MIME_RE.matches(it)) throw MediaFormatException("bad mime") }
|
||||
m.name?.let { n ->
|
||||
if (n.length > 1024 || n.any { it.code < 0x20 || it.code == 0x7f }) throw MediaFormatException("bad name")
|
||||
}
|
||||
listOf(m.durationMs, m.width, m.height, m.createdAt).forEach {
|
||||
if (it != null && it < 0) throw MediaFormatException("negative number in meta")
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
/** Parse strictly, like the TS reader: unknown shapes are refused, unknown keys ignored. */
|
||||
fun fromJson(json: String): MediaMeta {
|
||||
val o = try { JSONObject(json) } catch (e: JSONException) { throw MediaFormatException("meta is not a JSON object") }
|
||||
fun str(k: String): String? = if (!o.has(k)) null else (o.get(k) as? String ?: throw MediaFormatException("bad $k"))
|
||||
fun num(k: String): Long? {
|
||||
if (!o.has(k)) return null
|
||||
val v = o.get(k) as? Number ?: throw MediaFormatException("bad $k")
|
||||
val d = v.toDouble()
|
||||
if (d < 0 || d.isNaN() || d.isInfinite()) throw MediaFormatException("bad $k")
|
||||
return v.toLong()
|
||||
}
|
||||
val extra = if (!o.has("extra")) null else {
|
||||
val e = o.get("extra") as? JSONObject ?: throw MediaFormatException("extra must be an object of strings")
|
||||
val out = LinkedHashMap<String, String>()
|
||||
for (k in e.keys()) out[k] = e.get(k) as? String ?: throw MediaFormatException("extra values must be strings")
|
||||
out
|
||||
}
|
||||
return validate(MediaMeta(str("mime"), str("name"), num("durationMs"), num("width"), num("height"), num("createdAt"), extra))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Raw subkeys of a media item: segment key and meta key. */
|
||||
class MediaSubkeys(val segmentKey: ByteArray, val metaKey: ByteArray)
|
||||
|
||||
fun deriveMediaSubkeys(mediaKey: ByteArray, mediaId: ByteArray): MediaSubkeys {
|
||||
if (mediaKey.size != MEDIA_KEY_BYTES) throw MediaFormatException("mediaKey must be 32 bytes")
|
||||
if (mediaId.size != MEDIA_ID_BYTES) throw MediaFormatException("mediaId must be 16 bytes")
|
||||
return MediaSubkeys(
|
||||
Hkdf.computeHkdf("HMACSHA256", mediaKey, mediaId, INFO_SEGMENT, 32),
|
||||
Hkdf.computeHkdf("HMACSHA256", mediaKey, mediaId, INFO_META, 32),
|
||||
)
|
||||
}
|
||||
|
||||
internal fun u32(n: Long): ByteArray = ByteBuffer.allocate(4).putInt(n.toInt()).array()
|
||||
internal fun u64(n: Long): ByteArray = ByteBuffer.allocate(8).putLong(n).array()
|
||||
|
||||
fun segmentNonce(index: Long): ByteArray = u32(0) + u64(index)
|
||||
internal val META_NONCE: ByteArray = u32(1) + u64(0)
|
||||
|
||||
fun segmentAad(mediaId: ByteArray, index: Long, last: Boolean): ByteArray =
|
||||
SMF_MAGIC + mediaId + u64(index) + byteArrayOf(if (last) 1 else 0)
|
||||
|
||||
internal fun metaAad(mediaId: ByteArray): ByteArray = AAD_META_PREFIX + mediaId
|
||||
|
||||
internal fun sha256(b: ByteArray): ByteArray = MessageDigest.getInstance("SHA-256").digest(b)
|
||||
|
||||
/** AES-256-GCM with a caller-supplied nonce; returns ct‖tag (no nonce prefix). */
|
||||
internal fun gcmSeal(key: ByteArray, nonce: ByteArray, plaintext: ByteArray, aad: ByteArray): ByteArray {
|
||||
val c = Cipher.getInstance("AES/GCM/NoPadding")
|
||||
c.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))
|
||||
c.updateAAD(aad)
|
||||
return c.doFinal(plaintext)
|
||||
}
|
||||
|
||||
internal fun gcmOpen(key: ByteArray, nonce: ByteArray, ciphertext: ByteArray, aad: ByteArray): ByteArray {
|
||||
val c = Cipher.getInstance("AES/GCM/NoPadding")
|
||||
c.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))
|
||||
c.updateAAD(aad)
|
||||
return try {
|
||||
c.doFinal(ciphertext)
|
||||
} catch (e: AEADBadTagException) {
|
||||
throw MediaIntegrityException("AEAD authentication failed")
|
||||
}
|
||||
}
|
||||
|
||||
internal fun ctEquals(a: ByteArray, b: ByteArray): Boolean = MessageDigest.isEqual(a, b)
|
||||
|
||||
class Footer(val segmentSize: Int, val plaintextSize: Long, val metaLen: Int, val mediaId: ByteArray) {
|
||||
val segmentCount: Long get() = segmentCountFor(plaintextSize, segmentSize)
|
||||
|
||||
/** Offset and sealed length of segment `i`. */
|
||||
fun span(i: Long): Pair<Long, Int> {
|
||||
val n = segmentCount
|
||||
val plain = if (i < n - 1) segmentSize.toLong() else plaintextSize - (n - 1) * segmentSize
|
||||
return i * (segmentSize + TAG_BYTES) to (plain + TAG_BYTES).toInt()
|
||||
}
|
||||
|
||||
val sealedSize: Long
|
||||
get() = plaintextSize + segmentCount * TAG_BYTES + metaLen + segmentCount * DIGEST_BYTES + FOOTER_BYTES
|
||||
|
||||
fun encode(): ByteArray {
|
||||
val b = ByteBuffer.allocate(FOOTER_BYTES)
|
||||
b.put(SMF_MAGIC).put(SMF_VERSION.toByte()).put(0).put(0).put(0)
|
||||
b.putInt(segmentSize).putLong(plaintextSize).putInt(metaLen).put(mediaId)
|
||||
b.put(ByteArray(20)).put(SMF_MAGIC)
|
||||
return b.array()
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun decode(b: ByteArray): Footer {
|
||||
if (b.size != FOOTER_BYTES) throw MediaFormatException("footer must be 64 bytes")
|
||||
if (!b.copyOfRange(0, 4).contentEquals(SMF_MAGIC) || !b.copyOfRange(60, 64).contentEquals(SMF_MAGIC)) {
|
||||
throw MediaFormatException("not an SMF1 file (bad magic)")
|
||||
}
|
||||
if (b[4].toInt() != SMF_VERSION) throw MediaFormatException("unsupported SMF version ${b[4]}")
|
||||
if (b[5].toInt() != 0 || b[6].toInt() != 0 || b[7].toInt() != 0 || (40 until 60).any { b[it].toInt() != 0 }) {
|
||||
throw MediaFormatException("unknown SMF flags or non-zero reserved bytes")
|
||||
}
|
||||
val bb = ByteBuffer.wrap(b)
|
||||
val seg = bb.getInt(8)
|
||||
if (seg < MIN_SEGMENT_SIZE || seg > MAX_SEGMENT_SIZE) throw MediaFormatException("segmentSize out of range: $seg")
|
||||
val plain = bb.getLong(12)
|
||||
if (plain < 0 || plain > (1L shl 53)) throw MediaFormatException("plaintext size out of range")
|
||||
val metaLen = bb.getInt(20)
|
||||
if (metaLen < TAG_BYTES || metaLen > MAX_META_BYTES + TAG_BYTES) throw MediaFormatException("metaLen out of range: $metaLen")
|
||||
return Footer(seg, plain, metaLen, b.copyOfRange(24, 40))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun segmentCountFor(plaintextSize: Long, segmentSize: Int): Long =
|
||||
maxOf(1L, (plaintextSize + segmentSize - 1) / segmentSize)
|
||||
|
||||
class SealResult(
|
||||
val mediaId: ByteArray,
|
||||
val mediaKey: ByteArray,
|
||||
val rootDigest: ByteArray,
|
||||
val plaintextSize: Long,
|
||||
val sealedSize: Long,
|
||||
val segmentSize: Int,
|
||||
val segmentCount: Long,
|
||||
)
|
||||
|
||||
/**
|
||||
* Incremental sealer — feed plaintext in any chunking, write out what it
|
||||
* returns, in order. Constant memory (one segment). Mirror of the TS
|
||||
* `MediaSealer`: a segment is held back until more input proves it is not
|
||||
* the last one, because "last" is in its AAD.
|
||||
*/
|
||||
class MediaSealer private constructor(
|
||||
val mediaId: ByteArray,
|
||||
val mediaKey: ByteArray,
|
||||
val segmentSize: Int,
|
||||
meta: MediaMeta,
|
||||
) {
|
||||
constructor(meta: MediaMeta = MediaMeta(), segmentSize: Int = DEFAULT_SEGMENT_SIZE) :
|
||||
this(random(MEDIA_ID_BYTES), random(MEDIA_KEY_BYTES), segmentSize, meta)
|
||||
|
||||
private val keys = deriveMediaSubkeys(mediaKey, mediaId)
|
||||
private val metaJson = MediaMeta.validate(meta).toJson().toByteArray(Charsets.UTF_8)
|
||||
private val pending = java.io.ByteArrayOutputStream()
|
||||
private val digests = java.io.ByteArrayOutputStream()
|
||||
private var index = 0L
|
||||
private var plaintextSize = 0L
|
||||
private var sealedSize = 0L
|
||||
private var finished = false
|
||||
|
||||
init {
|
||||
if (segmentSize < MIN_SEGMENT_SIZE || segmentSize > MAX_SEGMENT_SIZE) {
|
||||
throw MediaFormatException("segmentSize out of range: $segmentSize")
|
||||
}
|
||||
if (metaJson.size > MAX_META_BYTES) throw MediaFormatException("meta too large")
|
||||
}
|
||||
|
||||
fun push(chunk: ByteArray): List<ByteArray> {
|
||||
check(!finished) { "push after finish" }
|
||||
pending.write(chunk)
|
||||
plaintextSize += chunk.size
|
||||
val out = ArrayList<ByteArray>()
|
||||
if (pending.size() > segmentSize) {
|
||||
val all = pending.toByteArray()
|
||||
var off = 0
|
||||
while (all.size - off > segmentSize) {
|
||||
out += sealSegment(all.copyOfRange(off, off + segmentSize), false)
|
||||
off += segmentSize
|
||||
}
|
||||
pending.reset()
|
||||
pending.write(all, off, all.size - off)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
fun finish(): Pair<List<ByteArray>, SealResult> {
|
||||
check(!finished) { "finish called twice" }
|
||||
finished = true
|
||||
val last = sealSegment(pending.toByteArray(), true)
|
||||
val metaBlock = gcmSeal(keys.metaKey, META_NONCE, metaJson, metaAad(mediaId))
|
||||
val footer = Footer(segmentSize, plaintextSize, metaBlock.size, mediaId).encode()
|
||||
val trailer = metaBlock + digests.toByteArray() + footer
|
||||
sealedSize += trailer.size
|
||||
keys.segmentKey.fill(0)
|
||||
keys.metaKey.fill(0)
|
||||
return listOf(last, trailer) to SealResult(mediaId, mediaKey, sha256(trailer), plaintextSize, sealedSize, segmentSize, index)
|
||||
}
|
||||
|
||||
private fun sealSegment(plain: ByteArray, last: Boolean): ByteArray {
|
||||
val i = index++
|
||||
val sealed = gcmSeal(keys.segmentKey, segmentNonce(i), plain, segmentAad(mediaId, i, last))
|
||||
digests.write(sha256(sealed))
|
||||
sealedSize += sealed.size
|
||||
return sealed
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val rng = SecureRandom()
|
||||
private fun random(n: Int) = ByteArray(n).also { rng.nextBytes(it) }
|
||||
|
||||
/** Pinned key and id — for cross-language vectors ONLY (nonces are per key). */
|
||||
internal fun withPinnedKeys(mediaId: ByteArray, mediaKey: ByteArray, meta: MediaMeta, segmentSize: Int) =
|
||||
MediaSealer(mediaId, mediaKey, segmentSize, meta)
|
||||
|
||||
/**
|
||||
* Seal a stream (a film from the gallery, a recording) to `out`, one
|
||||
* segment in memory at a time. Neither stream is closed.
|
||||
*/
|
||||
fun sealStream(
|
||||
input: java.io.InputStream,
|
||||
out: java.io.OutputStream,
|
||||
meta: MediaMeta = MediaMeta(),
|
||||
segmentSize: Int = DEFAULT_SEGMENT_SIZE,
|
||||
): SealResult {
|
||||
val sealer = MediaSealer(meta, segmentSize)
|
||||
val buf = ByteArray(segmentSize)
|
||||
while (true) {
|
||||
val n = input.read(buf)
|
||||
if (n < 0) break
|
||||
if (n > 0) sealer.push(buf.copyOf(n)).forEach { out.write(it) }
|
||||
}
|
||||
val (rest, result) = sealer.finish()
|
||||
rest.forEach { out.write(it) }
|
||||
out.flush()
|
||||
return result
|
||||
}
|
||||
|
||||
/** Seal bytes already in memory. */
|
||||
fun sealBytes(plaintext: ByteArray, meta: MediaMeta = MediaMeta(), segmentSize: Int = DEFAULT_SEGMENT_SIZE): Pair<ByteArray, SealResult> =
|
||||
MediaSealer(meta, segmentSize).sealAll(plaintext)
|
||||
}
|
||||
|
||||
internal fun sealAll(plaintext: ByteArray): Pair<ByteArray, SealResult> {
|
||||
val out = java.io.ByteArrayOutputStream()
|
||||
push(plaintext).forEach { out.write(it) }
|
||||
val (rest, result) = finish()
|
||||
rest.forEach { out.write(it) }
|
||||
return out.toByteArray() to result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package no.zyon.shade.media
|
||||
|
||||
import no.zyon.shade.serialization.stringifyJson
|
||||
import org.json.JSONException
|
||||
import org.json.JSONObject
|
||||
import java.net.URI
|
||||
import java.util.Base64
|
||||
|
||||
/**
|
||||
* Grants — mirror of `@shade/media/src/grant.ts`. A grant travels as a
|
||||
* message over an existing Shade session, or in the `#shade=` fragment of a
|
||||
* capability link. Parsing is strict: a field of the wrong size or shape is
|
||||
* refused, never guessed at.
|
||||
*/
|
||||
|
||||
const val MEDIA_GRANT_KIND = "shade.media-grant/v1"
|
||||
const val LIVE_GRANT_KIND = "shade.live-grant/v1"
|
||||
|
||||
sealed class Grant {
|
||||
/** The wire fields in TS `encodeGrant`'s order. */
|
||||
internal abstract fun toJsonMap(): Map<String, Any>
|
||||
|
||||
/** Wire JSON, byte for byte what TS `encodeGrant` writes (field order fixed, meta canonical). */
|
||||
fun encode(): String = stringifyJson(toJsonMap())
|
||||
|
||||
/** `pageUrl#shade=<base64url(json)>`: the link that opens it, the key in the fragment (never sent to a server). */
|
||||
fun capabilityUrl(pageUrl: String): String =
|
||||
"${pageUrl.substringBefore('#')}#shade=${b64u(encode().toByteArray(Charsets.UTF_8))}"
|
||||
}
|
||||
|
||||
class MediaGrant(
|
||||
val mediaId: ByteArray,
|
||||
val mediaKey: ByteArray,
|
||||
val rootDigest: ByteArray,
|
||||
val url: String? = null,
|
||||
val readToken: ByteArray? = null,
|
||||
val meta: MediaMeta? = null,
|
||||
) : Grant() {
|
||||
fun keys() = MediaKeys(mediaId, mediaKey, rootDigest)
|
||||
|
||||
/** Range source for the granted file, with the read token attached. */
|
||||
fun source(): HttpRangeSource {
|
||||
val u = url ?: throw MediaFormatException("grant has no URL")
|
||||
return HttpRangeSource(u, readToken?.let { mapOf("x-shade-read" to b64u(it)) } ?: emptyMap())
|
||||
}
|
||||
|
||||
fun open(): MediaReader = MediaReader.open(source(), keys())
|
||||
|
||||
override fun toJsonMap(): Map<String, Any> {
|
||||
val o = LinkedHashMap<String, Any>()
|
||||
o["kind"] = MEDIA_GRANT_KIND
|
||||
o["mediaId"] = b64u(mediaId)
|
||||
o["key"] = b64u(mediaKey)
|
||||
o["root"] = rootDigest.joinToString("") { "%02x".format(it) }
|
||||
url?.let { o["url"] = it }
|
||||
readToken?.let { o["token"] = b64u(it) }
|
||||
meta?.let { o["meta"] = MediaMeta.validate(it).toJsonMap() }
|
||||
return o
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** The grant for a file just sealed (and uploaded to `url`). */
|
||||
fun of(r: SealResult, url: String? = null, readToken: ByteArray? = null, meta: MediaMeta? = null) =
|
||||
MediaGrant(r.mediaId, r.mediaKey, r.rootDigest, url, readToken, meta)
|
||||
}
|
||||
}
|
||||
|
||||
class LiveGrant(
|
||||
val channelId: ByteArray,
|
||||
val signingKey: ByteArray,
|
||||
val epoch: Long,
|
||||
val seq: Long,
|
||||
val chainKey: ByteArray,
|
||||
val stickyKey: ByteArray,
|
||||
val url: String? = null,
|
||||
val readToken: ByteArray? = null,
|
||||
val meta: MediaMeta? = null,
|
||||
/** Link mode: reads this epoch and every later one, unaided. */
|
||||
val channelSecret: ByteArray? = null,
|
||||
) : Grant() {
|
||||
override fun toJsonMap(): Map<String, Any> {
|
||||
val o = LinkedHashMap<String, Any>()
|
||||
o["kind"] = LIVE_GRANT_KIND
|
||||
o["channelId"] = b64u(channelId)
|
||||
o["signingKey"] = b64u(signingKey)
|
||||
o["epoch"] = epoch
|
||||
o["seq"] = seq
|
||||
o["chainKey"] = b64u(chainKey)
|
||||
o["stickyKey"] = b64u(stickyKey)
|
||||
channelSecret?.let { o["channelSecret"] = b64u(it) }
|
||||
url?.let { o["url"] = it }
|
||||
readToken?.let { o["token"] = b64u(it) }
|
||||
meta?.let { o["meta"] = MediaMeta.validate(it).toJsonMap() }
|
||||
return o
|
||||
}
|
||||
}
|
||||
|
||||
internal fun b64u(b: ByteArray): String = Base64.getUrlEncoder().withoutPadding().encodeToString(b)
|
||||
|
||||
internal fun fromB64u(s: String, expected: Int? = null): ByteArray {
|
||||
if (!Regex("^[A-Za-z0-9_-]*$").matches(s)) throw MediaFormatException("not base64url")
|
||||
val b = try { Base64.getUrlDecoder().decode(s) } catch (e: IllegalArgumentException) { throw MediaFormatException("not base64url") }
|
||||
if (expected != null && b.size != expected) throw MediaFormatException("expected $expected bytes, got ${b.size}")
|
||||
return b
|
||||
}
|
||||
|
||||
internal fun fromHexStrict(s: String, expected: Int): ByteArray {
|
||||
if (!Regex("^(?:[0-9a-f]{2})*$").matches(s) || s.length != expected * 2) throw MediaFormatException("bad hex")
|
||||
return ByteArray(expected) { ((Character.digit(s[it * 2], 16) shl 4) + Character.digit(s[it * 2 + 1], 16)).toByte() }
|
||||
}
|
||||
|
||||
object Grants {
|
||||
fun parse(json: String): Grant {
|
||||
val o = try { JSONObject(json) } catch (e: JSONException) { throw MediaFormatException("grant is not JSON") }
|
||||
fun str(k: String): String = o.opt(k) as? String ?: throw MediaFormatException("grant.$k must be a string")
|
||||
fun optStr(k: String): String? = if (!o.has(k)) null else str(k)
|
||||
fun int(k: String, max: Long): Long {
|
||||
val v = o.opt(k) as? Number ?: throw MediaFormatException("grant.$k must be an integer")
|
||||
val l = v.toLong()
|
||||
if (l.toDouble() != v.toDouble() || l < 0 || l > max) throw MediaFormatException("grant.$k out of range")
|
||||
return l
|
||||
}
|
||||
val url = optStr("url")?.also {
|
||||
val scheme = try { URI(it).scheme } catch (e: Exception) { null }
|
||||
if (scheme !in setOf("http", "https", "ws", "wss")) throw MediaFormatException("grant.url must be http(s) or ws(s)")
|
||||
}
|
||||
val token = optStr("token")?.let { fromB64u(it) }?.also {
|
||||
if (it.size < 16 || it.size > 64) throw MediaFormatException("grant.token must be 16–64 bytes")
|
||||
}
|
||||
val meta = (o.opt("meta") as? JSONObject)?.let { MediaMeta.fromJson(it.toString()) }
|
||||
return when (o.opt("kind")) {
|
||||
MEDIA_GRANT_KIND -> MediaGrant(
|
||||
fromB64u(str("mediaId"), MEDIA_ID_BYTES),
|
||||
fromB64u(str("key"), MEDIA_KEY_BYTES),
|
||||
fromHexStrict(str("root"), DIGEST_BYTES),
|
||||
url, token, meta,
|
||||
)
|
||||
LIVE_GRANT_KIND -> LiveGrant(
|
||||
fromB64u(str("channelId"), 16),
|
||||
fromB64u(str("signingKey"), 32),
|
||||
int("epoch", 0xffff_ffffL),
|
||||
int("seq", (1L shl 53) - 1),
|
||||
fromB64u(str("chainKey"), 32),
|
||||
fromB64u(str("stickyKey"), 32),
|
||||
url, token, meta,
|
||||
optStr("channelSecret")?.let { fromB64u(it, 32) },
|
||||
)
|
||||
else -> throw MediaFormatException("unknown grant kind ${o.opt("kind")}")
|
||||
}
|
||||
}
|
||||
|
||||
/** Grant from a capability link `…#shade=<base64url(json)>`. */
|
||||
fun fromCapabilityUrl(link: String): Grant {
|
||||
val frag = link.substringAfter('#', link)
|
||||
val m = Regex("(?:^|&)shade=([A-Za-z0-9_-]+)").find(frag) ?: throw MediaFormatException("link carries no #shade= grant")
|
||||
return parse(String(fromB64u(m.groupValues[1]), Charsets.UTF_8))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package no.zyon.shade.media
|
||||
|
||||
import com.google.crypto.tink.subtle.Ed25519Sign
|
||||
import java.security.SecureRandom
|
||||
|
||||
/**
|
||||
* Who may upload to a relay and delete from it: an Ed25519 key and nothing
|
||||
* else (mirror of `@shade/media` owner.ts). Requests are signed over a fixed
|
||||
* string naming the operation, so a signature for one request cannot be
|
||||
* replayed as another, and over a timestamp the relay accepts within ten
|
||||
* minutes of its own clock.
|
||||
*/
|
||||
class MediaOwner(seed: ByteArray) {
|
||||
private val seed = seed.copyOf()
|
||||
private val signer = Ed25519Sign(seed)
|
||||
val publicKey: ByteArray = Ed25519Sign.KeyPair.newKeyPairFromSeed(seed).publicKey
|
||||
|
||||
init {
|
||||
require(seed.size == 32) { "owner seed must be 32 bytes" }
|
||||
}
|
||||
|
||||
/** The key as a relay's owner lists name it (`--owners`, `SHADE_MEDIA_OWNERS`). */
|
||||
val id: String get() = b64u(publicKey)
|
||||
|
||||
/** The seed, for keeping — in the Keystore-backed storage, never in plain prefs. */
|
||||
fun exportSeed(): ByteArray = seed.copyOf()
|
||||
|
||||
fun headers(op: OwnerOp, at: Long = System.currentTimeMillis()): Map<String, String> = mapOf(
|
||||
OWNER_HEADER to id,
|
||||
AT_HEADER to at.toString(),
|
||||
SIGNATURE_HEADER to b64u(signer.sign(message(op, at))),
|
||||
)
|
||||
|
||||
companion object {
|
||||
const val OWNER_HEADER = "x-shade-owner"
|
||||
const val AT_HEADER = "x-shade-at"
|
||||
const val SIGNATURE_HEADER = "x-shade-signature"
|
||||
const val READ_HASH_HEADER = "x-shade-read-hash"
|
||||
const val READ_TOKEN_HEADER = "x-shade-read"
|
||||
|
||||
fun generate(): MediaOwner = MediaOwner(ByteArray(32).also { SecureRandom().nextBytes(it) })
|
||||
|
||||
/** The exact bytes signed for `op` at `at` — shared with TS through `test-vectors/media.json`. */
|
||||
fun message(op: OwnerOp, at: Long): ByteArray = when (op) {
|
||||
is OwnerOp.Put -> "shade.media-put/v1|${op.id}|${op.size}|${op.readTokenHash}|$at"
|
||||
is OwnerOp.Upload -> "shade.media-upload/v1|${op.id}|${op.size}|${op.readTokenHash}|$at"
|
||||
is OwnerOp.Piece -> "shade.media-piece/v1|${op.id}|${op.offset}|${op.length}|$at"
|
||||
is OwnerOp.Abort -> "shade.media-abort/v1|${op.id}|$at"
|
||||
is OwnerOp.Delete -> "shade.media-delete/v1|${op.id}|$at"
|
||||
OwnerOp.List -> "shade.media-list/v1|$at"
|
||||
}.toByteArray(Charsets.UTF_8)
|
||||
}
|
||||
}
|
||||
|
||||
/** What an owner signs. `readTokenHash` is the hex SHA-256 of the read token, or "" for public ciphertext. */
|
||||
sealed class OwnerOp {
|
||||
data class Put(val id: String, val size: Long, val readTokenHash: String) : OwnerOp()
|
||||
data class Upload(val id: String, val size: Long, val readTokenHash: String) : OwnerOp()
|
||||
data class Piece(val id: String, val offset: Long, val length: Long) : OwnerOp()
|
||||
data class Abort(val id: String) : OwnerOp()
|
||||
data class Delete(val id: String) : OwnerOp()
|
||||
object List : OwnerOp()
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
package no.zyon.shade.media
|
||||
|
||||
import java.io.Closeable
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.channels.FileChannel
|
||||
import java.nio.file.StandardOpenOption
|
||||
|
||||
/** Where sealed bytes come from: a size and byte ranges, nothing else. */
|
||||
interface RangeSource {
|
||||
fun size(): Long
|
||||
|
||||
/** Exactly `length` bytes from `offset` (fewer only past the end). */
|
||||
fun read(offset: Long, length: Int): ByteArray
|
||||
}
|
||||
|
||||
class ByteArraySource(private val bytes: ByteArray) : RangeSource {
|
||||
override fun size(): Long = bytes.size.toLong()
|
||||
override fun read(offset: Long, length: Int): ByteArray {
|
||||
val start = offset.toInt().coerceAtMost(bytes.size)
|
||||
return bytes.copyOfRange(start, (start + length).coerceAtMost(bytes.size))
|
||||
}
|
||||
}
|
||||
|
||||
/** A sealed file on disk — a film too large to hold, uploaded a piece at a time. Safe to read from several threads. */
|
||||
class FileRangeSource(file: File) : RangeSource, Closeable {
|
||||
private val ch = FileChannel.open(file.toPath(), StandardOpenOption.READ)
|
||||
override fun size(): Long = ch.size()
|
||||
override fun read(offset: Long, length: Int): ByteArray {
|
||||
val buf = ByteBuffer.allocate(length.coerceAtMost((size() - offset).coerceAtLeast(0).toInt()))
|
||||
while (buf.hasRemaining()) {
|
||||
if (ch.read(buf, offset + buf.position()) < 0) break
|
||||
}
|
||||
return if (buf.hasRemaining()) buf.array().copyOf(buf.position()) else buf.array()
|
||||
}
|
||||
override fun close() = ch.close()
|
||||
}
|
||||
|
||||
/**
|
||||
* HTTP Range reads against the Shade media routes (or any Range-capable
|
||||
* server). The read token, when the grant carries one, rides in
|
||||
* `x-shade-read`. Retries network errors and 5xx; a 4xx is final.
|
||||
*/
|
||||
class HttpRangeSource(
|
||||
private val url: String,
|
||||
private val headers: Map<String, String> = emptyMap(),
|
||||
private val retries: Int = 3,
|
||||
private val timeoutMs: Int = 15_000,
|
||||
) : RangeSource {
|
||||
@Volatile private var knownSize: Long = -1
|
||||
|
||||
override fun size(): Long {
|
||||
if (knownSize >= 0) return knownSize
|
||||
val len = attempt {
|
||||
val c = open("HEAD", null)
|
||||
try {
|
||||
check4xx(c)
|
||||
c.getHeaderField("content-length")?.toLongOrNull() ?: throw MediaFormatException("HEAD $url gave no Content-Length")
|
||||
} finally {
|
||||
c.disconnect()
|
||||
}
|
||||
}
|
||||
knownSize = len
|
||||
return len
|
||||
}
|
||||
|
||||
override fun read(offset: Long, length: Int): ByteArray {
|
||||
if (length == 0) return ByteArray(0)
|
||||
return attempt {
|
||||
val c = open("GET", "bytes=$offset-${offset + length - 1}")
|
||||
try {
|
||||
check4xx(c)
|
||||
val body = c.inputStream.use { it.readBytes() }
|
||||
when (c.responseCode) {
|
||||
206 -> body
|
||||
// A server that ignores Range sends everything; correct, if wasteful.
|
||||
200 -> if (body.size >= offset + length) body.copyOfRange(offset.toInt(), (offset + length).toInt()) else throw MediaFormatException("short 200 body")
|
||||
else -> throw MediaFormatException("GET $url answered ${c.responseCode} to a Range request")
|
||||
}
|
||||
} finally {
|
||||
c.disconnect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun open(method: String, range: String?): HttpURLConnection {
|
||||
val c = URL(url).openConnection() as HttpURLConnection
|
||||
c.requestMethod = method
|
||||
c.connectTimeout = timeoutMs
|
||||
c.readTimeout = timeoutMs
|
||||
for ((k, v) in headers) c.setRequestProperty(k, v)
|
||||
if (range != null) c.setRequestProperty("Range", range)
|
||||
return c
|
||||
}
|
||||
|
||||
private fun check4xx(c: HttpURLConnection) {
|
||||
val code = c.responseCode
|
||||
if (code in 400..499) throw MediaFormatException("HTTP $code from $url")
|
||||
if (code >= 500) throw IOException("HTTP $code from $url")
|
||||
}
|
||||
|
||||
private fun <T> attempt(run: () -> T): T {
|
||||
var last: Exception? = null
|
||||
repeat(retries.coerceAtLeast(1)) { i ->
|
||||
try {
|
||||
return run()
|
||||
} catch (e: MediaFormatException) {
|
||||
throw e
|
||||
} catch (e: IOException) {
|
||||
last = e
|
||||
Thread.sleep(150L shl i)
|
||||
}
|
||||
}
|
||||
throw last ?: IOException("unreachable")
|
||||
}
|
||||
}
|
||||
|
||||
/** What a reader needs: the secret half of a grant. */
|
||||
class MediaKeys(val mediaId: ByteArray, val mediaKey: ByteArray, val rootDigest: ByteArray? = null)
|
||||
|
||||
/**
|
||||
* Random-access reader over a sealed file — mirror of the TS `MediaReader`.
|
||||
* `open` checks the trailer against the root digest; every `read` then
|
||||
* fetches only the segments under the range (neighbours in one request) and
|
||||
* checks each against the digest table before decrypting it.
|
||||
*
|
||||
* Thread-safe: ExoPlayer reads from its loader thread while the UI may seek.
|
||||
*/
|
||||
class MediaReader private constructor(
|
||||
private val source: RangeSource,
|
||||
private val footer: Footer,
|
||||
private val table: ByteArray,
|
||||
private val segmentKey: ByteArray,
|
||||
val meta: MediaMeta,
|
||||
private val cacheSegments: Int,
|
||||
private val maxSegmentsPerFetch: Int,
|
||||
) : AutoCloseable {
|
||||
val size: Long get() = footer.plaintextSize
|
||||
val segmentSize: Int get() = footer.segmentSize
|
||||
val segmentCount: Long get() = footer.segmentCount
|
||||
|
||||
private val cache = object : LinkedHashMap<Long, ByteArray>(16, 0.75f, true) {
|
||||
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, ByteArray>?) = size > cacheSegments
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun open(source: RangeSource, keys: MediaKeys, cacheSegments: Int = 8, maxSegmentsPerFetch: Int = 8): MediaReader {
|
||||
val total = source.size()
|
||||
if (total < FOOTER_BYTES) throw MediaFormatException("file too short to be SMF1")
|
||||
val footer = Footer.decode(source.read(total - FOOTER_BYTES, FOOTER_BYTES))
|
||||
if (!ctEquals(footer.mediaId, keys.mediaId)) throw MediaIntegrityException("file is a different media item than the grant names")
|
||||
if (footer.sealedSize != total) throw MediaIntegrityException("size mismatch: footer implies ${footer.sealedSize}, file has $total")
|
||||
val n = footer.segmentCount
|
||||
val trailerLen = footer.metaLen + n * DIGEST_BYTES + FOOTER_BYTES
|
||||
if (trailerLen > Int.MAX_VALUE) throw MediaFormatException("trailer too large")
|
||||
val trailer = source.read(total - trailerLen, trailerLen.toInt())
|
||||
if (keys.rootDigest != null && !ctEquals(sha256(trailer), keys.rootDigest)) {
|
||||
throw MediaIntegrityException("trailer does not match the root digest in the grant")
|
||||
}
|
||||
val sub = deriveMediaSubkeys(keys.mediaKey, keys.mediaId)
|
||||
val metaPlain = gcmOpen(sub.metaKey, META_NONCE, trailer.copyOfRange(0, footer.metaLen), metaAad(keys.mediaId))
|
||||
sub.metaKey.fill(0)
|
||||
val meta = MediaMeta.fromJson(String(metaPlain, Charsets.UTF_8))
|
||||
val table = trailer.copyOfRange(footer.metaLen, footer.metaLen + (n * DIGEST_BYTES).toInt())
|
||||
return MediaReader(source, footer, table, sub.segmentKey, meta, cacheSegments, maxSegmentsPerFetch.coerceAtLeast(1))
|
||||
}
|
||||
}
|
||||
|
||||
/** Plaintext `[offset, offset+length)`, clamped to the end. */
|
||||
fun read(offset: Long, length: Int): ByteArray {
|
||||
require(offset >= 0 && length >= 0) { "offset and length must be non-negative" }
|
||||
val end = minOf(size, offset + length)
|
||||
if (offset >= end) return ByteArray(0)
|
||||
val first = offset / segmentSize
|
||||
val last = (end - 1) / segmentSize
|
||||
val out = ByteArray((end - offset).toInt())
|
||||
var w = 0
|
||||
for ((i, seg) in segments(first, last).withIndex()) {
|
||||
val segStart = (first + i) * segmentSize
|
||||
val from = maxOf(offset, segStart) - segStart
|
||||
val to = minOf(end, segStart + seg.size) - segStart
|
||||
System.arraycopy(seg, from.toInt(), out, w, (to - from).toInt())
|
||||
w += (to - from).toInt()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** A plain InputStream over `[start, end)` — for players and file copies. */
|
||||
fun inputStream(start: Long = 0, end: Long = size): InputStream = object : InputStream() {
|
||||
private var pos = start
|
||||
override fun read(): Int {
|
||||
val b = ByteArray(1)
|
||||
return if (read(b, 0, 1) <= 0) -1 else b[0].toInt() and 0xff
|
||||
}
|
||||
override fun read(b: ByteArray, off: Int, len: Int): Int {
|
||||
if (pos >= end) return -1
|
||||
val n = minOf(len.toLong(), end - pos, segmentSize.toLong() * maxSegmentsPerFetch).toInt()
|
||||
val bytes = this@MediaReader.read(pos, n)
|
||||
System.arraycopy(bytes, 0, b, off, bytes.size)
|
||||
pos += bytes.size
|
||||
return bytes.size
|
||||
}
|
||||
override fun skip(n: Long): Long {
|
||||
val s = minOf(n, end - pos).coerceAtLeast(0)
|
||||
pos += s
|
||||
return s
|
||||
}
|
||||
}
|
||||
|
||||
private fun segments(first: Long, last: Long): List<ByteArray> {
|
||||
if (first < 0 || last >= segmentCount || first > last) throw IndexOutOfBoundsException("segments $first..$last")
|
||||
val out = ArrayList<ByteArray>()
|
||||
var i = first
|
||||
while (i <= last) {
|
||||
val cached = synchronized(cache) { cache[i] }
|
||||
if (cached != null) {
|
||||
out += cached
|
||||
i++
|
||||
continue
|
||||
}
|
||||
var j = i
|
||||
while (j + 1 <= last && j + 1 - i < maxSegmentsPerFetch && synchronized(cache) { !cache.containsKey(j + 1) }) j++
|
||||
val run = fetchRun(i, j)
|
||||
synchronized(cache) { run.forEachIndexed { k, s -> cache[i + k] = s } }
|
||||
out += run
|
||||
i = j + 1
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private fun fetchRun(first: Long, last: Long): List<ByteArray> {
|
||||
val (aOff, _) = footer.span(first)
|
||||
val (bOff, bLen) = footer.span(last)
|
||||
val len = bOff + bLen - aOff
|
||||
if (len > Int.MAX_VALUE) throw MediaFormatException("range too large")
|
||||
val bytes = source.read(aOff, len.toInt())
|
||||
if (bytes.size.toLong() != len) throw MediaIntegrityException("short read from media source")
|
||||
return (first..last).map { i ->
|
||||
val (off, l) = footer.span(i)
|
||||
val sealed = bytes.copyOfRange((off - aOff).toInt(), (off - aOff).toInt() + l)
|
||||
val want = table.copyOfRange((i * DIGEST_BYTES).toInt(), ((i + 1) * DIGEST_BYTES).toInt())
|
||||
if (!ctEquals(sha256(sealed), want)) throw MediaIntegrityException("segment $i does not match its digest")
|
||||
gcmOpen(segmentKey, segmentNonce(i), sealed, segmentAad(footer.mediaId, i, i == segmentCount - 1))
|
||||
}
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
synchronized(cache) { cache.clear() }
|
||||
segmentKey.fill(0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
package no.zyon.shade.media
|
||||
|
||||
import org.json.JSONException
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.security.MessageDigest
|
||||
import java.security.SecureRandom
|
||||
import java.util.ArrayDeque
|
||||
import java.util.TreeSet
|
||||
import java.util.concurrent.ExecutorCompletionService
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
/** Files up to this size go up in one PUT; larger ones in pieces (mirror of `@shade/media` upload.ts). */
|
||||
const val DEFAULT_CHUNK_BYTES = 16L * 1024 * 1024
|
||||
const val OFFSET_HEADER = "x-shade-offset"
|
||||
const val MAX_PIECE_BYTES = 64L * 1024 * 1024
|
||||
|
||||
/** Most pieces kept in flight, whatever window a relay offers. */
|
||||
const val MAX_CLIENT_WINDOW = 16
|
||||
|
||||
/** Failed tries in a row before a resumable upload gives up. */
|
||||
private const val MAX_TRIES = 8
|
||||
|
||||
/** The relay is restarting, overloaded or the network dropped: try again. */
|
||||
private class Transient(message: String) : IOException(message)
|
||||
|
||||
class MediaUploadException(message: String) : IOException(message)
|
||||
|
||||
/**
|
||||
* Upload sealed files to a Shade relay — mirror of the TS `MediaClient`, so a
|
||||
* phone can share a film or a video it recorded. Blocking: call it off the
|
||||
* main thread.
|
||||
*
|
||||
* A file above [DEFAULT_CHUNK_BYTES] goes in pieces, up to the relay's
|
||||
* window of them in flight. A dropped connection or a relay restart costs
|
||||
* the pieces in flight, not the upload: a failed piece is sent again after
|
||||
* asking the relay whether it landed after all. Calling [putSealed] again
|
||||
* with the same seal result and the same sealed file (after the app was
|
||||
* killed, say) resumes where the relay got to, since the media id is the same.
|
||||
*/
|
||||
class MediaUploader(
|
||||
server: String,
|
||||
private val owner: MediaOwner,
|
||||
private val timeoutMs: Int = 60_000,
|
||||
) {
|
||||
val server = server.trimEnd('/')
|
||||
|
||||
fun mediaUrl(mediaId: ByteArray): String = "$server/v1/media/${hex(mediaId)}"
|
||||
|
||||
/**
|
||||
* Upload an already sealed file; `body` must be exactly `result.sealedSize`
|
||||
* bytes. `readToken`: what viewers must present — a fresh random one by
|
||||
* default, `null` for public ciphertext. `onProgress(acked, total)` after
|
||||
* each piece the relay has.
|
||||
*/
|
||||
fun putSealed(
|
||||
result: SealResult,
|
||||
body: RangeSource,
|
||||
readToken: ByteArray? = newReadToken(),
|
||||
meta: MediaMeta? = null,
|
||||
onProgress: ((Long, Long) -> Unit)? = null,
|
||||
): MediaGrant {
|
||||
val size = body.size()
|
||||
if (size != result.sealedSize) throw MediaFormatException("body is $size bytes, the seal produced ${result.sealedSize}")
|
||||
val readTokenHash = readToken?.let { hex(MessageDigest.getInstance("SHA-256").digest(it)) } ?: ""
|
||||
val id = hex(result.mediaId)
|
||||
val url = mediaUrl(result.mediaId)
|
||||
if (size <= DEFAULT_CHUNK_BYTES) {
|
||||
val bytes = body.read(0, size.toInt())
|
||||
val headers = owner.headers(OwnerOp.Put(id, size, readTokenHash)) +
|
||||
mapOf("content-type" to "application/vnd.shade.smf1") +
|
||||
(if (readTokenHash != "") mapOf(MediaOwner.READ_HASH_HEADER to readTokenHash) else emptyMap())
|
||||
val res = try {
|
||||
request("PUT", url, headers, bytes)
|
||||
} catch (e: IOException) {
|
||||
throw MediaUploadException("upload failed: ${e.message}")
|
||||
}
|
||||
if (res.status != 201) throw MediaUploadException("upload failed: HTTP ${res.status} ${res.text()}")
|
||||
onProgress?.invoke(size, size)
|
||||
} else {
|
||||
Pieces("$url/upload", id, size, readTokenHash, body, onProgress).run()
|
||||
}
|
||||
return MediaGrant.of(result, url, readToken, meta)
|
||||
}
|
||||
|
||||
/** Seal in memory and upload — a photo, a short clip, a document. */
|
||||
fun uploadBytes(plaintext: ByteArray, meta: MediaMeta = MediaMeta(), readToken: ByteArray? = newReadToken()): MediaGrant {
|
||||
val (sealed, result) = MediaSealer.sealBytes(plaintext, meta)
|
||||
return putSealed(result, ByteArraySource(sealed), readToken, meta)
|
||||
}
|
||||
|
||||
/** Seal and upload an album; the grant opens every item in it (a season, the photos of a trip). */
|
||||
fun uploadAlbum(album: Album, readToken: ByteArray? = newReadToken()): MediaGrant =
|
||||
uploadBytes(Albums.encode(album), Albums.meta(album.title), readToken)
|
||||
|
||||
/**
|
||||
* Seal `input` into `sealedFile` and upload it — a film without holding it
|
||||
* in memory. The sealed copy is the caller's: keep it (with the returned
|
||||
* seal result) until this returns, to resume with [putSealed] if it fails.
|
||||
*/
|
||||
fun uploadStream(
|
||||
input: java.io.InputStream,
|
||||
sealedFile: File,
|
||||
meta: MediaMeta = MediaMeta(),
|
||||
readToken: ByteArray? = newReadToken(),
|
||||
onProgress: ((Long, Long) -> Unit)? = null,
|
||||
): MediaGrant {
|
||||
val result = sealedFile.outputStream().buffered().use { MediaSealer.sealStream(input, it, meta) }
|
||||
return FileRangeSource(sealedFile).use { putSealed(result, it, readToken, meta, onProgress) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload `source` as the job `key` in `jobs`, so that a run cut short (the
|
||||
* app killed, the phone out of signal for an hour) is resumed by calling
|
||||
* this again: sealed once, into the job's directory, then put with the
|
||||
* same media id. A job already done gives its grant again while the relay
|
||||
* still serves it — sharing the same video twice is one upload, one link.
|
||||
* `open` is only called when the file must be sealed.
|
||||
*/
|
||||
fun upload(
|
||||
jobs: UploadJobs,
|
||||
key: String,
|
||||
source: String,
|
||||
meta: MediaMeta,
|
||||
open: () -> java.io.InputStream,
|
||||
readToken: ByteArray? = newReadToken(),
|
||||
onProgress: ((Long, Long) -> Unit)? = null,
|
||||
): MediaGrant = jobs.claim(key).use {
|
||||
var job = jobs.load(key)
|
||||
job?.grant?.let { g ->
|
||||
if (!gone(g)) return@use g
|
||||
jobs.reset(key) // deleted from the relay since: a new upload
|
||||
job = null
|
||||
}
|
||||
val j = job ?: run {
|
||||
val sealed = jobs.sealedFile(key)
|
||||
val result = open().use { input -> sealed.outputStream().buffered().use { MediaSealer.sealStream(input, it, meta) } }
|
||||
UploadJobs.Job(result, readToken, meta, source, server = server).also { jobs.save(key, it) }
|
||||
}
|
||||
val grant = FileRangeSource(jobs.sealedFile(key)).use { putSealed(j.result, it, j.readToken, j.meta, onProgress) }
|
||||
jobs.done(key, j, grant)
|
||||
grant
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the relay says the file a grant opens is gone (deleted since).
|
||||
* A relay that cannot be reached has not said so: its link still stands.
|
||||
*/
|
||||
fun gone(grant: MediaGrant): Boolean {
|
||||
val u = grant.url ?: return true
|
||||
return try {
|
||||
request("HEAD", u, grant.readToken?.let { mapOf(MediaOwner.READ_TOKEN_HEADER to b64u(it)) } ?: emptyMap(), null).status in setOf(404, 410)
|
||||
} catch (e: IOException) {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove one of your files from the relay; false if it was not there. */
|
||||
fun delete(mediaId: ByteArray): Boolean {
|
||||
val res = request("DELETE", mediaUrl(mediaId), owner.headers(OwnerOp.Delete(hex(mediaId))), null)
|
||||
if (res.status == 404) return false
|
||||
if (res.status !in 200..299) throw MediaUploadException("delete failed: HTTP ${res.status} ${res.text()}")
|
||||
return true
|
||||
}
|
||||
|
||||
private inner class Pieces(
|
||||
private val at: String,
|
||||
private val id: String,
|
||||
private val size: Long,
|
||||
private val readTokenHash: String,
|
||||
private val body: RangeSource,
|
||||
private val onProgress: ((Long, Long) -> Unit)?,
|
||||
) {
|
||||
/**
|
||||
* How far the relay got. Checked before it is trusted (mirror of TS
|
||||
* `statusProblem`): a zero chunk would never get through the file, a
|
||||
* huge one would hold it all in memory, a huge window a thread per piece.
|
||||
*/
|
||||
private inner class Status(json: JSONObject) {
|
||||
val complete = json.optBoolean("complete", false)
|
||||
val chunk = if (complete) 0L else json.optLong("chunk", -1)
|
||||
val window = json.optInt("window", 1)
|
||||
val received = if (complete) size else json.optLong("received", -1)
|
||||
val landed: Set<Long> = if (complete) emptySet() else json.optJSONArray("landed")?.let { a ->
|
||||
(0 until a.length()).map { i -> (a.opt(i) as? Number)?.toLong()?.takeIf { it >= 0 } ?: unusable("landed is not a list of piece numbers") }.toSet()
|
||||
} ?: emptySet()
|
||||
|
||||
init {
|
||||
if (!complete) {
|
||||
if (chunk < 1024 * 1024 || chunk > MAX_PIECE_BYTES) unusable("chunk $chunk out of range")
|
||||
if (window < 1) unusable("window $window out of range")
|
||||
if (received < 0 || received > size) unusable("received $received out of range")
|
||||
}
|
||||
}
|
||||
|
||||
fun has(offset: Long) = offset < received || (offset / chunk) in landed
|
||||
}
|
||||
|
||||
private fun unusable(why: String): Nothing = throw MediaUploadException("upload failed: the relay's upload status is unusable: $why")
|
||||
|
||||
/** A request that got no answer (refused, reset, timed out) is worth repeating. */
|
||||
private fun send(method: String, headers: Map<String, String>, body: ByteArray?): Answer =
|
||||
try {
|
||||
request(method, at, headers, body)
|
||||
} catch (e: IOException) {
|
||||
throw Transient(e.message ?: e.javaClass.simpleName)
|
||||
}
|
||||
|
||||
private fun fail(res: Answer, what: String): Nothing {
|
||||
if (res.status >= 500 || res.status == 429) throw Transient("$what: HTTP ${res.status} ${res.text()}")
|
||||
throw MediaUploadException("upload failed: $what: HTTP ${res.status} ${res.text()}")
|
||||
}
|
||||
|
||||
/** Retry `fn` while it fails transiently, with backoff; `fn` learns which try it is. */
|
||||
private fun <T> retrying(fn: (attempt: Int) -> T): T {
|
||||
var attempt = 0
|
||||
while (true) {
|
||||
try {
|
||||
return fn(attempt)
|
||||
} catch (e: Transient) {
|
||||
if (attempt + 1 >= MAX_TRIES) throw MediaUploadException("upload failed after $MAX_TRIES tries: ${e.message}")
|
||||
attempt++
|
||||
Thread.sleep(minOf(30_000L, 500L shl attempt))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Start the upload, or learn how far it got. */
|
||||
private fun status(): Status {
|
||||
val headers = owner.headers(OwnerOp.Upload(id, size, readTokenHash)) +
|
||||
mapOf("x-shade-size" to size.toString()) +
|
||||
(if (readTokenHash != "") mapOf(MediaOwner.READ_HASH_HEADER to readTokenHash) else emptyMap())
|
||||
val res = send("POST", headers, ByteArray(0))
|
||||
if (res.status != 200 && res.status != 201) fail(res, "start")
|
||||
return try {
|
||||
Status(JSONObject(res.body))
|
||||
} catch (e: JSONException) {
|
||||
throw Transient("start: the relay's answer is not JSON")
|
||||
}
|
||||
}
|
||||
|
||||
private var chunk = 0L
|
||||
|
||||
/** One piece until the relay has it; true once the relay stored the whole file. */
|
||||
private fun sendPiece(offset: Long): Boolean = retrying { attempt ->
|
||||
if (attempt > 0) {
|
||||
// It may have landed before the connection dropped: ask before sending it again.
|
||||
val st = status()
|
||||
if (st.complete) return@retrying true
|
||||
if (st.has(offset)) return@retrying false
|
||||
}
|
||||
val length = minOf(chunk, size - offset)
|
||||
val piece = body.read(offset, length.toInt())
|
||||
if (piece.size.toLong() != length) throw MediaFormatException("the file shrank: read ${piece.size} of $length bytes at $offset")
|
||||
val res = send(
|
||||
"PUT",
|
||||
owner.headers(OwnerOp.Piece(id, offset, length)) +
|
||||
mapOf("content-type" to "application/octet-stream", OFFSET_HEADER to offset.toString()),
|
||||
piece,
|
||||
)
|
||||
when (res.status) {
|
||||
201 -> true
|
||||
200 -> false
|
||||
// Ahead of the window (pieces before it are still on the way): later.
|
||||
409 -> {
|
||||
val error = try { JSONObject(res.body).optString("error") } catch (e: JSONException) { "" }
|
||||
if (error == "OFFSET") throw Transient("piece ahead of the upload")
|
||||
throw MediaUploadException("upload failed: HTTP 409 ${res.text()}")
|
||||
}
|
||||
else -> fail(res, "piece at $offset")
|
||||
}
|
||||
}
|
||||
|
||||
private inner class Outcome(val offset: Long, val done: Boolean, val error: Throwable?)
|
||||
|
||||
fun run() {
|
||||
val opened = retrying { status() }
|
||||
if (opened.complete) {
|
||||
onProgress?.invoke(size, size)
|
||||
return
|
||||
}
|
||||
chunk = opened.chunk
|
||||
val window = opened.window.coerceAtMost(MAX_CLIENT_WINDOW)
|
||||
var acked = 0L
|
||||
var complete = false
|
||||
val todo = ArrayDeque<Long>()
|
||||
var off = 0L
|
||||
while (off < size) {
|
||||
if (opened.has(off)) acked += minOf(chunk, size - off) else todo.add(off)
|
||||
off += chunk
|
||||
}
|
||||
onProgress?.invoke(acked, size)
|
||||
|
||||
val pool = Executors.newFixedThreadPool(window) { r -> Thread(r, "shade-upload").apply { isDaemon = true } }
|
||||
val done = ExecutorCompletionService<Outcome>(pool)
|
||||
val flying = TreeSet<Long>()
|
||||
var failure: Throwable? = null
|
||||
/**
|
||||
* The relay takes `window` pieces past what it has from the start, so a
|
||||
* piece is only sent within `window` of the first one not yet answered:
|
||||
* one slow piece holds the window, rather than pieces past it bouncing.
|
||||
*/
|
||||
fun mayLaunch(): Boolean {
|
||||
if (todo.isEmpty() || flying.size >= window) return false
|
||||
val lowest = if (flying.isEmpty()) todo.first() else minOf(todo.first(), flying.first())
|
||||
return todo.first() < lowest + window * chunk
|
||||
}
|
||||
try {
|
||||
while (!complete && failure == null && (todo.isNotEmpty() || flying.isNotEmpty())) {
|
||||
while (mayLaunch()) {
|
||||
val o = todo.removeFirst()
|
||||
flying.add(o)
|
||||
done.submit {
|
||||
try {
|
||||
Outcome(o, sendPiece(o), null)
|
||||
} catch (e: Throwable) {
|
||||
Outcome(o, false, e)
|
||||
}
|
||||
}
|
||||
}
|
||||
val r = done.take().get()
|
||||
flying.remove(r.offset)
|
||||
if (r.error != null) {
|
||||
failure = failure ?: r.error
|
||||
continue
|
||||
}
|
||||
if (r.done) complete = true
|
||||
acked += minOf(chunk, size - r.offset)
|
||||
if (!complete) onProgress?.invoke(acked, size)
|
||||
}
|
||||
while (flying.isNotEmpty()) flying.remove(done.take().get().offset)
|
||||
} finally {
|
||||
pool.shutdownNow()
|
||||
}
|
||||
failure?.let { throw it }
|
||||
if (!complete) {
|
||||
// Every piece is in but no answer said so (they crossed a completion
|
||||
// that failed and was retried): an empty piece at the end finishes it.
|
||||
retrying {
|
||||
val res = send("PUT", owner.headers(OwnerOp.Piece(id, size, 0)) + mapOf(OFFSET_HEADER to size.toString()), ByteArray(0))
|
||||
if (res.status != 201) fail(res, "finish")
|
||||
}
|
||||
}
|
||||
onProgress?.invoke(size, size)
|
||||
}
|
||||
}
|
||||
|
||||
private class Answer(val status: Int, val body: String, private val contentType: String) {
|
||||
/**
|
||||
* What a refusal says, for an error message: the relay's JSON as it is,
|
||||
* but not an HTML error page (a proxy's) poured into a log.
|
||||
*/
|
||||
fun text(): String {
|
||||
if (contentType.contains("text/html") || body.trimStart().startsWith("<")) return ""
|
||||
return if (body.length > 300) "${body.take(300)}…" else body
|
||||
}
|
||||
}
|
||||
|
||||
private fun request(method: String, url: String, headers: Map<String, String>, body: ByteArray?): Answer {
|
||||
val c = java.net.URI(url).toURL().openConnection() as HttpURLConnection
|
||||
try {
|
||||
c.requestMethod = method
|
||||
c.connectTimeout = timeoutMs
|
||||
c.readTimeout = timeoutMs
|
||||
c.useCaches = false
|
||||
for ((k, v) in headers) c.setRequestProperty(k, v)
|
||||
if (body != null) {
|
||||
c.doOutput = true
|
||||
c.setFixedLengthStreamingMode(body.size)
|
||||
c.outputStream.use { it.write(body) }
|
||||
}
|
||||
val status = c.responseCode
|
||||
val stream = if (status >= 400) c.errorStream else c.inputStream
|
||||
val text = stream?.use { String(it.readBytes(), Charsets.UTF_8) } ?: ""
|
||||
return Answer(status, text, c.contentType ?: "")
|
||||
} finally {
|
||||
c.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val rng = SecureRandom()
|
||||
|
||||
fun newReadToken(): ByteArray = ByteArray(32).also { rng.nextBytes(it) }
|
||||
|
||||
private fun hex(b: ByteArray) = b.joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package no.zyon.shade.media
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONException
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* Subtitles — mirror of `@shade/media/src/subtitles.ts`. A film carries the
|
||||
* grants of its sealed subtitle files in its own sealed meta, under
|
||||
* `extra["shade.subtitles"]`: `[{"lang":"no","label":"…","grant":{…}}, …]`.
|
||||
*/
|
||||
|
||||
const val SUBTITLES_KEY = "shade.subtitles"
|
||||
private const val MAX_TRACKS = 64
|
||||
private val LANG_RE = Regex("^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$")
|
||||
|
||||
class SubtitleTrack(val grant: MediaGrant, val lang: String? = null, val label: String? = null)
|
||||
|
||||
object Subtitles {
|
||||
/** The subtitle tracks a film's meta names, strictly; none if it names none. */
|
||||
fun of(meta: MediaMeta?): List<SubtitleTrack> {
|
||||
val raw = meta?.extra?.get(SUBTITLES_KEY) ?: return emptyList()
|
||||
val list = try { JSONArray(raw) } catch (e: JSONException) { throw MediaFormatException("subtitles are not a JSON array") }
|
||||
if (list.length() > MAX_TRACKS) throw MediaFormatException("more than $MAX_TRACKS subtitle tracks")
|
||||
return (0 until list.length()).map { i ->
|
||||
val o = list.opt(i) as? JSONObject ?: throw MediaFormatException("subtitle $i is not an object")
|
||||
val g = Grants.parse((o.opt("grant") as? JSONObject ?: throw MediaFormatException("subtitle $i has no grant")).toString())
|
||||
if (g !is MediaGrant) throw MediaFormatException("subtitle $i is not a sealed file")
|
||||
val lang = if (!o.has("lang")) null else (o.opt("lang") as? String)?.takeIf { LANG_RE.matches(it) }
|
||||
?: throw MediaFormatException("subtitle $i: bad lang")
|
||||
val label = if (!o.has("label")) null else (o.opt("label") as? String)?.takeIf { it.length <= 200 }
|
||||
?: throw MediaFormatException("subtitle $i: bad label")
|
||||
SubtitleTrack(g, lang, label)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package no.zyon.shade.media
|
||||
|
||||
import org.json.JSONException
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.nio.channels.FileChannel
|
||||
import java.nio.channels.FileLock
|
||||
import java.nio.channels.OverlappingFileLockException
|
||||
import java.nio.file.StandardOpenOption
|
||||
import java.security.MessageDigest
|
||||
|
||||
/**
|
||||
* Uploads that outlive the app — mirror of `@shade/media` put-jobs.ts. A
|
||||
* phone kills an app that uploads for long (a film over mobile data); this is
|
||||
* what lets the next start send the same file again, with the same media id,
|
||||
* so the relay already has most of it. Each upload has a directory:
|
||||
*
|
||||
* sealed.smf the sealed copy, kept until the relay has all of it
|
||||
* job.json the seal result (with the file key), the read token, the
|
||||
* meta, and the grant once the relay stored it. Keep the
|
||||
* directory app-private (`filesDir`): it holds keys.
|
||||
* lock held (an OS file lock) by whoever is uploading it
|
||||
*
|
||||
* A job is keyed by what identifies the source (the relay, a content URI,
|
||||
* its size and name, …), so sharing the same video twice is one upload and
|
||||
* gives the same link. Jobs untouched for 30 days are removed.
|
||||
*/
|
||||
class UploadJobs(private val dir: File) {
|
||||
|
||||
class Job(
|
||||
val result: SealResult,
|
||||
/** Null for public ciphertext. */
|
||||
val readToken: ByteArray?,
|
||||
val meta: MediaMeta,
|
||||
/** What the job is of, for listing (a file name, a URI). */
|
||||
val source: String,
|
||||
/** Set once the relay stored the file. */
|
||||
val grant: MediaGrant? = null,
|
||||
/** The relay it goes to, for resuming it after a restart. */
|
||||
val server: String = "",
|
||||
)
|
||||
|
||||
class BusyException(message: String) : Exception(message)
|
||||
|
||||
/** The job for a source identified by `parts` (the relay URL first). */
|
||||
fun key(vararg parts: String): String {
|
||||
val md = MessageDigest.getInstance("SHA-256")
|
||||
for (p in parts) {
|
||||
val b = p.toByteArray(Charsets.UTF_8)
|
||||
md.update(byteArrayOf((b.size ushr 24).toByte(), (b.size ushr 16).toByte(), (b.size ushr 8).toByte(), b.size.toByte()))
|
||||
md.update(b)
|
||||
}
|
||||
return md.digest().copyOf(16).joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
private fun jobDir(key: String): File {
|
||||
require(KEY_RE.matches(key)) { "not a job key: $key" }
|
||||
return File(dir, key)
|
||||
}
|
||||
|
||||
fun sealedFile(key: String): File = File(jobDir(key), "sealed.smf")
|
||||
|
||||
/**
|
||||
* Take the job for this upload; release with `close()`. Throws
|
||||
* [BusyException] while another thread or process has it. A lock left by a
|
||||
* process that died is released by the OS, so it never needs clearing.
|
||||
*/
|
||||
fun claim(key: String): AutoCloseable {
|
||||
val d = jobDir(key).also { it.mkdirs() }
|
||||
val ch = FileChannel.open(File(d, "lock").toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE)
|
||||
val lock: FileLock? = try {
|
||||
ch.tryLock()
|
||||
} catch (e: OverlappingFileLockException) {
|
||||
null
|
||||
}
|
||||
if (lock == null) {
|
||||
ch.close()
|
||||
throw BusyException("this file is already being uploaded")
|
||||
}
|
||||
return AutoCloseable {
|
||||
lock.release()
|
||||
ch.close()
|
||||
}
|
||||
}
|
||||
|
||||
/** The job, if an earlier run got as far as sealing — and its sealed copy is whole, unless it is done. */
|
||||
fun load(key: String): Job? {
|
||||
val o = try {
|
||||
JSONObject(File(jobDir(key), "job.json").readText())
|
||||
} catch (e: java.io.IOException) {
|
||||
return null
|
||||
} catch (e: JSONException) {
|
||||
return null
|
||||
}
|
||||
if (o.optInt("v") != 1) return null
|
||||
val job = try {
|
||||
val r = o.getJSONObject("result")
|
||||
Job(
|
||||
SealResult(
|
||||
fromB64u(r.getString("mediaId"), MEDIA_ID_BYTES),
|
||||
fromB64u(r.getString("mediaKey"), MEDIA_KEY_BYTES),
|
||||
fromB64u(r.getString("rootDigest"), DIGEST_BYTES),
|
||||
r.getLong("plaintextSize"),
|
||||
r.getLong("sealedSize"),
|
||||
r.getInt("segmentSize"),
|
||||
r.getLong("segmentCount"),
|
||||
),
|
||||
if (o.isNull("readToken")) null else fromB64u(o.getString("readToken")),
|
||||
MediaMeta.fromJson(o.getString("meta")),
|
||||
o.optString("source"),
|
||||
if (o.has("grant")) Grants.parse(o.getString("grant")) as? MediaGrant else null,
|
||||
o.optString("server"),
|
||||
)
|
||||
} catch (e: JSONException) {
|
||||
return null
|
||||
} catch (e: MediaFormatException) {
|
||||
return null
|
||||
}
|
||||
if (job.grant != null) return job
|
||||
return if (sealedFile(key).length() == job.result.sealedSize) job else null
|
||||
}
|
||||
|
||||
fun save(key: String, job: Job) {
|
||||
val r = job.result
|
||||
val o = JSONObject()
|
||||
.put("v", 1)
|
||||
.put("source", job.source)
|
||||
.put("server", job.server)
|
||||
.put(
|
||||
"result",
|
||||
JSONObject()
|
||||
.put("mediaId", b64u(r.mediaId))
|
||||
.put("mediaKey", b64u(r.mediaKey))
|
||||
.put("rootDigest", b64u(r.rootDigest))
|
||||
.put("plaintextSize", r.plaintextSize)
|
||||
.put("sealedSize", r.sealedSize)
|
||||
.put("segmentSize", r.segmentSize)
|
||||
.put("segmentCount", r.segmentCount),
|
||||
)
|
||||
.put("readToken", job.readToken?.let { b64u(it) } ?: JSONObject.NULL)
|
||||
.put("meta", job.meta.toJson())
|
||||
job.grant?.let { o.put("grant", it.encode()) }
|
||||
val d = jobDir(key).also { it.mkdirs() }
|
||||
val tmp = File(d, "job.json.tmp")
|
||||
tmp.writeText(o.toString())
|
||||
if (!tmp.renameTo(File(d, "job.json"))) throw java.io.IOException("cannot write the job for $key")
|
||||
}
|
||||
|
||||
/** The relay has it: keep the grant, drop the sealed copy. */
|
||||
fun done(key: String, job: Job, grant: MediaGrant): Job {
|
||||
val finished = Job(job.result, job.readToken, job.meta, job.source, grant, job.server)
|
||||
save(key, finished)
|
||||
sealedFile(key).delete()
|
||||
return finished
|
||||
}
|
||||
|
||||
/** Start the job over (its file was deleted from the relay), keeping the claim. */
|
||||
fun reset(key: String) {
|
||||
File(jobDir(key), "job.json").delete()
|
||||
sealedFile(key).delete()
|
||||
}
|
||||
|
||||
fun forget(key: String) {
|
||||
jobDir(key).deleteRecursively()
|
||||
}
|
||||
|
||||
/** Jobs not yet done whose sealed copy is whole: what to resume after a restart. */
|
||||
fun unfinished(): List<Pair<String, Job>> =
|
||||
(dir.list() ?: emptyArray()).filter { KEY_RE.matches(it) }
|
||||
.mapNotNull { k -> load(k)?.takeIf { it.grant == null }?.let { k to it } }
|
||||
|
||||
/** Remove jobs nobody touched for 30 days, and half-sealed leftovers after an hour. */
|
||||
fun prune(now: Long = System.currentTimeMillis()): Int {
|
||||
var n = 0
|
||||
for (k in dir.list() ?: emptyArray()) {
|
||||
if (!KEY_RE.matches(k)) continue
|
||||
val jobFile = File(jobDir(k), "job.json")
|
||||
val touched = if (jobFile.exists()) jobFile.lastModified() else jobDir(k).lastModified()
|
||||
val stale = now - touched > MAX_AGE_MS || (!jobFile.exists() && now - touched > 3_600_000L)
|
||||
if (!stale) continue
|
||||
val held = try {
|
||||
claim(k)
|
||||
} catch (e: BusyException) {
|
||||
continue
|
||||
}
|
||||
held.close()
|
||||
forget(k)
|
||||
n++
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
private companion object {
|
||||
val KEY_RE = Regex("^[0-9a-f]{32}$")
|
||||
const val MAX_AGE_MS = 30L * 24 * 3600 * 1000
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package no.zyon.shade
|
||||
|
||||
import no.zyon.shade.media.Album
|
||||
import no.zyon.shade.media.Albums
|
||||
import no.zyon.shade.media.FileRangeSource
|
||||
import no.zyon.shade.media.Grants
|
||||
import no.zyon.shade.media.MediaGrant
|
||||
import no.zyon.shade.media.MediaMeta
|
||||
import no.zyon.shade.media.MediaOwner
|
||||
import no.zyon.shade.media.MediaSealer
|
||||
import no.zyon.shade.media.MediaUploader
|
||||
import no.zyon.shade.media.UploadJobs
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
import java.security.SecureRandom
|
||||
|
||||
/**
|
||||
* Live cross-check of [MediaUploader] against the real TS relay — skipped
|
||||
* unless `SHADE_MEDIA_LIVE_SPEC` points at the spec file a TS driver wrote.
|
||||
*
|
||||
* Run it via `bun run scripts/media-live-kotlin.ts`: the driver serves
|
||||
* `createMediaService` with two faults injected on the pieces, uploads a file
|
||||
* with the TS client and writes `{ url, seed, tsLink, tsSha256, scratch,
|
||||
* kotlinOut }`. This test opens the TS file, uploads a film in pieces and a
|
||||
* photo in one PUT, and records the links in `kotlinOut`; the driver then
|
||||
* reads the film back with the TS reader.
|
||||
*/
|
||||
class MediaLiveTest {
|
||||
|
||||
private fun sha256(b: ByteArray) = MessageDigest.getInstance("SHA-256").digest(b).joinToString("") { "%02x".format(it) }
|
||||
|
||||
private fun fromHex(s: String) =
|
||||
ByteArray(s.length / 2) { ((Character.digit(s[it * 2], 16) shl 4) + Character.digit(s[it * 2 + 1], 16)).toByte() }
|
||||
|
||||
@Test
|
||||
fun uploadsInPiecesThroughFaultsForTsToRead() {
|
||||
val specPath = System.getenv("SHADE_MEDIA_LIVE_SPEC")
|
||||
assumeTrue("SHADE_MEDIA_LIVE_SPEC not set — live cross-check skipped", !specPath.isNullOrEmpty())
|
||||
val spec = JSONObject(File(specPath!!).readText())
|
||||
val uploader = MediaUploader(spec.getString("url"), MediaOwner(fromHex(spec.getString("seed"))))
|
||||
|
||||
// Read what TS uploaded, from its link.
|
||||
val tsGrant = Grants.fromCapabilityUrl(spec.getString("tsLink")) as MediaGrant
|
||||
tsGrant.open().use { r -> assertEquals(spec.getString("tsSha256"), sha256(r.read(0, r.size.toInt()))) }
|
||||
|
||||
// A film from the phone: sealed to a file, up in three pieces (16 MiB each),
|
||||
// through a lost answer on the second and a refusal of the third.
|
||||
val plain = ByteArray(40 * 1024 * 1024).also { SecureRandom().nextBytes(it) }
|
||||
val sealedFile = File(spec.getString("scratch"), "film.smf")
|
||||
val meta = MediaMeta(name = "Fra telefonen — «Kveld».mp4", mime = "video/mp4", durationMs = 61_500, width = 1080, height = 1920)
|
||||
val progress = mutableListOf<Long>()
|
||||
val token = MediaUploader.newReadToken()
|
||||
val result = sealedFile.outputStream().buffered().use { MediaSealer.sealStream(plain.inputStream(), it, meta) }
|
||||
val film = FileRangeSource(sealedFile).use { body ->
|
||||
uploader.putSealed(result, body, token, meta) { acked, total ->
|
||||
synchronized(progress) { progress += acked }
|
||||
assertEquals(result.sealedSize, total)
|
||||
}
|
||||
}
|
||||
assertEquals(result.sealedSize, progress.last())
|
||||
assertTrue("progress only grows: $progress", progress.zipWithNext().all { (a, b) -> a <= b })
|
||||
film.open().use { r -> assertEquals(sha256(plain), sha256(r.read(0, r.size.toInt()))) }
|
||||
|
||||
// The same film again (the app was killed after the upload): the relay
|
||||
// already has it, nothing is sent, the link is the same.
|
||||
val again = FileRangeSource(sealedFile).use { uploader.putSealed(result, it, token, meta) }
|
||||
assertEquals(film.capabilityUrl("https://watch.example/"), again.capabilityUrl("https://watch.example/"))
|
||||
|
||||
// A shared video as an upload job: the app is killed after the first
|
||||
// piece; the next start resumes past it, and sharing it a third time
|
||||
// sends nothing and gives the same link.
|
||||
val jobs = UploadJobs(File(spec.getString("scratch"), "jobs"))
|
||||
val video = ByteArray(36 * 1024 * 1024).also { SecureRandom().nextBytes(it) }
|
||||
val key = jobs.key(spec.getString("url"), "content://media/external/video/42", video.size.toString())
|
||||
val videoMeta = MediaMeta(name = "VID_0042.mp4", mime = "video/mp4")
|
||||
var opened = 0
|
||||
val open = { opened++; video.inputStream() }
|
||||
class Killed : RuntimeException()
|
||||
try {
|
||||
uploader.upload(jobs, key, "VID_0042.mp4", videoMeta, open) { acked, _ -> if (acked > 0) throw Killed() }
|
||||
error("the upload should have been cut short")
|
||||
} catch (e: Killed) {
|
||||
// as if the app was killed mid-upload
|
||||
}
|
||||
assertEquals(1, jobs.unfinished().size)
|
||||
var firstSeen = -1L
|
||||
val resumed = uploader.upload(jobs, key, "VID_0042.mp4", videoMeta, open) { acked, _ -> if (firstSeen < 0) firstSeen = acked }
|
||||
assertTrue("resumed from $firstSeen", firstSeen > 0)
|
||||
assertEquals("sealed once", 1, opened)
|
||||
resumed.open().use { r -> assertEquals(sha256(video), sha256(r.read(0, r.size.toInt()))) }
|
||||
val third = uploader.upload(jobs, key, "VID_0042.mp4", videoMeta, open)
|
||||
assertEquals(resumed.encode(), third.encode())
|
||||
assertEquals(1, opened)
|
||||
assertTrue(jobs.unfinished().isEmpty())
|
||||
// Deleted from the relay since: the next share is a new upload with a new link.
|
||||
assertTrue(uploader.delete(resumed.mediaId))
|
||||
val fresh = uploader.upload(jobs, key, "VID_0042.mp4", videoMeta, open)
|
||||
assertNotEquals(resumed.encode(), fresh.encode())
|
||||
assertEquals(2, opened)
|
||||
|
||||
// A photo: one PUT; then deleted.
|
||||
val photo = uploader.uploadBytes(ByteArray(300_000).also { SecureRandom().nextBytes(it) }, MediaMeta(name = "IMG_0001.jpg", mime = "image/jpeg"))
|
||||
photo.open().use { assertEquals("IMG_0001.jpg", it.meta.name) }
|
||||
assertTrue(uploader.delete(photo.mediaId))
|
||||
assertFalse(uploader.delete(photo.mediaId))
|
||||
|
||||
// The photos of a trip, shared at once: one album link for all of them.
|
||||
val album = uploader.uploadAlbum(Album("Tur — «Lofoten»", listOf(film, fresh)))
|
||||
album.open().use { r ->
|
||||
val back = Albums.read(r)
|
||||
assertEquals("Tur — «Lofoten»", back.title)
|
||||
assertEquals(listOf(film.encode(), fresh.encode()), back.items.map { it.encode() })
|
||||
}
|
||||
|
||||
File(spec.getString("kotlinOut")).writeText(
|
||||
JSONObject()
|
||||
.put("film", JSONObject().put("link", film.capabilityUrl("https://watch.example/")).put("sha256", sha256(plain)).put("size", plain.size))
|
||||
.put("again", again.capabilityUrl("https://watch.example/"))
|
||||
.put("photo", JSONObject().put("url", photo.url))
|
||||
.put("album", album.capabilityUrl("https://watch.example/"))
|
||||
.toString(),
|
||||
)
|
||||
sealedFile.delete()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package no.zyon.shade
|
||||
|
||||
import com.sun.net.httpserver.HttpServer
|
||||
import no.zyon.shade.media.ByteArraySource
|
||||
import no.zyon.shade.media.DEFAULT_CHUNK_BYTES
|
||||
import no.zyon.shade.media.MediaOwner
|
||||
import no.zyon.shade.media.MediaSealer
|
||||
import no.zyon.shade.media.MediaUploadException
|
||||
import no.zyon.shade.media.MediaUploader
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.net.InetSocketAddress
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
/** What the uploader does with a relay that answers nonsense; the real conversation is `MediaLiveTest`. */
|
||||
class MediaUploaderTest {
|
||||
|
||||
private fun relay(answer: String, calls: AtomicInteger): HttpServer =
|
||||
HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply {
|
||||
createContext("/") { ex ->
|
||||
calls.incrementAndGet()
|
||||
ex.requestBody.readBytes()
|
||||
val b = answer.toByteArray()
|
||||
ex.responseHeaders.add("content-type", "application/json")
|
||||
ex.sendResponseHeaders(201, b.size.toLong())
|
||||
ex.responseBody.use { it.write(b) }
|
||||
}
|
||||
start()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anUnusableUploadStatusIsRefusedAtOnceNotLoopedOn() {
|
||||
val (sealed, result) = MediaSealer.sealBytes(ByteArray(DEFAULT_CHUNK_BYTES.toInt() + 4096))
|
||||
for (bad in listOf(
|
||||
"""{"chunk":0,"received":0}""",
|
||||
"""{"chunk":${64L * 1024 * 1024 * 4},"received":0}""",
|
||||
"""{"chunk":${DEFAULT_CHUNK_BYTES},"received":-1}""",
|
||||
"""{"chunk":${DEFAULT_CHUNK_BYTES},"received":0,"window":0}""",
|
||||
"""{"chunk":${DEFAULT_CHUNK_BYTES},"received":0,"landed":["x"]}""",
|
||||
)) {
|
||||
val calls = AtomicInteger()
|
||||
val server = relay(bad, calls)
|
||||
try {
|
||||
val up = MediaUploader("http://127.0.0.1:${server.address.port}", MediaOwner.generate())
|
||||
val e = assertThrows(MediaUploadException::class.java) { up.putSealed(result, ByteArraySource(sealed)) }
|
||||
assertTrue(bad, e.message!!.contains("unusable"))
|
||||
assertEquals(bad, 1, calls.get())
|
||||
} finally {
|
||||
server.stop(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
package no.zyon.shade
|
||||
|
||||
import no.zyon.shade.media.ALBUM_MIME
|
||||
import no.zyon.shade.media.Albums
|
||||
import no.zyon.shade.media.ByteArraySource
|
||||
import no.zyon.shade.media.FOOTER_BYTES
|
||||
import no.zyon.shade.media.Grants
|
||||
import no.zyon.shade.media.LIVE_GRANT_KIND
|
||||
import no.zyon.shade.media.LiveContent
|
||||
import no.zyon.shade.media.LiveGrant
|
||||
import no.zyon.shade.media.LiveKeyException
|
||||
import no.zyon.shade.media.LivePublisher
|
||||
import no.zyon.shade.media.LiveSubscriber
|
||||
import no.zyon.shade.media.MEDIA_GRANT_KIND
|
||||
import no.zyon.shade.media.MediaFormatException
|
||||
import no.zyon.shade.media.MediaGrant
|
||||
import no.zyon.shade.media.MediaIntegrityException
|
||||
import no.zyon.shade.media.MediaKeys
|
||||
import no.zyon.shade.media.MediaMeta
|
||||
import no.zyon.shade.media.MediaOwner
|
||||
import no.zyon.shade.media.MediaReader
|
||||
import no.zyon.shade.media.MediaSealer
|
||||
import no.zyon.shade.media.OwnerOp
|
||||
import no.zyon.shade.media.Subtitles
|
||||
import no.zyon.shade.media.chainStep
|
||||
import no.zyon.shade.media.decodeFrame
|
||||
import no.zyon.shade.media.deriveMediaSubkeys
|
||||
import no.zyon.shade.media.epochKeys
|
||||
import no.zyon.shade.media.linkEpochSeed
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* `@shade/media` against `test-vectors/media.json` — SMF1 sealed files and
|
||||
* SLF1 live frames, byte for byte. Generated by
|
||||
* `bun run scripts/generate-vectors.ts media.json`.
|
||||
*/
|
||||
class MediaVectorTest {
|
||||
|
||||
private val vectors: JSONArray = run {
|
||||
val obj = JSONObject(File("../../test-vectors/media.json").readText())
|
||||
assertEquals("media.json schema version", 2, obj.getInt("version"))
|
||||
obj.getJSONArray("vectors")
|
||||
}
|
||||
|
||||
private fun byPrefix(prefix: String): List<JSONObject> =
|
||||
(0 until vectors.length()).map { vectors.getJSONObject(it) }
|
||||
.filter { it.getString("description").startsWith(prefix) }
|
||||
.also { assertTrue("no vectors for '$prefix'", it.isNotEmpty()) }
|
||||
|
||||
private fun hex(s: String): ByteArray =
|
||||
ByteArray(s.length / 2) { ((Character.digit(s[it * 2], 16) shl 4) + Character.digit(s[it * 2 + 1], 16)).toByte() }
|
||||
|
||||
private fun toHex(b: ByteArray) = b.joinToString("") { "%02x".format(it) }
|
||||
|
||||
private val keys = byPrefix("smf1 keys").single()
|
||||
private val mediaId = hex(keys.getString("mediaId"))
|
||||
private val mediaKey = hex(keys.getString("mediaKey"))
|
||||
|
||||
@Test
|
||||
fun subkeys() {
|
||||
val k = deriveMediaSubkeys(mediaKey, mediaId)
|
||||
assertEquals(keys.getString("segmentKey"), toHex(k.segmentKey))
|
||||
assertEquals(keys.getString("metaKey"), toHex(k.metaKey))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sealedFilesReadAndResealByteForByte() {
|
||||
for (v in byPrefix("smf1 file")) {
|
||||
val sealed = hex(v.getString("sealed"))
|
||||
val plain = hex(v.getString("plaintext"))
|
||||
val reader = MediaReader.open(ByteArraySource(sealed), MediaKeys(mediaId, mediaKey, hex(v.getString("rootDigest"))))
|
||||
assertArrayEquals(v.getString("description"), plain, reader.read(0, plain.size))
|
||||
val meta = MediaMeta.fromJson(v.getString("metaJson"))
|
||||
assertEquals(meta, reader.meta)
|
||||
|
||||
// Writer parity: the same key, id and input give the same bytes.
|
||||
val (resealed, result) = MediaSealer.withPinnedKeys(mediaId, mediaKey, meta, v.getInt("segmentSize")).sealAll(plain)
|
||||
assertEquals(v.getString("description"), v.getString("sealed"), toHex(resealed))
|
||||
assertEquals(v.getString("rootDigest"), toHex(result.rootDigest))
|
||||
assertEquals(v.getLong("segmentCount"), result.segmentCount)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun randomAccessAndStreaming() {
|
||||
val v = byPrefix("smf1 file: three segments").single()
|
||||
val plain = hex(v.getString("plaintext"))
|
||||
val reader = MediaReader.open(ByteArraySource(hex(v.getString("sealed"))), MediaKeys(mediaId, mediaKey), cacheSegments = 0)
|
||||
for (off in listOf(0, 1, 4095, 4096, 4097, 8191, 8192, plain.size - 1)) {
|
||||
for (len in listOf(1, 100, 4096, 9000)) {
|
||||
assertArrayEquals("at $off+$len", plain.copyOfRange(off, minOf(plain.size, off + len)), reader.read(off.toLong(), len))
|
||||
}
|
||||
}
|
||||
assertArrayEquals(plain, reader.inputStream().readBytes())
|
||||
assertArrayEquals(plain.copyOfRange(5000, 9000), reader.inputStream(5000, 9000).readBytes())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun tamperedSegmentAndTrailerAreRefused() {
|
||||
val v = byPrefix("smf1 file: three segments").single()
|
||||
val sealed = hex(v.getString("sealed"))
|
||||
val root = hex(v.getString("rootDigest"))
|
||||
val bad = sealed.copyOf().also { it[5000] = (it[5000].toInt() xor 1).toByte() }
|
||||
val r = MediaReader.open(ByteArraySource(bad), MediaKeys(mediaId, mediaKey, root))
|
||||
assertThrows(MediaIntegrityException::class.java) { r.read(4096, 10) }
|
||||
val badTable = sealed.copyOf().also { it[it.size - FOOTER_BYTES - 1] = (it[it.size - FOOTER_BYTES - 1].toInt() xor 1).toByte() }
|
||||
assertThrows(MediaIntegrityException::class.java) { MediaReader.open(ByteArraySource(badTable), MediaKeys(mediaId, mediaKey, root)) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun liveKeySchedule() {
|
||||
val k = byPrefix("live keys").single()
|
||||
val channelId = hex(k.getString("channelId"))
|
||||
val seed = linkEpochSeed(hex(k.getString("channelSecret")), channelId, 0)
|
||||
assertEquals(k.getString("epochSeed"), toHex(seed))
|
||||
assertEquals(k.getString("epochSeed1"), toHex(linkEpochSeed(hex(k.getString("channelSecret")), channelId, 1)))
|
||||
val ek = epochKeys(seed, channelId, 0)
|
||||
assertEquals(k.getString("chainKey0"), toHex(ek.chainKey))
|
||||
assertEquals(k.getString("stickyKey"), toHex(ek.stickyKey))
|
||||
val (mk0, ck1) = chainStep(ek.chainKey)
|
||||
assertEquals(k.getString("messageKey0"), toHex(mk0))
|
||||
assertEquals(k.getString("chainKey1"), toHex(ck1))
|
||||
assertEquals(k.getString("messageKey1"), toHex(chainStep(ck1).first))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun liveFramesOpenFromTheLinkGrantAcrossARotation() {
|
||||
val g = Grants.parse(byPrefix("live grant").single().getString("json")) as LiveGrant
|
||||
assertNotNull(g.channelSecret)
|
||||
assertEquals(byPrefix("live grant").single().getString("json"), g.encode())
|
||||
val sub = LiveSubscriber(g)
|
||||
for (v in byPrefix("live frame")) {
|
||||
val f = sub.open(hex(v.getString("wire")))
|
||||
assertNotNull(v.getString("description"), f)
|
||||
assertEquals(v.getLong("seq"), f!!.seq)
|
||||
assertEquals(v.getString("payload"), toHex(f.content.encode()))
|
||||
// Replays are dropped quietly.
|
||||
assertNull(sub.open(hex(v.getString("wire"))))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun livePublisherReproducesTheWireBytes() {
|
||||
val k = byPrefix("live keys").single()
|
||||
val pub = LivePublisher(hex(k.getString("channelId")), hex(k.getString("signingSecret")), hex(k.getString("channelSecret")))
|
||||
assertEquals(k.getString("signingKey"), toHex(pub.signingKey))
|
||||
val frames = byPrefix("live frame: seq")
|
||||
for ((i, v) in frames.withIndex()) {
|
||||
val content = LiveContent.decode(hex(v.getString("payload")))
|
||||
val sticky = v.getString("description").contains("sticky")
|
||||
val keyframe = decodeFrame(hex(v.getString("wire"))).header.flags and 0x02 != 0
|
||||
val wire = pub.frame(content, keyframe = keyframe, sticky = sticky, timestamp = 1_786_600_000_000L + i * 100)
|
||||
assertEquals(v.getString("description"), v.getString("wire"), toHex(wire))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun forgedFramesAndForeignEpochsAreRefused() {
|
||||
val k = byPrefix("live keys").single()
|
||||
val channelId = hex(k.getString("channelId"))
|
||||
val pub = LivePublisher(channelId, ByteArray(32) { 7 }, null)
|
||||
val sub = LiveSubscriber(pub.grant(from = "now"))
|
||||
val good = pub.frame(LiveContent.Text("hei"))
|
||||
val mallory = LivePublisher(channelId, ByteArray(32) { 9 }, null)
|
||||
assertThrows(MediaIntegrityException::class.java) { sub.open(mallory.frame(LiveContent.Text("falsk"))) }
|
||||
assertEquals(LiveContent.Text("hei"), sub.open(good)!!.content)
|
||||
pub.rotate()
|
||||
assertThrows(LiveKeyException::class.java) { sub.open(pub.frame(LiveContent.Text("etter"))) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mediaGrantParses() {
|
||||
val g = Grants.parse(
|
||||
"""{"kind":"shade.media-grant/v1","mediaId":"${java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(mediaId)}","key":"${java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(mediaKey)}","root":"${"ab".repeat(32)}","url":"https://relay.example/v1/media/x","token":"${"A".repeat(43)}"}""",
|
||||
) as MediaGrant
|
||||
assertArrayEquals(mediaId, g.mediaId)
|
||||
assertThrows(Exception::class.java) { Grants.parse("""{"kind":"shade.media-grant/v1","mediaId":"AA","key":"AA","root":"ab"}""") }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun albumOpensFromTheSealedVector() {
|
||||
val v = byPrefix("album:").single()
|
||||
val reader = MediaReader.open(ByteArraySource(hex(v.getString("sealed"))), MediaKeys(mediaId, mediaKey, hex(v.getString("rootDigest"))))
|
||||
assertEquals(ALBUM_MIME, reader.meta.mime)
|
||||
val album = Albums.read(reader)
|
||||
assertEquals(v.getString("title"), album.title)
|
||||
// And written back: the same plaintext, sealed to the same bytes.
|
||||
val plain = Albums.encode(album)
|
||||
assertEquals(v.getString("plaintext"), String(plain, Charsets.UTF_8))
|
||||
val (resealed, _) = MediaSealer.withPinnedKeys(mediaId, mediaKey, Albums.meta(album.title), 4096).sealAll(plain)
|
||||
assertEquals(v.getString("sealed"), toHex(resealed))
|
||||
val kinds = v.getJSONArray("itemKinds")
|
||||
val names = v.getJSONArray("itemNames")
|
||||
assertEquals(kinds.length(), album.items.size)
|
||||
album.items.forEachIndexed { i, g ->
|
||||
assertEquals(kinds.getString(i), if (g is MediaGrant) MEDIA_GRANT_KIND else LIVE_GRANT_KIND)
|
||||
val meta = when (g) {
|
||||
is MediaGrant -> g.meta
|
||||
is LiveGrant -> g.meta
|
||||
}
|
||||
assertEquals(names.getString(i), meta?.name)
|
||||
}
|
||||
assertTrue(Albums.isAlbum(album.items[1]))
|
||||
assertFalse(Albums.isAlbum(album.items[0]))
|
||||
// Strict: a bad item, the wrong kind, invalid UTF-8.
|
||||
assertThrows(MediaFormatException::class.java) { Albums.parse("""{"kind":"shade.album/v1","title":"","items":[{"kind":"x"}]}""".toByteArray()) }
|
||||
assertThrows(MediaFormatException::class.java) { Albums.parse("""{"kind":"shade.album/v2","title":"","items":[]}""".toByteArray()) }
|
||||
assertThrows(MediaFormatException::class.java) { Albums.parse(byteArrayOf(0xff.toByte(), 0xfe.toByte())) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun subtitlesInAFilmsMetaParse() {
|
||||
val v = byPrefix("subtitles:").single()
|
||||
val tracks = Subtitles.of(MediaMeta.fromJson(v.getString("meta")))
|
||||
val langs = v.getJSONArray("langs")
|
||||
val labels = v.getJSONArray("labels")
|
||||
val ids = v.getJSONArray("mediaIds")
|
||||
assertEquals(langs.length(), tracks.size)
|
||||
tracks.forEachIndexed { i, t ->
|
||||
assertEquals(langs.getString(i), t.lang)
|
||||
assertEquals(if (labels.isNull(i)) null else labels.getString(i), t.label)
|
||||
assertEquals(ids.getString(i), toHex(t.grant.mediaId))
|
||||
}
|
||||
assertEquals(emptyList<Any>(), Subtitles.of(MediaMeta(name = "no subtitles")))
|
||||
assertThrows(MediaFormatException::class.java) {
|
||||
Subtitles.of(MediaMeta(extra = mapOf("shade.subtitles" to """[{"lang":"no; x","grant":{}}]""")))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ownerSignaturesMatchTheRelaysByteForByte() {
|
||||
val v = byPrefix("owner:").single()
|
||||
val owner = MediaOwner(hex(v.getString("seed")))
|
||||
assertEquals(v.getString("owner"), owner.id)
|
||||
val at = v.getLong("at")
|
||||
val requests = v.getJSONArray("requests")
|
||||
for (i in 0 until requests.length()) {
|
||||
val r = requests.getJSONObject(i)
|
||||
val op = when (r.getString("op")) {
|
||||
"put" -> OwnerOp.Put(r.getString("id"), r.getLong("size"), r.getString("readTokenHash"))
|
||||
"upload" -> OwnerOp.Upload(r.getString("id"), r.getLong("size"), r.getString("readTokenHash"))
|
||||
"piece" -> OwnerOp.Piece(r.getString("id"), r.getLong("offset"), r.getLong("length"))
|
||||
"abort" -> OwnerOp.Abort(r.getString("id"))
|
||||
"delete" -> OwnerOp.Delete(r.getString("id"))
|
||||
"list" -> OwnerOp.List
|
||||
else -> error("unknown op ${r.getString("op")}")
|
||||
}
|
||||
assertEquals(r.getString("message"), String(MediaOwner.message(op, at)))
|
||||
val want = r.getJSONObject("headers")
|
||||
val got = owner.headers(op, at)
|
||||
assertEquals(want.keySet(), got.keys)
|
||||
for (k in got.keys) assertEquals("${r.getString("op")} $k", want.getString(k), got[k])
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun grantsEncodeToTheSameJsonAndLinkAsTs() {
|
||||
val v = byPrefix("grant encode:").single()
|
||||
val g = MediaGrant(
|
||||
hex(v.getString("mediaId")),
|
||||
hex(v.getString("mediaKey")),
|
||||
hex(v.getString("rootDigest")),
|
||||
v.getString("url"),
|
||||
hex(v.getString("readToken")),
|
||||
MediaMeta.fromJson(v.getString("meta")),
|
||||
)
|
||||
assertEquals(v.getString("json"), g.encode())
|
||||
assertEquals(v.getString("link"), g.capabilityUrl(v.getString("pageUrl")))
|
||||
// And back.
|
||||
val back = Grants.fromCapabilityUrl(v.getString("link")) as MediaGrant
|
||||
assertEquals(v.getString("json"), back.encode())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package no.zyon.shade
|
||||
|
||||
import no.zyon.shade.media.MediaGrant
|
||||
import no.zyon.shade.media.MediaMeta
|
||||
import no.zyon.shade.media.MediaSealer
|
||||
import no.zyon.shade.media.UploadJobs
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
|
||||
class UploadJobsTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private fun sealed(jobs: UploadJobs, key: String, meta: MediaMeta = MediaMeta(name = "Kveld.mp4")): UploadJobs.Job {
|
||||
val result = jobs.sealedFile(key).also { it.parentFile.mkdirs() }.outputStream().use {
|
||||
MediaSealer.sealStream(ByteArray(200_000) { i -> i.toByte() }.inputStream(), it, meta)
|
||||
}
|
||||
return UploadJobs.Job(result, ByteArray(32) { 9 }, meta, "content://media/1", server = "https://relay")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun keysAreTheSourceAndTheRelay() {
|
||||
val jobs = UploadJobs(tmp.root)
|
||||
val k = jobs.key("https://relay", "content://media/1", "1234", "Kveld.mp4")
|
||||
assertEquals(k, jobs.key("https://relay", "content://media/1", "1234", "Kveld.mp4"))
|
||||
assertNotEquals(k, jobs.key("https://other", "content://media/1", "1234", "Kveld.mp4"))
|
||||
// Parts are length-prefixed: moving a separator is another job.
|
||||
assertNotEquals(jobs.key("ab", "c"), jobs.key("a", "bc"))
|
||||
assertTrue(Regex("^[0-9a-f]{32}$").matches(k))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resumableOnlyWithAWholeSealedCopyAndDoneKeepsTheGrant() {
|
||||
val jobs = UploadJobs(tmp.root)
|
||||
val key = jobs.key("r", "s")
|
||||
jobs.claim(key).use {
|
||||
val job = sealed(jobs, key)
|
||||
jobs.save(key, job)
|
||||
val back = jobs.load(key)!!
|
||||
assertArrayEquals(job.result.mediaKey, back.result.mediaKey)
|
||||
assertArrayEquals(job.readToken, back.readToken)
|
||||
assertEquals("Kveld.mp4", back.meta.name)
|
||||
assertEquals("https://relay", back.server)
|
||||
assertEquals(listOf(key), jobs.unfinished().map { it.first })
|
||||
|
||||
// Cut short: not resumable.
|
||||
val f = jobs.sealedFile(key)
|
||||
val whole = f.readBytes()
|
||||
f.writeBytes(whole.copyOf(whole.size - 1))
|
||||
assertNull(jobs.load(key))
|
||||
f.writeBytes(whole)
|
||||
|
||||
val grant = MediaGrant.of(job.result, "http://relay/v1/media/x", job.readToken, job.meta)
|
||||
jobs.done(key, job, grant)
|
||||
assertFalse(f.exists())
|
||||
assertEquals(grant.encode(), jobs.load(key)!!.grant!!.encode())
|
||||
assertTrue(jobs.unfinished().isEmpty())
|
||||
|
||||
jobs.reset(key)
|
||||
assertNull(jobs.load(key))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun oneUploadPerJobAndTheLockGoesWithItsHolder() {
|
||||
val jobs = UploadJobs(tmp.root)
|
||||
val key = jobs.key("r", "busy")
|
||||
val held = jobs.claim(key)
|
||||
assertThrows(UploadJobs.BusyException::class.java) { jobs.claim(key) }
|
||||
held.close()
|
||||
jobs.claim(key).close()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun pruneOldJobsAndHalfSealedLeftoversButNotOnesInUse() {
|
||||
val jobs = UploadJobs(tmp.root)
|
||||
val now = System.currentTimeMillis()
|
||||
val old = jobs.key("old")
|
||||
val fresh = jobs.key("fresh")
|
||||
val half = jobs.key("half")
|
||||
val busy = jobs.key("busy")
|
||||
for (k in listOf(old, fresh, busy)) jobs.claim(k).use { jobs.save(k, sealed(jobs, k)) }
|
||||
jobs.claim(half).close()
|
||||
java.io.File(tmp.root, "$old/job.json").setLastModified(now - 31L * 86_400_000)
|
||||
java.io.File(tmp.root, "$busy/job.json").setLastModified(now - 31L * 86_400_000)
|
||||
java.io.File(tmp.root, half).setLastModified(now - 7_200_000)
|
||||
jobs.claim(busy).use { assertEquals(2, jobs.prune(now)) }
|
||||
assertNotNull(jobs.load(fresh))
|
||||
assertNotNull(jobs.load(busy))
|
||||
assertFalse(java.io.File(tmp.root, old).exists())
|
||||
assertFalse(java.io.File(tmp.root, half).exists())
|
||||
}
|
||||
}
|
||||
46
android/shade-media-demo/build.gradle.kts
Normal file
@@ -0,0 +1,46 @@
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
kotlin("android")
|
||||
}
|
||||
|
||||
// Demo player for sealed Shade media: open a `…/watch/#shade=…` link and
|
||||
// play it with ExoPlayer through `ShadeMediaDataSource`. Debug-signed, for
|
||||
// the dev phone; not a product.
|
||||
|
||||
android {
|
||||
namespace = "no.zyon.shade.mediademo"
|
||||
compileSdk = 35
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "no.zyon.shade.mediademo"
|
||||
minSdk = 28 // the owner key lives in the Keystore (:shade-android-keystore)
|
||||
targetSdk = 35
|
||||
versionCode = 1
|
||||
versionName = "4.15.0"
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
kotlinOptions {
|
||||
jvmTarget = "17"
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
isMinifyEnabled = false
|
||||
}
|
||||
}
|
||||
|
||||
packaging {
|
||||
resources.excludes += setOf("META-INF/versions/9/OSGI-INF/MANIFEST.MF")
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(project(":shade-android-media"))
|
||||
implementation(project(":shade-android-keystore"))
|
||||
implementation("androidx.media3:media3-ui:1.5.1")
|
||||
}
|
||||
54
android/shade-media-demo/src/main/AndroidManifest.xml
Normal file
@@ -0,0 +1,54 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<!-- Uploading a film runs in the foreground, with its progress shown. -->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
|
||||
<!-- Cleartext is allowed so the demo can reach a relay on the LAN
|
||||
(`shade media serve` speaks plain HTTP). The media is sealed end to
|
||||
end either way; TLS would hide only which file is fetched. -->
|
||||
<application
|
||||
android:label="Shade Media"
|
||||
android:usesCleartextTraffic="true"
|
||||
android:theme="@android:style/Theme.Material.NoActionBar">
|
||||
<activity
|
||||
android:name=".PlayerActivity"
|
||||
android:exported="true"
|
||||
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
<!-- Share a watch link to the app from any browser or chat. -->
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.SEND" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<data android:mimeType="text/plain" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<!-- Share a video, photo, song or document: sealed here, uploaded to your relay. -->
|
||||
<activity
|
||||
android:name=".ShareActivity"
|
||||
android:exported="true"
|
||||
android:label="Share to Shade"
|
||||
android:excludeFromRecents="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.SEND" />
|
||||
<action android:name="android.intent.action.SEND_MULTIPLE" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<data android:mimeType="video/*" />
|
||||
<data android:mimeType="image/*" />
|
||||
<data android:mimeType="audio/*" />
|
||||
<data android:mimeType="application/*" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<service
|
||||
android:name=".UploadService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="dataSync" />
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,363 @@
|
||||
package no.zyon.shade.mediademo
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.Color
|
||||
import android.os.Bundle
|
||||
import android.view.Gravity
|
||||
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
|
||||
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
|
||||
import android.widget.Button
|
||||
import android.widget.EditText
|
||||
import android.widget.ImageView
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.ScrollView
|
||||
import android.widget.TextView
|
||||
import androidx.annotation.OptIn
|
||||
import androidx.media3.common.PlaybackException
|
||||
import androidx.media3.common.Player
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.exoplayer.ExoPlayer
|
||||
import androidx.media3.ui.PlayerView
|
||||
import no.zyon.shade.media.ALBUM_MIME
|
||||
import no.zyon.shade.media.Album
|
||||
import no.zyon.shade.media.Albums
|
||||
import no.zyon.shade.media.LiveContent
|
||||
import no.zyon.shade.media.LiveGrant
|
||||
import no.zyon.shade.media.MediaGrant
|
||||
import no.zyon.shade.media.ReceivedFrame
|
||||
import no.zyon.shade.media.android.LiveWatcher
|
||||
import no.zyon.shade.media.android.ShadeFilm
|
||||
import no.zyon.shade.media.android.ShadeMedia
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
/**
|
||||
* Plays a sealed Shade film, video, song or picture, or watches a live
|
||||
* channel: live video/audio through ExoPlayer, a live log as scrolling text,
|
||||
* live pictures (a webcam, a watched folder) one after another.
|
||||
*
|
||||
* The link comes from a share (`ACTION_SEND` text), from an upload's
|
||||
* notification (see [ShareActivity]), from
|
||||
* `adb shell am start -n no.zyon.shade.mediademo/.PlayerActivity --es link '<link>'`,
|
||||
* or is pasted into the field. Opening the reader fetches the footer and
|
||||
* trailer over the network, so it runs off the main thread.
|
||||
*/
|
||||
@OptIn(UnstableApi::class)
|
||||
class PlayerActivity : Activity() {
|
||||
private val io = Executors.newSingleThreadExecutor()
|
||||
private var player: ExoPlayer? = null
|
||||
private var film: ShadeFilm? = null
|
||||
private var watcher: LiveWatcher? = null
|
||||
private lateinit var status: TextView
|
||||
private lateinit var view: PlayerView
|
||||
private lateinit var log: TextView
|
||||
private lateinit var logScroll: ScrollView
|
||||
private lateinit var picture: ImageView
|
||||
private lateinit var share: Button
|
||||
private lateinit var albumList: LinearLayout
|
||||
private lateinit var albumScroll: ScrollView
|
||||
/** The album the item on screen came from, to go back to. */
|
||||
private var album: Album? = null
|
||||
/** The link playing now, to hand on. */
|
||||
private var current: String? = null
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
val field = EditText(this).apply {
|
||||
hint = "https://…/watch/#shade=…"
|
||||
setSingleLine()
|
||||
}
|
||||
val open = Button(this).apply {
|
||||
text = "Open"
|
||||
setOnClickListener { play(field.text.toString().trim()) }
|
||||
}
|
||||
status = TextView(this).apply {
|
||||
setTextColor(Color.LTGRAY)
|
||||
setPadding(24, 12, 24, 12)
|
||||
}
|
||||
view = PlayerView(this).apply { setBackgroundColor(Color.BLACK) }
|
||||
log = TextView(this).apply {
|
||||
setTextColor(Color.rgb(214, 219, 225))
|
||||
typeface = android.graphics.Typeface.MONOSPACE
|
||||
textSize = 11f
|
||||
setPadding(24, 12, 24, 12)
|
||||
}
|
||||
logScroll = ScrollView(this).apply {
|
||||
addView(log)
|
||||
visibility = android.view.View.GONE
|
||||
}
|
||||
picture = ImageView(this).apply {
|
||||
scaleType = ImageView.ScaleType.FIT_CENTER
|
||||
setBackgroundColor(Color.BLACK)
|
||||
visibility = android.view.View.GONE
|
||||
}
|
||||
share = Button(this).apply {
|
||||
text = "Share"
|
||||
visibility = android.view.View.GONE
|
||||
setOnClickListener {
|
||||
current?.let { link ->
|
||||
startActivity(Intent.createChooser(Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_TEXT, link), "Share link"))
|
||||
}
|
||||
}
|
||||
}
|
||||
albumList = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
|
||||
albumScroll = ScrollView(this).apply {
|
||||
addView(albumList)
|
||||
visibility = android.view.View.GONE
|
||||
}
|
||||
val bar = LinearLayout(this).apply {
|
||||
orientation = LinearLayout.HORIZONTAL
|
||||
gravity = Gravity.CENTER_VERTICAL
|
||||
addView(field, LinearLayout.LayoutParams(0, WRAP_CONTENT, 1f))
|
||||
addView(open)
|
||||
addView(share)
|
||||
}
|
||||
setContentView(
|
||||
LinearLayout(this).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
setBackgroundColor(Color.rgb(15, 17, 21))
|
||||
addView(bar, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT))
|
||||
addView(status, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT))
|
||||
addView(view, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f))
|
||||
addView(logScroll, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f))
|
||||
addView(picture, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f))
|
||||
addView(albumScroll, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f))
|
||||
},
|
||||
)
|
||||
linkFrom(intent)?.let {
|
||||
field.setText(it)
|
||||
play(it)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
linkFrom(intent)?.let { play(it) }
|
||||
}
|
||||
|
||||
private fun linkFrom(intent: Intent?): String? = when (intent?.action) {
|
||||
Intent.ACTION_SEND -> intent.getStringExtra(Intent.EXTRA_TEXT)
|
||||
else -> intent?.getStringExtra("link")
|
||||
}?.let { text -> Regex("\\S*#\\S*shade=[A-Za-z0-9_-]+").find(text)?.value }
|
||||
|
||||
private fun play(link: String) {
|
||||
if (link.isEmpty()) return
|
||||
stop()
|
||||
val grant = runCatching { ShadeMedia.grant(link) }.getOrElse {
|
||||
status.text = "Not a Shade link: ${it.message}"
|
||||
return
|
||||
}
|
||||
current = link
|
||||
share.visibility = android.view.View.VISIBLE
|
||||
album = null
|
||||
open(grant)
|
||||
}
|
||||
|
||||
/** Open a grant: from a link, or an item of the album on screen. */
|
||||
private fun open(grant: no.zyon.shade.media.Grant) {
|
||||
stop()
|
||||
when (grant) {
|
||||
is LiveGrant -> watch(grant)
|
||||
is MediaGrant -> {
|
||||
status.text = "Opening…"
|
||||
io.execute {
|
||||
val opened = runCatching { ShadeMedia.openFilm(grant) }
|
||||
runOnUiThread {
|
||||
opened.fold(
|
||||
onSuccess = { start(it) },
|
||||
onFailure = { status.text = "Cannot open: ${it.message}" },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun watch(g: LiveGrant) {
|
||||
val name = g.meta?.name ?: "live channel"
|
||||
val mime = g.meta?.mime ?: ""
|
||||
if (mime.startsWith("video/") || mime.startsWith("audio/")) {
|
||||
show(View.PLAYER)
|
||||
val p = newPlayer()
|
||||
status.text = "$name · live · end-to-end encrypted"
|
||||
p.setMediaSource(ShadeMedia.liveMediaSource(g))
|
||||
p.prepare()
|
||||
p.play()
|
||||
return
|
||||
}
|
||||
// Text and images: follow the channel directly.
|
||||
show(if (mime.startsWith("image/")) View.PICTURE else View.LOG)
|
||||
log.text = ""
|
||||
status.text = "$name · connecting…"
|
||||
watcher = LiveWatcher(g, object : LiveWatcher.Listener {
|
||||
override fun onFrame(frame: ReceivedFrame) {
|
||||
val c = frame.content
|
||||
runOnUiThread {
|
||||
when (c) {
|
||||
is LiveContent.Text -> {
|
||||
show(View.LOG)
|
||||
appendLog(c.text)
|
||||
}
|
||||
is LiveContent.Image -> showPicture(c.bytes)
|
||||
is LiveContent.End -> status.text = "$name · the broadcast has ended"
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onState(state: LiveWatcher.State) {
|
||||
runOnUiThread { status.text = "$name · ${state.name.lowercase()} · end-to-end encrypted" }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private fun appendLog(text: String) {
|
||||
val atBottom = !logScroll.canScrollVertically(1)
|
||||
log.append(text)
|
||||
// Bound the view: a log channel runs for days.
|
||||
if (log.length() > MAX_LOG_CHARS) log.text = log.text.subSequence(log.length() - MAX_LOG_CHARS / 2, log.length())
|
||||
if (atBottom) logScroll.post { logScroll.fullScroll(android.view.View.FOCUS_DOWN) }
|
||||
}
|
||||
|
||||
/**
|
||||
* An album: its items as a list, each opening in place. Back returns to
|
||||
* the list. Read already (it is small), so this needs no network.
|
||||
*/
|
||||
private fun showAlbum(a: Album) {
|
||||
album = a
|
||||
show(View.ALBUM)
|
||||
status.text = "${a.title} · ${a.items.size} item(s) · end-to-end encrypted"
|
||||
albumList.removeAllViews()
|
||||
a.items.forEachIndexed { i, g ->
|
||||
val meta = when (g) {
|
||||
is MediaGrant -> g.meta
|
||||
is LiveGrant -> g.meta
|
||||
}
|
||||
val kind = when {
|
||||
g is LiveGrant -> "live"
|
||||
Albums.isAlbum(g) -> "album"
|
||||
else -> meta?.mime?.substringBefore('/') ?: "file"
|
||||
}
|
||||
albumList.addView(Button(this).apply {
|
||||
text = "${meta?.name ?: "item ${i + 1}"} · $kind"
|
||||
isAllCaps = false
|
||||
gravity = Gravity.START or Gravity.CENTER_VERTICAL
|
||||
setOnClickListener { open(g) }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@Deprecated("Activity.onBackPressed")
|
||||
override fun onBackPressed() {
|
||||
val a = album
|
||||
if (a != null && albumScroll.visibility != android.view.View.VISIBLE) {
|
||||
stop()
|
||||
showAlbum(a)
|
||||
return
|
||||
}
|
||||
@Suppress("DEPRECATION")
|
||||
super.onBackPressed()
|
||||
}
|
||||
|
||||
private enum class View { PLAYER, LOG, PICTURE, ALBUM }
|
||||
|
||||
private fun show(which: View) {
|
||||
fun vis(on: Boolean) = if (on) android.view.View.VISIBLE else android.view.View.GONE
|
||||
view.visibility = vis(which == View.PLAYER)
|
||||
logScroll.visibility = vis(which == View.LOG)
|
||||
picture.visibility = vis(which == View.PICTURE)
|
||||
albumScroll.visibility = vis(which == View.ALBUM)
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode off the UI thread, scaled to the screen: a 40-megapixel photo
|
||||
* decoded whole is 160 MB of bitmap. A picture that will not decode is
|
||||
* reported and skipped — the next one may.
|
||||
*/
|
||||
private fun showPicture(bytes: ByteArray) {
|
||||
show(View.PICTURE)
|
||||
val target = maxOf(resources.displayMetrics.widthPixels, resources.displayMetrics.heightPixels)
|
||||
io.execute {
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
|
||||
var sample = 1
|
||||
while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= target) sample *= 2
|
||||
val bmp: Bitmap? = BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample })
|
||||
runOnUiThread {
|
||||
if (bmp == null) status.text = "${status.text} · a picture could not be decoded" else picture.setImageBitmap(bmp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun newPlayer(): ExoPlayer {
|
||||
val p = ExoPlayer.Builder(this).build()
|
||||
player = p
|
||||
view.player = p
|
||||
p.addListener(object : Player.Listener {
|
||||
override fun onPlayerError(error: PlaybackException) {
|
||||
status.text = "Playback failed: ${error.cause?.message ?: error.message}"
|
||||
}
|
||||
})
|
||||
return p
|
||||
}
|
||||
|
||||
private fun start(f: ShadeFilm) {
|
||||
film = f
|
||||
val meta0 = f.reader.meta
|
||||
if (meta0.mime == ALBUM_MIME) {
|
||||
val read = runCatching { Albums.read(f.reader) }
|
||||
read.fold(onSuccess = { showAlbum(it) }, onFailure = { status.text = "Cannot read the album: ${it.message}" })
|
||||
return
|
||||
}
|
||||
if (meta0.mime?.startsWith("image/") == true) {
|
||||
status.text = "${meta0.name ?: "picture"} · ${meta0.mime} · ${f.reader.size / 1024} KiB · end-to-end encrypted"
|
||||
if (f.reader.size > MAX_PICTURE_BYTES) {
|
||||
status.text = "${status.text} · too large to show here"
|
||||
return
|
||||
}
|
||||
show(View.PICTURE)
|
||||
io.execute {
|
||||
val bytes = runCatching { f.reader.read(0, f.reader.size.toInt()) }
|
||||
runOnUiThread { bytes.fold(onSuccess = { showPicture(it) }, onFailure = { status.text = "Cannot read: ${it.message}" }) }
|
||||
}
|
||||
return
|
||||
}
|
||||
show(View.PLAYER)
|
||||
val p = newPlayer()
|
||||
val meta = f.reader.meta
|
||||
val subs = if (f.subtitles.isEmpty()) "" else " · ${f.subtitles.size} subtitle track(s)"
|
||||
status.text = "${meta.name ?: "sealed file"} · ${meta.mime ?: "?"} · ${f.reader.size / 1024} KiB$subs · end-to-end encrypted"
|
||||
p.setMediaSource(ShadeMedia.mediaSource(f))
|
||||
p.prepare()
|
||||
p.play()
|
||||
}
|
||||
|
||||
private fun stop() {
|
||||
picture.setImageDrawable(null)
|
||||
watcher?.close()
|
||||
watcher = null
|
||||
view.player = null
|
||||
player?.release()
|
||||
player = null
|
||||
film?.close()
|
||||
film = null
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
super.onStop()
|
||||
player?.pause()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
stop()
|
||||
io.shutdown()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val MAX_LOG_CHARS = 200_000
|
||||
const val MAX_PICTURE_BYTES = 64L * 1024 * 1024
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package no.zyon.shade.mediademo
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Intent
|
||||
import android.graphics.Color
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.provider.OpenableColumns
|
||||
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
|
||||
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
|
||||
import android.widget.Button
|
||||
import android.widget.EditText
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
/**
|
||||
* «Share to Shade»: a video, photo, song or document shared from the gallery
|
||||
* or a file manager is sealed on the phone and uploaded to your relay; the
|
||||
* link to it comes back as a notification. The first time, enter the relay
|
||||
* and add the owner id shown here to its owners
|
||||
* (`shade media serve --owners <id>`).
|
||||
*/
|
||||
class ShareActivity : Activity() {
|
||||
private val io = Executors.newSingleThreadExecutor()
|
||||
private var album = "Shared"
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
val uris = UploadService.urisOf(intent)
|
||||
val pad = (16 * resources.displayMetrics.density).toInt()
|
||||
fun label(t: String, size: Float = 14f, color: Int = Color.LTGRAY) = TextView(this).apply {
|
||||
text = t
|
||||
textSize = size
|
||||
setTextColor(color)
|
||||
setPadding(0, pad / 2, 0, pad / 2)
|
||||
}
|
||||
val files = label(if (uris.isEmpty()) "Nothing to upload" else "${uris.size} file(s)", 16f, Color.WHITE)
|
||||
val relay = EditText(this).apply {
|
||||
hint = "http://192.168.1.10:3900"
|
||||
setSingleLine()
|
||||
setText(Uploads.relay(this@ShareActivity) ?: "")
|
||||
setTextColor(Color.WHITE)
|
||||
}
|
||||
val albumTitle = EditText(this).apply {
|
||||
hint = "Album title"
|
||||
setSingleLine()
|
||||
setText("Shared ${java.text.DateFormat.getDateInstance().format(java.util.Date())}")
|
||||
setTextColor(Color.WHITE)
|
||||
}
|
||||
val ownerId = label("Owner key: …", 12f)
|
||||
val copy = Button(this).apply { text = "Copy owner id"; isEnabled = false }
|
||||
val upload = Button(this).apply { text = "Seal and upload"; isEnabled = uris.isNotEmpty() }
|
||||
val note = label("Sealed on this phone: the relay stores only ciphertext, and the key travels in the link.", 12f)
|
||||
setContentView(
|
||||
LinearLayout(this).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
setBackgroundColor(Color.rgb(15, 17, 21))
|
||||
setPadding(pad, pad, pad, pad)
|
||||
addView(label("Share to Shade", 22f, Color.WHITE))
|
||||
addView(files)
|
||||
addView(label("Relay"))
|
||||
addView(relay, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT))
|
||||
if (uris.size > 1) {
|
||||
addView(label("One link for all of them: an album"))
|
||||
addView(albumTitle, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT))
|
||||
}
|
||||
addView(ownerId)
|
||||
addView(copy)
|
||||
addView(upload)
|
||||
addView(note)
|
||||
},
|
||||
)
|
||||
|
||||
// Off the main thread: the Keystore may be a StrongBox chip, and names come from a provider.
|
||||
io.execute {
|
||||
val owner = runCatching { Uploads.owner(this) }
|
||||
val names = uris.map { uri ->
|
||||
runCatching {
|
||||
contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null)?.use { c ->
|
||||
if (!c.moveToFirst()) null else "${c.getString(0)} · ${"%.1f".format(c.getLong(1) / 1048576.0)} MiB"
|
||||
}
|
||||
}.getOrNull() ?: uri.lastPathSegment ?: "file"
|
||||
}
|
||||
runOnUiThread {
|
||||
if (names.isNotEmpty()) files.text = names.joinToString("\n")
|
||||
owner.fold(
|
||||
onSuccess = { o ->
|
||||
ownerId.text = "Owner key (add to the relay's owners):\n${o.id}"
|
||||
copy.isEnabled = true
|
||||
copy.setOnClickListener {
|
||||
getSystemService(ClipboardManager::class.java).setPrimaryClip(ClipData.newPlainText("Shade owner id", o.id))
|
||||
}
|
||||
},
|
||||
onFailure = { ownerId.text = "No owner key: ${it.message}"; upload.isEnabled = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
upload.setOnClickListener {
|
||||
val url = relay.text.toString().trim()
|
||||
if (!Regex("^https?://[^\\s/]+.*$").matches(url)) {
|
||||
relay.error = "http(s)://host:port"
|
||||
return@setOnClickListener
|
||||
}
|
||||
Uploads.setRelay(this, url)
|
||||
album = albumTitle.text.toString().trim().ifEmpty { "Shared" }.take(512)
|
||||
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
|
||||
requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 1)
|
||||
} else {
|
||||
send(uris)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
|
||||
// Without notifications the upload still runs; only its progress and link are not shown.
|
||||
send(UploadService.urisOf(intent))
|
||||
}
|
||||
|
||||
private fun send(uris: List<android.net.Uri>) {
|
||||
val clip = ClipData.newRawUri("shared", uris.first()).apply { uris.drop(1).forEach { addItem(ClipData.Item(it)) } }
|
||||
val svc = Intent(this, UploadService::class.java).apply {
|
||||
clipData = clip
|
||||
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
if (uris.size > 1) putExtra(UploadService.EXTRA_ALBUM, album)
|
||||
}
|
||||
startForegroundService(svc)
|
||||
finish()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
io.shutdown()
|
||||
super.onDestroy()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package no.zyon.shade.mediademo
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.app.Service
|
||||
import android.content.Intent
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.IBinder
|
||||
import android.os.Looper
|
||||
import android.os.PowerManager
|
||||
import no.zyon.shade.media.Album
|
||||
import no.zyon.shade.media.MediaGrant
|
||||
import no.zyon.shade.media.UploadJobs
|
||||
import no.zyon.shade.media.android.ShadeUpload
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
/**
|
||||
* Seals and uploads shared files one after another, in the foreground (with
|
||||
* a progress notification) so Android lets a film finish. A file that was
|
||||
* sealed before the app was killed is resumed when the service starts again;
|
||||
* one that was still being sealed is started over the next time it is shared.
|
||||
* Several files shared at once become one album (one link for the photos of
|
||||
* a trip). When a file is up, a notification opens it, or shares its link.
|
||||
*/
|
||||
class UploadService : Service() {
|
||||
private val worker = Executors.newSingleThreadExecutor()
|
||||
private val pending = AtomicInteger(0)
|
||||
private val ids = AtomicInteger(100)
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
/** Jobs queued or running in this run, so a redelivered share is not done twice. Main thread only. */
|
||||
private val queued = HashSet<String>()
|
||||
private var lastStart = 0
|
||||
private lateinit var nm: NotificationManager
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
nm = getSystemService(NotificationManager::class.java)
|
||||
nm.createNotificationChannel(NotificationChannel(PROGRESS, "Uploads", NotificationManager.IMPORTANCE_LOW))
|
||||
nm.createNotificationChannel(NotificationChannel(DONE, "Uploaded", NotificationManager.IMPORTANCE_DEFAULT))
|
||||
goForeground(progress("Shade", "Preparing…", 0, 0))
|
||||
// What an earlier run sealed but did not get up.
|
||||
val jobs = Uploads.jobs(this)
|
||||
jobs.prune()
|
||||
for ((key, job) in jobs.unfinished()) {
|
||||
if (job.server.isEmpty()) continue
|
||||
val name = job.meta.name ?: "file"
|
||||
enqueue(key, name) { progress ->
|
||||
Uploads.uploader(this, job.server).upload(jobs, key, job.source, job.meta, {
|
||||
throw IllegalStateException("sealed copy missing")
|
||||
}) { acked, total -> progress(name, acked, total) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
lastStart = startId
|
||||
val relay = Uploads.relay(this)
|
||||
val uris = intent?.let(::urisOf).orEmpty()
|
||||
if (relay != null && uris.isNotEmpty()) {
|
||||
val uploader = Uploads.uploader(this, relay)
|
||||
val jobs = Uploads.jobs(this)
|
||||
// Described now, while the share's read permission still holds.
|
||||
val items = uris.mapNotNull { uri ->
|
||||
try {
|
||||
ShadeUpload.describe(this, uri)
|
||||
} catch (e: Exception) {
|
||||
failed(uri.lastPathSegment ?: "file", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
val album = intent?.getStringExtra(EXTRA_ALBUM)
|
||||
if (album != null && items.size > 1) {
|
||||
// One link for all of them: each file is its own job, then the album of their grants.
|
||||
val keys = items.map { ShadeUpload.jobKey(jobs, uploader, it) }
|
||||
enqueue(keys.joinToString(","), album) { progress ->
|
||||
val grants = items.mapIndexed { i, item ->
|
||||
val label = "${i + 1}/${items.size} · ${item.meta.name ?: "file"}"
|
||||
ShadeUpload.upload(this, uploader, jobs, item) { acked, total -> progress(label, acked, total) }
|
||||
}
|
||||
uploader.uploadAlbum(Album(album, grants))
|
||||
}
|
||||
} else {
|
||||
for (item in items) {
|
||||
val name = item.meta.name ?: "file"
|
||||
enqueue(ShadeUpload.jobKey(jobs, uploader, item), name) { progress ->
|
||||
ShadeUpload.upload(this, uploader, jobs, item) { acked, total -> progress(name, acked, total) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pending.get() == 0) stopSelf(startId)
|
||||
return START_REDELIVER_INTENT
|
||||
}
|
||||
|
||||
/** `run` reports progress as (what, acked, total). */
|
||||
private fun enqueue(key: String, name: String, run: ((String, Long, Long) -> Unit) -> MediaGrant) {
|
||||
if (!queued.add(key)) return
|
||||
pending.incrementAndGet()
|
||||
worker.execute {
|
||||
val wake = getSystemService(PowerManager::class.java).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "shade:upload")
|
||||
wake.acquire(6 * 3600_000L)
|
||||
var shown = ""
|
||||
try {
|
||||
val grant = run { what, acked, total ->
|
||||
val pct = if (total > 0) (acked * 100 / total).toInt() else 0
|
||||
if ("$what $pct" != shown) {
|
||||
shown = "$what $pct"
|
||||
nm.notify(FOREGROUND_ID, progress(what, "${mib(acked)} of ${mib(total)} MiB", pct, 100))
|
||||
}
|
||||
}
|
||||
uploaded(name, grant)
|
||||
} catch (e: UploadJobs.BusyException) {
|
||||
// Already on its way in this run.
|
||||
} catch (e: Exception) {
|
||||
failed(name, e)
|
||||
} finally {
|
||||
wake.release()
|
||||
pending.decrementAndGet()
|
||||
// On the main thread, after any share that came in meanwhile has queued its files.
|
||||
main.post {
|
||||
queued.remove(key)
|
||||
if (pending.get() == 0) stopSelf(lastStart)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun uploaded(name: String, grant: MediaGrant) {
|
||||
val link = grant.capabilityUrl(watchPage(grant))
|
||||
val open = PendingIntent.getActivity(
|
||||
this, ids.get(),
|
||||
Intent(this, PlayerActivity::class.java).putExtra("link", link).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
val share = PendingIntent.getActivity(
|
||||
this, ids.get() + 1,
|
||||
Intent.createChooser(Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_TEXT, link), "Share $name"),
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
val n = builder(DONE)
|
||||
.setSmallIcon(android.R.drawable.stat_sys_upload_done)
|
||||
.setContentTitle(name)
|
||||
.setContentText("Uploaded, end-to-end encrypted — tap to play")
|
||||
.setContentIntent(open)
|
||||
.setAutoCancel(true)
|
||||
.addAction(Notification.Action.Builder(null, "Share link", share).build())
|
||||
.build()
|
||||
nm.notify(ids.getAndAdd(2), n)
|
||||
}
|
||||
|
||||
private fun failed(name: String, e: Throwable) {
|
||||
val n = builder(DONE)
|
||||
.setSmallIcon(android.R.drawable.stat_notify_error)
|
||||
.setContentTitle("$name was not uploaded")
|
||||
.setContentText(e.message ?: e.javaClass.simpleName)
|
||||
.setStyle(Notification.BigTextStyle().bigText(e.message ?: e.javaClass.simpleName))
|
||||
.build()
|
||||
nm.notify(ids.getAndAdd(2), n)
|
||||
}
|
||||
|
||||
private fun progress(title: String, text: String, value: Int, max: Int): Notification =
|
||||
builder(PROGRESS)
|
||||
.setSmallIcon(android.R.drawable.stat_sys_upload)
|
||||
.setContentTitle(title)
|
||||
.setContentText(text)
|
||||
.setOngoing(true)
|
||||
.setProgress(max, value, max == 0)
|
||||
.build()
|
||||
|
||||
private fun builder(channel: String): Notification.Builder = Notification.Builder(this, channel)
|
||||
|
||||
private fun goForeground(n: Notification) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
startForeground(FOREGROUND_ID, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
|
||||
} else {
|
||||
startForeground(FOREGROUND_ID, n)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
worker.shutdownNow()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val PROGRESS = "uploads"
|
||||
private const val DONE = "uploaded"
|
||||
private const val FOREGROUND_ID = 1
|
||||
|
||||
/** A share of several files becomes one album with this title. */
|
||||
const val EXTRA_ALBUM = "no.zyon.shade.mediademo.ALBUM"
|
||||
|
||||
private fun mib(b: Long) = "%.1f".format(b / 1048576.0)
|
||||
|
||||
/** The relay's own watch page opens the link in a browser too. */
|
||||
fun watchPage(grant: MediaGrant): String = grant.url!!.substringBefore("/v1/media/") + "/watch/"
|
||||
|
||||
fun urisOf(intent: Intent): List<Uri> {
|
||||
val out = LinkedHashSet<Uri>()
|
||||
intent.data?.let(out::add)
|
||||
intent.clipData?.let { c -> for (i in 0 until c.itemCount) c.getItemAt(i).uri?.let(out::add) }
|
||||
// A share names its files in EXTRA_STREAM (Android usually mirrors them into the clip).
|
||||
@Suppress("DEPRECATION")
|
||||
when (intent.action) {
|
||||
Intent.ACTION_SEND -> (intent.getParcelableExtra(Intent.EXTRA_STREAM) as? Uri)?.let(out::add)
|
||||
Intent.ACTION_SEND_MULTIPLE -> intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM)?.let(out::addAll)
|
||||
}
|
||||
return out.toList()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package no.zyon.shade.mediademo
|
||||
|
||||
import android.content.Context
|
||||
import no.zyon.shade.keystore.KeystoreSecretFile
|
||||
import no.zyon.shade.media.MediaOwner
|
||||
import no.zyon.shade.media.MediaUploader
|
||||
import no.zyon.shade.media.UploadJobs
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Where the demo uploads to and as whom. The relay URL is not a secret and
|
||||
* lives in prefs; the owner seed signs every upload and lives in a
|
||||
* Keystore-encrypted file. The relay must list [owner]'s id among its owners
|
||||
* (`shade media serve --owners <id>`), which the share screen shows to copy.
|
||||
*/
|
||||
object Uploads {
|
||||
private const val PREFS = "shade-media-demo"
|
||||
private const val RELAY = "relay"
|
||||
|
||||
fun relay(context: Context): String? =
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(RELAY, null)?.takeIf { it.isNotBlank() }
|
||||
|
||||
fun setRelay(context: Context, url: String) {
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(RELAY, url.trim().trimEnd('/')).apply()
|
||||
}
|
||||
|
||||
private fun secret(context: Context) = KeystoreSecretFile(File(context.filesDir, "media-owner.sks"), "shade-media-owner")
|
||||
|
||||
/**
|
||||
* The owner key, made on first use. If its Keystore key is gone (the app's
|
||||
* data restored onto another phone), a new owner is made: the relay must
|
||||
* then be told the new id — the old one cannot be recovered by design.
|
||||
*/
|
||||
@Synchronized
|
||||
fun owner(context: Context): MediaOwner {
|
||||
val s = secret(context)
|
||||
val seed = try {
|
||||
s.getOrCreate(32)
|
||||
} catch (e: KeystoreSecretFile.SecretLostException) {
|
||||
s.destroy()
|
||||
s.getOrCreate(32)
|
||||
}
|
||||
return MediaOwner(seed).also { seed.fill(0) }
|
||||
}
|
||||
|
||||
fun jobs(context: Context) = UploadJobs(File(context.filesDir, "media-uploads"))
|
||||
|
||||
fun uploader(context: Context, relay: String) = MediaUploader(relay, owner(context))
|
||||
}
|
||||
7
bench/media-relay.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
/** A live relay in its own process for bench/media.ts; prints its port. */
|
||||
import { websocket } from 'hono/bun';
|
||||
import { createLiveRelay, MemoryLivePinStore } from '../packages/shade-media/src/server.js';
|
||||
|
||||
const relay = createLiveRelay({ pins: new MemoryLivePinStore(), viewerHighWater: 32 * 1024 * 1024 });
|
||||
const server = Bun.serve({ port: 0, fetch: (req, srv) => relay.app.fetch(req, { server: srv }), websocket, idleTimeout: 0 });
|
||||
console.log(server.port);
|
||||
67
bench/media-results.json
Normal file
@@ -0,0 +1,67 @@
|
||||
{
|
||||
"at": "2026-10-18T19:15:13.188Z",
|
||||
"bun": "1.3.5",
|
||||
"bigMiB": 1024,
|
||||
"seal": {
|
||||
"mibPerSec": 259.1,
|
||||
"ms": 3951.4,
|
||||
"overheadPct": 0.0046
|
||||
},
|
||||
"readDisk": {
|
||||
"mibPerSec": 480.2,
|
||||
"ms": 2132.4
|
||||
},
|
||||
"upload": {
|
||||
"mibPerSec": 50.9
|
||||
},
|
||||
"readHttp": {
|
||||
"mibPerSec": 209.5,
|
||||
"ms": 4889
|
||||
},
|
||||
"open": {
|
||||
"p50": 3.28,
|
||||
"p95": 6.58
|
||||
},
|
||||
"seek": {
|
||||
"p50": 3.98,
|
||||
"p95": 8.21,
|
||||
"max": 16.08
|
||||
},
|
||||
"live": [
|
||||
{
|
||||
"viewers": 1,
|
||||
"delivered": 100,
|
||||
"p50": 3,
|
||||
"p95": 12,
|
||||
"max": 14
|
||||
},
|
||||
{
|
||||
"viewers": 10,
|
||||
"delivered": 100,
|
||||
"p50": 6,
|
||||
"p95": 20,
|
||||
"max": 49
|
||||
},
|
||||
{
|
||||
"viewers": 50,
|
||||
"delivered": 100,
|
||||
"p50": 22,
|
||||
"p95": 58,
|
||||
"max": 213
|
||||
},
|
||||
{
|
||||
"viewers": 100,
|
||||
"delivered": 100,
|
||||
"p50": 15,
|
||||
"p95": 72,
|
||||
"max": 255
|
||||
},
|
||||
{
|
||||
"viewers": 200,
|
||||
"delivered": 100,
|
||||
"p50": 28,
|
||||
"p95": 151,
|
||||
"max": 443
|
||||
}
|
||||
]
|
||||
}
|
||||
26
bench/media-store-relay.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Media routes over one store, in their own process, for bench/media-store.ts
|
||||
* (so the relay's memory is measured alone). Prints its port.
|
||||
*
|
||||
* bun bench/media-store-relay.ts file <dir>
|
||||
* bun bench/media-store-relay.ts s3 <s3 url> [<postgres url>]
|
||||
*/
|
||||
import { createMediaRoutes, FileMediaStore, MemoryMediaIndex, ObjectMediaStore, S3Bucket, mediaMaxRequestBody } from '../packages/shade-media/src/server.js';
|
||||
import type { MediaIndex, MediaStore } from '../packages/shade-media/src/server.js';
|
||||
|
||||
const [kind, where, pg] = process.argv.slice(2);
|
||||
let store: MediaStore;
|
||||
if (kind === 'file') {
|
||||
store = new FileMediaStore(where!);
|
||||
} else {
|
||||
const { bucket, prefix } = S3Bucket.fromUrl(where!);
|
||||
let index: MediaIndex = new MemoryMediaIndex();
|
||||
if (pg !== undefined) {
|
||||
const { PostgresMediaIndex } = await import('../packages/shade-storage-postgres/src/index.js');
|
||||
index = await PostgresMediaIndex.create(pg);
|
||||
}
|
||||
store = new ObjectMediaStore(bucket, index, { prefix });
|
||||
}
|
||||
const app = createMediaRoutes(store);
|
||||
const server = Bun.serve({ port: 0, fetch: (req) => app.fetch(req), idleTimeout: 0, maxRequestBodySize: mediaMaxRequestBody() });
|
||||
console.log(server.port);
|
||||
42
bench/media-store-results.json
Normal file
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"sizesMiB": [
|
||||
512,
|
||||
1536
|
||||
],
|
||||
"runs": 3,
|
||||
"bun": "1.3.5",
|
||||
"results": {
|
||||
"512": {
|
||||
"disk (FileMediaStore)": {
|
||||
"uploadMiBs": 171,
|
||||
"readMiBs": 239.5,
|
||||
"seekP50": 3.78,
|
||||
"seekP95": 7.03,
|
||||
"peakRssMiB": 330
|
||||
},
|
||||
"S3 + Postgres (ObjectMediaStore)": {
|
||||
"uploadMiBs": 179.9,
|
||||
"readMiBs": 146.3,
|
||||
"seekP50": 15.96,
|
||||
"seekP95": 28.66,
|
||||
"peakRssMiB": 360
|
||||
}
|
||||
},
|
||||
"1536": {
|
||||
"disk (FileMediaStore)": {
|
||||
"uploadMiBs": 286.6,
|
||||
"readMiBs": 199.6,
|
||||
"seekP50": 9.05,
|
||||
"seekP95": 19.37,
|
||||
"peakRssMiB": 369
|
||||
},
|
||||
"S3 + Postgres (ObjectMediaStore)": {
|
||||
"uploadMiBs": 79.3,
|
||||
"readMiBs": 107.4,
|
||||
"seekP50": 20.37,
|
||||
"seekP95": 31.89,
|
||||
"peakRssMiB": 358
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
125
bench/media-store.chart.json
Normal file
@@ -0,0 +1,125 @@
|
||||
[
|
||||
{
|
||||
"type": "bar",
|
||||
"title": "Sealed film store: disk vs S3 (MiB/s)",
|
||||
"subtitle": "1536 MiB film through the real media routes, median of 3 runs; relay in its own process; S3 = local SeaweedFS",
|
||||
"y": {
|
||||
"label": "MiB/s",
|
||||
"min": 0
|
||||
},
|
||||
"note": "Bun 1.3.5. Uploads go up in 16 MiB pieces, up to 4 in flight. Disk: each piece fsynced before it is acknowledged. S3: each piece is one SHA-256-signed multipart part.",
|
||||
"source": {
|
||||
"path": "media-store-results.json"
|
||||
},
|
||||
"series": [
|
||||
{
|
||||
"name": "disk (FileMediaStore)",
|
||||
"data": [
|
||||
[
|
||||
"upload (pieces)",
|
||||
286.6
|
||||
],
|
||||
[
|
||||
"read + verify (Range)",
|
||||
199.6
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "S3 + Postgres (ObjectMediaStore)",
|
||||
"data": [
|
||||
[
|
||||
"upload (pieces)",
|
||||
79.3
|
||||
],
|
||||
[
|
||||
"read + verify (Range)",
|
||||
107.4
|
||||
]
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "bar",
|
||||
"title": "Relay memory does not grow with the film",
|
||||
"subtitle": "Peak relay RSS growth during one upload (VmHWM − RSS before), worst of 3 runs, per film size",
|
||||
"y": {
|
||||
"label": "MiB",
|
||||
"min": 0
|
||||
},
|
||||
"note": "Bounded by the upload window (4 pieces of 16 MiB) and garbage not yet collected. Before pieces, one PUT of a 512 MiB film put 762 MiB (disk) and 1011 MiB (S3) in the relay: Bun.serve reads a request body as fast as the client sends.",
|
||||
"source": {
|
||||
"path": "media-store-results.json"
|
||||
},
|
||||
"series": [
|
||||
{
|
||||
"name": "disk (FileMediaStore)",
|
||||
"data": [
|
||||
[
|
||||
"512 MiB film",
|
||||
330
|
||||
],
|
||||
[
|
||||
"1536 MiB film",
|
||||
369
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "S3 + Postgres (ObjectMediaStore)",
|
||||
"data": [
|
||||
[
|
||||
"512 MiB film",
|
||||
360
|
||||
],
|
||||
[
|
||||
"1536 MiB film",
|
||||
358
|
||||
]
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "bar",
|
||||
"title": "Seek latency, disk vs S3 (ms)",
|
||||
"subtitle": "64 KiB at a random offset of the 1536 MiB film, fresh reader each (n = 50 per run, median of 3 runs)",
|
||||
"y": {
|
||||
"label": "ms",
|
||||
"min": 0
|
||||
},
|
||||
"note": "Includes opening: footer + trailer + root check, then the range.",
|
||||
"source": {
|
||||
"path": "media-store-results.json"
|
||||
},
|
||||
"series": [
|
||||
{
|
||||
"name": "disk (FileMediaStore)",
|
||||
"data": [
|
||||
[
|
||||
"p50",
|
||||
9.05
|
||||
],
|
||||
[
|
||||
"p95",
|
||||
19.37
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "S3 + Postgres (ObjectMediaStore)",
|
||||
"data": [
|
||||
[
|
||||
"p50",
|
||||
20.37
|
||||
],
|
||||
[
|
||||
"p95",
|
||||
31.89
|
||||
]
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
174
bench/media-store.ts
Normal file
@@ -0,0 +1,174 @@
|
||||
/**
|
||||
* Where sealed films live: the disk store against the S3 store
|
||||
* (ObjectMediaStore), through the real media routes, each relay in its own
|
||||
* process.
|
||||
*
|
||||
* Run: SHADE_BENCH_S3_URL=http://key:secret@127.0.0.1:58333/bench \
|
||||
* [SHADE_BENCH_PG_URL=postgres://…] bun bench/media-store.ts [--mib 512,1536]
|
||||
*
|
||||
* Per store: upload (a sealed file in pieces, as `media put` sends it), full read + verify over
|
||||
* Range, seek latency (64 KiB at random offsets, fresh reader each), and the
|
||||
* relay's own peak memory during the upload (VmHWM − VmRSS before) — at
|
||||
* each film size, to show it does not grow with the film.
|
||||
* Writes bench/media-store-results.json and bench/media-store.chart.json.
|
||||
*/
|
||||
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { sealFile } from '../packages/shade-media/src/node.js';
|
||||
import { MediaClient, openGrant } from '../packages/shade-media/src/client.js';
|
||||
import { OwnerKey } from '../packages/shade-media/src/owner.js';
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const SIZES = (args.includes('--mib') ? args[args.indexOf('--mib') + 1]! : '512,1536').split(',').map(Number);
|
||||
if (SIZES.some((n) => !Number.isInteger(n) || n < 1)) throw new Error('--mib takes sizes in MiB, comma-separated');
|
||||
// Disk and bucket speed swing with whatever else the machine does: median of several runs.
|
||||
const RUNS = args.includes('--runs') ? Number(args[args.indexOf('--runs') + 1]) : 3;
|
||||
const S3 = process.env.SHADE_BENCH_S3_URL;
|
||||
const PG = process.env.SHADE_BENCH_PG_URL;
|
||||
if (S3 === undefined) throw new Error('set SHADE_BENCH_S3_URL (a bucket that may be written to)');
|
||||
const MiB = 1024 * 1024;
|
||||
const pct = (xs: number[], p: number) => {
|
||||
const s = [...xs].sort((a, b) => a - b);
|
||||
return Math.round(s[Math.min(s.length - 1, Math.floor((p / 100) * s.length))]! * 100) / 100;
|
||||
};
|
||||
const kib = async (pid: number, field: 'VmRSS' | 'VmHWM') =>
|
||||
Number(new RegExp(`${field}:\\s+(\\d+) kB`).exec(await readFile(`/proc/${pid}/status`, 'utf8'))![1]);
|
||||
|
||||
async function relay(argv: string[]) {
|
||||
const proc = Bun.spawn(['bun', join(import.meta.dir, 'media-store-relay.ts'), ...argv], { stdout: 'pipe', stderr: 'inherit' });
|
||||
const reader = proc.stdout.getReader();
|
||||
const { value } = await reader.read();
|
||||
const port = Number(new TextDecoder().decode(value).trim());
|
||||
return { proc, base: `http://localhost:${port}` };
|
||||
}
|
||||
|
||||
type Result = { uploadMiBs: number; readMiBs: number; seekP50: number; seekP95: number; peakRssMiB: number };
|
||||
const S3_NAME = PG !== undefined ? 'S3 + Postgres (ObjectMediaStore)' : 'S3 (ObjectMediaStore)';
|
||||
const DISK_NAME = 'disk (FileMediaStore)';
|
||||
|
||||
/** One film of `mib` MiB through each store. */
|
||||
async function run(mib: number, work: string): Promise<Record<string, Result>> {
|
||||
const plain = join(work, 'film.bin');
|
||||
const sealed = join(work, 'film.smf');
|
||||
{
|
||||
const f = Bun.file(plain).writer();
|
||||
const chunk = new Uint8Array(MiB);
|
||||
for (let i = 0; i < mib; i++) {
|
||||
crypto.getRandomValues(chunk.subarray(0, 65536));
|
||||
for (let o = 65536; o < MiB; o += 65536) chunk.copyWithin(o, 0, 65536);
|
||||
chunk[0] = i & 0xff;
|
||||
f.write(chunk);
|
||||
}
|
||||
await f.end();
|
||||
}
|
||||
const sealResult = await sealFile(plain, sealed, { meta: { name: 'bench.bin' } });
|
||||
await rm(plain);
|
||||
const sealedSize = Bun.file(sealed).size;
|
||||
|
||||
const stores: [string, string[]][] = [
|
||||
[DISK_NAME, ['file', join(work, `store-${mib}`)]],
|
||||
[S3_NAME, ['s3', `${S3!.replace(/\/$/, '')}/bench-${Date.now().toString(36)}`, ...(PG !== undefined ? [PG] : [])]],
|
||||
];
|
||||
const results: Record<string, Result> = {};
|
||||
for (const [name, argv] of stores) {
|
||||
const runs: Result[] = [];
|
||||
for (let i = 0; i < RUNS; i++) {
|
||||
// A fresh relay per run: its high-water mark is this upload's alone.
|
||||
const { proc, base } = await relay(argv);
|
||||
try {
|
||||
const client = new MediaClient(base, OwnerKey.generate());
|
||||
await Bun.sleep(300);
|
||||
const rssBefore = await kib(proc.pid, 'VmRSS');
|
||||
let t = performance.now();
|
||||
const grant = await client.putSealed(sealResult, Bun.file(sealed));
|
||||
const upSec = (performance.now() - t) / 1000;
|
||||
const peak = (await kib(proc.pid, 'VmHWM')) - rssBefore;
|
||||
|
||||
const reader = await openGrant(grant);
|
||||
t = performance.now();
|
||||
for (let off = 0; off < reader.size; off += 8 * MiB) await reader.read(off, Math.min(8 * MiB, reader.size - off));
|
||||
const readSec = (performance.now() - t) / 1000;
|
||||
|
||||
const seeks: number[] = [];
|
||||
for (let j = 0; j < 50; j++) {
|
||||
const r = await openGrant(grant);
|
||||
const at = Math.floor(Math.random() * (r.size - 65536));
|
||||
const s = performance.now();
|
||||
await r.read(at, 65536);
|
||||
seeks.push(performance.now() - s);
|
||||
}
|
||||
runs.push({
|
||||
uploadMiBs: sealedSize / MiB / upSec,
|
||||
readMiBs: mib / readSec,
|
||||
seekP50: pct(seeks, 50),
|
||||
seekP95: pct(seeks, 95),
|
||||
peakRssMiB: peak / 1024,
|
||||
});
|
||||
await client.delete(grant.mediaId);
|
||||
} finally {
|
||||
proc.kill();
|
||||
await proc.exited;
|
||||
}
|
||||
}
|
||||
const median = (k: keyof Result) => pct(runs.map((r) => r[k]), 50);
|
||||
results[name] = {
|
||||
uploadMiBs: Math.round(median('uploadMiBs') * 10) / 10,
|
||||
readMiBs: Math.round(median('readMiBs') * 10) / 10,
|
||||
seekP50: median('seekP50'),
|
||||
seekP95: median('seekP95'),
|
||||
// Memory is a bound, not a typical value: the worst run.
|
||||
peakRssMiB: Math.round(Math.max(...runs.map((r) => r.peakRssMiB))),
|
||||
};
|
||||
console.log(`${mib} MiB`, name, results[name], `(${RUNS} runs; upload ${runs.map((r) => r.uploadMiBs.toFixed(0)).join('/')} MiB/s)`);
|
||||
}
|
||||
await rm(sealed);
|
||||
await rm(join(work, `store-${mib}`), { recursive: true, force: true });
|
||||
return results;
|
||||
}
|
||||
|
||||
const work = await mkdtemp(join(tmpdir(), 'shade-bench-store-'));
|
||||
try {
|
||||
const bySize: Record<string, Record<string, Result>> = {};
|
||||
for (const mib of SIZES) bySize[mib] = await run(mib, work);
|
||||
await writeFile(
|
||||
join(import.meta.dir, 'media-store-results.json'),
|
||||
`${JSON.stringify({ sizesMiB: SIZES, runs: RUNS, bun: Bun.version, results: bySize }, null, 2)}\n`,
|
||||
);
|
||||
const largest = Math.max(...SIZES);
|
||||
const results = bySize[largest]!;
|
||||
const names = [DISK_NAME, S3_NAME];
|
||||
const charts = [
|
||||
{
|
||||
type: 'bar',
|
||||
title: 'Sealed film store: disk vs S3 (MiB/s)',
|
||||
subtitle: `${largest} MiB film through the real media routes, median of ${RUNS} runs; relay in its own process; S3 = local SeaweedFS`,
|
||||
y: { label: 'MiB/s', min: 0 },
|
||||
note: `Bun ${Bun.version}. Uploads go up in 16 MiB pieces, up to 4 in flight. Disk: each piece fsynced before it is acknowledged. S3: each piece is one SHA-256-signed multipart part.`,
|
||||
source: { path: 'media-store-results.json' },
|
||||
series: names.map((n) => ({ name: n, data: [['upload (pieces)', results[n]!.uploadMiBs], ['read + verify (Range)', results[n]!.readMiBs]] })),
|
||||
},
|
||||
{
|
||||
type: 'bar',
|
||||
title: 'Relay memory does not grow with the film',
|
||||
subtitle: `Peak relay RSS growth during one upload (VmHWM − RSS before), worst of ${RUNS} runs, per film size`,
|
||||
y: { label: 'MiB', min: 0 },
|
||||
note: 'Bounded by the upload window (4 pieces of 16 MiB) and garbage not yet collected. Before pieces, one PUT of a 512 MiB film put 762 MiB (disk) and 1011 MiB (S3) in the relay: Bun.serve reads a request body as fast as the client sends.',
|
||||
source: { path: 'media-store-results.json' },
|
||||
series: names.map((n) => ({ name: n, data: SIZES.map((mib) => [`${mib} MiB film`, bySize[mib]![n]!.peakRssMiB]) })),
|
||||
},
|
||||
{
|
||||
type: 'bar',
|
||||
title: 'Seek latency, disk vs S3 (ms)',
|
||||
subtitle: `64 KiB at a random offset of the ${largest} MiB film, fresh reader each (n = 50 per run, median of ${RUNS} runs)`,
|
||||
y: { label: 'ms', min: 0 },
|
||||
note: 'Includes opening: footer + trailer + root check, then the range.',
|
||||
source: { path: 'media-store-results.json' },
|
||||
series: names.map((n) => ({ name: n, data: [['p50', results[n]!.seekP50], ['p95', results[n]!.seekP95]] })),
|
||||
},
|
||||
];
|
||||
await writeFile(join(import.meta.dir, 'media-store.chart.json'), `${JSON.stringify(charts, null, 2)}\n`);
|
||||
console.log('wrote bench/media-store-results.json and bench/media-store.chart.json');
|
||||
} finally {
|
||||
await rm(work, { recursive: true, force: true });
|
||||
}
|
||||
147
bench/media.chart.json
Normal file
@@ -0,0 +1,147 @@
|
||||
[
|
||||
{
|
||||
"type": "bar",
|
||||
"title": "Sealed media throughput (MiB/s)",
|
||||
"subtitle": "1024 MiB of incompressible data, 1 MiB segments, one core",
|
||||
"y": {
|
||||
"label": "MiB/s",
|
||||
"min": 0
|
||||
},
|
||||
"note": "Bun 1.3.5; HTTP is localhost through the real media routes; size overhead 0.0046 %",
|
||||
"source": {
|
||||
"path": "media-results.json"
|
||||
},
|
||||
"series": [
|
||||
{
|
||||
"name": "MiB/s",
|
||||
"data": [
|
||||
[
|
||||
"seal (disk → disk)",
|
||||
259.1
|
||||
],
|
||||
[
|
||||
"read + verify (disk)",
|
||||
480.2
|
||||
],
|
||||
[
|
||||
"upload (HTTP PUT)",
|
||||
50.9
|
||||
],
|
||||
[
|
||||
"read + verify (HTTP Range)",
|
||||
209.5
|
||||
]
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "bar",
|
||||
"title": "Seeking in a sealed film over HTTP (ms)",
|
||||
"subtitle": "open = footer + trailer + root check; seek = first 64 KiB at a random offset, no cache",
|
||||
"y": {
|
||||
"label": "ms",
|
||||
"min": 0
|
||||
},
|
||||
"note": "n = 10 opens, 100 seeks; localhost",
|
||||
"source": {
|
||||
"path": "media-results.json"
|
||||
},
|
||||
"series": [
|
||||
{
|
||||
"name": "p50",
|
||||
"data": [
|
||||
[
|
||||
"open",
|
||||
3.28
|
||||
],
|
||||
[
|
||||
"seek",
|
||||
3.98
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "p95",
|
||||
"data": [
|
||||
[
|
||||
"open",
|
||||
6.58
|
||||
],
|
||||
[
|
||||
"seek",
|
||||
8.21
|
||||
]
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "line",
|
||||
"title": "Live fan-out: latency publish → decrypted, by viewers",
|
||||
"subtitle": "10 fps × 32 KiB frames (≈ 2.6 Mbit/s) for 6 s; relay in its own process, all viewers in one",
|
||||
"x": {
|
||||
"label": "viewers"
|
||||
},
|
||||
"y": {
|
||||
"label": "ms",
|
||||
"min": 0
|
||||
},
|
||||
"note": "delivered: 1 → 100 %, 10 → 100 %, 50 → 100 %, 100 → 100 %, 200 → 100 %. Every viewer verifies every signature and decrypts every frame, in one process, so the curve is mostly the viewers' CPU, not the relay's.",
|
||||
"source": {
|
||||
"path": "media-results.json"
|
||||
},
|
||||
"series": [
|
||||
{
|
||||
"name": "p50",
|
||||
"data": [
|
||||
[
|
||||
1,
|
||||
3
|
||||
],
|
||||
[
|
||||
10,
|
||||
6
|
||||
],
|
||||
[
|
||||
50,
|
||||
22
|
||||
],
|
||||
[
|
||||
100,
|
||||
15
|
||||
],
|
||||
[
|
||||
200,
|
||||
28
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "p95",
|
||||
"data": [
|
||||
[
|
||||
1,
|
||||
12
|
||||
],
|
||||
[
|
||||
10,
|
||||
20
|
||||
],
|
||||
[
|
||||
50,
|
||||
58
|
||||
],
|
||||
[
|
||||
100,
|
||||
72
|
||||
],
|
||||
[
|
||||
200,
|
||||
151
|
||||
]
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
236
bench/media.ts
Normal file
@@ -0,0 +1,236 @@
|
||||
/**
|
||||
* @shade/media benchmarks — what streaming under Shade costs.
|
||||
*
|
||||
* Run: bun bench/media.ts [--big-mib 1024] [--viewers 1,10,50,200]
|
||||
*
|
||||
* 1. Seal and read throughput, sealed file on disk (1 MiB segments).
|
||||
* 2. The same read over HTTP Range from the real media routes.
|
||||
* 3. Seek: time to the first decrypted byte at a random offset over HTTP.
|
||||
* 4. Live fan-out: one publisher, N viewers, relay in its own process —
|
||||
* delivered fraction and end-to-end latency (publish → decrypted).
|
||||
*
|
||||
* Writes bench/media-results.json (raw numbers) and bench/media.chart.json
|
||||
* (charts for the log post, `scaffold-agent chart block`).
|
||||
*/
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
|
||||
import { createWriteStream } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { Hono } from 'hono';
|
||||
import { websocket } from 'hono/bun';
|
||||
import { sealFile, FileSource } from '../packages/shade-media/src/node.js';
|
||||
import { MediaReader } from '../packages/shade-media/src/sealed.js';
|
||||
import { createMediaRoutes, FileMediaStore, mediaMaxRequestBody } from '../packages/shade-media/src/server.js';
|
||||
import { MediaClient, openGrant } from '../packages/shade-media/src/client.js';
|
||||
import { OwnerKey } from '../packages/shade-media/src/owner.js';
|
||||
import { LivePublisher } from '../packages/shade-media/src/live/channel.js';
|
||||
import { LivePublishClient, LiveWatchClient } from '../packages/shade-media/src/live/client.js';
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const flag = (k: string, d: string) => {
|
||||
const i = args.indexOf(`--${k}`);
|
||||
return i >= 0 ? args[i + 1]! : d;
|
||||
};
|
||||
const BIG_MIB = Number(flag('big-mib', '1024'));
|
||||
const VIEWERS = flag('viewers', '1,10,50,200').split(',').map(Number);
|
||||
const MiB = 1024 * 1024;
|
||||
const now = () => performance.now();
|
||||
const pct = (xs: number[], p: number) => {
|
||||
const s = [...xs].sort((a, b) => a - b);
|
||||
return s[Math.min(s.length - 1, Math.floor((p / 100) * s.length))]!;
|
||||
};
|
||||
const round = (x: number, d = 1) => Math.round(x * 10 ** d) / 10 ** d;
|
||||
|
||||
async function writeRandomFile(path: string, mib: number): Promise<void> {
|
||||
// Random bytes (incompressible, like video). One 1 MiB block reused with a
|
||||
// counter stamped in, so generation is not the thing being measured.
|
||||
const block = new Uint8Array(MiB);
|
||||
globalThis.crypto.getRandomValues(block.subarray(0, 65536));
|
||||
for (let i = 65536; i < MiB; i += 65536) block.copyWithin(i, 0, 65536);
|
||||
const ws = createWriteStream(path);
|
||||
for (let i = 0; i < mib; i++) {
|
||||
new DataView(block.buffer).setUint32(0, i);
|
||||
if (!ws.write(Buffer.from(block))) await new Promise<void>((r) => ws.once('drain', () => r()));
|
||||
}
|
||||
await new Promise<void>((r) => ws.end(() => r()));
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'shade-media-bench-'));
|
||||
const results: Record<string, unknown> = { at: new Date().toISOString(), bun: Bun.version, bigMiB: BIG_MIB };
|
||||
try {
|
||||
// ─── 1. Seal + local read ──────────────────────────────────
|
||||
const plain = join(dir, 'film.bin');
|
||||
const sealedPath = join(dir, 'film.smf');
|
||||
await writeRandomFile(plain, BIG_MIB);
|
||||
let t = now();
|
||||
const res = await sealFile(plain, sealedPath, { meta: { mime: 'video/mp4', name: 'film.bin' } });
|
||||
const sealMs = now() - t;
|
||||
const keys = { mediaId: res.mediaId, mediaKey: res.mediaKey, rootDigest: res.rootDigest };
|
||||
t = now();
|
||||
const reader = await MediaReader.open(new FileSource(sealedPath), keys, { cacheSegments: 0, maxSegmentsPerFetch: 8 });
|
||||
let n = 0;
|
||||
for await (const c of reader.stream()) n += c.length;
|
||||
const readMs = now() - t;
|
||||
if (n !== BIG_MIB * MiB) throw new Error(`read ${n} bytes`);
|
||||
const overhead = (res.sealedSize - res.plaintextSize) / res.plaintextSize;
|
||||
results.seal = { mibPerSec: round((BIG_MIB / sealMs) * 1000), ms: round(sealMs), overheadPct: round(overhead * 100, 4) };
|
||||
results.readDisk = { mibPerSec: round((BIG_MIB / readMs) * 1000), ms: round(readMs) };
|
||||
console.log(`seal ${BIG_MIB} MiB: ${round((BIG_MIB / sealMs) * 1000)} MiB/s size overhead ${round(overhead * 100, 4)} %`);
|
||||
console.log(`read ${BIG_MIB} MiB (disk): ${round((BIG_MIB / readMs) * 1000)} MiB/s`);
|
||||
|
||||
// ─── 2 + 3. Over HTTP ──────────────────────────────────────
|
||||
const app = new Hono();
|
||||
app.route('/', createMediaRoutes(new FileMediaStore(join(dir, 'store'))));
|
||||
const server = Bun.serve({ port: 0, fetch: (req, srv) => app.fetch(req, { server: srv }), websocket, idleTimeout: 0, maxRequestBodySize: mediaMaxRequestBody() });
|
||||
const base = `http://localhost:${server.port}`;
|
||||
try {
|
||||
const client = new MediaClient(base, OwnerKey.generate());
|
||||
t = now();
|
||||
const grant = await client.putSealed(res, Bun.file(sealedPath));
|
||||
const uploadMs = now() - t;
|
||||
t = now();
|
||||
const hr = await openGrant(grant, { cacheSegments: 0, maxSegmentsPerFetch: 8 });
|
||||
n = 0;
|
||||
for await (const c of hr.stream()) n += c.length;
|
||||
const httpMs = now() - t;
|
||||
results.upload = { mibPerSec: round((BIG_MIB / uploadMs) * 1000) };
|
||||
results.readHttp = { mibPerSec: round((BIG_MIB / httpMs) * 1000), ms: round(httpMs) };
|
||||
console.log(`upload (localhost): ${round((BIG_MIB / uploadMs) * 1000)} MiB/s read over HTTP Range: ${round((BIG_MIB / httpMs) * 1000)} MiB/s`);
|
||||
|
||||
// Seek: a fresh reader per probe would measure open(); one reader with
|
||||
// no cache measures what a seek in a playing film costs.
|
||||
const opened: number[] = [];
|
||||
for (let i = 0; i < 10; i++) {
|
||||
t = now();
|
||||
await openGrant(grant);
|
||||
opened.push(now() - t);
|
||||
}
|
||||
const seeks: number[] = [];
|
||||
const sr = await openGrant(grant, { cacheSegments: 0 });
|
||||
for (let i = 0; i < 100; i++) {
|
||||
const off = Math.floor(Math.random() * (BIG_MIB * MiB - 65536));
|
||||
t = now();
|
||||
await sr.read(off, 65536);
|
||||
seeks.push(now() - t);
|
||||
}
|
||||
results.open = { p50: round(pct(opened, 50), 2), p95: round(pct(opened, 95), 2) };
|
||||
results.seek = { p50: round(pct(seeks, 50), 2), p95: round(pct(seeks, 95), 2), max: round(Math.max(...seeks), 2) };
|
||||
console.log(`open (footer+trailer): p50 ${round(pct(opened, 50), 2)} ms seek→first byte: p50 ${round(pct(seeks, 50), 2)} ms, p95 ${round(pct(seeks, 95), 2)} ms`);
|
||||
} finally {
|
||||
server.stop(true);
|
||||
}
|
||||
|
||||
// ─── 4. Live fan-out ───────────────────────────────────────
|
||||
const relayProc = Bun.spawn(['bun', join(import.meta.dir, 'media-relay.ts')], { stdout: 'pipe', stderr: 'inherit' });
|
||||
const portLine = await new Response(relayProc.stdout).body!.getReader().read();
|
||||
const relayBase = `http://localhost:${new TextDecoder().decode(portLine.value).trim()}`;
|
||||
const live: Array<{ viewers: number; delivered: number; p50: number; p95: number; max: number }> = [];
|
||||
try {
|
||||
for (const v of VIEWERS) {
|
||||
const fps = 10;
|
||||
const frameBytes = 32 * 1024; // ≈ 2.6 Mbit/s, a 720p stream
|
||||
const seconds = 6;
|
||||
const pub = new LivePublisher();
|
||||
const pc = new LivePublishClient({ relay: relayBase, publisher: pub, readToken: new Uint8Array(32).fill(1) });
|
||||
await pc.whenReady();
|
||||
const grant = pc.grant('now');
|
||||
const lat: number[] = [];
|
||||
let got = 0;
|
||||
const viewers: LiveWatchClient[] = [];
|
||||
let ready = 0;
|
||||
for (let i = 0; i < v; i++) {
|
||||
viewers.push(
|
||||
new LiveWatchClient(grant, {
|
||||
onState: (s) => {
|
||||
if (s === 'live') ready++;
|
||||
},
|
||||
onFrame: (f) => {
|
||||
got++;
|
||||
lat.push(Date.now() - f.timestamp);
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
while (ready < v) await Bun.sleep(20);
|
||||
const payload = new Uint8Array(frameBytes);
|
||||
globalThis.crypto.getRandomValues(payload.subarray(0, 65536 > frameBytes ? frameBytes : 65536));
|
||||
const total = fps * seconds;
|
||||
const start = Date.now();
|
||||
for (let i = 0; i < total; i++) {
|
||||
await pc.send({ type: 'chunk', bytes: payload }, { keyframe: i % fps === 0 });
|
||||
const due = start + ((i + 1) * 1000) / fps;
|
||||
const wait = due - Date.now();
|
||||
if (wait > 0) await Bun.sleep(wait);
|
||||
}
|
||||
await Bun.sleep(1500);
|
||||
const delivered = got / (total * v);
|
||||
const row = { viewers: v, delivered: round(delivered * 100, 2), p50: pct(lat, 50), p95: pct(lat, 95), max: Math.max(...lat) };
|
||||
live.push(row);
|
||||
console.log(`live ${v} viewer(s): delivered ${row.delivered} %, latency p50 ${row.p50} ms, p95 ${row.p95} ms, max ${row.max} ms`);
|
||||
for (const w of viewers) w.close();
|
||||
pc.close();
|
||||
await Bun.sleep(300);
|
||||
}
|
||||
} finally {
|
||||
relayProc.kill();
|
||||
}
|
||||
results.live = live;
|
||||
|
||||
await writeFile(join(import.meta.dir, 'media-results.json'), `${JSON.stringify(results, null, 2)}\n`);
|
||||
const r = results as any;
|
||||
const charts = [
|
||||
{
|
||||
type: 'bar',
|
||||
title: 'Sealed media throughput (MiB/s)',
|
||||
subtitle: `${BIG_MIB} MiB of incompressible data, 1 MiB segments, one core`,
|
||||
y: { label: 'MiB/s', min: 0 },
|
||||
note: `Bun ${Bun.version}; HTTP is localhost through the real media routes; size overhead ${r.seal.overheadPct} %`,
|
||||
source: { path: 'media-results.json' },
|
||||
series: [
|
||||
{
|
||||
name: 'MiB/s',
|
||||
data: [
|
||||
['seal (disk → disk)', r.seal.mibPerSec],
|
||||
['read + verify (disk)', r.readDisk.mibPerSec],
|
||||
['upload (HTTP PUT)', r.upload.mibPerSec],
|
||||
['read + verify (HTTP Range)', r.readHttp.mibPerSec],
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'bar',
|
||||
title: 'Seeking in a sealed film over HTTP (ms)',
|
||||
subtitle: 'open = footer + trailer + root check; seek = first 64 KiB at a random offset, no cache',
|
||||
y: { label: 'ms', min: 0 },
|
||||
note: 'n = 10 opens, 100 seeks; localhost',
|
||||
source: { path: 'media-results.json' },
|
||||
series: [
|
||||
{ name: 'p50', data: [['open', r.open.p50], ['seek', r.seek.p50]] },
|
||||
{ name: 'p95', data: [['open', r.open.p95], ['seek', r.seek.p95]] },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'line',
|
||||
title: 'Live fan-out: latency publish → decrypted, by viewers',
|
||||
subtitle: '10 fps × 32 KiB frames (≈ 2.6 Mbit/s) for 6 s; relay in its own process, all viewers in one',
|
||||
x: { label: 'viewers' },
|
||||
y: { label: 'ms', min: 0 },
|
||||
note: `delivered: ${live.map((l) => `${l.viewers} → ${l.delivered} %`).join(', ')}. Every viewer verifies every signature and decrypts every frame, in one process, so the curve is mostly the viewers' CPU, not the relay's.`,
|
||||
source: { path: 'media-results.json' },
|
||||
series: [
|
||||
{ name: 'p50', data: live.map((l) => [l.viewers, l.p50]) },
|
||||
{ name: 'p95', data: live.map((l) => [l.viewers, l.p95]) },
|
||||
],
|
||||
},
|
||||
];
|
||||
await writeFile(join(import.meta.dir, 'media.chart.json'), `${JSON.stringify(charts, null, 2)}\n`);
|
||||
console.log('wrote bench/media-results.json and bench/media.chart.json');
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
await main();
|
||||
process.exit(0);
|
||||
73
bun.lock
@@ -18,7 +18,7 @@
|
||||
},
|
||||
"packages/shade-cli": {
|
||||
"name": "@shade/cli",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
"bin": {
|
||||
"shade": "src/cli.ts",
|
||||
},
|
||||
@@ -26,8 +26,10 @@
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/crypto-web": "workspace:*",
|
||||
"@shade/keychain": "workspace:*",
|
||||
"@shade/media": "workspace:*",
|
||||
"@shade/sdk": "workspace:*",
|
||||
"@shade/storage-encrypted": "workspace:*",
|
||||
"@shade/storage-postgres": "workspace:*",
|
||||
"@shade/storage-sqlite": "workspace:*",
|
||||
"@shade/transport": "workspace:*",
|
||||
},
|
||||
@@ -37,7 +39,7 @@
|
||||
},
|
||||
"packages/shade-core": {
|
||||
"name": "@shade/core",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
"dependencies": {
|
||||
"@shade/observability": "workspace:*",
|
||||
},
|
||||
@@ -50,7 +52,7 @@
|
||||
},
|
||||
"packages/shade-crypto-web": {
|
||||
"name": "@shade/crypto-web",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.0.1",
|
||||
"@noble/hashes": "^2.0.1",
|
||||
@@ -60,7 +62,7 @@
|
||||
},
|
||||
"packages/shade-dashboard": {
|
||||
"name": "@shade/dashboard",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
"dependencies": {
|
||||
"@shade/widgets": "workspace:*",
|
||||
"react": "^19.0.0",
|
||||
@@ -75,7 +77,7 @@
|
||||
},
|
||||
"packages/shade-files": {
|
||||
"name": "@shade/files",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/crypto-web": "workspace:*",
|
||||
@@ -102,7 +104,7 @@
|
||||
},
|
||||
"packages/shade-inbox": {
|
||||
"name": "@shade/inbox",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/proto": "workspace:*",
|
||||
@@ -115,7 +117,7 @@
|
||||
},
|
||||
"packages/shade-inbox-server": {
|
||||
"name": "@shade/inbox-server",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/observability": "workspace:*",
|
||||
@@ -133,7 +135,7 @@
|
||||
},
|
||||
"packages/shade-key-transparency": {
|
||||
"name": "@shade/key-transparency",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
"dependencies": {
|
||||
"@noble/hashes": "^2.0.1",
|
||||
"@shade/core": "workspace:*",
|
||||
@@ -145,11 +147,20 @@
|
||||
},
|
||||
"packages/shade-keychain": {
|
||||
"name": "@shade/keychain",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
},
|
||||
"packages/shade-media": {
|
||||
"name": "@shade/media",
|
||||
"version": "4.15.0",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.0.1",
|
||||
"@noble/hashes": "^2.0.1",
|
||||
"hono": "^4.12.18",
|
||||
},
|
||||
},
|
||||
"packages/shade-observability": {
|
||||
"name": "@shade/observability",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
"dependencies": {
|
||||
"@noble/hashes": "^2.0.1",
|
||||
},
|
||||
@@ -167,7 +178,7 @@
|
||||
},
|
||||
"packages/shade-observer": {
|
||||
"name": "@shade/observer",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/server": "workspace:*",
|
||||
@@ -179,14 +190,14 @@
|
||||
},
|
||||
"packages/shade-proto": {
|
||||
"name": "@shade/proto",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
},
|
||||
},
|
||||
"packages/shade-recovery": {
|
||||
"name": "@shade/recovery",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/crypto-web": "workspace:*",
|
||||
@@ -199,13 +210,14 @@
|
||||
},
|
||||
"packages/shade-sdk": {
|
||||
"name": "@shade/sdk",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/crypto-web": "workspace:*",
|
||||
"@shade/files": "workspace:*",
|
||||
"@shade/inbox": "workspace:*",
|
||||
"@shade/key-transparency": "workspace:*",
|
||||
"@shade/media": "workspace:*",
|
||||
"@shade/observability": "workspace:*",
|
||||
"@shade/observer": "workspace:*",
|
||||
"@shade/proto": "workspace:*",
|
||||
@@ -229,11 +241,12 @@
|
||||
},
|
||||
"packages/shade-server": {
|
||||
"name": "@shade/server",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/inbox-server": "workspace:*",
|
||||
"@shade/key-transparency": "workspace:*",
|
||||
"@shade/media": "workspace:*",
|
||||
"@shade/observability": "workspace:*",
|
||||
"@shade/storage-sqlite": "workspace:*",
|
||||
"@shade/vault": "workspace:*",
|
||||
@@ -251,7 +264,7 @@
|
||||
},
|
||||
"packages/shade-storage-encrypted": {
|
||||
"name": "@shade/storage-encrypted",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
"dependencies": {
|
||||
"@noble/hashes": "^2.0.1",
|
||||
"@shade/core": "workspace:*",
|
||||
@@ -273,7 +286,7 @@
|
||||
},
|
||||
"packages/shade-storage-indexeddb": {
|
||||
"name": "@shade/storage-indexeddb",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"idb": "^8.0.3",
|
||||
@@ -285,22 +298,24 @@
|
||||
},
|
||||
"packages/shade-storage-postgres": {
|
||||
"name": "@shade/storage-postgres",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/inbox-server": "workspace:*",
|
||||
"@shade/key-transparency": "workspace:*",
|
||||
"@shade/media": "workspace:*",
|
||||
"@shade/server": "workspace:*",
|
||||
"drizzle-orm": "^0.45.2",
|
||||
"postgres": "^3.4.9",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@shade/crypto-web": "workspace:*",
|
||||
"hono": "^4.12.18",
|
||||
},
|
||||
},
|
||||
"packages/shade-storage-sqlite": {
|
||||
"name": "@shade/storage-sqlite",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/crypto-web": "workspace:*",
|
||||
@@ -313,7 +328,7 @@
|
||||
},
|
||||
"packages/shade-streams": {
|
||||
"name": "@shade/streams",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
"dependencies": {
|
||||
"@noble/hashes": "^2.0.1",
|
||||
"@shade/core": "workspace:*",
|
||||
@@ -325,7 +340,7 @@
|
||||
},
|
||||
"packages/shade-transfer": {
|
||||
"name": "@shade/transfer",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/crypto-web": "workspace:*",
|
||||
@@ -342,7 +357,7 @@
|
||||
},
|
||||
"packages/shade-transport": {
|
||||
"name": "@shade/transport",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/crypto-web": "workspace:*",
|
||||
@@ -353,7 +368,7 @@
|
||||
},
|
||||
"packages/shade-transport-bridge": {
|
||||
"name": "@shade/transport-bridge",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/server": "workspace:*",
|
||||
@@ -375,7 +390,7 @@
|
||||
},
|
||||
"packages/shade-transport-webrtc": {
|
||||
"name": "@shade/transport-webrtc",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/streams": "workspace:*",
|
||||
@@ -384,7 +399,7 @@
|
||||
},
|
||||
"packages/shade-vault": {
|
||||
"name": "@shade/vault",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
"dependencies": {
|
||||
"@noble/hashes": "^2.0.1",
|
||||
"@shade/core": "workspace:*",
|
||||
@@ -397,7 +412,7 @@
|
||||
},
|
||||
"packages/shade-widgets": {
|
||||
"name": "@shade/widgets",
|
||||
"version": "4.13.0",
|
||||
"version": "4.15.0",
|
||||
"dependencies": {
|
||||
"@shade/recovery": "workspace:*",
|
||||
"@shade/sdk": "workspace:*",
|
||||
@@ -592,6 +607,8 @@
|
||||
|
||||
"@shade/keychain": ["@shade/keychain@workspace:packages/shade-keychain"],
|
||||
|
||||
"@shade/media": ["@shade/media@workspace:packages/shade-media"],
|
||||
|
||||
"@shade/observability": ["@shade/observability@workspace:packages/shade-observability"],
|
||||
|
||||
"@shade/observer": ["@shade/observer@workspace:packages/shade-observer"],
|
||||
@@ -782,10 +799,14 @@
|
||||
|
||||
"@shade/inbox-server/hono": ["hono@4.13.2", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="],
|
||||
|
||||
"@shade/media/hono": ["hono@4.13.2", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="],
|
||||
|
||||
"@shade/observer/hono": ["hono@4.13.2", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="],
|
||||
|
||||
"@shade/server/hono": ["hono@4.13.2", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="],
|
||||
|
||||
"@shade/storage-postgres/hono": ["hono@4.13.2", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="],
|
||||
|
||||
"@shade/transport-bridge/hono": ["hono@4.13.2", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="],
|
||||
|
||||
"@shade/vault/hono": ["hono@4.13.2", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="],
|
||||
|
||||
608
docs/media.md
Normal file
@@ -0,0 +1,608 @@
|
||||
# `@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
|
||||
|
||||
# Record a channel until it ends, and keep it as a sealed film with its own link.
|
||||
shade live record '<link>' -o Kveldssending --put --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.
|
||||
|
||||
`shade live record` writes what the channel carries: text to `base.txt`, video or
|
||||
sound to `base.webm`/`base.mp4` (the init segment, then every chunk, in the order they
|
||||
were sent; a chunk that arrives after newer ones is left out and counted), pictures
|
||||
to `base-images/`. If the publisher starts over with a different init, the recording
|
||||
goes on in `base-2.…`. When the channel ends (or on Ctrl-C), ffmpeg, if present,
|
||||
rewrites each recording without re-encoding: an index for seeking, the clock from
|
||||
0:00. `--put` then seals and uploads it like `media put`, under the channel's name; a
|
||||
recording of several files becomes an album. Every channel kind now sends its name as
|
||||
a sticky `meta` frame, so a viewer without the grant's meta learns it too.
|
||||
|
||||
`--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 (`PUT`, 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.
|
||||
- **Behind a load balancer**, let a request that cannot reach one instance go to the
|
||||
next. A piece is a `PUT` (idempotent: sent twice, the second is a no-op), which
|
||||
nginx already retries on the next upstream. The `POST` that starts an upload or asks
|
||||
how far it got is just as safe to repeat, but nginx does not retry it by default:
|
||||
`location ~ ^/v1/media/[0-9a-f]+/upload$ { proxy_next_upstream error timeout non_idempotent; … }`.
|
||||
Without it the client still retries, but a balancer that keeps sending its
|
||||
retries to a dead instance makes the run stop; running it again resumes.
|
||||
- **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
|
||||
|
||||
```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.
|
||||
|
||||
Uploading from a phone is `MediaUploader` (blocking; off the main thread):
|
||||
|
||||
```kotlin
|
||||
val owner = MediaOwner(seed) // 32 bytes, kept in the Keystore-backed storage
|
||||
val up = MediaUploader("https://relay.example", owner)
|
||||
val grant = contentResolver.openInputStream(uri)!!.use { input ->
|
||||
up.uploadStream(input, File(cacheDir, "film.smf"), MediaMeta(name = "Kveld.mp4", mime = "video/mp4")) { acked, total -> … }
|
||||
}
|
||||
share(grant.capabilityUrl("https://relay.example/watch/"))
|
||||
```
|
||||
|
||||
It speaks the same piece protocol as `media put` (one PUT up to 16 MiB, then pieces
|
||||
with the relay's window, retries and a resync after a lost answer). To survive the
|
||||
app being killed, keep the sealed file and the `SealResult` and call `putSealed`
|
||||
again: the media id is the same, so the relay picks up where it stopped, and a file it
|
||||
already has gives the same link without sending anything. The relay must list
|
||||
`owner.id` among its owners.
|
||||
|
||||
`UploadJobs` does that bookkeeping: `uploader.upload(jobs, key, …)` seals once into an
|
||||
app-private job directory (sealed copy + seal result, file key included — keep it in
|
||||
`filesDir`), resumes after a kill with the same media id, and gives a finished job's
|
||||
grant again unless the relay says the file is gone. On Android, `ShadeUpload.describe(
|
||||
context, uri)` turns a shared `content://` URI into the meta to seal (name, type, size,
|
||||
duration, picture size as shown — nothing else, no location) and `ShadeUpload.upload`
|
||||
runs it as a job. `KeystoreSecretFile` (`:shade-android-keystore`) keeps the owner seed
|
||||
encrypted under a hardware-backed Keystore key.
|
||||
|
||||
The demo app shows the whole flow: share a video, photo, song or document to «Share to
|
||||
Shade», enter the relay once and add the owner id it shows to the relay's
|
||||
`--owners`; a foreground service seals and uploads with a progress notification, and
|
||||
the finished notification plays the file or shares its link. Several files shared at
|
||||
once become one album (`uploader.uploadAlbum(Album(title, grants))`), which the player
|
||||
shows as a list. Android 15 limits
|
||||
`dataSync` foreground services to 6 hours a day, which is a lot of film; a killed
|
||||
upload resumes when the service starts again.
|
||||
|
||||
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`), owner signatures and encoded grants included.
|
||||
- `bun run scripts/media-live-kotlin.ts`: the Kotlin uploader against a real TS relay,
|
||||
with a lost answer and a refused piece injected; TS reads the 40 MiB film back
|
||||
byte for byte (`MediaLiveTest`, skipped without the driver). The same run kills an
|
||||
upload job after its first piece and resumes it, and uploads a video shared by its
|
||||
`content://` URI under Robolectric (`ShadeUploadTest`).
|
||||
- `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 |
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/cli",
|
||||
"version": "4.14.1",
|
||||
"version": "4.15.0",
|
||||
"type": "module",
|
||||
"main": "src/cli.ts",
|
||||
"bin": {
|
||||
@@ -10,8 +10,10 @@
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/crypto-web": "workspace:*",
|
||||
"@shade/keychain": "workspace:*",
|
||||
"@shade/media": "workspace:*",
|
||||
"@shade/sdk": "workspace:*",
|
||||
"@shade/storage-encrypted": "workspace:*",
|
||||
"@shade/storage-postgres": "workspace:*",
|
||||
"@shade/storage-sqlite": "workspace:*",
|
||||
"@shade/transport": "workspace:*"
|
||||
},
|
||||
|
||||
@@ -56,6 +56,8 @@ Commands:
|
||||
rotate-storage-key Re-key the encrypted SQLite store (V3.2)
|
||||
--key-source / --passphrase / … (current key — same flags as migrate)
|
||||
--new-key-source / --new-passphrase / … (target key)
|
||||
media … / live … E2E-encrypted streaming of films, video, images, audio and logs
|
||||
(run \`shade media\` or \`shade live\` for the subcommands)
|
||||
help Show this message
|
||||
|
||||
Config:
|
||||
@@ -127,6 +129,15 @@ async function main(): Promise<void> {
|
||||
await rotateStorageKeyCommand(opts);
|
||||
break;
|
||||
}
|
||||
case 'media':
|
||||
case 'live': {
|
||||
const { runMediaCli } = await import('@shade/media/cli');
|
||||
process.exitCode = await runMediaCli(cmd, args.slice(1), {
|
||||
// Loaded only by `media serve --s3 … --pg …`.
|
||||
sharedBackend: async (o) => (await import('@shade/storage-postgres')).createSharedMediaBackend(o),
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'help':
|
||||
case '--help':
|
||||
case '-h':
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/core",
|
||||
"version": "4.14.1",
|
||||
"version": "4.15.0",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/crypto-web",
|
||||
"version": "4.14.1",
|
||||
"version": "4.15.0",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/dashboard",
|
||||
"version": "4.14.1",
|
||||
"version": "4.15.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/files",
|
||||
"version": "4.14.1",
|
||||
"version": "4.15.0",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/inbox-server",
|
||||
"version": "4.14.1",
|
||||
"version": "4.15.0",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/inbox",
|
||||
"version": "4.14.1",
|
||||
"version": "4.15.0",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/key-transparency",
|
||||
"version": "4.14.1",
|
||||
"version": "4.15.0",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/keychain",
|
||||
"version": "4.14.1",
|
||||
"version": "4.15.0",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
27
packages/shade-media/package.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "@shade/media",
|
||||
"version": "4.15.1",
|
||||
"description": "End-to-end encrypted media streaming for Shade — seekable sealed films, videos, images and audio, and live channels for logs, text and live video",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./node": "./src/node.ts",
|
||||
"./server": "./src/server.ts",
|
||||
"./browser": "./src/browser/index.ts",
|
||||
"./worker": "./src/browser/worker.ts",
|
||||
"./cli": "./src/cli.ts",
|
||||
"./testing": "./src/testing.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.0.1",
|
||||
"@noble/hashes": "^2.0.1",
|
||||
"hono": "^4.12.18"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "bun test",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"build:sw": "bun build src/browser/sw.ts --outfile dist/shade-media-sw.js --target browser --minify"
|
||||
}
|
||||
}
|
||||
83
packages/shade-media/src/aead.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* AES-256-GCM with a caller-supplied nonce.
|
||||
*
|
||||
* `CryptoProvider.aesGcmEncrypt` draws a random nonce, which is right for
|
||||
* objects sealed one at a time. A sealed film is not: segment `i` must be
|
||||
* decryptable from its index alone, so a reader can seek to it without a
|
||||
* per-segment nonce table. That is safe because every key used here is
|
||||
* unique to one file (or one live frame) and every nonce is unique under it.
|
||||
*
|
||||
* Imported keys are cached: importing per segment is a measurable share of
|
||||
* the cost of playing a film.
|
||||
*/
|
||||
|
||||
import { bs } from './bytes.js';
|
||||
import { MediaIntegrityError } from './errors.js';
|
||||
|
||||
export const NONCE_BYTES = 12;
|
||||
export const TAG_BYTES = 16;
|
||||
|
||||
export class AeadKey {
|
||||
private keyPromise: Promise<CryptoKey> | null;
|
||||
|
||||
constructor(raw: Uint8Array) {
|
||||
if (raw.length !== 32) throw new Error('AES-256-GCM key must be 32 bytes');
|
||||
this.keyPromise = globalThis.crypto.subtle.importKey('raw', bs(raw), 'AES-GCM', false, [
|
||||
'encrypt',
|
||||
'decrypt',
|
||||
]);
|
||||
}
|
||||
|
||||
private key(): Promise<CryptoKey> {
|
||||
if (this.keyPromise === null) throw new Error('AeadKey used after destroy()');
|
||||
return this.keyPromise;
|
||||
}
|
||||
|
||||
async seal(nonce: Uint8Array, plaintext: Uint8Array, aad: Uint8Array): Promise<Uint8Array> {
|
||||
if (nonce.length !== NONCE_BYTES) throw new Error('nonce must be 12 bytes');
|
||||
const out = await globalThis.crypto.subtle.encrypt(
|
||||
{ name: 'AES-GCM', iv: bs(nonce), additionalData: bs(aad) },
|
||||
await this.key(),
|
||||
bs(plaintext),
|
||||
);
|
||||
return new Uint8Array(out);
|
||||
}
|
||||
|
||||
async open(nonce: Uint8Array, ciphertext: Uint8Array, aad: Uint8Array): Promise<Uint8Array> {
|
||||
if (nonce.length !== NONCE_BYTES) throw new Error('nonce must be 12 bytes');
|
||||
try {
|
||||
const out = await globalThis.crypto.subtle.decrypt(
|
||||
{ name: 'AES-GCM', iv: bs(nonce), additionalData: bs(aad) },
|
||||
await this.key(),
|
||||
bs(ciphertext),
|
||||
);
|
||||
return new Uint8Array(out);
|
||||
} catch {
|
||||
throw new MediaIntegrityError('AEAD authentication failed');
|
||||
}
|
||||
}
|
||||
|
||||
/** Drop the reference; a non-extractable CryptoKey cannot be zeroed further. */
|
||||
destroy(): void {
|
||||
this.keyPromise = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** One-shot open/seal for keys used exactly once (live frame keys). */
|
||||
export async function sealOnce(
|
||||
key: Uint8Array,
|
||||
nonce: Uint8Array,
|
||||
plaintext: Uint8Array,
|
||||
aad: Uint8Array,
|
||||
): Promise<Uint8Array> {
|
||||
return new AeadKey(key).seal(nonce, plaintext, aad);
|
||||
}
|
||||
|
||||
export async function openOnce(
|
||||
key: Uint8Array,
|
||||
nonce: Uint8Array,
|
||||
ciphertext: Uint8Array,
|
||||
aad: Uint8Array,
|
||||
): Promise<Uint8Array> {
|
||||
return new AeadKey(key).open(nonce, ciphertext, aad);
|
||||
}
|
||||
91
packages/shade-media/src/album.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* Albums: one link for many files.
|
||||
*
|
||||
* A season of a series, a photo album, a playlist, a wall of cameras. An
|
||||
* album is itself a sealed file (SMF1) whose plaintext is a list of grants,
|
||||
* with the MIME type `application/vnd.shade.album+json`. So:
|
||||
*
|
||||
* - one capability link opens every item, and nothing else;
|
||||
* - the relay stores it like any other object: it cannot tell an album
|
||||
* from a film, let alone count or name what is in it;
|
||||
* - an album may hold live grants (a camera wall) and other albums.
|
||||
*
|
||||
* Holding an album means holding every item's keys. Deleting the album
|
||||
* object does not revoke them from anyone who already opened it — delete
|
||||
* the items to do that.
|
||||
*/
|
||||
|
||||
import { MediaFormatError } from './errors.js';
|
||||
import { encodeGrant, parseGrant } from './grant.js';
|
||||
import type { Grant, MediaGrant } from './grant.js';
|
||||
import type { MediaMeta } from './sealed.js';
|
||||
|
||||
export const ALBUM_KIND = 'shade.album/v1';
|
||||
export const ALBUM_MIME = 'application/vnd.shade.album+json';
|
||||
|
||||
/** Enough for any season or camera roll, small enough to parse without thought. */
|
||||
export const MAX_ALBUM_ITEMS = 10_000;
|
||||
const MAX_TITLE = 512;
|
||||
|
||||
export interface Album {
|
||||
title: string;
|
||||
items: Grant[];
|
||||
}
|
||||
|
||||
const enc = new TextEncoder();
|
||||
const dec = new TextDecoder('utf-8', { fatal: true });
|
||||
|
||||
export function encodeAlbum(album: Album): Uint8Array {
|
||||
checkTitle(album.title);
|
||||
if (album.items.length > MAX_ALBUM_ITEMS) throw new MediaFormatError(`album holds more than ${MAX_ALBUM_ITEMS} items`);
|
||||
// Grants are embedded as objects, each in its own wire form.
|
||||
const items = album.items.map((g) => JSON.parse(encodeGrant(g)) as unknown);
|
||||
return enc.encode(JSON.stringify({ kind: ALBUM_KIND, title: album.title, items }));
|
||||
}
|
||||
|
||||
/** Parse an album's plaintext, strictly: every item must be a valid grant. */
|
||||
export function parseAlbum(bytes: Uint8Array): Album {
|
||||
let o: unknown;
|
||||
try {
|
||||
o = JSON.parse(dec.decode(bytes));
|
||||
} catch {
|
||||
throw new MediaFormatError('album is not UTF-8 JSON');
|
||||
}
|
||||
if (typeof o !== 'object' || o === null || Array.isArray(o)) throw new MediaFormatError('album must be an object');
|
||||
const r = o as Record<string, unknown>;
|
||||
if (r.kind !== ALBUM_KIND) throw new MediaFormatError(`not an album (kind ${String(r.kind)})`);
|
||||
if (typeof r.title !== 'string') throw new MediaFormatError('album.title must be a string');
|
||||
checkTitle(r.title);
|
||||
if (!Array.isArray(r.items)) throw new MediaFormatError('album.items must be an array');
|
||||
if (r.items.length > MAX_ALBUM_ITEMS) throw new MediaFormatError(`album holds more than ${MAX_ALBUM_ITEMS} items`);
|
||||
const items = r.items.map((it, i) => {
|
||||
if (typeof it !== 'object' || it === null || Array.isArray(it)) throw new MediaFormatError(`album item ${i} is not a grant`);
|
||||
try {
|
||||
return parseGrant(JSON.stringify(it));
|
||||
} catch (e) {
|
||||
throw new MediaFormatError(`album item ${i}: ${(e as Error).message}`);
|
||||
}
|
||||
});
|
||||
return { title: r.title, items };
|
||||
}
|
||||
|
||||
/** Does this grant (by its meta preview) or this sealed meta name an album? */
|
||||
export function isAlbum(x: Grant | MediaMeta | undefined): boolean {
|
||||
if (x === undefined) return false;
|
||||
const meta = 'kind' in x ? x.meta : x;
|
||||
return meta?.mime === ALBUM_MIME;
|
||||
}
|
||||
|
||||
/** The meta an album's sealed file carries. */
|
||||
export function albumMeta(title: string): MediaMeta {
|
||||
return { mime: ALBUM_MIME, name: title };
|
||||
}
|
||||
|
||||
/** Narrow for callers that only take sealed files. */
|
||||
export function isMediaGrant(g: Grant): g is MediaGrant {
|
||||
return g.kind === 'shade.media-grant/v1';
|
||||
}
|
||||
|
||||
function checkTitle(t: string): void {
|
||||
if (t.length > MAX_TITLE) throw new MediaFormatError(`album title longer than ${MAX_TITLE} characters`);
|
||||
}
|
||||
64
packages/shade-media/src/browser/index.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* Page-side helpers: hand grants to the Service Worker, and play live
|
||||
* channels through Media Source Extensions.
|
||||
*/
|
||||
|
||||
import { encodeGrant } from '../grant.js';
|
||||
import type { MediaGrant } from '../grant.js';
|
||||
import { toHex } from '../bytes.js';
|
||||
|
||||
export { LivePlayer } from './player.js';
|
||||
export type { LivePlayerOptions, LivePlayerStats } from './player.js';
|
||||
|
||||
/**
|
||||
* Register the media worker and wait until it controls this page. `scope`
|
||||
* is the directory the virtual `media/<id>` URLs live under.
|
||||
*/
|
||||
export async function installMediaWorker(swUrl: string, scope?: string): Promise<MediaKeyring> {
|
||||
if (!('serviceWorker' in navigator)) throw new Error('this browser has no Service Workers');
|
||||
const reg = await navigator.serviceWorker.register(swUrl, scope !== undefined ? { scope } : {});
|
||||
await navigator.serviceWorker.ready;
|
||||
if (navigator.serviceWorker.controller === null) {
|
||||
// First visit: the worker claims the page on activate.
|
||||
await new Promise<void>((resolve) =>
|
||||
navigator.serviceWorker.addEventListener('controllerchange', () => resolve(), { once: true }),
|
||||
);
|
||||
}
|
||||
return new MediaKeyring(reg.scope);
|
||||
}
|
||||
|
||||
/**
|
||||
* The page's copy of its grants. The worker can be stopped by the browser at
|
||||
* any time and loses its memory; it then asks the page, and this answers.
|
||||
*/
|
||||
export class MediaKeyring {
|
||||
private readonly grants = new Map<string, string>();
|
||||
|
||||
constructor(readonly scope: string) {
|
||||
navigator.serviceWorker.addEventListener('message', (e) => {
|
||||
const msg = e.data as { type?: string; id?: string } | null;
|
||||
if (msg?.type !== 'shade-media-need' || typeof msg.id !== 'string') return;
|
||||
e.ports[0]?.postMessage(this.grants.get(msg.id) ?? null);
|
||||
});
|
||||
}
|
||||
|
||||
/** Register a grant with the worker; returns the URL to put in `src`. */
|
||||
async add(grant: MediaGrant): Promise<string> {
|
||||
const id = toHex(grant.mediaId);
|
||||
const json = encodeGrant(grant);
|
||||
this.grants.set(id, json);
|
||||
const sw = navigator.serviceWorker.controller;
|
||||
if (sw === null) throw new Error('media worker is not controlling this page');
|
||||
const res = await new Promise<{ ok: boolean; error?: string }>((resolve) => {
|
||||
const ch = new MessageChannel();
|
||||
ch.port1.onmessage = (m) => resolve(m.data);
|
||||
sw.postMessage({ type: 'shade-media-grant', grant: json }, [ch.port2]);
|
||||
});
|
||||
if (!res.ok) throw new Error(res.error ?? 'worker refused the grant');
|
||||
return this.urlFor(grant);
|
||||
}
|
||||
|
||||
urlFor(grant: MediaGrant): string {
|
||||
return new URL(`media/${toHex(grant.mediaId)}`, this.scope).toString();
|
||||
}
|
||||
}
|
||||
186
packages/shade-media/src/browser/player.ts
Normal file
@@ -0,0 +1,186 @@
|
||||
/**
|
||||
* Live video/audio in a `<video>` element via Media Source Extensions.
|
||||
*
|
||||
* Frames come from a `LiveWatchClient`; this turns them into SourceBuffer
|
||||
* appends. The rules that make live MSE work:
|
||||
*
|
||||
* - the sticky `init` frame creates the SourceBuffer (its MIME names the
|
||||
* codecs) and is appended first; the same init again is skipped;
|
||||
* - media `chunk`s are dropped until the first keyframe — a decoder cannot
|
||||
* start mid-GOP — and again after any gap, until the next keyframe;
|
||||
* - a viewer that joins late has timestamps that start at, say, 37 s: the
|
||||
* playhead is moved to the start of what is buffered;
|
||||
* - the playhead is kept close to the live edge, and old media is evicted
|
||||
* so the buffer does not hit the browser's quota.
|
||||
*/
|
||||
|
||||
import { LiveWatchClient } from '../live/client.js';
|
||||
import type { LiveState } from '../live/client.js';
|
||||
import type { ReceivedFrame } from '../live/channel.js';
|
||||
import type { LiveGrant } from '../grant.js';
|
||||
import { equalBytes } from '../bytes.js';
|
||||
|
||||
export interface LivePlayerOptions {
|
||||
/** Jump forward when further than this behind the live edge. Default 4 s. */
|
||||
maxLatencySeconds?: number;
|
||||
/** Media kept behind the playhead. Default 30 s. */
|
||||
keepSeconds?: number;
|
||||
onState?: (s: LiveState) => void;
|
||||
onError?: (e: Error) => void;
|
||||
/** Non-media frames (text, images, meta) on the same channel. */
|
||||
onOther?: (f: ReceivedFrame) => void;
|
||||
}
|
||||
|
||||
export interface LivePlayerStats {
|
||||
trail: string[];
|
||||
framesIn: number;
|
||||
/** Times a frame was missing in the sequence (relay dropped it for a slow viewer). */
|
||||
gaps: number;
|
||||
appended: number;
|
||||
droppedBeforeKeyframe: number;
|
||||
bufferedSeconds: number;
|
||||
latencySeconds: number;
|
||||
}
|
||||
|
||||
export class LivePlayer {
|
||||
readonly client: LiveWatchClient;
|
||||
private readonly ms = new MediaSource();
|
||||
private sb: SourceBuffer | null = null;
|
||||
private lastInit: Uint8Array | null = null;
|
||||
private queue: Uint8Array[] = [];
|
||||
private needKeyframe = true;
|
||||
private lastSeq = -1;
|
||||
private lastEpoch = -1;
|
||||
private readonly sourceOpen: Promise<void>;
|
||||
private readonly stat = { framesIn: 0, appended: 0, droppedBeforeKeyframe: 0, gaps: 0 };
|
||||
/** Last few frames handled, for diagnosing a player that stalls. */
|
||||
private readonly trail: string[] = [];
|
||||
|
||||
constructor(
|
||||
private readonly video: HTMLMediaElement,
|
||||
grant: LiveGrant,
|
||||
private readonly opts: LivePlayerOptions = {},
|
||||
) {
|
||||
this.sourceOpen = new Promise((r) => this.ms.addEventListener('sourceopen', () => r(), { once: true }));
|
||||
video.src = URL.createObjectURL(this.ms);
|
||||
this.client = new LiveWatchClient(grant, {
|
||||
onFrame: (f) => this.onFrame(f),
|
||||
...(opts.onState !== undefined ? { onState: opts.onState } : {}),
|
||||
...(opts.onError !== undefined ? { onError: opts.onError } : {}),
|
||||
});
|
||||
setInterval(() => this.housekeeping(), 1000);
|
||||
}
|
||||
|
||||
stats(): LivePlayerStats {
|
||||
const b = this.video.buffered;
|
||||
const end = b.length > 0 ? b.end(b.length - 1) : 0;
|
||||
return {
|
||||
...this.stat,
|
||||
trail: [...this.trail],
|
||||
bufferedSeconds: b.length > 0 ? end - b.start(0) : 0,
|
||||
latencySeconds: Math.max(0, end - this.video.currentTime),
|
||||
};
|
||||
}
|
||||
|
||||
private async onFrame(f: ReceivedFrame): Promise<void> {
|
||||
this.stat.framesIn++;
|
||||
this.trail.push(`${f.epoch}/${f.seq}${f.keyframe ? '*' : ''}${f.sticky ? 's' : ''}:${f.content.type}`);
|
||||
if (this.trail.length > 16) this.trail.shift();
|
||||
// Every frame takes a seq, whatever it carries, so a gap is a frame lost
|
||||
// (dropped by a relay for a slow viewer) — and that breaks the GOP.
|
||||
// Sticky frames are replayed out of their chain position (a late joiner
|
||||
// gets seq 0 then seq 119), so they do not count.
|
||||
if (!f.sticky) {
|
||||
if (f.epoch === this.lastEpoch && f.seq !== this.lastSeq + 1) {
|
||||
this.stat.gaps++;
|
||||
this.needKeyframe = true;
|
||||
}
|
||||
this.lastEpoch = f.epoch;
|
||||
this.lastSeq = f.seq;
|
||||
}
|
||||
const c = f.content;
|
||||
if (c.type === 'init') {
|
||||
await this.sourceOpen;
|
||||
if (this.lastInit !== null && equalBytes(this.lastInit, c.bytes)) return;
|
||||
if (this.sb === null) {
|
||||
if (!MediaSource.isTypeSupported(c.mime)) {
|
||||
this.opts.onError?.(new Error(`this browser cannot play ${c.mime}`));
|
||||
return;
|
||||
}
|
||||
this.sb = this.ms.addSourceBuffer(c.mime);
|
||||
this.sb.mode = 'segments';
|
||||
this.sb.addEventListener('updateend', () => this.pump());
|
||||
}
|
||||
this.lastInit = c.bytes.slice();
|
||||
this.enqueue(c.bytes);
|
||||
this.needKeyframe = true;
|
||||
return;
|
||||
}
|
||||
if (c.type !== 'chunk') {
|
||||
this.opts.onOther?.(f);
|
||||
return;
|
||||
}
|
||||
if (this.sb === null || (this.needKeyframe && !f.keyframe)) {
|
||||
this.stat.droppedBeforeKeyframe++;
|
||||
return;
|
||||
}
|
||||
this.needKeyframe = false;
|
||||
this.enqueue(c.bytes);
|
||||
}
|
||||
|
||||
private enqueue(b: Uint8Array): void {
|
||||
this.queue.push(b);
|
||||
this.pump();
|
||||
}
|
||||
|
||||
private pump(): void {
|
||||
const sb = this.sb;
|
||||
if (sb === null || sb.updating || this.queue.length === 0) return;
|
||||
const next = this.queue.shift()!;
|
||||
try {
|
||||
sb.appendBuffer(next as Uint8Array<ArrayBuffer>);
|
||||
this.stat.appended++;
|
||||
} catch (e) {
|
||||
if ((e as DOMException).name === 'QuotaExceededError') {
|
||||
this.queue.unshift(next);
|
||||
this.evict(5);
|
||||
} else {
|
||||
this.opts.onError?.(e as Error);
|
||||
}
|
||||
}
|
||||
this.seekIntoBuffer();
|
||||
}
|
||||
|
||||
private seekIntoBuffer(): void {
|
||||
const b = this.video.buffered;
|
||||
if (b.length === 0) return;
|
||||
const start = b.start(0);
|
||||
const end = b.end(b.length - 1);
|
||||
const t = this.video.currentTime;
|
||||
if (t < start || t > end) this.video.currentTime = start;
|
||||
if (this.video.paused) void this.video.play().catch(() => {});
|
||||
}
|
||||
|
||||
private evict(extra = 0): void {
|
||||
const sb = this.sb;
|
||||
const b = this.video.buffered;
|
||||
if (sb === null || sb.updating || b.length === 0) return;
|
||||
const keep = this.opts.keepSeconds ?? 30;
|
||||
const cut = this.video.currentTime - keep + extra;
|
||||
if (cut > b.start(0) + 1) sb.remove(b.start(0), cut);
|
||||
}
|
||||
|
||||
private housekeeping(): void {
|
||||
const b = this.video.buffered;
|
||||
if (b.length === 0) return;
|
||||
const end = b.end(b.length - 1);
|
||||
const max = this.opts.maxLatencySeconds ?? 4;
|
||||
if (end - this.video.currentTime > max) this.video.currentTime = Math.max(b.start(b.length - 1), end - 1);
|
||||
this.evict();
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.client.close();
|
||||
if (this.ms.readyState === 'open') this.ms.endOfStream();
|
||||
}
|
||||
}
|
||||
20
packages/shade-media/src/browser/range.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
/** Single `bytes=` range against `size` — shared by the routes and the Service Worker. */
|
||||
export function parseRange(
|
||||
header: string | null | undefined,
|
||||
size: number,
|
||||
): { start: number; end: number } | 'invalid' | null {
|
||||
if (header === null || header === undefined) return null;
|
||||
const m = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
|
||||
if (m === null) return 'invalid';
|
||||
const [, a, b] = m;
|
||||
if (a === '' && b === '') return 'invalid';
|
||||
if (a === '') {
|
||||
const n = Number(b);
|
||||
if (n === 0 || size === 0) return 'invalid';
|
||||
return { start: Math.max(0, size - n), end: size };
|
||||
}
|
||||
const start = Number(a);
|
||||
const end = b === '' ? size : Math.min(size, Number(b) + 1);
|
||||
if (start >= size || end <= start) return 'invalid';
|
||||
return { start, end };
|
||||
}
|
||||
25
packages/shade-media/src/browser/sw.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Service Worker: makes a sealed file look like a normal one to the browser.
|
||||
*
|
||||
* The page points `<video src>` (or `<audio>`, `<img>`, a download link) at
|
||||
* `<scope>media/<mediaId>`. This worker answers those requests itself —
|
||||
* Range requests included, so seeking works — by fetching only the sealed
|
||||
* segments under the requested range from wherever the grant says the file
|
||||
* lives, verifying and decrypting them, and streaming the plaintext back.
|
||||
*
|
||||
* Keys live in this worker's memory only. A worker the browser stopped
|
||||
* forgets them; it then asks the page (which still holds the grant) again.
|
||||
*/
|
||||
|
||||
|
||||
import { installShadeMedia } from './worker.js';
|
||||
import type { WorkerScope } from './worker.js';
|
||||
|
||||
declare const self: WorkerScope;
|
||||
|
||||
// Standalone: this worker owns its scope and takes over open pages at once.
|
||||
self.addEventListener('install', () => {
|
||||
void self.skipWaiting();
|
||||
});
|
||||
self.addEventListener('activate', (e) => e.waitUntil(self.clients.claim()));
|
||||
installShadeMedia(self);
|
||||
392
packages/shade-media/src/browser/watch-app.ts
Normal file
@@ -0,0 +1,392 @@
|
||||
/**
|
||||
* The watch page: open a capability link, play what it grants.
|
||||
*
|
||||
* /watch/#shade=<grant>
|
||||
*
|
||||
* A sealed file plays through the Service Worker in a native element —
|
||||
* `<video>`, `<audio>`, `<img>` or a text view — with seeking. A live
|
||||
* channel plays through MSE (video/audio) or as a scrolling log (text),
|
||||
* with images replacing each other in place. An album shows its items as a
|
||||
* grid; opening one pushes a view, and Back returns to the album.
|
||||
*
|
||||
* The grant never leaves the browser: it is in the fragment, which is not
|
||||
* sent to the server, and the page drops it from the address bar once read.
|
||||
*/
|
||||
|
||||
import { ALBUM_MIME, parseAlbum } from '../album.js';
|
||||
import type { Album } from '../album.js';
|
||||
import { fromB64u } from '../bytes.js';
|
||||
import { fromCapabilityUrl } from '../grant.js';
|
||||
import type { Grant, LiveGrant, MediaGrant } from '../grant.js';
|
||||
import { LiveWatchClient } from '../live/client.js';
|
||||
import type { ReceivedFrame } from '../live/channel.js';
|
||||
import { installMediaWorker } from './index.js';
|
||||
import type { MediaKeyring } from './index.js';
|
||||
import { LivePlayer } from './player.js';
|
||||
import { srtToVtt, subtitlesOf } from '../subtitles.js';
|
||||
import type { SubtitleTrack } from '../subtitles.js';
|
||||
import type { MediaMeta } from '../sealed.js';
|
||||
|
||||
interface Stats {
|
||||
kind: 'media' | 'live' | 'album' | 'none';
|
||||
items?: number;
|
||||
subtitles?: string[];
|
||||
state: string;
|
||||
mime?: string;
|
||||
frames: number;
|
||||
lines: number;
|
||||
images: number;
|
||||
error?: string;
|
||||
player?: () => unknown;
|
||||
}
|
||||
|
||||
const stats: Stats = { kind: 'none', state: 'starting', frames: 0, lines: 0, images: 0 };
|
||||
(globalThis as unknown as { __shade: Stats }).__shade = stats;
|
||||
|
||||
const $ = <T extends HTMLElement>(sel: string) => document.querySelector(sel) as T;
|
||||
|
||||
function setStatus(text: string, tone: 'ok' | 'warn' | 'bad' = 'ok'): void {
|
||||
stats.state = text;
|
||||
const el = $('#status');
|
||||
el.textContent = text;
|
||||
el.dataset.tone = tone;
|
||||
}
|
||||
|
||||
function fail(message: string): void {
|
||||
stats.error = message;
|
||||
setStatus(message, 'bad');
|
||||
}
|
||||
|
||||
function human(n: number): string {
|
||||
const u = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
let i = 0;
|
||||
while (n >= 1024 && i < u.length - 1) {
|
||||
n /= 1024;
|
||||
i++;
|
||||
}
|
||||
return `${n.toFixed(i === 0 ? 0 : 1)} ${u[i]}`;
|
||||
}
|
||||
|
||||
// ─── Views ──────────────────────────────────────────────────────
|
||||
//
|
||||
// A stack of views mirrored in the history, so Back leaves an item for its
|
||||
// album. History entries hold only the depth: the grants stay in memory.
|
||||
|
||||
type View = () => Promise<void> | void;
|
||||
const views: View[] = [];
|
||||
let cleanups: (() => void)[] = [];
|
||||
|
||||
function reset(): void {
|
||||
for (const c of cleanups) c();
|
||||
cleanups = [];
|
||||
const stage = $('#stage');
|
||||
for (const m of stage.querySelectorAll('video, audio')) (m as HTMLMediaElement).pause();
|
||||
stage.replaceChildren();
|
||||
stage.className = '';
|
||||
$('#actions').replaceChildren();
|
||||
$('#sub').textContent = '';
|
||||
Object.assign(stats, { kind: 'none', state: 'starting', frames: 0, lines: 0, images: 0 });
|
||||
delete stats.error;
|
||||
delete stats.player;
|
||||
delete stats.items;
|
||||
delete stats.subtitles;
|
||||
}
|
||||
|
||||
async function render(view: View): Promise<void> {
|
||||
reset();
|
||||
if (views.length > 1) {
|
||||
const back = document.createElement('a');
|
||||
back.href = '#';
|
||||
back.id = 'back';
|
||||
back.textContent = '← Back';
|
||||
back.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
history.back();
|
||||
});
|
||||
$('#actions').append(back);
|
||||
}
|
||||
try {
|
||||
await view();
|
||||
} catch (e) {
|
||||
fail(String((e as Error)?.message ?? e));
|
||||
}
|
||||
}
|
||||
|
||||
function push(view: View): Promise<void> {
|
||||
views.push(view);
|
||||
history.pushState({ depth: views.length - 1 }, '');
|
||||
return render(view);
|
||||
}
|
||||
|
||||
window.addEventListener('popstate', (e: PopStateEvent) => {
|
||||
const depth = Math.min((e.state as { depth?: number } | null)?.depth ?? 0, views.length - 1);
|
||||
views.length = depth + 1;
|
||||
void render(views[depth]!);
|
||||
});
|
||||
|
||||
let keyring: Promise<MediaKeyring> | null = null;
|
||||
function ring(): Promise<MediaKeyring> {
|
||||
keyring ??= installMediaWorker(new URL('sw.js', location.href).pathname, new URL('./', location.href).pathname);
|
||||
return keyring;
|
||||
}
|
||||
|
||||
async function open(g: Grant): Promise<void> {
|
||||
if (g.kind === 'shade.media-grant/v1') await playMedia(g);
|
||||
else playLive(g);
|
||||
}
|
||||
|
||||
async function playMedia(g: MediaGrant): Promise<void> {
|
||||
stats.kind = 'media';
|
||||
setStatus('starting the decryption worker…');
|
||||
const src = await (await ring()).add(g);
|
||||
const head = await fetch(src, { method: 'HEAD' });
|
||||
if (!head.ok) return fail(`could not open: ${head.status} ${await head.text()}`);
|
||||
const mime = head.headers.get('content-type') ?? 'application/octet-stream';
|
||||
const size = Number(head.headers.get('content-length'));
|
||||
stats.mime = mime;
|
||||
if (mime === ALBUM_MIME) return showAlbum(parseAlbum(new Uint8Array(await (await fetch(src)).arrayBuffer())));
|
||||
const name = decodeURIComponent(/filename\*=UTF-8''([^;]+)/.exec(head.headers.get('content-disposition') ?? '')?.[1] ?? '');
|
||||
$('#title').textContent = g.meta?.name ?? (name || 'Sealed media');
|
||||
$('#sub').textContent = `${mime} · ${human(size)} · end-to-end encrypted`;
|
||||
const stage = $('#stage');
|
||||
if (mime.startsWith('video/') || mime.startsWith('audio/')) {
|
||||
const el = document.createElement(mime.startsWith('video/') ? 'video' : 'audio');
|
||||
el.controls = true;
|
||||
el.autoplay = true;
|
||||
el.muted = true; // autoplay policy; the viewer unmutes
|
||||
el.src = src;
|
||||
el.id = 'player';
|
||||
el.addEventListener('playing', () => setStatus('playing'));
|
||||
el.addEventListener('waiting', () => setStatus('buffering…', 'warn'));
|
||||
el.addEventListener('error', () => fail(`player error: ${el.error?.message ?? el.error?.code}`));
|
||||
stage.append(el);
|
||||
const metaHeader = head.headers.get('x-shade-meta');
|
||||
if (el instanceof HTMLVideoElement && metaHeader !== null) {
|
||||
const meta = JSON.parse(new TextDecoder().decode(fromB64u(metaHeader))) as MediaMeta;
|
||||
void addSubtitles(el, meta);
|
||||
}
|
||||
} else if (mime.startsWith('image/')) {
|
||||
const img = document.createElement('img');
|
||||
img.src = src;
|
||||
img.id = 'player';
|
||||
img.addEventListener('load', () => setStatus(`showing ${img.naturalWidth}×${img.naturalHeight}`));
|
||||
img.addEventListener('error', () => fail('image failed to decode'));
|
||||
stage.append(img);
|
||||
} else if (mime.startsWith('text/') || mime === 'application/json') {
|
||||
const pre = document.createElement('pre');
|
||||
pre.id = 'log';
|
||||
pre.textContent = await (await fetch(src)).text();
|
||||
stage.append(pre);
|
||||
setStatus('showing text');
|
||||
} else {
|
||||
setStatus('ready to download');
|
||||
}
|
||||
const a = document.createElement('a');
|
||||
a.href = src;
|
||||
a.download = name || 'download';
|
||||
a.textContent = 'Download decrypted';
|
||||
$('#actions').append(a);
|
||||
}
|
||||
|
||||
/**
|
||||
* The film's subtitle files, decrypted through the worker like the film,
|
||||
* as `<track>`s. One that fails to load is skipped; the film plays on.
|
||||
*/
|
||||
async function addSubtitles(video: HTMLVideoElement, meta: MediaMeta): Promise<void> {
|
||||
let tracks: SubtitleTrack[];
|
||||
try {
|
||||
tracks = subtitlesOf(meta);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (tracks.length === 0) return;
|
||||
const kr = await ring();
|
||||
const names = typeof Intl.DisplayNames === 'function' ? new Intl.DisplayNames([navigator.language], { type: 'language' }) : null;
|
||||
// Macrolanguages: a browser set to Bokmål (nb) should pick a `no` file.
|
||||
const base = (tag: string) => {
|
||||
const l = tag.split('-')[0]!.toLowerCase();
|
||||
return l === 'nb' || l === 'nn' ? 'no' : l;
|
||||
};
|
||||
const want = base(navigator.language);
|
||||
let chosen = false;
|
||||
stats.subtitles = [];
|
||||
for (const t of tracks) {
|
||||
try {
|
||||
const text = await (await fetch(await kr.add(t.grant))).text();
|
||||
const url = URL.createObjectURL(new Blob([srtToVtt(text)], { type: 'text/vtt' }));
|
||||
cleanups.push(() => URL.revokeObjectURL(url));
|
||||
const el = document.createElement('track');
|
||||
el.kind = 'subtitles';
|
||||
el.src = url;
|
||||
if (t.lang !== undefined) el.srclang = t.lang;
|
||||
el.label = t.label ?? (t.lang !== undefined ? (names?.of(t.lang) ?? t.lang) : 'Subtitles');
|
||||
video.append(el);
|
||||
// `default` on a track added after load is not honoured everywhere; say it.
|
||||
if (!chosen && t.lang !== undefined && base(t.lang) === want) {
|
||||
el.default = true;
|
||||
el.track.mode = 'showing';
|
||||
chosen = true;
|
||||
}
|
||||
stats.subtitles.push(el.label);
|
||||
} catch {
|
||||
// A broken subtitle file must not stop the film.
|
||||
}
|
||||
}
|
||||
// One track at a time. Chromium switches on the first track it was given
|
||||
// once it loads, after this has run, so hold the line where it changes:
|
||||
// more than one showing → back to the current choice; exactly one → that
|
||||
// is the viewer's pick from the menu, and becomes the choice.
|
||||
let current: TextTrack | null = [...video.textTracks].find((t) => t.mode === 'showing' && base(t.language) === want) ?? null;
|
||||
if (!chosen) current = null;
|
||||
const enforce = () => {
|
||||
const showing = [...video.textTracks].filter((t) => t.mode === 'showing');
|
||||
if (showing.length === 1) current = showing[0]!;
|
||||
else if (showing.length > 1) for (const t of showing) if (t !== current) t.mode = 'disabled';
|
||||
};
|
||||
video.textTracks.addEventListener('change', enforce);
|
||||
cleanups.push(() => video.textTracks.removeEventListener('change', enforce));
|
||||
enforce();
|
||||
}
|
||||
|
||||
/** What an item is, from its grant's meta preview (before opening it). */
|
||||
function itemKind(g: Grant): string {
|
||||
if (g.kind === 'shade.live-grant/v1') return 'live';
|
||||
const mime = g.meta?.mime ?? '';
|
||||
if (mime === ALBUM_MIME) return 'album';
|
||||
return mime.split('/')[0] || 'file';
|
||||
}
|
||||
|
||||
const ICONS: Record<string, string> = { album: '▦', audio: '♪', text: '≡', live: '●', file: '⬚', video: '▶', image: '◩' };
|
||||
|
||||
async function showAlbum(album: Album): Promise<void> {
|
||||
stats.kind = 'album';
|
||||
stats.items = album.items.length;
|
||||
$('#title').textContent = album.title || 'Album';
|
||||
const counts = new Map<string, number>();
|
||||
for (const it of album.items) counts.set(itemKind(it), (counts.get(itemKind(it)) ?? 0) + 1);
|
||||
$('#sub').textContent = `album · ${[...counts].map(([k, n]) => `${n} ${k}`).join(', ') || 'empty'} · end-to-end encrypted`;
|
||||
const stage = $('#stage');
|
||||
stage.className = 'album';
|
||||
const grid = document.createElement('div');
|
||||
grid.className = 'grid';
|
||||
stage.append(grid);
|
||||
const kr = await ring();
|
||||
for (const [i, item] of album.items.entries()) {
|
||||
const kind = itemKind(item);
|
||||
const card = document.createElement('button');
|
||||
card.className = 'card';
|
||||
card.dataset.kind = kind;
|
||||
const thumb = document.createElement('div');
|
||||
thumb.className = 'thumb';
|
||||
thumb.textContent = ICONS[kind] ?? ICONS.file!;
|
||||
const label = document.createElement('div');
|
||||
label.className = 'name';
|
||||
label.textContent = item.meta?.name ?? `Item ${i + 1}`;
|
||||
const sub = document.createElement('div');
|
||||
sub.className = 'kind';
|
||||
sub.textContent = kind === 'live' ? 'live channel' : kind === 'album' ? 'album' : (item.meta?.mime ?? kind);
|
||||
card.append(thumb, label, sub);
|
||||
card.addEventListener('click', () => void push(() => open(item)));
|
||||
grid.append(card);
|
||||
// Previews decrypt through the worker like the item itself: an image
|
||||
// shows itself, a video its first frame. Fetched only as cards scroll in.
|
||||
if (item.kind === 'shade.media-grant/v1' && (kind === 'image' || kind === 'video')) {
|
||||
const io = new IntersectionObserver(async (entries) => {
|
||||
if (!entries.some((e) => e.isIntersecting)) return;
|
||||
io.disconnect();
|
||||
const src = await kr.add(item);
|
||||
if (kind === 'image') {
|
||||
const img = document.createElement('img');
|
||||
img.alt = '';
|
||||
img.addEventListener('load', () => thumb.replaceChildren(img));
|
||||
img.src = src;
|
||||
} else {
|
||||
const v = document.createElement('video');
|
||||
v.muted = true;
|
||||
v.preload = 'metadata';
|
||||
v.addEventListener('loadeddata', () => thumb.replaceChildren(v));
|
||||
v.src = `${src}#t=1`;
|
||||
}
|
||||
});
|
||||
io.observe(card);
|
||||
cleanups.push(() => io.disconnect());
|
||||
}
|
||||
}
|
||||
setStatus(`${album.items.length} item(s)`);
|
||||
}
|
||||
|
||||
function playLive(g: LiveGrant): void {
|
||||
stats.kind = 'live';
|
||||
$('#title').textContent = g.meta?.name ?? 'Live channel';
|
||||
const mime = g.meta?.mime ?? '';
|
||||
stats.mime = mime;
|
||||
$('#sub').textContent = `live · ${mime || 'text'} · end-to-end encrypted`;
|
||||
const stage = $('#stage');
|
||||
const states = (s: string) => setStatus(s === 'live' ? 'live' : s === 'waiting' ? 'waiting for the publisher…' : s, s === 'live' ? 'ok' : 'warn');
|
||||
const onErr = (e: Error) => {
|
||||
stats.error = e.message;
|
||||
};
|
||||
|
||||
let log: HTMLPreElement | null = null;
|
||||
let img: HTMLImageElement | null = null;
|
||||
const other = (f: ReceivedFrame) => {
|
||||
stats.frames++;
|
||||
const c = f.content;
|
||||
if (c.type === 'text') {
|
||||
if (log === null) {
|
||||
log = document.createElement('pre');
|
||||
log.id = 'log';
|
||||
stage.append(log);
|
||||
}
|
||||
const atBottom = log.scrollTop + log.clientHeight >= log.scrollHeight - 4;
|
||||
log.append(document.createTextNode(c.text));
|
||||
stats.lines += c.text.split('\n').length - 1;
|
||||
// Bound the DOM: a log stream runs for days.
|
||||
while (log.childNodes.length > 5000) log.firstChild!.remove();
|
||||
if (atBottom) log.scrollTop = log.scrollHeight;
|
||||
} else if (c.type === 'image') {
|
||||
if (img === null) {
|
||||
img = document.createElement('img');
|
||||
img.id = 'player';
|
||||
stage.prepend(img);
|
||||
}
|
||||
const old = img.src;
|
||||
img.src = URL.createObjectURL(new Blob([c.bytes as Uint8Array<ArrayBuffer>], { type: c.mime }));
|
||||
if (old.startsWith('blob:')) URL.revokeObjectURL(old);
|
||||
stats.images++;
|
||||
} else if (c.type === 'end') {
|
||||
setStatus('the broadcast has ended', 'warn');
|
||||
}
|
||||
};
|
||||
|
||||
if (mime.startsWith('video/') || mime.startsWith('audio/')) {
|
||||
const el = document.createElement(mime.startsWith('video/') ? 'video' : 'audio');
|
||||
el.controls = true;
|
||||
el.autoplay = true;
|
||||
el.muted = true;
|
||||
el.id = 'player';
|
||||
stage.append(el);
|
||||
const player = new LivePlayer(el, g, { onState: states, onError: onErr, onOther: other });
|
||||
cleanups.push(() => player.close());
|
||||
stats.player = () => ({ ...player.stats(), currentTime: el.currentTime, paused: el.paused, readyState: el.readyState });
|
||||
} else {
|
||||
const client = new LiveWatchClient(g, { onFrame: other, onState: states, onError: onErr });
|
||||
cleanups.push(() => client.close());
|
||||
}
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
let grant;
|
||||
try {
|
||||
grant = fromCapabilityUrl(location.href);
|
||||
} catch (e) {
|
||||
$('#title').textContent = 'Shade';
|
||||
return fail(`no grant in this link — ${(e as Error).message}`);
|
||||
}
|
||||
// Keep the key out of the history and out of anything that reads the URL later.
|
||||
history.replaceState({ depth: 0 }, '', location.pathname + location.search);
|
||||
views.push(() => open(grant));
|
||||
await render(views[0]!);
|
||||
}
|
||||
|
||||
main().catch((e) => fail(String((e as Error)?.message ?? e)));
|
||||
195
packages/shade-media/src/browser/worker.ts
Normal file
@@ -0,0 +1,195 @@
|
||||
/**
|
||||
* The sealed-media half of a Service Worker, for an app that has its own.
|
||||
*
|
||||
* A worker serves the requests of the pages it controls, whatever their URL,
|
||||
* so an installed PWA with a worker at `/` never lets `media/<id>` reach a
|
||||
* second worker registered beside it. The app imports this into its own
|
||||
* worker instead:
|
||||
*
|
||||
* ```ts
|
||||
* import { installShadeMedia, isShadeMediaRequest } from '@shade/media/worker';
|
||||
* installShadeMedia(self);
|
||||
* self.addEventListener('fetch', (e) => {
|
||||
* if (isShadeMediaRequest(e.request)) return; // answered above
|
||||
* // … the app's own caching
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* or routes the requests itself with `shadeMediaResponse(request)`, and
|
||||
* registers its own worker with `installMediaWorker('/app-sw.js')`.
|
||||
*/
|
||||
|
||||
import { parseGrant, mediaKeysOf } from '../grant.js';
|
||||
import type { MediaGrant } from '../grant.js';
|
||||
import { MediaReader } from '../sealed.js';
|
||||
import { HttpRangeSource } from '../source.js';
|
||||
import { READ_TOKEN_HEADER } from '../owner.js';
|
||||
import { toB64u } from '../bytes.js';
|
||||
import { parseRange } from './range.js';
|
||||
|
||||
// The WebWorker lib cannot be combined with DOM in one tsconfig; this is the
|
||||
// small slice of the worker scope we use.
|
||||
export interface FetchEventLike extends Event {
|
||||
request: Request;
|
||||
respondWith(r: Promise<Response> | Response): void;
|
||||
}
|
||||
export interface ExtendableEventLike extends Event {
|
||||
waitUntil(p: Promise<unknown>): void;
|
||||
}
|
||||
export interface ExtendableMessageEventLike extends Event {
|
||||
data: unknown;
|
||||
ports: readonly MessagePort[];
|
||||
}
|
||||
export interface ClientLike {
|
||||
postMessage(msg: unknown, transfer?: Transferable[]): void;
|
||||
}
|
||||
export interface WorkerScope {
|
||||
registration: { scope: string };
|
||||
clients: { claim(): Promise<void>; matchAll(o?: { includeUncontrolled?: boolean }): Promise<ClientLike[]> };
|
||||
skipWaiting(): Promise<void>;
|
||||
addEventListener(type: 'install' | 'activate', cb: (e: ExtendableEventLike) => void): void;
|
||||
addEventListener(type: 'fetch', cb: (e: FetchEventLike) => void): void;
|
||||
addEventListener(type: 'message', cb: (e: ExtendableMessageEventLike) => void): void;
|
||||
}
|
||||
|
||||
let scope: WorkerScope | null = null;
|
||||
function host(): WorkerScope {
|
||||
if (scope === null) throw new Error('installShadeMedia(self) has not been called in this worker');
|
||||
return scope;
|
||||
}
|
||||
|
||||
const grants = new Map<string, MediaGrant>();
|
||||
const readers = new Map<string, Promise<MediaReader>>();
|
||||
|
||||
function hexId(g: MediaGrant): string {
|
||||
let s = '';
|
||||
for (const b of g.mediaId) s += b.toString(16).padStart(2, '0');
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Ask every open page for a grant we lost (the worker was restarted). */
|
||||
async function askPages(id: string): Promise<MediaGrant | null> {
|
||||
const pages = await host().clients.matchAll({ includeUncontrolled: true });
|
||||
const answers = pages.map(
|
||||
(c) =>
|
||||
new Promise<string | null>((resolve) => {
|
||||
const ch = new MessageChannel();
|
||||
const t = setTimeout(() => resolve(null), 3000);
|
||||
ch.port1.onmessage = (m) => {
|
||||
clearTimeout(t);
|
||||
resolve(typeof m.data === 'string' ? m.data : null);
|
||||
};
|
||||
c.postMessage({ type: 'shade-media-need', id }, [ch.port2]);
|
||||
}),
|
||||
);
|
||||
for (const a of await Promise.all(answers)) {
|
||||
if (a === null) continue;
|
||||
try {
|
||||
const g = parseGrant(a);
|
||||
if (g.kind === 'shade.media-grant/v1' && hexId(g) === id) {
|
||||
grants.set(id, g);
|
||||
return g;
|
||||
}
|
||||
} catch {
|
||||
// A page answering garbage is ignored; another may answer properly.
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function readerFor(id: string, g: MediaGrant): Promise<MediaReader> {
|
||||
let r = readers.get(id);
|
||||
if (r === undefined) {
|
||||
if (g.url === undefined) return Promise.reject(new Error('grant has no URL'));
|
||||
const source = new HttpRangeSource(g.url, {
|
||||
...(g.readToken !== undefined ? { headers: { [READ_TOKEN_HEADER]: toB64u(g.readToken) } } : {}),
|
||||
});
|
||||
r = MediaReader.open(source, mediaKeysOf(g), { cacheSegments: 16, maxSegmentsPerFetch: 4 });
|
||||
// A failed open must not be cached: the next request should retry.
|
||||
r.catch(() => readers.delete(id));
|
||||
readers.set(id, r);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
async function serve(req: Request, id: string): Promise<Response> {
|
||||
const g = grants.get(id) ?? (await askPages(id));
|
||||
if (g === null) return new Response('no grant for this media in this browser', { status: 403 });
|
||||
let reader: MediaReader;
|
||||
try {
|
||||
reader = await readerFor(id, g);
|
||||
} catch (e) {
|
||||
return new Response(`cannot open sealed media: ${(e as Error).message}`, { status: 502 });
|
||||
}
|
||||
const size = reader.size;
|
||||
const headers: Record<string, string> = {
|
||||
'content-type': reader.meta.mime ?? g.meta?.mime ?? 'application/octet-stream',
|
||||
'accept-ranges': 'bytes',
|
||||
'cache-control': 'no-store',
|
||||
// The sealed meta, for the page (subtitles, title). Never leaves the
|
||||
// browser: this response is made here, not fetched.
|
||||
'x-shade-meta': toB64u(new TextEncoder().encode(JSON.stringify(reader.meta))),
|
||||
};
|
||||
if (reader.meta.name !== undefined) {
|
||||
headers['content-disposition'] = `inline; filename*=UTF-8''${encodeURIComponent(reader.meta.name)}`;
|
||||
}
|
||||
const range = parseRange(req.headers.get('range'), size);
|
||||
if (range === 'invalid') {
|
||||
return new Response(null, { status: 416, headers: { ...headers, 'content-range': `bytes */${size}` } });
|
||||
}
|
||||
const { start, end } = range ?? { start: 0, end: size };
|
||||
headers['content-length'] = String(end - start);
|
||||
if (range !== null) headers['content-range'] = `bytes ${start}-${end - 1}/${size}`;
|
||||
const body = req.method === 'HEAD' ? null : reader.stream(start, end);
|
||||
return new Response(body, { status: range !== null ? 206 : 200, headers });
|
||||
}
|
||||
|
||||
function mediaId(req: Request): string | null {
|
||||
const url = new URL(req.url);
|
||||
const prefix = new URL('media/', host().registration.scope).pathname;
|
||||
if (!url.pathname.startsWith(prefix)) return null;
|
||||
const id = url.pathname.slice(prefix.length);
|
||||
return /^[0-9a-f]{32}$/.test(id) ? id : null;
|
||||
}
|
||||
|
||||
/** True for the `media/<id>` requests this module answers; an app's own fetch listener skips these. */
|
||||
export function isShadeMediaRequest(req: Request): boolean {
|
||||
return mediaId(req) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The decrypted response for a request under `<scope>media/<id>`, or null
|
||||
* when the request is not one of ours and the app should handle it.
|
||||
*/
|
||||
export function shadeMediaResponse(req: Request): Promise<Response> | null {
|
||||
const id = mediaId(req);
|
||||
return id === null ? null : serve(req, id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Take grants from the pages and answer `media/<id>` requests in this
|
||||
* worker. Call once. An app with its own fetch listener returns early for
|
||||
* `isShadeMediaRequest(e.request)` (a request answered twice is an error),
|
||||
* or passes `{ fetch: false }` and calls `shadeMediaResponse` itself.
|
||||
*/
|
||||
export function installShadeMedia(self: WorkerScope, opts: { fetch?: boolean } = {}): void {
|
||||
if (scope !== null) return;
|
||||
scope = self;
|
||||
self.addEventListener('message', (e) => {
|
||||
const msg = e.data as { type?: string; grant?: string } | null;
|
||||
if (msg?.type !== 'shade-media-grant' || typeof msg.grant !== 'string') return;
|
||||
try {
|
||||
const g = parseGrant(msg.grant);
|
||||
if (g.kind !== 'shade.media-grant/v1') throw new Error('not a media grant');
|
||||
grants.set(hexId(g), g);
|
||||
e.ports[0]?.postMessage({ ok: true, id: hexId(g) });
|
||||
} catch (err) {
|
||||
e.ports[0]?.postMessage({ ok: false, error: String((err as Error).message) });
|
||||
}
|
||||
});
|
||||
if (opts.fetch === false) return;
|
||||
self.addEventListener('fetch', (e) => {
|
||||
const res = shadeMediaResponse(e.request);
|
||||
if (res !== null) e.respondWith(res);
|
||||
});
|
||||
}
|
||||
103
packages/shade-media/src/bytes.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* Byte helpers shared by the sealed-media and live formats.
|
||||
*
|
||||
* Everything here is pure and synchronous so it behaves the same in Bun, a
|
||||
* browser tab and a Service Worker — the three places a media file is read.
|
||||
*/
|
||||
|
||||
import { MediaFormatError } from './errors.js';
|
||||
|
||||
export const enc = new TextEncoder();
|
||||
export const dec = new TextDecoder('utf-8', { fatal: true });
|
||||
|
||||
export function concat(parts: readonly Uint8Array[]): Uint8Array {
|
||||
let total = 0;
|
||||
for (const p of parts) total += p.length;
|
||||
const out = new Uint8Array(total);
|
||||
let off = 0;
|
||||
for (const p of parts) {
|
||||
out.set(p, off);
|
||||
off += p.length;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function u32be(n: number): Uint8Array {
|
||||
const out = new Uint8Array(4);
|
||||
new DataView(out.buffer).setUint32(0, n, false);
|
||||
return out;
|
||||
}
|
||||
|
||||
export function u64be(n: number | bigint): Uint8Array {
|
||||
const out = new Uint8Array(8);
|
||||
new DataView(out.buffer).setBigUint64(0, BigInt(n), false);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Read a u64 that must fit in a JS number (2^53) — sizes and counts do. */
|
||||
export function readU64(view: DataView, offset: number): number {
|
||||
const v = view.getBigUint64(offset, false);
|
||||
if (v > BigInt(Number.MAX_SAFE_INTEGER)) {
|
||||
throw new MediaFormatError('u64 field exceeds 2^53');
|
||||
}
|
||||
return Number(v);
|
||||
}
|
||||
|
||||
export function equalBytes(a: Uint8Array, b: Uint8Array): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
let diff = 0;
|
||||
for (let i = 0; i < a.length; i++) diff |= a[i]! ^ b[i]!;
|
||||
return diff === 0;
|
||||
}
|
||||
|
||||
export function randomBytes(n: number): Uint8Array {
|
||||
const out = new Uint8Array(n);
|
||||
globalThis.crypto.getRandomValues(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
export function toHex(b: Uint8Array): string {
|
||||
let s = '';
|
||||
for (const v of b) s += v.toString(16).padStart(2, '0');
|
||||
return s;
|
||||
}
|
||||
|
||||
export function fromHex(s: string, expectedLen?: number): Uint8Array {
|
||||
if (!/^(?:[0-9a-f]{2})*$/.test(s)) throw new MediaFormatError('not lowercase hex');
|
||||
const out = new Uint8Array(s.length / 2);
|
||||
for (let i = 0; i < out.length; i++) out[i] = parseInt(s.slice(i * 2, i * 2 + 2), 16);
|
||||
if (expectedLen !== undefined && out.length !== expectedLen) {
|
||||
throw new MediaFormatError(`expected ${expectedLen} bytes, got ${out.length}`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** base64url without padding — what grants and capability links carry. */
|
||||
export function toB64u(b: Uint8Array): string {
|
||||
let bin = '';
|
||||
for (let i = 0; i < b.length; i += 0x8000) {
|
||||
bin += String.fromCharCode(...b.subarray(i, i + 0x8000));
|
||||
}
|
||||
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
}
|
||||
|
||||
export function fromB64u(s: string, expectedLen?: number): Uint8Array {
|
||||
if (!/^[A-Za-z0-9_-]*$/.test(s)) throw new MediaFormatError('not base64url');
|
||||
const pad = s.length % 4 === 0 ? '' : '='.repeat(4 - (s.length % 4));
|
||||
const bin = atob(s.replace(/-/g, '+').replace(/_/g, '/') + pad);
|
||||
const out = new Uint8Array(bin.length);
|
||||
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
||||
if (expectedLen !== undefined && out.length !== expectedLen) {
|
||||
throw new MediaFormatError(`expected ${expectedLen} bytes, got ${out.length}`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** SubtleCrypto takes BufferSource; the DOM alias is not worth the lib churn. */
|
||||
export function bs(u: Uint8Array): ArrayBuffer {
|
||||
return u as unknown as ArrayBuffer;
|
||||
}
|
||||
|
||||
export async function sha256(data: Uint8Array): Promise<Uint8Array> {
|
||||
return new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', bs(data)));
|
||||
}
|
||||
1047
packages/shade-media/src/cli.ts
Normal file
337
packages/shade-media/src/client.ts
Normal file
@@ -0,0 +1,337 @@
|
||||
/**
|
||||
* Client for the media routes: upload sealed files, list and delete your
|
||||
* own, and open anything you hold a grant for.
|
||||
*/
|
||||
|
||||
import { ALBUM_MIME, albumMeta, encodeAlbum, parseAlbum } from './album.js';
|
||||
import type { Album } from './album.js';
|
||||
import { randomBytes, sha256, toB64u, toHex } from './bytes.js';
|
||||
import { MediaFormatError } from './errors.js';
|
||||
import { mediaGrantFrom, mediaKeysOf } from './grant.js';
|
||||
import type { MediaGrant } from './grant.js';
|
||||
import { READ_HASH_HEADER, READ_TOKEN_HEADER } from './owner.js';
|
||||
import type { OwnerKey } from './owner.js';
|
||||
import { MediaReader, sealMediaBytes } from './sealed.js';
|
||||
import type { MediaMeta, ReaderOptions, SealOptions, SealResult } from './sealed.js';
|
||||
import { HttpRangeSource } from './source.js';
|
||||
import { DEFAULT_CHUNK_BYTES, MAX_CLIENT_WINDOW, OFFSET_HEADER, statusProblem } from './upload.js';
|
||||
|
||||
export function mediaUrl(server: string, mediaId: Uint8Array): string {
|
||||
return `${server.replace(/\/$/, '')}/v1/media/${toHex(mediaId)}`;
|
||||
}
|
||||
|
||||
export interface MediaList {
|
||||
items: { id: string; size: number; createdAt: number }[];
|
||||
usage: number;
|
||||
}
|
||||
|
||||
export interface PutOptions {
|
||||
/** Token viewers must present. Default: a fresh random one per file. `null` = public ciphertext. */
|
||||
readToken?: Uint8Array | null;
|
||||
/** Copied into the grant so a library can list titles without opening each file. */
|
||||
meta?: MediaMeta;
|
||||
/** Bytes the relay has acknowledged so far, after each piece. */
|
||||
onProgress?: (sent: number, total: number) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a refusal says, for an error message: the relay's JSON as it is, but
|
||||
* not an HTML error page (a proxy's, or Bun's own) poured into a terminal.
|
||||
*/
|
||||
async function answerText(res: Response): Promise<string> {
|
||||
const text = await res.text().catch(() => '');
|
||||
if ((res.headers.get('content-type') ?? '').includes('text/html') || /^\s*</.test(text)) return '';
|
||||
return text.length > 300 ? `${text.slice(0, 300)}…` : text;
|
||||
}
|
||||
|
||||
/** Failed tries in a row before a resumable upload gives up. */
|
||||
const MAX_TRIES = 8;
|
||||
|
||||
/** The relay is restarting, overloaded or the network dropped: try again. */
|
||||
class Transient extends Error {}
|
||||
|
||||
// setTimeout, not Bun.sleep: the client runs in browsers and Node too.
|
||||
const backoff = (attempt: number) => new Promise<void>((r) => setTimeout(r, Math.min(30_000, 500 * 2 ** attempt)));
|
||||
|
||||
export class MediaClient {
|
||||
private readonly fetchFn: typeof fetch;
|
||||
|
||||
constructor(
|
||||
private readonly server: string,
|
||||
private readonly owner: OwnerKey,
|
||||
opts: { fetch?: typeof fetch } = {},
|
||||
) {
|
||||
this.fetchFn = opts.fetch ?? globalThis.fetch.bind(globalThis);
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload an already sealed file. `body` must be exactly `result.sealedSize`
|
||||
* bytes — a Blob/`Bun.file` streams from disk without loading the film.
|
||||
*/
|
||||
async putSealed(result: SealResult, body: Blob | Uint8Array, opts: PutOptions = {}): Promise<MediaGrant> {
|
||||
const size = body instanceof Uint8Array ? body.length : body.size;
|
||||
if (size !== result.sealedSize) {
|
||||
throw new MediaFormatError(`body is ${size} bytes, the seal produced ${result.sealedSize}`);
|
||||
}
|
||||
const readToken = opts.readToken === undefined ? randomBytes(32) : opts.readToken;
|
||||
const readTokenHash = readToken === null ? '' : toHex(await sha256(readToken));
|
||||
const id = toHex(result.mediaId);
|
||||
const url = mediaUrl(this.server, result.mediaId);
|
||||
if (size <= DEFAULT_CHUNK_BYTES) {
|
||||
const res = await this.fetchFn(url, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'content-type': 'application/vnd.shade.smf1',
|
||||
'content-length': String(size),
|
||||
...(readTokenHash !== '' ? { [READ_HASH_HEADER]: readTokenHash } : {}),
|
||||
...this.owner.headers({ op: 'put', id, size, readTokenHash }),
|
||||
},
|
||||
body: body as Blob,
|
||||
});
|
||||
if (res.status !== 201) {
|
||||
throw new Error(`upload failed: HTTP ${res.status} ${await answerText(res)}`);
|
||||
}
|
||||
opts.onProgress?.(size, size);
|
||||
} else {
|
||||
await this.putInPieces(url, id, size, readTokenHash, body, opts.onProgress);
|
||||
}
|
||||
return mediaGrantFrom(result, {
|
||||
url,
|
||||
...(readToken !== null ? { readToken } : {}),
|
||||
...(opts.meta !== undefined ? { meta: opts.meta } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A film, in pieces (see `upload.ts`), up to the relay's window of them in
|
||||
* flight. A dropped connection or a relay restart costs the pieces in
|
||||
* flight, not the upload: a failed piece is sent again after asking the
|
||||
* relay whether it landed after all.
|
||||
*/
|
||||
private async putInPieces(
|
||||
url: string,
|
||||
id: string,
|
||||
size: number,
|
||||
readTokenHash: string,
|
||||
body: Blob | Uint8Array,
|
||||
onProgress?: (sent: number, total: number) => void,
|
||||
): Promise<void> {
|
||||
const at = `${url}/upload`;
|
||||
// One piece per request in memory, read from the file only when it is
|
||||
// sent. Read here rather than handed to fetch as a `Bun.file().slice()`:
|
||||
// Bun (1.3.5) never finishes sending a sliced file as a request body.
|
||||
const cut = async (start: number, end: number): Promise<Uint8Array> => {
|
||||
if (body instanceof Uint8Array) return body.subarray(start, end);
|
||||
const piece = new Uint8Array(await (body as Blob & { slice(s: number, e: number): Blob }).slice(start, end).arrayBuffer());
|
||||
if (piece.length !== end - start) throw new MediaFormatError(`the file shrank: read ${piece.length} of ${end - start} bytes at ${start}`);
|
||||
return piece;
|
||||
};
|
||||
/** A request that did not get an answer (refused, reset, timed out) is worth repeating. */
|
||||
const send = async (init: RequestInit): Promise<Response> => {
|
||||
try {
|
||||
return await this.fetchFn(at, init);
|
||||
} catch (e) {
|
||||
throw new Transient((e as Error).message);
|
||||
}
|
||||
};
|
||||
const fail = async (res: Response, what: string): Promise<never> => {
|
||||
const text = await answerText(res);
|
||||
if (res.status >= 500 || res.status === 429) throw new Transient(`${what}: HTTP ${res.status} ${text}`);
|
||||
throw new Error(`upload failed: ${what}: HTTP ${res.status} ${text}`);
|
||||
};
|
||||
/** Retry `fn` while it fails transiently, with backoff; `fn` learns which try it is. */
|
||||
const retrying = async <T>(fn: (attempt: number) => Promise<T>): Promise<T> => {
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
try {
|
||||
return await fn(attempt);
|
||||
} catch (e) {
|
||||
if (!(e instanceof Transient)) throw e;
|
||||
if (attempt + 1 >= MAX_TRIES) throw new Error(`upload failed after ${MAX_TRIES} tries: ${e.message}`);
|
||||
await backoff(attempt + 1);
|
||||
}
|
||||
}
|
||||
};
|
||||
type Status = { chunk: number; window?: number; received: number; landed?: number[]; complete?: boolean };
|
||||
/** Start the upload, or learn how far it got. */
|
||||
const status = async (): Promise<Status> => {
|
||||
const res = await send({
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'x-shade-size': String(size),
|
||||
...(readTokenHash !== '' ? { [READ_HASH_HEADER]: readTokenHash } : {}),
|
||||
...this.owner.headers({ op: 'upload', id, size, readTokenHash }),
|
||||
},
|
||||
});
|
||||
if (res.status !== 200 && res.status !== 201) return fail(res, 'start');
|
||||
const st = (await res.json().catch(() => {
|
||||
throw new Transient("start: the relay's answer is not JSON");
|
||||
})) as Status;
|
||||
if (st.complete === true) return st;
|
||||
const problem = statusProblem(st, size);
|
||||
if (problem !== null) throw new Error(`upload failed: the relay's upload status is unusable: ${problem}`);
|
||||
return st;
|
||||
};
|
||||
const has = (st: Status, offset: number) => offset < st.received || (st.landed ?? []).includes(offset / st.chunk);
|
||||
|
||||
const opened = await retrying(status);
|
||||
if (opened.complete === true) {
|
||||
onProgress?.(size, size);
|
||||
return;
|
||||
}
|
||||
const { chunk } = opened;
|
||||
const window = Math.min(MAX_CLIENT_WINDOW, Math.max(1, opened.window ?? 1));
|
||||
let acked = 0;
|
||||
let complete = false;
|
||||
const todo: number[] = [];
|
||||
for (let off = 0; off < size; off += chunk) {
|
||||
if (has(opened, off)) acked += Math.min(chunk, size - off);
|
||||
else todo.push(off);
|
||||
}
|
||||
onProgress?.(acked, size);
|
||||
|
||||
/** One piece until the relay has it; true once the relay stored the whole file. */
|
||||
const sendPiece = (offset: number) =>
|
||||
retrying(async (attempt): Promise<boolean> => {
|
||||
if (attempt > 0) {
|
||||
// It may have landed before the connection dropped: ask before sending it again.
|
||||
const st = await status();
|
||||
if (st.complete === true) return true;
|
||||
if (has(st, offset)) return false;
|
||||
}
|
||||
const length = Math.min(chunk, size - offset);
|
||||
const piece = await cut(offset, offset + length);
|
||||
const res = await send({
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'content-type': 'application/octet-stream',
|
||||
'content-length': String(length),
|
||||
[OFFSET_HEADER]: String(offset),
|
||||
...this.owner.headers({ op: 'piece', id, offset, length }),
|
||||
},
|
||||
body: piece as Uint8Array<ArrayBuffer>,
|
||||
});
|
||||
if (res.status === 201) return true;
|
||||
if (res.status === 200) return false;
|
||||
// Ahead of the window (pieces before it are still on the way): later.
|
||||
if (res.status === 409) {
|
||||
const j = (await res.json().catch(() => ({}))) as { error?: string };
|
||||
if (j.error === 'OFFSET') throw new Transient('piece ahead of the upload');
|
||||
throw new Error(`upload failed: HTTP 409 ${JSON.stringify(j)}`);
|
||||
}
|
||||
return fail(res, `piece at ${offset}`);
|
||||
});
|
||||
|
||||
let failure: unknown = null;
|
||||
const inFlight = new Set<Promise<void>>();
|
||||
const flying = new Set<number>();
|
||||
/**
|
||||
* The relay takes `window` pieces past what it has from the start, so a
|
||||
* piece is only sent within `window` of the first one not yet answered:
|
||||
* one slow piece holds the window, rather than pieces past it bouncing.
|
||||
*/
|
||||
const mayLaunch = () => {
|
||||
if (todo.length === 0 || inFlight.size >= window) return false;
|
||||
const lowest = Math.min(todo[0]!, ...flying);
|
||||
return todo[0]! < lowest + window * chunk;
|
||||
};
|
||||
const launch = (offset: number) => {
|
||||
flying.add(offset);
|
||||
const p: Promise<void> = sendPiece(offset).then(
|
||||
(done) => {
|
||||
flying.delete(offset);
|
||||
inFlight.delete(p);
|
||||
if (done) complete = true;
|
||||
acked += Math.min(chunk, size - offset);
|
||||
if (!complete) onProgress?.(acked, size);
|
||||
},
|
||||
(e: unknown) => {
|
||||
flying.delete(offset);
|
||||
inFlight.delete(p);
|
||||
failure ??= e;
|
||||
},
|
||||
);
|
||||
inFlight.add(p);
|
||||
};
|
||||
while (!complete && failure === null && (todo.length > 0 || inFlight.size > 0)) {
|
||||
while (failure === null && !complete && mayLaunch()) launch(todo.shift()!);
|
||||
await Promise.race(inFlight);
|
||||
}
|
||||
await Promise.allSettled(inFlight);
|
||||
if (failure !== null) throw failure;
|
||||
if (!complete) {
|
||||
// Every piece is in but no answer said so (they crossed a completion
|
||||
// that failed and was retried): an empty piece at the end finishes it.
|
||||
await retrying(async () => {
|
||||
const res = await send({
|
||||
method: 'PUT',
|
||||
headers: { 'content-length': '0', [OFFSET_HEADER]: String(size), ...this.owner.headers({ op: 'piece', id, offset: size, length: 0 }) },
|
||||
});
|
||||
if (res.status !== 201) return fail(res, 'finish');
|
||||
});
|
||||
}
|
||||
onProgress?.(size, size);
|
||||
}
|
||||
|
||||
/** Seal in memory and upload — images, clips, documents. */
|
||||
async uploadBytes(plaintext: Uint8Array, opts: SealOptions & PutOptions = {}): Promise<MediaGrant> {
|
||||
const { bytes, result } = await sealMediaBytes(plaintext, opts);
|
||||
return this.putSealed(result, bytes, opts.meta !== undefined ? { ...opts, meta: opts.meta } : opts);
|
||||
}
|
||||
|
||||
/** Seal and upload an album; the grant opens every item in it. */
|
||||
async uploadAlbum(album: Album, opts: Omit<PutOptions, 'meta'> = {}): Promise<MediaGrant> {
|
||||
const meta = albumMeta(album.title);
|
||||
return this.uploadBytes(encodeAlbum(album), { ...opts, meta });
|
||||
}
|
||||
|
||||
async delete(mediaId: Uint8Array): Promise<boolean> {
|
||||
const id = toHex(mediaId);
|
||||
const res = await this.fetchFn(mediaUrl(this.server, mediaId), {
|
||||
method: 'DELETE',
|
||||
headers: this.owner.headers({ op: 'delete', id }),
|
||||
});
|
||||
if (res.status === 404) return false;
|
||||
if (!res.ok) throw new Error(`delete failed: HTTP ${res.status}`);
|
||||
return true;
|
||||
}
|
||||
|
||||
async list(): Promise<MediaList> {
|
||||
const res = await this.fetchFn(`${this.server.replace(/\/$/, '')}/v1/media`, {
|
||||
headers: this.owner.headers({ op: 'list' }),
|
||||
});
|
||||
if (!res.ok) throw new Error(`list failed: HTTP ${res.status}`);
|
||||
return (await res.json()) as MediaList;
|
||||
}
|
||||
}
|
||||
|
||||
/** Open a granted file over HTTP. */
|
||||
export function openGrant(
|
||||
grant: MediaGrant,
|
||||
opts: ReaderOptions & { fetch?: typeof fetch; url?: string } = {},
|
||||
): Promise<MediaReader> {
|
||||
const url = opts.url ?? grant.url;
|
||||
if (url === undefined) throw new MediaFormatError('grant has no URL');
|
||||
const source = new HttpRangeSource(url, {
|
||||
...(grant.readToken !== undefined ? { headers: { [READ_TOKEN_HEADER]: toB64u(grant.readToken) } } : {}),
|
||||
...(opts.fetch !== undefined ? { fetch: opts.fetch } : {}),
|
||||
});
|
||||
return MediaReader.open(source, mediaKeysOf(grant), opts);
|
||||
}
|
||||
|
||||
/** An album holds at most 10 000 grants of well under 1 KiB each. */
|
||||
const MAX_ALBUM_BYTES = 16 * 1024 * 1024;
|
||||
|
||||
/** Open a granted album and read its items. */
|
||||
export async function openAlbum(
|
||||
grant: MediaGrant,
|
||||
opts: ReaderOptions & { fetch?: typeof fetch; url?: string } = {},
|
||||
): Promise<Album> {
|
||||
return readAlbum(await openGrant(grant, opts));
|
||||
}
|
||||
|
||||
/** The items of an album already opened as a reader. */
|
||||
export async function readAlbum(reader: MediaReader): Promise<Album> {
|
||||
if (reader.meta.mime !== ALBUM_MIME) throw new MediaFormatError(`not an album (${reader.meta.mime ?? 'no type'})`);
|
||||
if (reader.size > MAX_ALBUM_BYTES) throw new MediaFormatError('album larger than 16 MiB');
|
||||
return parseAlbum(await reader.read(0, reader.size));
|
||||
}
|
||||
84
packages/shade-media/src/ed25519.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* Ed25519 for per-frame signatures.
|
||||
*
|
||||
* Live frames are signed one by one, so the signature is on the hot path: a
|
||||
* log stream can carry thousands of frames a second. WebCrypto's Ed25519
|
||||
* (Bun, Chrome ≥ 137, Firefox ≥ 129, Safari ≥ 17) is ~10× faster than the
|
||||
* pure-JS implementation; that one remains the fallback where the runtime
|
||||
* lacks it. Both produce identical RFC 8032 signatures — Ed25519 is
|
||||
* deterministic — so a frame signed one way verifies the other.
|
||||
*/
|
||||
|
||||
import { ed25519 } from '@noble/curves/ed25519.js';
|
||||
import { bs, concat } from './bytes.js';
|
||||
|
||||
/** PKCS#8 prefix for a raw 32-byte Ed25519 seed (RFC 8410). */
|
||||
const PKCS8_PREFIX = new Uint8Array([
|
||||
0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20,
|
||||
]);
|
||||
|
||||
let subtleOk: Promise<boolean> | null = null;
|
||||
|
||||
function hasSubtleEd25519(): Promise<boolean> {
|
||||
subtleOk ??= (async () => {
|
||||
try {
|
||||
const seed = new Uint8Array(32);
|
||||
const k = await globalThis.crypto.subtle.importKey('pkcs8', bs(concat([PKCS8_PREFIX, seed])), { name: 'Ed25519' }, false, ['sign']);
|
||||
const sig = new Uint8Array(await globalThis.crypto.subtle.sign('Ed25519', k, bs(new Uint8Array(1))));
|
||||
// Guard against a runtime whose "Ed25519" disagrees with RFC 8032.
|
||||
return ed25519.verify(sig, new Uint8Array(1), ed25519.getPublicKey(seed));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
})();
|
||||
return subtleOk;
|
||||
}
|
||||
|
||||
export class Ed25519Signer {
|
||||
readonly publicKey: Uint8Array;
|
||||
private key: Promise<CryptoKey | null>;
|
||||
|
||||
constructor(private readonly seed: Uint8Array) {
|
||||
this.publicKey = ed25519.getPublicKey(seed);
|
||||
this.key = hasSubtleEd25519().then((ok) =>
|
||||
ok
|
||||
? globalThis.crypto.subtle.importKey('pkcs8', bs(concat([PKCS8_PREFIX, seed])), { name: 'Ed25519' }, false, ['sign'])
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
async sign(message: Uint8Array): Promise<Uint8Array> {
|
||||
const k = await this.key;
|
||||
if (k === null) return ed25519.sign(message, this.seed);
|
||||
return new Uint8Array(await globalThis.crypto.subtle.sign('Ed25519', k, bs(message)));
|
||||
}
|
||||
}
|
||||
|
||||
export class Ed25519Verifier {
|
||||
private key: Promise<CryptoKey | null>;
|
||||
|
||||
constructor(readonly publicKey: Uint8Array) {
|
||||
this.key = hasSubtleEd25519().then((ok) =>
|
||||
ok
|
||||
? globalThis.crypto.subtle
|
||||
.importKey('raw', bs(publicKey), { name: 'Ed25519' }, false, ['verify'])
|
||||
// An invalid point is refused at import by some runtimes; let the
|
||||
// pure-JS path give the (false) answer instead of throwing.
|
||||
.catch(() => null)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
async verify(signature: Uint8Array, message: Uint8Array): Promise<boolean> {
|
||||
if (signature.length !== 64) return false;
|
||||
const k = await this.key;
|
||||
if (k === null) {
|
||||
try {
|
||||
return ed25519.verify(signature, message, this.publicKey);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return globalThis.crypto.subtle.verify('Ed25519', k, bs(signature), bs(message));
|
||||
}
|
||||
}
|
||||
18
packages/shade-media/src/errors.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
/** A file, frame or grant is malformed — bad magic, a length that does not add up. */
|
||||
export class MediaFormatError extends Error {
|
||||
override readonly name = 'MediaFormatError';
|
||||
}
|
||||
|
||||
/**
|
||||
* Bytes failed authentication: a segment whose hash is not in the table, an
|
||||
* AEAD tag that does not verify, a live frame with a bad signature. Never
|
||||
* retried silently — it means someone between the writer and us changed them.
|
||||
*/
|
||||
export class MediaIntegrityError extends Error {
|
||||
override readonly name = 'MediaIntegrityError';
|
||||
}
|
||||
|
||||
/** A live frame arrived that this subscriber holds no key for. */
|
||||
export class LiveKeyError extends Error {
|
||||
override readonly name = 'LiveKeyError';
|
||||
}
|
||||
401
packages/shade-media/src/fmp4.ts
Normal file
@@ -0,0 +1,401 @@
|
||||
/**
|
||||
* Fragmented MP4 → live frames.
|
||||
*
|
||||
* A live fMP4 stream (ffmpeg `-movflags frag_keyframe+empty_moov+default_base_moof`,
|
||||
* OBS, hardware encoders, CMAF) is a run of top-level boxes:
|
||||
*
|
||||
* ftyp moov → init, one sticky frame
|
||||
* [styp] [sidx] [prft] [emsg] moof mdat → one fragment, one frame
|
||||
*
|
||||
* For Media Source Extensions that is the same split as WebM: the init makes
|
||||
* the SourceBuffer, every fragment after it is appendable on its own. A
|
||||
* fragment is a keyframe when the first sample of its video track is a sync
|
||||
* sample, which is what a late joiner needs to start on.
|
||||
*
|
||||
* Streaming parser: push bytes in any chunking, get whole pieces out.
|
||||
*/
|
||||
|
||||
import { concat } from './bytes.js';
|
||||
import { MediaFormatError } from './errors.js';
|
||||
|
||||
export type Fmp4Piece =
|
||||
| { type: 'init'; mime: string; bytes: Uint8Array }
|
||||
| { type: 'fragment'; keyframe: boolean; bytes: Uint8Array };
|
||||
|
||||
/** Boxes that may come before a `moof` and belong to its fragment. */
|
||||
const FRAGMENT_PREFIX = new Set(['styp', 'sidx', 'prft', 'emsg', 'free', 'skip']);
|
||||
/** Index boxes a muxer writes at the end; a live viewer has no use for them. */
|
||||
const TRAILING_INDEX = new Set(['mfra']);
|
||||
/** Boxes that end the init. */
|
||||
const FRAGMENT_START = new Set(['moof', ...FRAGMENT_PREFIX]);
|
||||
|
||||
/** Largest box accepted: a fragment of an 8K keyframe is tens of MiB, not GiBs. */
|
||||
const MAX_BOX = 256 * 1024 * 1024;
|
||||
|
||||
interface Box {
|
||||
type: string;
|
||||
/** Offset of the box's payload (after size, type and any largesize). */
|
||||
body: number;
|
||||
/** Offset one past the box. */
|
||||
end: number;
|
||||
}
|
||||
|
||||
function fourcc(b: Uint8Array, at: number): string {
|
||||
return String.fromCharCode(b[at]!, b[at + 1]!, b[at + 2]!, b[at + 3]!);
|
||||
}
|
||||
|
||||
function u32(b: Uint8Array, at: number): number {
|
||||
return ((b[at]! << 24) | (b[at + 1]! << 16) | (b[at + 2]! << 8) | b[at + 3]!) >>> 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The box header at `at`, or null if more bytes are needed. `limit` is where
|
||||
* the enclosing container ends; a box running past it is malformed.
|
||||
*/
|
||||
function readBox(b: Uint8Array, at: number, limit: number): Box | null {
|
||||
if (at + 8 > limit) return null;
|
||||
let size = u32(b, at);
|
||||
const type = fourcc(b, at + 4);
|
||||
let body = at + 8;
|
||||
if (size === 1) {
|
||||
if (at + 16 > limit) return null;
|
||||
const hi = u32(b, at + 8);
|
||||
const lo = u32(b, at + 12);
|
||||
if (hi > 0x1f_ffff) throw new MediaFormatError(`fMP4: ${type} box too large`);
|
||||
size = hi * 2 ** 32 + lo;
|
||||
body = at + 16;
|
||||
} else if (size === 0) {
|
||||
// "Extends to the end of the file": meaningless in a live stream.
|
||||
throw new MediaFormatError(`fMP4: ${type} box of open size in a live stream`);
|
||||
}
|
||||
if (size < body - at) throw new MediaFormatError(`fMP4: ${type} box smaller than its header`);
|
||||
if (size > MAX_BOX) throw new MediaFormatError(`fMP4: ${type} box of ${size} bytes`);
|
||||
return { type, body, end: at + size };
|
||||
}
|
||||
|
||||
/** The child boxes of a container, fully present in `b[from, to)`. */
|
||||
function children(b: Uint8Array, from: number, to: number): Box[] {
|
||||
const out: Box[] = [];
|
||||
let at = from;
|
||||
while (at + 8 <= to) {
|
||||
const box = readBox(b, at, to);
|
||||
if (box === null || box.end > to) throw new MediaFormatError('fMP4: truncated box');
|
||||
out.push(box);
|
||||
at = box.end;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function child(b: Uint8Array, parent: Box, type: string): Box | undefined {
|
||||
return children(b, parent.body, parent.end).find((c) => c.type === type);
|
||||
}
|
||||
|
||||
function hex(n: number, width = 2): string {
|
||||
return n.toString(16).padStart(width, '0');
|
||||
}
|
||||
|
||||
// ─── Codec strings (RFC 6381 and the codec-specific registrations) ───
|
||||
|
||||
/** `avc1.PPCCLL` from an avcC box. */
|
||||
function avcCodec(entry: string, b: Uint8Array, avcC: Box): string {
|
||||
return `${entry}.${hex(b[avcC.body + 1]!)}${hex(b[avcC.body + 2]!)}${hex(b[avcC.body + 3]!)}`;
|
||||
}
|
||||
|
||||
/** `hvc1.P.C.TL.B…` from an hvcC box (ISO/IEC 14496-15 Annex E). */
|
||||
function hevcCodec(entry: string, b: Uint8Array, hvcC: Box): string {
|
||||
const p = hvcC.body;
|
||||
const space = b[p + 1]! >> 6;
|
||||
const tier = (b[p + 1]! >> 5) & 1;
|
||||
const profile = b[p + 1]! & 0x1f;
|
||||
// general_profile_compatibility_flags, bit-reversed.
|
||||
let compat = u32(b, p + 2);
|
||||
let rev = 0;
|
||||
for (let i = 0; i < 32; i++) {
|
||||
rev = (rev << 1) | (compat & 1);
|
||||
compat >>>= 1;
|
||||
}
|
||||
const level = b[p + 12]!;
|
||||
const constraints: string[] = [];
|
||||
for (let i = 0; i < 6; i++) constraints.push(hex(b[p + 6 + i]!).toUpperCase());
|
||||
while (constraints.length > 0 && constraints[constraints.length - 1] === '00') constraints.pop();
|
||||
const spaceTag = ['', 'A', 'B', 'C'][space]!;
|
||||
return [
|
||||
entry,
|
||||
`${spaceTag}${profile}`,
|
||||
(rev >>> 0).toString(16).toUpperCase(),
|
||||
`${tier ? 'H' : 'L'}${level}`,
|
||||
...constraints,
|
||||
].join('.');
|
||||
}
|
||||
|
||||
/** `av01.P.LLT.DD` from an av1C box (AV1 ISOBMFF binding §5). */
|
||||
function av1Codec(b: Uint8Array, av1C: Box): string {
|
||||
const p = av1C.body;
|
||||
const profile = b[p + 1]! >> 5;
|
||||
const level = b[p + 1]! & 0x1f;
|
||||
const tier = b[p + 2]! >> 7;
|
||||
const high = (b[p + 2]! >> 6) & 1;
|
||||
const twelve = (b[p + 2]! >> 5) & 1;
|
||||
const depth = high ? (twelve ? 12 : 10) : 8;
|
||||
return `av01.${profile}.${String(level).padStart(2, '0')}${tier ? 'H' : 'M'}.${String(depth).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/** `vp09.PP.LL.DD` from a vpcC box (VP Codec ISOBMFF binding). */
|
||||
function vp9Codec(b: Uint8Array, vpcC: Box): string {
|
||||
const p = vpcC.body + 4; // FullBox
|
||||
const d2 = (n: number) => String(n).padStart(2, '0');
|
||||
return `vp09.${d2(b[p]!)}.${d2(b[p + 1]!)}.${d2(b[p + 2]! >> 4)}`;
|
||||
}
|
||||
|
||||
/** An MPEG-4 descriptor's tag and body, with its 1–4 byte length. */
|
||||
function descriptor(b: Uint8Array, at: number, end: number): { tag: number; body: number; end: number } | null {
|
||||
if (at >= end) return null;
|
||||
const tag = b[at]!;
|
||||
let len = 0;
|
||||
let p = at + 1;
|
||||
for (let i = 0; i < 4 && p < end; i++) {
|
||||
const x = b[p++]!;
|
||||
len = (len << 7) | (x & 0x7f);
|
||||
if ((x & 0x80) === 0) break;
|
||||
}
|
||||
return { tag, body: p, end: Math.min(end, p + len) };
|
||||
}
|
||||
|
||||
/** `mp4a.OO.A` from an esds box: objectTypeIndication and the audio object type. */
|
||||
function aacCodec(b: Uint8Array, esds: Box): string {
|
||||
const es = descriptor(b, esds.body + 4, esds.end);
|
||||
if (es === null || es.tag !== 0x03) return 'mp4a.40.2';
|
||||
let p = es.body + 2; // ES_ID
|
||||
const flags = b[p++]!;
|
||||
if (flags & 0x80) p += 2; // dependsOn_ES_ID
|
||||
if (flags & 0x40) p += 1 + b[p]!; // URL
|
||||
if (flags & 0x20) p += 2; // OCR_ES_ID
|
||||
const dc = descriptor(b, p, es.end);
|
||||
if (dc === null || dc.tag !== 0x04) return 'mp4a.40.2';
|
||||
const oti = b[dc.body]!;
|
||||
const dsi = descriptor(b, dc.body + 13, dc.end);
|
||||
if (oti !== 0x40 || dsi === null || dsi.tag !== 0x05) return `mp4a.${hex(oti)}`;
|
||||
let aot = b[dsi.body]! >> 3;
|
||||
if (aot === 31) aot = 32 + (((b[dsi.body]! & 0x07) << 3) | (b[dsi.body + 1]! >> 5));
|
||||
return `mp4a.40.${aot}`;
|
||||
}
|
||||
|
||||
/** Size of a sample entry's fixed fields, before its child boxes. */
|
||||
const VISUAL_ENTRY = 78;
|
||||
const AUDIO_ENTRY = 28;
|
||||
|
||||
function sampleEntryCodec(b: Uint8Array, entry: Box): string | null {
|
||||
const kind = entry.type;
|
||||
const visual = ['avc1', 'avc3', 'hvc1', 'hev1', 'av01', 'vp09', 'encv'].includes(kind);
|
||||
const audio = ['mp4a', 'Opus', 'fLaC', 'ac-3', 'ec-3', 'enca'].includes(kind);
|
||||
if (!visual && !audio) return null;
|
||||
const sub = children(b, entry.body + (visual ? VISUAL_ENTRY : AUDIO_ENTRY), entry.end);
|
||||
const find = (t: string) => sub.find((c) => c.type === t);
|
||||
switch (kind) {
|
||||
case 'avc1':
|
||||
case 'avc3': {
|
||||
const c = find('avcC');
|
||||
return c ? avcCodec(kind, b, c) : kind;
|
||||
}
|
||||
case 'hvc1':
|
||||
case 'hev1': {
|
||||
const c = find('hvcC');
|
||||
return c ? hevcCodec(kind, b, c) : kind;
|
||||
}
|
||||
case 'av01': {
|
||||
const c = find('av1C');
|
||||
return c ? av1Codec(b, c) : 'av01';
|
||||
}
|
||||
case 'vp09': {
|
||||
const c = find('vpcC');
|
||||
return c ? vp9Codec(b, c) : 'vp09';
|
||||
}
|
||||
case 'mp4a': {
|
||||
const c = find('esds');
|
||||
return c ? aacCodec(b, c) : 'mp4a.40.2';
|
||||
}
|
||||
case 'Opus':
|
||||
return 'opus';
|
||||
case 'fLaC':
|
||||
return 'flac';
|
||||
case 'ac-3':
|
||||
return 'ac-3';
|
||||
case 'ec-3':
|
||||
return 'ec-3';
|
||||
default:
|
||||
// encv / enca: CENC-encrypted tracks — Shade already encrypts; refuse
|
||||
// rather than guess the original format from sinf.
|
||||
throw new MediaFormatError(`fMP4: ${kind} (CENC-encrypted) tracks are not supported`);
|
||||
}
|
||||
}
|
||||
|
||||
interface Track {
|
||||
id: number;
|
||||
handler: string;
|
||||
codec: string | null;
|
||||
/** trex default_sample_flags, the fallback for fragments that state none. */
|
||||
defaultFlags: number;
|
||||
}
|
||||
|
||||
function parseMoov(b: Uint8Array, moov: Box): Track[] {
|
||||
const tracks: Track[] = [];
|
||||
const top = children(b, moov.body, moov.end);
|
||||
for (const trak of top.filter((c) => c.type === 'trak')) {
|
||||
const tkhd = child(b, trak, 'tkhd');
|
||||
const mdia = child(b, trak, 'mdia');
|
||||
if (!tkhd || !mdia) continue;
|
||||
const version = b[tkhd.body]!;
|
||||
const id = u32(b, tkhd.body + 4 + (version === 1 ? 16 : 8));
|
||||
const hdlr = child(b, mdia, 'hdlr');
|
||||
const handler = hdlr ? fourcc(b, hdlr.body + 8) : '';
|
||||
const minf = child(b, mdia, 'minf');
|
||||
const stbl = minf && child(b, minf, 'stbl');
|
||||
const stsd = stbl && child(b, stbl, 'stsd');
|
||||
let codec: string | null = null;
|
||||
if (stsd) {
|
||||
const entries = children(b, stsd.body + 8, stsd.end);
|
||||
if (entries[0]) codec = sampleEntryCodec(b, entries[0]);
|
||||
}
|
||||
tracks.push({ id, handler, codec, defaultFlags: 0 });
|
||||
}
|
||||
const mvex = top.find((c) => c.type === 'mvex');
|
||||
if (mvex) {
|
||||
for (const trex of children(b, mvex.body, mvex.end).filter((c) => c.type === 'trex')) {
|
||||
const t = tracks.find((x) => x.id === u32(b, trex.body + 4));
|
||||
if (t) t.defaultFlags = u32(b, trex.body + 20);
|
||||
}
|
||||
}
|
||||
return tracks;
|
||||
}
|
||||
|
||||
/** The MSE type string, e.g. `video/mp4; codecs="avc1.64001f,mp4a.40.2"`. */
|
||||
export function fmp4Mime(tracks: readonly { handler: string; codec: string | null }[]): string {
|
||||
const media = tracks.filter((t) => t.handler === 'vide' || t.handler === 'soun');
|
||||
const codecs = media.map((t) => t.codec).filter((c): c is string => c !== null);
|
||||
const video = media.some((t) => t.handler === 'vide');
|
||||
return `${video ? 'video' : 'audio'}/mp4${codecs.length > 0 ? `; codecs="${codecs.join(',')}"` : ''}`;
|
||||
}
|
||||
|
||||
/** sample_is_non_sync_sample, ISO/IEC 14496-12 §8.8.3.1. */
|
||||
const NON_SYNC = 0x0001_0000;
|
||||
|
||||
export class Fmp4Splitter {
|
||||
private buf: Uint8Array = new Uint8Array(0);
|
||||
private initDone = false;
|
||||
private tracks: Track[] = [];
|
||||
private videoTracks = new Set<number>();
|
||||
|
||||
push(chunk: Uint8Array): Fmp4Piece[] {
|
||||
this.buf = this.buf.length === 0 ? chunk.slice() : concat([this.buf, chunk]);
|
||||
const out: Fmp4Piece[] = [];
|
||||
if (!this.initDone) {
|
||||
const init = this.tryInit();
|
||||
if (init === null) return out;
|
||||
out.push(init);
|
||||
}
|
||||
for (;;) {
|
||||
const f = this.tryFragment();
|
||||
if (f === null) break;
|
||||
out.push(f);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** End of stream. A half-written last fragment is dropped, not sent. */
|
||||
finish(): Fmp4Piece[] {
|
||||
this.buf = new Uint8Array(0);
|
||||
return [];
|
||||
}
|
||||
|
||||
private tryInit(): Fmp4Piece | null {
|
||||
let at = 0;
|
||||
let moov: Box | null = null;
|
||||
let first = true;
|
||||
for (;;) {
|
||||
const box = readBox(this.buf, at, this.buf.length);
|
||||
if (box === null) return null;
|
||||
if (first && box.type !== 'ftyp' && box.type !== 'moov') {
|
||||
throw new MediaFormatError(`not a fragmented MP4 stream (starts with ${JSON.stringify(box.type)})`);
|
||||
}
|
||||
first = false;
|
||||
if (box.type === 'moof' && moov === null) throw new MediaFormatError('fMP4: no moov before the first fragment');
|
||||
// free/skip before the moov are padding in the init, after it a fragment's prefix.
|
||||
if (moov !== null && FRAGMENT_START.has(box.type)) break;
|
||||
if (box.type === 'mdat') throw new MediaFormatError('fMP4: mdat before moof — not a fragmented MP4 (use -movflags frag_keyframe+empty_moov)');
|
||||
if (box.end > this.buf.length) return null;
|
||||
if (box.type === 'moov') moov = box;
|
||||
at = box.end;
|
||||
}
|
||||
this.tracks = parseMoov(this.buf, moov!);
|
||||
if (!this.tracks.some((t) => t.codec !== null)) throw new MediaFormatError('fMP4: no audio or video track');
|
||||
for (const t of this.tracks) if (t.handler === 'vide') this.videoTracks.add(t.id);
|
||||
this.initDone = true;
|
||||
const bytes = this.buf.slice(0, at);
|
||||
this.buf = this.buf.slice(at);
|
||||
return { type: 'init', mime: fmp4Mime(this.tracks), bytes };
|
||||
}
|
||||
|
||||
/** `[prefix boxes] moof … mdat` once the mdat is complete. */
|
||||
private tryFragment(): Fmp4Piece | null {
|
||||
let at = 0;
|
||||
let moof: Box | null = null;
|
||||
for (;;) {
|
||||
const box = readBox(this.buf, at, this.buf.length);
|
||||
if (box === null) return null;
|
||||
if (moof === null && at === 0 && TRAILING_INDEX.has(box.type)) {
|
||||
if (box.end > this.buf.length) return null;
|
||||
this.buf = this.buf.slice(box.end);
|
||||
continue;
|
||||
}
|
||||
if (moof === null) {
|
||||
if (box.type !== 'moof' && !FRAGMENT_PREFIX.has(box.type)) {
|
||||
throw new MediaFormatError(`fMP4: unexpected ${JSON.stringify(box.type)} box between fragments`);
|
||||
}
|
||||
} else if (box.type !== 'mdat') {
|
||||
throw new MediaFormatError(`fMP4: ${JSON.stringify(box.type)} between moof and mdat`);
|
||||
}
|
||||
if (box.end > this.buf.length) return null;
|
||||
if (box.type === 'moof') moof = box;
|
||||
at = box.end;
|
||||
if (box.type === 'mdat') break;
|
||||
}
|
||||
const bytes = this.buf.slice(0, at);
|
||||
this.buf = this.buf.slice(at);
|
||||
return { type: 'fragment', keyframe: this.isKeyframe(bytes, moof!), bytes };
|
||||
}
|
||||
|
||||
/** Is the first sample of the video track in this fragment a sync sample? */
|
||||
private isKeyframe(b: Uint8Array, moof: Box): boolean {
|
||||
if (this.videoTracks.size === 0) return true; // audio only: every fragment is a start
|
||||
for (const traf of children(b, moof.body, moof.end).filter((c) => c.type === 'traf')) {
|
||||
const tfhd = child(b, traf, 'tfhd');
|
||||
if (!tfhd) continue;
|
||||
const tfFlags = u32(b, tfhd.body) & 0xffffff;
|
||||
const trackId = u32(b, tfhd.body + 4);
|
||||
if (!this.videoTracks.has(trackId)) continue;
|
||||
let defaultFlags = this.tracks.find((t) => t.id === trackId)?.defaultFlags ?? 0;
|
||||
let p = tfhd.body + 8;
|
||||
if (tfFlags & 0x01) p += 8; // base_data_offset
|
||||
if (tfFlags & 0x02) p += 4; // sample_description_index
|
||||
if (tfFlags & 0x08) p += 4; // default_sample_duration
|
||||
if (tfFlags & 0x10) p += 4; // default_sample_size
|
||||
if (tfFlags & 0x20) defaultFlags = u32(b, p);
|
||||
const trun = child(b, traf, 'trun');
|
||||
if (!trun) continue;
|
||||
const trFlags = u32(b, trun.body) & 0xffffff;
|
||||
const count = u32(b, trun.body + 4);
|
||||
if (count === 0) continue;
|
||||
let q = trun.body + 8;
|
||||
if (trFlags & 0x001) q += 4; // data_offset
|
||||
if (trFlags & 0x004) return (u32(b, q) & NON_SYNC) === 0; // first_sample_flags
|
||||
if (trFlags & 0x400) {
|
||||
// Per-sample flags: skip the first sample's duration and size.
|
||||
if (trFlags & 0x100) q += 4;
|
||||
if (trFlags & 0x200) q += 4;
|
||||
return (u32(b, q) & NON_SYNC) === 0;
|
||||
}
|
||||
return (defaultFlags & NON_SYNC) === 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
222
packages/shade-media/src/grant.ts
Normal file
@@ -0,0 +1,222 @@
|
||||
/**
|
||||
* Grants: how a viewer gets the keys.
|
||||
*
|
||||
* A grant is a small JSON object the owner sends over an **existing Shade
|
||||
* session** — `shade.send(peer, encodeGrant(g))`. That is the whole trust
|
||||
* story: the Double Ratchet authenticates who sent it and gives it forward
|
||||
* secrecy, the relay that stores the film never sees it, and a viewer
|
||||
* removed later still holds only what was granted to them.
|
||||
*
|
||||
* For a device with no Shade session — the TV, a browser on the couch — the
|
||||
* same grant can ride in a capability link: the grant sits in the URL
|
||||
* *fragment*, which browsers never send to a server. Whoever holds the link
|
||||
* can watch; treat it like a key.
|
||||
*/
|
||||
|
||||
import { dec, enc, fromB64u, fromHex, toB64u, toHex } from './bytes.js';
|
||||
import { MediaFormatError } from './errors.js';
|
||||
import { MEDIA_ID_BYTES, MEDIA_KEY_BYTES, DIGEST_BYTES, validateMeta } from './sealed.js';
|
||||
import type { MediaKeys, MediaMeta, SealResult } from './sealed.js';
|
||||
|
||||
export const MEDIA_GRANT_KIND = 'shade.media-grant/v1';
|
||||
export const LIVE_GRANT_KIND = 'shade.live-grant/v1';
|
||||
|
||||
/** Keys and location of one sealed file. */
|
||||
export interface MediaGrant {
|
||||
kind: typeof MEDIA_GRANT_KIND;
|
||||
mediaId: Uint8Array;
|
||||
mediaKey: Uint8Array;
|
||||
rootDigest: Uint8Array;
|
||||
/** Where the sealed bytes live — any URL that answers Range requests. */
|
||||
url?: string;
|
||||
/** Bearer token the media routes ask for; not a key, just a door. */
|
||||
readToken?: Uint8Array;
|
||||
/** A preview of the sealed metadata, so a list can render before opening. */
|
||||
meta?: MediaMeta;
|
||||
}
|
||||
|
||||
/** Keys to join a live channel from a given point. */
|
||||
export interface LiveGrant {
|
||||
kind: typeof LIVE_GRANT_KIND;
|
||||
channelId: Uint8Array;
|
||||
/** Publisher's Ed25519 public key for this channel: every frame is signed by it. */
|
||||
signingKey: Uint8Array;
|
||||
epoch: number;
|
||||
/** First seq this grant can decrypt. */
|
||||
seq: number;
|
||||
/** Chain key at `seq`. Earlier frames cannot be derived from it. */
|
||||
chainKey: Uint8Array;
|
||||
/** Key for the epoch's sticky frames (codec init, channel header). */
|
||||
stickyKey: Uint8Array;
|
||||
/** WebSocket URL of the relay, e.g. `wss://relay/v1/live/<id>`. */
|
||||
url?: string;
|
||||
readToken?: Uint8Array;
|
||||
/** Channel title etc., as the publisher described it. */
|
||||
meta?: MediaMeta;
|
||||
/**
|
||||
* Link mode only: the secret every epoch seed derives from. A grant with
|
||||
* it reads this epoch and every later one, with no further grants.
|
||||
*/
|
||||
channelSecret?: Uint8Array;
|
||||
}
|
||||
|
||||
export type Grant = MediaGrant | LiveGrant;
|
||||
|
||||
export function mediaGrantFrom(
|
||||
r: SealResult,
|
||||
extra: { url?: string; readToken?: Uint8Array; meta?: MediaMeta } = {},
|
||||
): MediaGrant {
|
||||
return {
|
||||
kind: MEDIA_GRANT_KIND,
|
||||
mediaId: r.mediaId,
|
||||
mediaKey: r.mediaKey,
|
||||
rootDigest: r.rootDigest,
|
||||
...(extra.url !== undefined ? { url: extra.url } : {}),
|
||||
...(extra.readToken !== undefined ? { readToken: extra.readToken } : {}),
|
||||
...(extra.meta !== undefined ? { meta: extra.meta } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function mediaKeysOf(g: MediaGrant): MediaKeys {
|
||||
return { mediaId: g.mediaId, mediaKey: g.mediaKey, rootDigest: g.rootDigest };
|
||||
}
|
||||
|
||||
/**
|
||||
* Wire JSON: binary fields as base64url, the digest as hex (it is a hash, and
|
||||
* greppable). The meta is written in its canonical order, so a grant always
|
||||
* encodes to the same link, however its meta object was built.
|
||||
*/
|
||||
export function encodeGrant(g: Grant): string {
|
||||
if (g.kind === MEDIA_GRANT_KIND) {
|
||||
return JSON.stringify({
|
||||
kind: g.kind,
|
||||
mediaId: toB64u(g.mediaId),
|
||||
key: toB64u(g.mediaKey),
|
||||
root: toHex(g.rootDigest),
|
||||
...(g.url !== undefined ? { url: g.url } : {}),
|
||||
...(g.readToken !== undefined ? { token: toB64u(g.readToken) } : {}),
|
||||
...(g.meta !== undefined ? { meta: validateMeta(g.meta) } : {}),
|
||||
});
|
||||
}
|
||||
return JSON.stringify({
|
||||
kind: g.kind,
|
||||
channelId: toB64u(g.channelId),
|
||||
signingKey: toB64u(g.signingKey),
|
||||
epoch: g.epoch,
|
||||
seq: g.seq,
|
||||
chainKey: toB64u(g.chainKey),
|
||||
stickyKey: toB64u(g.stickyKey),
|
||||
...(g.channelSecret !== undefined ? { channelSecret: toB64u(g.channelSecret) } : {}),
|
||||
...(g.url !== undefined ? { url: g.url } : {}),
|
||||
...(g.readToken !== undefined ? { token: toB64u(g.readToken) } : {}),
|
||||
...(g.meta !== undefined ? { meta: validateMeta(g.meta) } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function str(o: Record<string, unknown>, k: string): string {
|
||||
const v = o[k];
|
||||
if (typeof v !== 'string') throw new MediaFormatError(`grant.${k} must be a string`);
|
||||
return v;
|
||||
}
|
||||
|
||||
function int(o: Record<string, unknown>, k: string, max: number): number {
|
||||
const v = o[k];
|
||||
if (typeof v !== 'number' || !Number.isInteger(v) || v < 0 || v > max) {
|
||||
throw new MediaFormatError(`grant.${k} must be an integer in [0, ${max}]`);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
function optUrl(o: Record<string, unknown>): { url?: string } {
|
||||
if (o.url === undefined) return {};
|
||||
const url = str(o, 'url');
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(url);
|
||||
} catch {
|
||||
throw new MediaFormatError('grant.url is not a URL');
|
||||
}
|
||||
if (!['http:', 'https:', 'ws:', 'wss:'].includes(parsed.protocol)) {
|
||||
throw new MediaFormatError('grant.url must be http(s) or ws(s)');
|
||||
}
|
||||
return { url };
|
||||
}
|
||||
|
||||
function optToken(o: Record<string, unknown>): { readToken?: Uint8Array } {
|
||||
if (o.token === undefined) return {};
|
||||
const t = fromB64u(str(o, 'token'));
|
||||
if (t.length < 16 || t.length > 64) throw new MediaFormatError('grant.token must be 16–64 bytes');
|
||||
return { readToken: t };
|
||||
}
|
||||
|
||||
function optMeta(o: Record<string, unknown>): { meta?: MediaMeta } {
|
||||
if (o.meta === undefined) return {};
|
||||
return { meta: validateMeta(o.meta) };
|
||||
}
|
||||
|
||||
/** Parse a grant from wire JSON, strictly. Anything unexpected is refused. */
|
||||
export function parseGrant(json: string): Grant {
|
||||
let o: Record<string, unknown>;
|
||||
try {
|
||||
o = JSON.parse(json);
|
||||
} catch {
|
||||
throw new MediaFormatError('grant is not JSON');
|
||||
}
|
||||
if (typeof o !== 'object' || o === null || Array.isArray(o)) {
|
||||
throw new MediaFormatError('grant must be an object');
|
||||
}
|
||||
if (o.kind === MEDIA_GRANT_KIND) {
|
||||
return {
|
||||
kind: MEDIA_GRANT_KIND,
|
||||
mediaId: fromB64u(str(o, 'mediaId'), MEDIA_ID_BYTES),
|
||||
mediaKey: fromB64u(str(o, 'key'), MEDIA_KEY_BYTES),
|
||||
rootDigest: fromHex(str(o, 'root'), DIGEST_BYTES),
|
||||
...optUrl(o),
|
||||
...optToken(o),
|
||||
...optMeta(o),
|
||||
};
|
||||
}
|
||||
if (o.kind === LIVE_GRANT_KIND) {
|
||||
return {
|
||||
kind: LIVE_GRANT_KIND,
|
||||
channelId: fromB64u(str(o, 'channelId'), 16),
|
||||
signingKey: fromB64u(str(o, 'signingKey'), 32),
|
||||
epoch: int(o, 'epoch', 0xffff_ffff),
|
||||
seq: int(o, 'seq', Number.MAX_SAFE_INTEGER),
|
||||
chainKey: fromB64u(str(o, 'chainKey'), 32),
|
||||
stickyKey: fromB64u(str(o, 'stickyKey'), 32),
|
||||
...(o.channelSecret !== undefined ? { channelSecret: fromB64u(str(o, 'channelSecret'), 32) } : {}),
|
||||
...optUrl(o),
|
||||
...optToken(o),
|
||||
...optMeta(o),
|
||||
};
|
||||
}
|
||||
throw new MediaFormatError(`unknown grant kind ${String(o.kind)}`);
|
||||
}
|
||||
|
||||
/** Is this decrypted Shade message a grant? Cheap check before `parseGrant`. */
|
||||
export function isGrantMessage(plaintext: string): boolean {
|
||||
return (
|
||||
plaintext.startsWith('{') &&
|
||||
(plaintext.includes(`"${MEDIA_GRANT_KIND}"`) || plaintext.includes(`"${LIVE_GRANT_KIND}"`))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Capability link: `<page>#shade=<base64url(grant JSON)>`.
|
||||
*
|
||||
* The fragment never leaves the browser, so the page host learns nothing;
|
||||
* the page reads it, hands the grant to its Service Worker, and plays.
|
||||
*/
|
||||
export function toCapabilityUrl(pageUrl: string, g: Grant): string {
|
||||
const u = new URL(pageUrl);
|
||||
u.hash = `shade=${toB64u(enc.encode(encodeGrant(g)))}`;
|
||||
return u.toString();
|
||||
}
|
||||
|
||||
export function fromCapabilityUrl(link: string): Grant {
|
||||
const hash = link.includes('#') ? link.slice(link.indexOf('#') + 1) : link;
|
||||
const m = /(?:^|&)shade=([A-Za-z0-9_-]+)/.exec(hash);
|
||||
if (m === null) throw new MediaFormatError('link carries no #shade= grant');
|
||||
return parseGrant(dec.decode(fromB64u(m[1]!)));
|
||||
}
|
||||
161
packages/shade-media/src/image-stream.ts
Normal file
@@ -0,0 +1,161 @@
|
||||
/**
|
||||
* Split a byte stream of back-to-back images into whole images: what
|
||||
* `ffmpeg … -f image2pipe -c:v mjpeg -` (a webcam, a screen grab) or
|
||||
* `-c:v png` writes, for `shade live images`.
|
||||
*
|
||||
* JPEG is walked marker by marker, not searched for FFD9: an EXIF APP1
|
||||
* segment can hold a whole thumbnail JPEG, end marker included. Segments up
|
||||
* to SOS carry their length; after SOS, entropy-coded data stuffs every
|
||||
* 0xFF with 0x00, so the next 0xFF followed by anything but 0x00 or a
|
||||
* restart marker is the next real marker. PNG is walked chunk by chunk to
|
||||
* IEND.
|
||||
*/
|
||||
|
||||
import { MediaFormatError } from './errors.js';
|
||||
|
||||
export interface StreamImage {
|
||||
mime: 'image/jpeg' | 'image/png';
|
||||
bytes: Uint8Array;
|
||||
}
|
||||
|
||||
const PNG_SIG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
|
||||
|
||||
export class ImageStreamSplitter {
|
||||
private buf = new Uint8Array(0);
|
||||
/** Where scanning resumes inside the current image (bytes before are known to be one image's). */
|
||||
private scan = 0;
|
||||
private inEntropy = false;
|
||||
|
||||
/** @param maxImageBytes an image larger than this is refused, not buffered without end. */
|
||||
constructor(private readonly maxImageBytes = 16 * 1024 * 1024) {}
|
||||
|
||||
push(chunk: Uint8Array): StreamImage[] {
|
||||
const next = new Uint8Array(this.buf.length + chunk.length);
|
||||
next.set(this.buf);
|
||||
next.set(chunk, this.buf.length);
|
||||
this.buf = next;
|
||||
const out: StreamImage[] = [];
|
||||
for (;;) {
|
||||
const img = this.take();
|
||||
if (img === null) break;
|
||||
out.push(img);
|
||||
}
|
||||
if (this.buf.length > this.maxImageBytes) {
|
||||
throw new MediaFormatError(`an image in the stream is larger than ${this.maxImageBytes} bytes`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Call at end of input: leftover bytes are a truncated image. */
|
||||
finish(): void {
|
||||
if (this.buf.length > 0) throw new MediaFormatError(`the stream ended inside an image (${this.buf.length} bytes left)`);
|
||||
}
|
||||
|
||||
private take(): StreamImage | null {
|
||||
const b = this.buf;
|
||||
if (b.length === 0) return null;
|
||||
// Judge the start as soon as it can be judged: junk is refused, not waited on.
|
||||
const jpeg = b[0] === 0xff && (b.length < 2 || b[1] === 0xd8);
|
||||
const png = PNG_SIG.every((x, i) => i >= b.length || b[i] === x);
|
||||
if (!jpeg && !png) throw new MediaFormatError('not a stream of JPEG or PNG images');
|
||||
if (b.length < 8) return null;
|
||||
let end: number | null;
|
||||
let mime: StreamImage['mime'];
|
||||
if (b[0] === 0xff && b[1] === 0xd8) {
|
||||
mime = 'image/jpeg';
|
||||
end = this.jpegEnd();
|
||||
} else if (PNG_SIG.every((x, i) => b[i] === x)) {
|
||||
mime = 'image/png';
|
||||
end = this.pngEnd();
|
||||
} else {
|
||||
throw new MediaFormatError('not a stream of JPEG or PNG images');
|
||||
}
|
||||
if (end === null) return null;
|
||||
if (end > this.maxImageBytes) throw new MediaFormatError(`an image in the stream is larger than ${this.maxImageBytes} bytes`);
|
||||
const bytes = b.slice(0, end);
|
||||
this.buf = b.slice(end);
|
||||
this.scan = 0;
|
||||
this.inEntropy = false;
|
||||
return { mime, bytes };
|
||||
}
|
||||
|
||||
private jpegEnd(): number | null {
|
||||
const b = this.buf;
|
||||
let i = this.scan === 0 ? 2 : this.scan;
|
||||
for (;;) {
|
||||
if (this.inEntropy) {
|
||||
// Find the marker that ends the scan.
|
||||
for (; i + 1 < b.length; i++) {
|
||||
if (b[i] !== 0xff) continue;
|
||||
const m = b[i + 1]!;
|
||||
if (m === 0x00 || (m >= 0xd0 && m <= 0xd7) || m === 0xff) continue;
|
||||
break;
|
||||
}
|
||||
if (i + 1 >= b.length) {
|
||||
this.scan = i;
|
||||
return null;
|
||||
}
|
||||
this.inEntropy = false;
|
||||
}
|
||||
if (i + 2 > b.length) {
|
||||
this.scan = i;
|
||||
return null;
|
||||
}
|
||||
if (b[i] !== 0xff) throw new MediaFormatError(`JPEG: expected a marker at byte ${i}`);
|
||||
const m = b[i + 1]!;
|
||||
if (m === 0xff) {
|
||||
i++; // fill byte
|
||||
continue;
|
||||
}
|
||||
if (m === 0xd9) return i + 2; // EOI
|
||||
if ((m >= 0xd0 && m <= 0xd7) || m === 0x01) {
|
||||
i += 2; // no length
|
||||
continue;
|
||||
}
|
||||
if (i + 4 > b.length) {
|
||||
this.scan = i;
|
||||
return null;
|
||||
}
|
||||
const len = (b[i + 2]! << 8) | b[i + 3]!;
|
||||
if (len < 2) throw new MediaFormatError('JPEG: bad segment length');
|
||||
if (i + 2 + len > b.length) {
|
||||
this.scan = i;
|
||||
return null;
|
||||
}
|
||||
i += 2 + len;
|
||||
if (m === 0xda) this.inEntropy = true; // SOS: entropy-coded data follows its header
|
||||
}
|
||||
}
|
||||
|
||||
private pngEnd(): number | null {
|
||||
const b = this.buf;
|
||||
let i = this.scan === 0 ? 8 : this.scan;
|
||||
const v = new DataView(b.buffer, b.byteOffset, b.byteLength);
|
||||
for (;;) {
|
||||
if (i + 8 > b.length) {
|
||||
this.scan = i;
|
||||
return null;
|
||||
}
|
||||
const len = v.getUint32(i);
|
||||
const type = String.fromCharCode(b[i + 4]!, b[i + 5]!, b[i + 6]!, b[i + 7]!);
|
||||
if (!/^[A-Za-z]{4}$/.test(type)) throw new MediaFormatError('PNG: bad chunk type');
|
||||
const next = i + 12 + len;
|
||||
if (next > b.length) {
|
||||
this.scan = i;
|
||||
return null;
|
||||
}
|
||||
i = next;
|
||||
if (type === 'IEND') return i;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Image files `live images` publishes, by extension. */
|
||||
export const IMAGE_MIME: Record<string, string> = {
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.png': 'image/png',
|
||||
'.webp': 'image/webp',
|
||||
'.gif': 'image/gif',
|
||||
'.avif': 'image/avif',
|
||||
};
|
||||
41
packages/shade-media/src/index.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
export * from './errors.js';
|
||||
export {
|
||||
MediaSealer,
|
||||
MediaReader,
|
||||
sealMediaStream,
|
||||
sealMediaBytes,
|
||||
validateMeta,
|
||||
decodeFooter,
|
||||
encodeFooter,
|
||||
segmentCountFor,
|
||||
sealedSizeFor,
|
||||
DEFAULT_SEGMENT_SIZE,
|
||||
MIN_SEGMENT_SIZE,
|
||||
MAX_SEGMENT_SIZE,
|
||||
FOOTER_BYTES,
|
||||
} from './sealed.js';
|
||||
export type { MediaMeta, MediaKeys, SealResult, SealOptions, ReaderOptions, Footer } from './sealed.js';
|
||||
export { MemorySource, HttpRangeSource } from './source.js';
|
||||
export type { RangeSource, HttpRangeSourceOptions } from './source.js';
|
||||
export * from './grant.js';
|
||||
export { OwnerKey, verifyOwner, READ_TOKEN_HEADER, READ_HASH_HEADER } from './owner.js';
|
||||
export type { OwnerOp } from './owner.js';
|
||||
export { MediaClient, openGrant, openAlbum, readAlbum, mediaUrl } from './client.js';
|
||||
export { ALBUM_KIND, ALBUM_MIME, MAX_ALBUM_ITEMS, encodeAlbum, parseAlbum, isAlbum, albumMeta, isMediaGrant } from './album.js';
|
||||
export type { Album } from './album.js';
|
||||
export type { PutOptions } from './client.js';
|
||||
export { MAX_PIECE_BYTES, DEFAULT_CHUNK_BYTES, MAX_UPLOAD_BYTES, MAX_CLIENT_WINDOW, OFFSET_HEADER, UPLOAD_WINDOW, chunkFor, statusProblem } from './upload.js';
|
||||
export { LivePublisher, LiveSubscriber, epochKeys, chainStep, MAX_SKIP, MAX_SKIPPED_KEYS } from './live/channel.js';
|
||||
export type { FrameOptions, PublisherOptions, GrantOptions, ReceivedFrame } from './live/channel.js';
|
||||
export { encodeContent, decodeContent, decodeFrame, FLAG_STICKY, FLAG_KEYFRAME, FLAG_END } from './live/frame.js';
|
||||
export type { LiveContent, FrameHeader } from './live/frame.js';
|
||||
export { LivePublishClient, LiveWatchClient, liveUrl } from './live/client.js';
|
||||
export type { LiveState, PublishOptions, WatchOptions } from './live/client.js';
|
||||
export { MediaSplitter, sniffContainer } from './splitter.js';
|
||||
export type { MediaPiece, LiveContainer } from './splitter.js';
|
||||
export { WebmSplitter, webmMime } from './webm.js';
|
||||
export type { WebmPiece } from './webm.js';
|
||||
export { Fmp4Splitter, fmp4Mime } from './fmp4.js';
|
||||
export type { Fmp4Piece } from './fmp4.js';
|
||||
export { SUBTITLES_KEY, SUBTITLE_EXTENSIONS, withSubtitles, subtitlesOf, subtitleFor, srtToVtt } from './subtitles.js';
|
||||
export type { SubtitleTrack } from './subtitles.js';
|
||||
112
packages/shade-media/src/library.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* This machine's record of what it uploaded: names and links.
|
||||
*
|
||||
* The relay knows ids and sizes, never names, and a link is only printed
|
||||
* once. Lose the link and a film you own is unreachable. So every upload is
|
||||
* written down here, with its grant, under `$XDG_CONFIG_HOME/shade/` beside
|
||||
* the owner key, mode 0600: a grant is a key.
|
||||
*
|
||||
* Format: one JSON object per line, appended (`{"op":"add",…}`,
|
||||
* `{"op":"rm","id":…}`). Appends of a line are atomic on a local disk, so two
|
||||
* `shade media put` running at once cannot lose each other's entries, and no
|
||||
* lock is needed. Reading folds the lines; a damaged line is skipped.
|
||||
*/
|
||||
|
||||
import { appendFile, mkdir, readFile } from 'node:fs/promises';
|
||||
import { dirname } from 'node:path';
|
||||
import { toHex } from './bytes.js';
|
||||
import { encodeGrant, parseGrant } from './grant.js';
|
||||
import type { MediaGrant } from './grant.js';
|
||||
|
||||
export interface LibraryEntry {
|
||||
/** Lowercase hex media id. */
|
||||
id: string;
|
||||
/** Relay base URL it was uploaded to. */
|
||||
server: string;
|
||||
name?: string;
|
||||
mime?: string;
|
||||
/** Sealed bytes on the relay. */
|
||||
size: number;
|
||||
createdAt: number;
|
||||
grant: MediaGrant;
|
||||
}
|
||||
|
||||
export class MediaLibrary {
|
||||
private constructor(
|
||||
readonly path: string,
|
||||
private readonly byId: Map<string, LibraryEntry>,
|
||||
) {}
|
||||
|
||||
static async open(path: string): Promise<MediaLibrary> {
|
||||
const byId = new Map<string, LibraryEntry>();
|
||||
let text = '';
|
||||
try {
|
||||
text = await readFile(path, 'utf8');
|
||||
} catch (e) {
|
||||
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e;
|
||||
}
|
||||
for (const line of text.split('\n')) {
|
||||
if (line.trim() === '') continue;
|
||||
try {
|
||||
const o = JSON.parse(line) as Record<string, unknown>;
|
||||
if (o.op === 'rm' && typeof o.id === 'string') {
|
||||
byId.delete(o.id);
|
||||
} else if (o.op === 'add' && typeof o.id === 'string' && typeof o.server === 'string') {
|
||||
const grant = parseGrant(JSON.stringify(o.grant));
|
||||
if (grant.kind !== 'shade.media-grant/v1') continue;
|
||||
byId.set(o.id, {
|
||||
id: o.id,
|
||||
server: o.server,
|
||||
...(typeof o.name === 'string' ? { name: o.name } : {}),
|
||||
...(typeof o.mime === 'string' ? { mime: o.mime } : {}),
|
||||
size: typeof o.size === 'number' ? o.size : 0,
|
||||
createdAt: typeof o.createdAt === 'number' ? o.createdAt : 0,
|
||||
grant,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// A torn or hand-edited line costs that entry, not the library.
|
||||
}
|
||||
}
|
||||
return new MediaLibrary(path, byId);
|
||||
}
|
||||
|
||||
entries(): LibraryEntry[] {
|
||||
return [...this.byId.values()].sort((a, b) => b.createdAt - a.createdAt);
|
||||
}
|
||||
|
||||
get(id: string): LibraryEntry | undefined {
|
||||
return this.byId.get(id);
|
||||
}
|
||||
|
||||
/** Entries whose id starts with `query`, or whose name contains it (any case). */
|
||||
find(query: string): LibraryEntry[] {
|
||||
const q = query.toLowerCase();
|
||||
return this.entries().filter((e) => e.id.startsWith(q) || (e.name ?? '').toLowerCase().includes(q));
|
||||
}
|
||||
|
||||
async add(server: string, grant: MediaGrant, size: number): Promise<LibraryEntry> {
|
||||
const entry: LibraryEntry = {
|
||||
id: toHex(grant.mediaId),
|
||||
server: server.replace(/\/$/, ''),
|
||||
...(grant.meta?.name !== undefined ? { name: grant.meta.name } : {}),
|
||||
...(grant.meta?.mime !== undefined ? { mime: grant.meta.mime } : {}),
|
||||
size,
|
||||
createdAt: Date.now(),
|
||||
grant,
|
||||
};
|
||||
await this.append({ op: 'add', ...entry, grant: JSON.parse(encodeGrant(grant)) as unknown });
|
||||
this.byId.set(entry.id, entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
async remove(id: string): Promise<void> {
|
||||
await this.append({ op: 'rm', id });
|
||||
this.byId.delete(id);
|
||||
}
|
||||
|
||||
private async append(o: unknown): Promise<void> {
|
||||
await mkdir(dirname(this.path), { recursive: true, mode: 0o700 });
|
||||
await appendFile(this.path, `${JSON.stringify(o)}\n`, { mode: 0o600 });
|
||||
}
|
||||
}
|
||||
507
packages/shade-media/src/live/channel.ts
Normal file
@@ -0,0 +1,507 @@
|
||||
/**
|
||||
* Live channels: one publisher, any number of viewers, a dumb relay between.
|
||||
*
|
||||
* The key schedule is Signal's **Sender Keys**, the construction WhatsApp and
|
||||
* Signal use for groups, adapted to a broadcast:
|
||||
*
|
||||
* epochSeed random 32 bytes 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(ck[i], 0x01) frame key for seq i, used once
|
||||
* ck[i+1] = HMAC(ck[i], 0x02) one-way: ck[i] cannot be recovered
|
||||
* nonce = u32(epoch) ‖ u64(seq) aad = the 48-byte frame header
|
||||
*
|
||||
* Every frame is also **signed** with the channel's Ed25519 key. Viewers all
|
||||
* hold the same chain key, so without the signature any one of them could
|
||||
* forge frames to the others through the relay; with it, only the publisher
|
||||
* can speak. The signing key's public half travels in the grant, which
|
||||
* travels over an authenticated Shade session — that is what binds the
|
||||
* channel to a person.
|
||||
*
|
||||
* Joining late: a grant carries the chain key *at some seq*. The publisher
|
||||
* keeps snapshots of the chain at recent keyframes (bounded), so a new viewer
|
||||
* can be handed the key at a point the relay still has buffered and start
|
||||
* from there — never earlier. Removing a viewer is a new epoch: fresh seed,
|
||||
* fresh grants for everyone still in.
|
||||
*
|
||||
* Sticky frames (codec init, the channel's own description) are sealed under
|
||||
* the epoch's `stickyKey` instead of the chain, so a viewer who joins an hour
|
||||
* in can still decode the init segment the publisher sent at second zero.
|
||||
*/
|
||||
|
||||
import { ed25519 } from '@noble/curves/ed25519.js';
|
||||
import { hkdf } from '@noble/hashes/hkdf.js';
|
||||
import { hmac } from '@noble/hashes/hmac.js';
|
||||
import { sha256 } from '@noble/hashes/sha2.js';
|
||||
import { openOnce, sealOnce } from '../aead.js';
|
||||
import { Ed25519Signer, Ed25519Verifier } from '../ed25519.js';
|
||||
import { concat, enc, equalBytes, randomBytes, toB64u, u32be, u64be } from '../bytes.js';
|
||||
import { LiveKeyError, MediaFormatError, MediaIntegrityError } from '../errors.js';
|
||||
import { LIVE_GRANT_KIND } from '../grant.js';
|
||||
import type { LiveGrant } from '../grant.js';
|
||||
import type { MediaMeta } from '../sealed.js';
|
||||
import {
|
||||
CHANNEL_ID_BYTES,
|
||||
FLAG_END,
|
||||
FLAG_KEYFRAME,
|
||||
FLAG_STICKY,
|
||||
MAX_FRAME_PAYLOAD,
|
||||
decodeContent,
|
||||
decodeFrame,
|
||||
encodeContent,
|
||||
encodeHeader,
|
||||
} from './frame.js';
|
||||
import type { LiveContent } from './frame.js';
|
||||
|
||||
const INFO_CHAIN = enc.encode('shade-live/v1\0chain');
|
||||
const INFO_STICKY = enc.encode('shade-live/v1\0sticky');
|
||||
const INFO_EPOCH = enc.encode('shade-live/v1\0epoch');
|
||||
const MK = new Uint8Array([0x01]);
|
||||
const CK = new Uint8Array([0x02]);
|
||||
|
||||
/** Furthest a subscriber will derive forward to reach one frame. */
|
||||
export const MAX_SKIP = 100_000;
|
||||
/** Frame keys a subscriber keeps for frames that may still arrive out of order. */
|
||||
export const MAX_SKIPPED_KEYS = 2_000;
|
||||
|
||||
export function epochKeys(
|
||||
epochSeed: Uint8Array,
|
||||
channelId: Uint8Array,
|
||||
epoch: number,
|
||||
): { chainKey: Uint8Array; stickyKey: Uint8Array } {
|
||||
const salt = concat([channelId, u32be(epoch)]);
|
||||
return {
|
||||
chainKey: hkdf(sha256, epochSeed, salt, INFO_CHAIN, 32),
|
||||
stickyKey: hkdf(sha256, epochSeed, salt, INFO_STICKY, 32),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Link mode: the seed of epoch `e` derived from a long-lived channel secret,
|
||||
* so a holder of the secret can follow every epoch on its own — across
|
||||
* publisher restarts and rotations, with no one to hand it a new grant.
|
||||
*/
|
||||
export function linkEpochSeed(channelSecret: Uint8Array, channelId: Uint8Array, epoch: number): Uint8Array {
|
||||
return hkdf(sha256, channelSecret, channelId, concat([INFO_EPOCH, u32be(epoch)]), 32);
|
||||
}
|
||||
|
||||
/** One chain step: the frame key for this seq, and the chain key for the next. */
|
||||
export function chainStep(ck: Uint8Array): { messageKey: Uint8Array; next: Uint8Array } {
|
||||
return { messageKey: hmac(sha256, ck, MK), next: hmac(sha256, ck, CK) };
|
||||
}
|
||||
|
||||
export function frameNonce(epoch: number, seq: number): Uint8Array {
|
||||
return concat([u32be(epoch), u64be(seq)]);
|
||||
}
|
||||
|
||||
export interface FrameOptions {
|
||||
/** A viewer can start here (a video keyframe, a log batch boundary). */
|
||||
keyframe?: boolean;
|
||||
/** Keep for every late joiner, sealed under the epoch's sticky key. */
|
||||
sticky?: boolean;
|
||||
/** Publisher clock, ms. Defaults to `Date.now()`. */
|
||||
timestamp?: number;
|
||||
}
|
||||
|
||||
export interface PublisherOptions {
|
||||
meta?: MediaMeta;
|
||||
/** Chain snapshots kept for late joiners. Default 64 keyframes. */
|
||||
snapshots?: number;
|
||||
/** Bring your own channel identity (to resume a channel after a restart). */
|
||||
channelId?: Uint8Array;
|
||||
signingSecret?: Uint8Array;
|
||||
/**
|
||||
* Link mode. Epoch seeds are derived from this secret instead of drawn at
|
||||
* random, and grants made with `{ link: true }` carry it — so a capability
|
||||
* link keeps working across restarts and rotations. The price: no forward
|
||||
* secrecy against a link holder, and no removing one short of a new
|
||||
* channel. Session grants stay per-epoch either way.
|
||||
*/
|
||||
channelSecret?: Uint8Array;
|
||||
/** First epoch (resume a channel after a restart with `lastEpoch + 1`). */
|
||||
epoch?: number;
|
||||
/** Start a new epoch every this many frames, so catching up stays cheap. */
|
||||
rotateEvery?: number;
|
||||
}
|
||||
|
||||
export interface GrantOptions {
|
||||
/**
|
||||
* Where the viewer can start: `oldest` keyframe snapshot still kept (most
|
||||
* backlog), the `latest` keyframe, or `now` (only frames sent after this).
|
||||
* Default `oldest`.
|
||||
*/
|
||||
from?: 'oldest' | 'latest' | 'now';
|
||||
url?: string;
|
||||
readToken?: Uint8Array;
|
||||
/** Include the channel secret (link mode only): the grant then covers every epoch from now on. */
|
||||
link?: boolean;
|
||||
}
|
||||
|
||||
interface Snapshot {
|
||||
seq: number;
|
||||
chainKey: Uint8Array;
|
||||
}
|
||||
|
||||
/**
|
||||
* The sending side of a live channel. Not safe to call `frame` concurrently —
|
||||
* frames are numbered in call order; await each before the next (the
|
||||
* `LiveClient` does this for you).
|
||||
*/
|
||||
export class LivePublisher {
|
||||
readonly channelId: Uint8Array;
|
||||
readonly signingKey: Uint8Array;
|
||||
readonly meta: MediaMeta | undefined;
|
||||
private readonly signingSecret: Uint8Array;
|
||||
private readonly signer: Ed25519Signer;
|
||||
private epochValue = 0;
|
||||
private seq = 0;
|
||||
private chainKey: Uint8Array;
|
||||
private stickyKey: Uint8Array;
|
||||
private snapshots: Snapshot[] = [];
|
||||
private readonly snapshotLimit: number;
|
||||
/** Plaintext of sticky content, re-sealed into every new epoch. */
|
||||
private stickyContent: { content: LiveContent; opts: FrameOptions }[] = [];
|
||||
/** Sealed sticky frames of the current epoch — what a relay must keep. */
|
||||
private stickyFrames: Uint8Array[] = [];
|
||||
private closed = false;
|
||||
private readonly channelSecret: Uint8Array | null;
|
||||
private readonly rotateEvery: number;
|
||||
|
||||
constructor(opts: PublisherOptions = {}) {
|
||||
this.channelId = opts.channelId ?? randomBytes(CHANNEL_ID_BYTES);
|
||||
if (this.channelId.length !== CHANNEL_ID_BYTES) throw new MediaFormatError('channelId must be 16 bytes');
|
||||
this.signingSecret = opts.signingSecret ?? ed25519.utils.randomSecretKey();
|
||||
this.signer = new Ed25519Signer(this.signingSecret);
|
||||
this.signingKey = this.signer.publicKey;
|
||||
this.meta = opts.meta;
|
||||
this.snapshotLimit = Math.max(1, opts.snapshots ?? 64);
|
||||
this.channelSecret = opts.channelSecret ?? null;
|
||||
if (this.channelSecret !== null && this.channelSecret.length !== 32) {
|
||||
throw new MediaFormatError('channelSecret must be 32 bytes');
|
||||
}
|
||||
this.rotateEvery = opts.rotateEvery ?? Number.POSITIVE_INFINITY;
|
||||
this.epochValue = opts.epoch ?? 0;
|
||||
const k = epochKeys(this.seedFor(this.epochValue), this.channelId, this.epochValue);
|
||||
this.chainKey = k.chainKey;
|
||||
this.stickyKey = k.stickyKey;
|
||||
}
|
||||
|
||||
private seedFor(epoch: number): Uint8Array {
|
||||
return this.channelSecret !== null ? linkEpochSeed(this.channelSecret, this.channelId, epoch) : randomBytes(32);
|
||||
}
|
||||
|
||||
/** True when the next frame should go out in a fresh epoch (see `rotateEvery`). */
|
||||
get rotationDue(): boolean {
|
||||
return this.seq >= this.rotateEvery;
|
||||
}
|
||||
|
||||
get epoch(): number {
|
||||
return this.epochValue;
|
||||
}
|
||||
|
||||
get nextSeq(): number {
|
||||
return this.seq;
|
||||
}
|
||||
|
||||
/** Sticky frames of the current epoch, in order — replay these to a fresh relay. */
|
||||
get sticky(): readonly Uint8Array[] {
|
||||
return this.stickyFrames;
|
||||
}
|
||||
|
||||
/** Seal one frame. */
|
||||
async frame(content: LiveContent, opts: FrameOptions = {}): Promise<Uint8Array> {
|
||||
if (this.closed) throw new Error('LivePublisher is closed');
|
||||
const plain = encodeContent(content);
|
||||
if (plain.length > MAX_FRAME_PAYLOAD) throw new MediaFormatError('live frame payload too large');
|
||||
const seq = this.seq++;
|
||||
const sticky = opts.sticky === true;
|
||||
const keyframe = opts.keyframe === true;
|
||||
let flags = 0;
|
||||
if (sticky) flags |= FLAG_STICKY;
|
||||
if (keyframe) flags |= FLAG_KEYFRAME;
|
||||
if (content.type === 'end') flags |= FLAG_END;
|
||||
|
||||
// The chain advances on every seq, sticky or not, so a viewer's position
|
||||
// in the chain is always just the seq.
|
||||
if (keyframe && !sticky) this.snapshot(seq, this.chainKey);
|
||||
const step = chainStep(this.chainKey);
|
||||
this.chainKey.fill(0);
|
||||
this.chainKey = step.next;
|
||||
|
||||
const header = encodeHeader({
|
||||
flags,
|
||||
channelId: this.channelId,
|
||||
epoch: this.epochValue,
|
||||
seq,
|
||||
timestamp: Math.floor(opts.timestamp ?? Date.now()),
|
||||
ctLen: plain.length + 16,
|
||||
});
|
||||
const key = sticky ? this.stickyKey : step.messageKey;
|
||||
const ct = await sealOnce(key, frameNonce(this.epochValue, seq), plain, header);
|
||||
step.messageKey.fill(0);
|
||||
const signed = concat([header, ct]);
|
||||
const frame = concat([signed, await this.signer.sign(signed)]);
|
||||
if (sticky) {
|
||||
this.stickyFrames.push(frame);
|
||||
this.stickyContent.push({ content, opts });
|
||||
}
|
||||
return frame;
|
||||
}
|
||||
|
||||
private snapshot(seq: number, ck: Uint8Array): void {
|
||||
this.snapshots.push({ seq, chainKey: ck.slice() });
|
||||
while (this.snapshots.length > this.snapshotLimit) this.snapshots.shift()!.chainKey.fill(0);
|
||||
}
|
||||
|
||||
/** Keys for one viewer to join from `opts.from`. Send it over a Shade session. */
|
||||
grant(opts: GrantOptions = {}): LiveGrant {
|
||||
const from = opts.from ?? 'oldest';
|
||||
let point: Snapshot;
|
||||
if (from === 'now' || this.snapshots.length === 0) {
|
||||
point = { seq: this.seq, chainKey: this.chainKey };
|
||||
} else {
|
||||
point = from === 'latest' ? this.snapshots[this.snapshots.length - 1]! : this.snapshots[0]!;
|
||||
}
|
||||
return {
|
||||
kind: LIVE_GRANT_KIND,
|
||||
channelId: this.channelId,
|
||||
signingKey: this.signingKey,
|
||||
epoch: this.epochValue,
|
||||
seq: point.seq,
|
||||
chainKey: point.chainKey.slice(),
|
||||
stickyKey: this.stickyKey.slice(),
|
||||
...(opts.url !== undefined ? { url: opts.url } : {}),
|
||||
...(opts.readToken !== undefined ? { readToken: opts.readToken } : {}),
|
||||
...(this.meta !== undefined ? { meta: this.meta } : {}),
|
||||
...(opts.link === true ? { channelSecret: this.requireSecret().slice() } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
private requireSecret(): Uint8Array {
|
||||
if (this.channelSecret === null) throw new Error('link grants need a publisher created with channelSecret');
|
||||
return this.channelSecret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start a new epoch: fresh seed, seq back to 0, snapshots dropped. Returns
|
||||
* the sticky frames re-sealed for the new epoch — send them first. Grant
|
||||
* everyone who should stay; anyone not re-granted is out.
|
||||
*/
|
||||
async rotate(): Promise<Uint8Array[]> {
|
||||
if (this.epochValue >= 0xffff_ffff) throw new Error('epoch counter exhausted');
|
||||
this.epochValue++;
|
||||
this.seq = 0;
|
||||
for (const s of this.snapshots) s.chainKey.fill(0);
|
||||
this.snapshots = [];
|
||||
this.chainKey.fill(0);
|
||||
this.stickyKey.fill(0);
|
||||
const k = epochKeys(this.seedFor(this.epochValue), this.channelId, this.epochValue);
|
||||
this.chainKey = k.chainKey;
|
||||
this.stickyKey = k.stickyKey;
|
||||
const content = this.stickyContent;
|
||||
this.stickyContent = [];
|
||||
this.stickyFrames = [];
|
||||
const out: Uint8Array[] = [];
|
||||
for (const c of content) out.push(await this.frame(c.content, c.opts));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The signed hello a relay pins the channel with. */
|
||||
hello(readTokenHash: Uint8Array, at = Date.now()): { body: string; signature: Uint8Array } {
|
||||
const body = JSON.stringify({
|
||||
kind: 'shade.live-hello/v1',
|
||||
channelId: toB64u(this.channelId),
|
||||
signingKey: toB64u(this.signingKey),
|
||||
readTokenHash: toB64u(readTokenHash),
|
||||
at,
|
||||
});
|
||||
return { body, signature: ed25519.sign(enc.encode(body), this.signingSecret) };
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.closed = true;
|
||||
this.chainKey.fill(0);
|
||||
this.stickyKey.fill(0);
|
||||
for (const s of this.snapshots) s.chainKey.fill(0);
|
||||
this.snapshots = [];
|
||||
}
|
||||
}
|
||||
|
||||
export interface ReceivedFrame {
|
||||
epoch: number;
|
||||
seq: number;
|
||||
timestamp: number;
|
||||
sticky: boolean;
|
||||
keyframe: boolean;
|
||||
content: LiveContent;
|
||||
}
|
||||
|
||||
interface EpochState {
|
||||
stickyKey: Uint8Array;
|
||||
nextSeq: number;
|
||||
chainKey: Uint8Array;
|
||||
skipped: Map<number, Uint8Array>;
|
||||
stickySeen: Set<number>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The viewing side. Feed it frames in any order; it returns each decrypted
|
||||
* frame once, or `null` for one it should silently drop — a duplicate after
|
||||
* a reconnect, or backlog from before the grant's starting point.
|
||||
*/
|
||||
export class LiveSubscriber {
|
||||
private readonly epochs = new Map<number, EpochState>();
|
||||
readonly channelId: Uint8Array;
|
||||
readonly signingKey: Uint8Array;
|
||||
private readonly verifier: Ed25519Verifier;
|
||||
/** Link mode: derive epochs from here on by ourselves. */
|
||||
private link: { secret: Uint8Array; fromEpoch: number } | null = null;
|
||||
|
||||
constructor(grant: LiveGrant) {
|
||||
this.channelId = grant.channelId;
|
||||
this.signingKey = grant.signingKey;
|
||||
this.verifier = new Ed25519Verifier(grant.signingKey);
|
||||
this.addGrant(grant);
|
||||
}
|
||||
|
||||
/** Can this subscriber read epoch `e` (now, or by deriving it)? */
|
||||
canRead(epoch: number): boolean {
|
||||
return this.epochs.has(epoch) || (this.link !== null && epoch >= this.link.fromEpoch);
|
||||
}
|
||||
|
||||
private epochState(epoch: number): EpochState | undefined {
|
||||
const st = this.epochs.get(epoch);
|
||||
if (st !== undefined || this.link === null || epoch < this.link.fromEpoch) return st;
|
||||
const k = epochKeys(linkEpochSeed(this.link.secret, this.channelId, epoch), this.channelId, epoch);
|
||||
const fresh: EpochState = {
|
||||
stickyKey: k.stickyKey,
|
||||
nextSeq: 0,
|
||||
chainKey: k.chainKey,
|
||||
skipped: new Map(),
|
||||
stickySeen: new Set(),
|
||||
};
|
||||
this.epochs.set(epoch, fresh);
|
||||
// A link viewer moves forward with the channel; old epochs are dropped.
|
||||
this.forgetBefore(epoch);
|
||||
return fresh;
|
||||
}
|
||||
|
||||
/** Add the grant for a new epoch (after a rotation). Older epochs are kept until `forgetBefore`. */
|
||||
addGrant(g: LiveGrant): void {
|
||||
if (!equalBytes(g.channelId, this.channelId)) throw new MediaFormatError('grant is for another channel');
|
||||
if (!equalBytes(g.signingKey, this.signingKey)) {
|
||||
// A new signing key mid-channel would let whoever sent this grant speak
|
||||
// as the publisher. A publisher that truly re-keys starts a new channel.
|
||||
throw new MediaIntegrityError('grant changes the channel signing key');
|
||||
}
|
||||
if (g.channelSecret !== undefined) {
|
||||
if (this.link === null || g.epoch < this.link.fromEpoch) this.link = { secret: g.channelSecret.slice(), fromEpoch: g.epoch };
|
||||
}
|
||||
const existing = this.epochs.get(g.epoch);
|
||||
if (existing !== undefined && existing.nextSeq <= g.seq) return;
|
||||
this.epochs.set(g.epoch, {
|
||||
stickyKey: g.stickyKey.slice(),
|
||||
nextSeq: g.seq,
|
||||
chainKey: g.chainKey.slice(),
|
||||
skipped: new Map(),
|
||||
stickySeen: new Set(),
|
||||
});
|
||||
}
|
||||
|
||||
/** Drop key state for epochs older than `epoch` (forward secrecy after rotation). */
|
||||
forgetBefore(epoch: number): void {
|
||||
for (const [e, st] of this.epochs) {
|
||||
if (e < epoch) {
|
||||
st.chainKey.fill(0);
|
||||
st.stickyKey.fill(0);
|
||||
for (const k of st.skipped.values()) k.fill(0);
|
||||
this.epochs.delete(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
get latestEpoch(): number {
|
||||
return Math.max(...this.epochs.keys());
|
||||
}
|
||||
|
||||
/** Verify and decrypt one frame. Throws on forgery; `null` means "drop, harmlessly". */
|
||||
async open(frame: Uint8Array): Promise<ReceivedFrame | null> {
|
||||
const f = decodeFrame(frame);
|
||||
const h = f.header;
|
||||
if (!equalBytes(h.channelId, this.channelId)) throw new MediaFormatError('frame is for another channel');
|
||||
if (!(await this.verifier.verify(f.signature, f.signed))) {
|
||||
throw new MediaIntegrityError('live frame signature does not verify');
|
||||
}
|
||||
const st = this.epochState(h.epoch);
|
||||
if (st === undefined) {
|
||||
throw new LiveKeyError(`no grant for epoch ${h.epoch} (have ${[...this.epochs.keys()].join(', ')})`);
|
||||
}
|
||||
const sticky = (h.flags & FLAG_STICKY) !== 0;
|
||||
const nonce = frameNonce(h.epoch, h.seq);
|
||||
let plain: Uint8Array;
|
||||
if (sticky) {
|
||||
if (st.stickySeen.has(h.seq)) return null;
|
||||
plain = await openOnce(st.stickyKey, nonce, f.ciphertext, f.headerBytes);
|
||||
st.stickySeen.add(h.seq);
|
||||
} else {
|
||||
const mk = this.messageKey(st, h.seq);
|
||||
if (mk === null) return null;
|
||||
try {
|
||||
plain = await openOnce(mk, nonce, f.ciphertext, f.headerBytes);
|
||||
} finally {
|
||||
mk.fill(0);
|
||||
}
|
||||
}
|
||||
return {
|
||||
epoch: h.epoch,
|
||||
seq: h.seq,
|
||||
timestamp: h.timestamp,
|
||||
sticky,
|
||||
keyframe: (h.flags & FLAG_KEYFRAME) !== 0,
|
||||
content: decodeContent(plain),
|
||||
};
|
||||
}
|
||||
|
||||
private messageKey(st: EpochState, seq: number): Uint8Array | null {
|
||||
if (seq < st.nextSeq) {
|
||||
const k = st.skipped.get(seq);
|
||||
if (k === undefined) return null; // before the grant, or already seen
|
||||
st.skipped.delete(seq);
|
||||
return k;
|
||||
}
|
||||
if (seq - st.nextSeq > MAX_SKIP) {
|
||||
throw new LiveKeyError(`frame ${seq} is ${seq - st.nextSeq} ahead — beyond MAX_SKIP`);
|
||||
}
|
||||
// Derive forward, keeping keys for the frames we skip in case they
|
||||
// arrive late. Oldest are evicted first: a frame that late is useless
|
||||
// for live playback anyway.
|
||||
let ck = st.chainKey;
|
||||
for (let s = st.nextSeq; s < seq; s++) {
|
||||
const step = chainStep(ck);
|
||||
ck.fill(0);
|
||||
ck = step.next;
|
||||
if (seq - s <= MAX_SKIPPED_KEYS) {
|
||||
st.skipped.set(s, step.messageKey);
|
||||
if (st.skipped.size > MAX_SKIPPED_KEYS) {
|
||||
const oldest = st.skipped.keys().next().value!;
|
||||
st.skipped.get(oldest)!.fill(0);
|
||||
st.skipped.delete(oldest);
|
||||
}
|
||||
} else {
|
||||
step.messageKey.fill(0);
|
||||
}
|
||||
}
|
||||
const step = chainStep(ck);
|
||||
ck.fill(0);
|
||||
st.chainKey = step.next;
|
||||
st.nextSeq = seq + 1;
|
||||
return step.messageKey;
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.forgetBefore(Number.MAX_SAFE_INTEGER);
|
||||
this.link?.secret.fill(0);
|
||||
this.link = null;
|
||||
}
|
||||
}
|
||||
|
||||