Repository navigation
Streaming media pipeline + native file handles for multi-GB sources - #24
Merged
Merged
Conversation
Sync stage was failing on multi-GB recordings with the cryptic "File could not be read! Code=-1" because every decode path (decodeAudioData, ffmpeg.wasm MEMFS) loads the whole file into a single ArrayBuffer and Chromium caps that at ~2 GiB. New streaming pipeline for files ≥ 500 MiB: - chunkedReader feeds 4 MiB batches from File.stream() - mp4-moov-locator pre-fetches the moov box from the tail (phone recordings put moov last) so mp4box can parse track info without buffering the entire mdat - streaming-mp4-audio.ts wires mp4box's chunked appendBuffer to a WebCodecs AudioDecoder + linear-interp mono resampler, with releaseUsedSamples between batches to keep memory bounded - streaming-mp3.ts parses MPEG Layer III frames directly + MP3 AudioDecoder; streaming-wav.ts handles RIFF/WAVE sequentially - codec/index.ts auto-routes by Blob.size; <500 MiB stays on the existing fast path. forceBackend: "streaming" added for tests. Verified live on a 9 GB / 16-min H.264 phone recording: full audio extraction in 11 s with peak JS heap of 15 MB (vs OOM before). Capability gating + Upload UI: - supportsLargeMediaFiles(caps) checks for AudioDecoder + VideoDecoder - Upload.tsx shows a banner on browsers without WebCodecs and rejects files > 1.9 GiB upfront with a clear message instead of letting them blow up deep in the sync stage Defensive cleanup discovered during the bug hunt: - ffmpeg/audio-decode + frames/ffmpeg: replaced @ffmpeg/util's fetchFile (legacy FileReader path that rejects OPFS-backed Files with "Code=-1" on some Chromium builds) with source.arrayBuffer() - codec/index.ts: chained error message surfaces both WebCodecs and ffmpeg failure reasons when both backends fail - jobs.ts runSync catch: prefixes job.error with progress.stage so the JobPage banner shows e.g. "[decoding-studio-audio] …" instead of a context-free decoder message Demux/video-side streaming for moov-last big files is still future work — mp4box's video-track sample extraction silently fails after a moov-prefetched chunked feed (audio works fine on the same file). demux.ts is refactored to an AsyncIterable shape so the streaming upgrade can land without touching callers (CamFrameStream, extractFrameStripWebcodecs already iterate via for-await). Tests: 731 unit (+21 new), 192/193 browser (1 perf-test flake unrelated to this change). New browser e2e for the OPFS+ffmpeg path (`codec-resolver.browser.test.ts`), streaming sub-decoders (`streaming/*.browser.test.ts`), routing (`streaming-routing.browser.test.ts`), capability flag (`capabilities.test.ts`), and Upload UI gating (`Upload.test.tsx`). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Replaces mp4box's processSamples/onSamples dispatch with direct
sample-table extraction:
1. Pre-fetch the moov box from the tail (phone recordings put moov
last; locateMoov walks box headers from the head, jumping over
mdat by its declared size — never reads the body).
2. Feed mp4box only [head] + [moov bytes] so it can parse the
stbl/stco/stsz tables. The mdat body is never handed to mp4box.
3. After onReady, read trakBox.samples[] directly — mp4box already
populated each entry's {offset, size, cts, dts, duration,
is_sync, timescale} when it parsed stbl.
4. The AsyncIterable yields one sample at a time via
`Blob.slice(offset, offset+size).arrayBuffer()` — random-access
reads with no buffering.
Why bypass mp4box's processSamples: it requires contiguous bytes from
byte 0 to fire the per-track sample dispatcher. After a moov-prefetched
chunked feed, the audio-track dispatcher works but the video one
silently doesn't — root cause is in mp4box's per-track state machine
and out of scope here. We do the byte-fetching ourselves; mp4box still
parses the structural boxes.
Verified live on the user's 9 GB / 16-min H.264 phone recording:
- 48,130 video chunks demuxed in 17 s (515 MB/s effective throughput)
- Peak JS heap 14 MB (vs OOM with the old eager arrayBuffer path)
- Same VideoChunk shape — CamFrameStream / extractFrameStripWebcodecs
consume it unchanged via for-await
Frame-strip strategy tweak (related concern surfaced by user):
- Default maxTiles: 200 → 100 (a 16-min recording at 100 tiles is
~9.6 s per tile, still useful for the timeline)
- New step bands for long files: ≤30 min → 5s, >30 min → 10s
(avoids hitting the cap with arbitrary step values)
Tests: 733 unit (+2 new strategy tests), 193/193 browser. Existing
demux unit tests pass unchanged — small files (<64 KiB head probe
contains the entire moov) skip the tail fetch entirely.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
When the browser exposes `showOpenFilePicker` (Chrome / Edge / Brave),
upload picks return a `FileSystemFileHandle` that we persist directly
on the asset row. The bytes never leave the user's disk:
- 9 GB phone recording → previously 9 GB OPFS copy (18 GB total
on disk). Now: just a handle reference in IDB, sub-MB.
- Project survives reload: handles are persisted via IndexedDB's
structured clone. On reopen, JobPermissionRoute checks each
handle's read state via `queryPermission`; if "prompt", a
one-click "Allow access" gate triggers `requestPermission` from
a real user gesture (the browser's strict requirement).
Safari / Firefox without `showOpenFilePicker` keep working: the
file-picker module falls back to a hidden `<input type=file>` and
the picked file's bytes get copied to OPFS (the legacy v2 path).
PickedAsset's `handle: null` is the discriminator — `persistPickedAsset`
either returns the handle as-is or writes to OPFS based on its presence.
## Architecture
- `local/asset-source.ts` — `AssetSource` discriminated union
(`{kind:'opfs', path}` | `{kind:'handle', handle}`) plus
`loadAsset` / `loadAssetFile` (schema-tolerant for v2 rows) /
`persistPickedAsset` / `deleteAssetIfOwned` /
`checkReadPermission` / `requestReadPermission` /
`AssetPermissionError`.
- `local/file-picker.ts` — `pickAudioFile` / `pickVideoFiles` /
`pickVideoOrImageFiles` capability-aware picker. Returns
`PickedAsset[]` shape regardless of which path ran.
- `components/PermissionGate.tsx` — pre-renders an "Allow access"
prompt for handle assets whose permission is not currently
granted. No-op for OPFS-backed (always granted) sources.
- `components/JobPermissionRoute.tsx` — route wrapper that loads a
job's asset list and feeds the gate. Wraps `<JobPage>`,
`<Editor>`, `<RenderScreen>`.
## Schema migration
`VideoAsset.source?: AssetSource`, `ImageAsset.source?: AssetSource`,
`LocalJob.audioSource?: AssetSource` are all optional additions.
Legacy v2 rows continue to work — `loadAssetFile()` and
`assetSource()` derive an OPFS source from the existing `opfsPath` /
`audioFilename`+ext when no explicit source is set. New jobs stamp
`schemaVersion: 3`.
## Edit-worker boundary
`CamWorkerInput.opfsPath` → `source: AssetSource`. Handles are
structured-clone-transferable across `postMessage`, so the worker
can `loadAsset(c.source)` directly without going through OPFS.
`EditWorkerInput.videoPath` → `videoSource` for the legacy single-cam
fast path.
## UI
- `Upload.tsx` — `<label>` + `<input>` replaced by `<button>`s that
call `pickAudioFile` / `pickVideoFiles`. A "Files stay where you
keep them" tag shows under the form on supporting browsers.
- `AddMediaButton.tsx` (editor "+ Media") — same: button calls
`pickVideoOrImageFiles` directly.
## Tests
- 17 new asset-source unit tests (loadAsset, loadAssetFile fallback,
persistPickedAsset both branches, deleteAssetIfOwned no-ops on
handles, AssetPermissionError shape).
- Upload.test.tsx + AddMediaButton.test.tsx rewired to mock the new
picker module.
- jobs.browser.test.ts uses `pick(file)` helper to wrap Files into
`PickedAsset`s for the legacy/fallback path. Schema-version
expectation bumped from 2 → 3.
Total: 751 unit (+17), 193/193 browser. Existing 9 GB streaming
e2e (audio + demux) keeps passing — the streaming pipeline reads
handle-backed Files identically to OPFS-backed ones.
The handle-backed flow itself can't be exercised end-to-end in
headless Chromium (real `FileSystemFileHandle` requires a user
gesture; mock objects fail IDB structured clone). The OPFS-fallback
path is fully covered by the existing test suite.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Replaces sequential full-stream decode with random-access keyframe
extraction. Frame-strip generation for the user's 9 GB / 16-min phone
recording goes from ~minutes to **4.1 seconds** (100 tiles, 48 MB
peak heap, progress bar advances every 400 ms).
## Why
The previous extractor streamed every encoded sample (~48 000 frames
for the user's recording) through the VideoDecoder, advancing a
nextTargetIdx pointer to snapshot the first frame past each tile
timestamp. The decoder dutifully chewed through every B/P frame even
though only ~100 thumbnails were needed — a ~480× decode-side waste.
## Strategy
1. `openVideoDemux` now exposes `sampleTable` + `loadSample(idx)`
in addition to the existing `samples` AsyncIterable. The sample
table is parsed up-front from mp4box's stbl (no mdat reads, sub-MB
for hour-long recordings); `loadSample` does a random-access
`Blob.slice` for one sample's bytes on demand.
2. `extractFrameStripWebcodecs` builds a list of keyframe sample
indices and binary-searches for the keyframe nearest each tile
timestamp. For typical phone recordings with a 1–4 s keyframe
interval and our 5–10 s tile spacing, the snap is invisible.
3. Per tile: load just that keyframe's bytes, decode, snapshot to
the canvas. Consecutive tiles that resolve to the same keyframe
reuse the cached `VideoFrame` without re-decoding.
4. After each `decode({type:"key"})` we call `decoder.flush()` to
force output — single-chunk feeds otherwise sit in the decoder's
B-frame lookahead queue forever.
## Numbers (user's 9 GB file)
- Tiles requested: 100 (default cap)
- Decoder calls: 100 keyframe decodes (vs 48 130 sequential before)
- Wall time: 4.1 s
- Peak heap: 48 MB (random-access slice + one cached VideoFrame
+ one canvas tile-strip)
- Output: 189 KB WebP strip (142×80 tiles)
- Progress: smooth 10 %/400 ms — no stalls
## API addition
```ts
interface DemuxedVideoStream {
info: VideoTrackInfo;
samples: AsyncIterable<VideoChunk>;
// new:
sampleTable: ReadonlyArray<SampleMeta>; // {offset,size,cts,dts,
// duration,timescale,isKey}
loadSample(idx: number): Promise<VideoChunk>;
cancel(): Promise<void>;
}
```
`SampleMeta` is our slim projection of mp4box's internal Sample so
callers don't depend on the upstream type.
## Tests
- 5 frames.browser.test.ts pass unchanged (smaller fixture exercises
the same keyframe-search path; first keyframe always covers t=0).
- 193/193 browser tests still pass (CamFrameStream and edit.ts use
the AsyncIterable path, untouched).
- 751 unit tests pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…backs
The sync stage's progress bar used to jump 0 → 40 → 60 → frames%
with multi-second freezes between hops — the audio decode and the
sync algorithm were both atomic blocks with no visible motion.
Decode is the slowest piece (10 s for the user's 9 GB recording),
so plumbing its bytes-read fraction up to `reportProgress` is the
biggest UX win.
## What changed
- The three streaming decoders (`streaming-mp4-audio`, `streaming-mp3`,
`streaming-wav`) gained an `onProgress?: (frac: number) => void`
option. After every read batch they call it with
`position / source.size` (capped at 0.95 to leave room for the
final flush + resampler emit).
- `codec/index.ts::decodeAudioToMonoPcm` threads `onProgress` from
its options through to whichever sub-decoder runs. The fast
`decodeAudioData` path emits 0 → 1 (no sub-progress available);
the streaming path forwards the bytes-read fraction faithfully.
- `runCamPrep` maps the decoder's 0..1 onto its 0..0.4 band of the
cam's slice — the `syncing-cam-N` stage now ticks every ~500 ms
on big files instead of sitting at 0% for 10 s and then jumping.
- `runSync` does the same for the master-audio stage on the 2..5%
band of the global bar.
## Numbers (user's 9 GB recording)
- 2 146 progress callbacks across 10.5 s of decode
- 5%/500 ms steady cadence on the bar
- No regression in decode throughput (still ~10 s / 9 GB streaming)
The 40 → 60 jump (sync-algo runs in the WASM worker, atomic) and the
60 → frames-band hop are still discrete — the algo is fast enough on
the 22 050 Hz mono PCM that they're sub-second blips, no longer the
multi-second stalls users perceived as "stuck".
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Five-commit branch that takes the upload + sync + frame-extraction
pipeline from "falls over with a cryptic 'File could not be read! Code=-1' on anything past ~2 GiB" to
handle-backed, streaming-decoded, keyframe-extracted, smoothly-progressing —
verified end-to-end on a real 9 GB / 16-min H.264 phone recording.
The original report was a sync failure on a 9 GB MP4. Root cause: every decode path
(`AudioContext.decodeAudioData`, ffmpeg.wasm MEMFS, `mp4box.appendBuffer`) loaded the
whole file into a single `ArrayBuffer`, hitting Chromium's ~2 GiB cap. After the fix:
Commits
`ec77aeb` feat(codec): streaming audio decode for >2 GiB media files — `File.stream()` → 4 MiB batches → mp4box chunked + WebCodecs `AudioDecoder`. Pre-fetches moov from the tail (phone recordings put it last) so onReady fires without buffering mdat. New `streaming-mp4-audio.ts`, `streaming-mp3.ts`, `streaming-wav.ts`. Routes by file size (`>= 500 MiB` → streaming, smaller files keep the `decodeAudioData` fast path with ffmpeg.wasm fallback).
`70f9e1a` feat(demux): bounded-memory video demux for >2 GiB files — `openVideoDemux` returns track info + an `AsyncIterable` of encoded samples that's fed by random-access `Blob.slice()` per sample, bypassing mp4box's `processSamples` (which silently doesn't fire for video tracks after a moov-prefetched chunked feed).
`da3149b` feat(upload): hold user files via FileSystemFileHandle, no OPFS copy — `showOpenFilePicker` returns persistable handles; bytes never leave the user's disk. Schema v3 adds optional `source` field on assets; legacy v2 rows fall through to the OPFS path (`loadAssetFile` is schema-tolerant). `PermissionGate` + `JobPermissionRoute` re-acquire read permission with a single click after page reloads. Safari/Firefox without the API fall back to the OPFS-copy path.
`1049a5c` perf(frames): keyframe-only seek-and-decode for thumbnails — exposes `sampleTable` + `loadSample(idx)` on `DemuxedVideoStream`. Frame extractor binary-searches keyframes for each tile timestamp and decodes ~100 frames instead of streaming all 48 000. ~480× decoder-side reduction.
`4a9084f` feat(progress): smooth sync-stage progress via streaming-decoder callbacks — streaming decoders emit a bytes-read fraction per batch; `runCamPrep` maps it to its 0..0.4 slice of the cam's progress band. 2 146 callbacks across a 10.5 s decode = smooth motion instead of a 10 s freeze at 0 %.
Test plan
🤖 Generated with Claude Code