Research: streaming the browser decode into the analysis #
The question came from a time audit: the browser decoder was 11 seconds on a sixty-minute mix, and every engine that could have started reading samples at the first one was waiting for the last.
Short answer: not through decodeAudioData — that API is whole-file in, whole AudioBuffer out, on
the window thread only, and there is no chunked form of it in any browser. It is possible by changing
the decoder: WebCodecs AudioDecoder is a real queue, it lives in a worker, and it hands out samples
a chunk at a time. Four of the five consumers in this app can eat those chunks as they land; one
genuinely cannot, and it is the cheap one.
1. The measurement #
Ten loads from a desktop Chrome on a twelve-core machine, LAN server, http://hm.mission (so: no
Cache Storage, no WebGPU, no WebCodecs — see "secure": false in the same file).
| track | container | audio | body | browser decoder |
|---|---|---|---|---|
| September Jungle 2021 | m4a | 3464 s | 0.23 s / 28.3 MB | 11.77 s |
| The Dream Team Mix 1995 | m4a | 3688 s | 0.24 s / 31.7 MB | 11.42 s |
| Summer of 92 | m4a | 4015 s | 0.30 s / 34.8 MB | 12.14 s |
| Remember The Roller | flac | 196 s | 0.71 s / 22.7 MB | 0.60 s |
| I'm Not an Answer (demo) | flac | 175 s | 0.13 s / 21.3 MB | 0.59 s |
| Kicks to Try (demo) | flac | 130 s | 0.21 s / 16.6 MB | 0.40 s |
| Hitman (remix) | flac | 212 s | 0.23 s / 26.2 MB | 1.33 s |
| Sub Code Records Mix | m4a | — | 0.15 s / 31.6 MB | 5.83 s, then Unable to decode audio data |
| Return of the Rollers Vol. 1 | m4a | — | 0.29 s / 41.5 MB | 7.55 s, then Unable to decode audio data |
Three things fall out of it.
The rate is the same whatever the container. 3.0–3.4 ms per audio-second for the m4a files, and 3.0–3.4 for the FLACs (the 6.3 ms outlier decodes while another track is decoding). FLAC turns over a bitstream in one pass; AAC does not. When both cost the same per second of audio, what is being paid for is not the codec: it is 48000 × 2 × 4 = 384 kB of PCM per audio-second being allocated, written, and in all likelihood resampled out of the file's own rate into the context's — about 124 MB/s, which is memory-bound, not compute-bound.
The size is the other half of the cost. One 67-minute mix is a 1.44 GiB AudioBuffer, and
analyze.ts:278's mono(buffer) allocates a further 0.72 GiB beside it (detect.ts:660
mixDown makes a full-length Float32Array). Peak for one track: ~2.15 GiB. DECODED_CAP = 5
(store.ts:198) means five long mixes is ~7.2 GiB resident. The comment beside that cap says "a
decoded CD-quality minute is ~10 MB"; at 48 kHz stereo float32 it is ~23 MB.
Decode is the gate, and the waits are downstream of it. For Summer of 92: bytes in hand at 0.32 s, decoder answered at 12.47 s, first sample armed at 15.14 s (the 2.7 s between those two was the fingerprint sharing a turn with the arm — since fixed), beat grid landed at 45.9 s. The model only ever looks at the first 180 seconds of any track, so every one of those 33 seconds of inference was waiting on 4.5% of a decode.
The rate did not move when everything else did. A second audit of the same kind of file — a
59.7-minute m4a, 30.8 MB, this time on localhost with the disk tier and the GPU both available —
decoded in 10.96 s: 3.06 ms per audio-second, within noise of the 3.0–3.4 above. The decode is
not waiting on anything the origin can unlock. What the origin unlocked is everything after it: the
beat model went from 18–34 s to 6.2 s (gpu: true, ~190 ms a window against ~2.5 s a window on
wasm), and with the arm no longer queued behind the fingerprint the first sound came 9.6 ms after
the decoder answered rather than 2.7 s after it. What is left of that load's 11.5 s is the decode:
95% of it, and the only big lever still on the table for time-to-sound.
The second half of that number is the interesting one. The fingerprint was still running inside
beginPlayback, so it was measured as the arming — a 2063 ms arm the audio thread bar, which is
the very bar you consult to rule the arm out. Moving the ask outside the span's close() fixed the
reading; it did not remove the work, and the same audit shows what the work costs the thread: 675 ms
of unmeasured mono fold, then 1161 ms of fingerprint + chroma, and across that window the waveform
fold's 17 slices took 2.36 s of wall clock to do what its own budget says is ~0.3 s of
arithmetic. It yields every 8 ms and still cannot get the thread. That is stage 3 below.
2. What decodeAudioData will not do #
- Whole file, or nothing. "This method only works on complete file data, not fragments of audio
file data." A
Rangefetch of the head does not decode. - No progress, no cancellation, no partial answer. There is no event between the call and the promise; the load audit can only draw one bar.
- One allocation, at the context's rate. It resamples the whole file if the file's rate is not
the
AudioContext's, which on these files is a sinc pass over 190 million frames. - Window thread only.
BaseAudioContextis[Exposed=Window]: there is noAudioContextin a worker, so "do the decode over there" is not a line of code that exists. - It takes the buffer. The ArrayBuffer is detached — which is why the decode bar used to report
bytes=0for a 28 MB file, readingbyteLengthafter the await.
There is no streaming decode in Web Audio and none planned. The spec issues asking for partial and
chunked decoding (WebAudio/web-audio-api #335, #337, and the deprecation argument in #1305) are still
open, and there is no Chromium intent for a decodeMultiChunkData or anything like it: it is not in
the editor's draft and not in blink-dev. WebCodecs is the answer the spec editors point at, and they
mean it.
3. What can stream, and what each one costs #
| route | streaming | worker | holds whole PCM | cost |
|---|---|---|---|---|
WebCodecs AudioDecoder |
yes — decode(EncodedAudioChunk) in, AudioData out |
yes (Exposed=(Window,DedicatedWorker)) |
no | needs its own demuxer; SecureContext only; codec support is per-browser, probe with isConfigSupported |
| mediabunny over WebCodecs | yes — AudioSampleSink.samples(from, to) yields decoded samples, and CustomAudioDecoder covers gaps |
yes | no | a dependency, and a second demuxer's correctness to trust |
| wasm decoders (per-codec, or ffmpeg.wasm) | yes | yes | no | ships and instantiates a runtime (ffmpeg.wasm is tens of MB); ~60–70% of native speed |
| MediaSource | yes, for playback | — | never exposed to JS | no sample access: useless to the analysis |
<audio> element |
yes, for playback | — | never | same |
| server-computed peaks/features | n/a — skips the question | n/a | no | server work, a cache, a schema; covers the waveform and BPM, not the fingerprint |
AudioData arrives at the file's own sample rate and copyTo(..., { format: "f32-planar" }) puts
each channel straight into a Float32Array the page owns — which means the transferable array a
worker wants is the natural output, and the 1.3 GB AudioBuffer stops being a prerequisite for
measuring anything. Two rules come with it: every AudioData must be close()d (they hold native
memory the collector will not reclaim), and backpressure is decodeQueueSize plus the dequeue
event — the decoder will accept more chunks than it can turn over.
The demuxer is the real work, and m4a is the hard case: the moov box that says where every sample
lives is at the end of the file unless the encoder wrote it fast-start. Options are a Range fetch
of head and tail, mp4box.js/mediabunny doing it progressively, or asking Navidrome for a
container this route handles trivially (format=flac, whose STREAMINFO carries the geometry). The
warm tiers are keyed on the encoded bytes plus the container already, so nothing in
src/lib/player/media.ts has to change for any of this.
4. Can the consumers eat chunks? #
| consumer | today | streamable? | the thing in the way |
|---|---|---|---|
| waveform fold | peaks.ts foldRange, sliced at ~8 ms by store.ts pumpShapes |
yes | bucket count comes from total length (per = length / buckets); song.duration from the index gives it up front, and the fold only ever walks left to right |
| beat model | beatmodel.ts:63 MODEL_ANALYSIS_SECONDS = 180, :254 subarray(0, wanted) |
yes, and it only needs the head | nothing algorithmic — today the head is trapped behind the whole decode. Its main-thread mixDown of the first 180 s (a 34 MB copy) belongs in the decode worker too |
| fingerprint + chroma | chroma.ts:336, run on the main thread by analyze.ts:278 |
yes, as two passes | pass 1 (:364, the STFT) is per-frame and streams with a size * decimate carry-over. Pass 2 is relative to three globals: the peak (:405 log1p(6m/peak)), the median loudness mask (:460) and typicality. Stream pass 1 into the linear band matrix, keep a running peak, run pass 2 once at the end — same numbers, and the samples never have to exist |
| loop search | detect.ts searchSeries, in detect.worker.ts |
no, and it does not matter | a lag-L self-similarity column needs frames L apart; it is inherently after the last chunk. It costs 0.02–3.7 s on a worker core |
| playback | engine.play, one AudioBufferSourceNode with stopAt |
not in this design | instant seek anywhere, armed seams and A–B boundaries all assume whole PCM. Either build the AudioBuffer when the samples land, or schedule chunked sources behind a seek map — a different change, with the varispeed and shift worklet in it |
So the honest shape is: stream the decode into the three analysers, keep whole PCM for the audio thread. The 11 seconds stops being a wall because nothing that can start early has to wait for it, and the 1.3 GB stops being allocated twice.
5. What to build first #
- Head-only decode for the beat model. Demux and decode the first ~180 s (a
Rangeover the first megabytes plus themoov, or a short transcode), and let the model's question go out at ~1 s instead of 12.5 s. On the audit's mix that moves the grid and the snapped loop from 45.9 s to roughly "as fast as the model is", and it touches neither playback nor any other consumer. It is also stage one of everything below: same demuxer, same decoder, sameAudioDatahandling. - Streaming peaks. The row starts drawing at the first chunk instead of after the decode; the fold's slice machinery is already written, it just needs to be fed a prefix rather than a buffer.
- Streaming chroma, off the main thread. Pass 1 per chunk inside the decode worker; the fingerprint stops being 1.0–1.4 s of the page's own thread on a long mix — the change that moved it behind the arm made it late-breaking rather than absent, and this one makes it gone.
- Chunked playback (optional, biggest blast radius): first sound at ~1 s regardless of length. Decide it deliberately, because it is the one step that trades away the property the whole deck is built on.
Each stage must keep the current path as the fallback: isConfigSupported per codec, a demuxer that
can say no, and the existing decodeAudioData call underneath. This is a player first; a decoder
that is only available on Chrome over https is an optimisation, not a requirement.
6. What to measure it with #
The bars already exist; two additions make the claim checkable rather than argued:
browser decodershould carrydecoded=<seconds>as it goes, plus afirst sample decodedmark, so "when could the analysis have started" is readable off the graph.bytes=on that bar is fixed (media.tssnapshots the length before the call — it read 0 for every real decode before that).- Acceptance on the same 60-minute m4a:
beat modelopens before 2 s;wait for the bytesis no longer gated by a decode that has to finish first; nothing allocates aFloat32Arraythe length of the track. - The two m4a files that failed outright must fall back to a transcode rather than dying at
candidates=1— fixed already, inmedia.ts: a container's verdict is now the first bet rather than the only one, and a file's own disagreement is remembered against the file.
7. Open questions #
- Whose sample rate wins.
AudioDecoderpreserves the file's. Playing 44.1 kHz PCM in a 48 kHz context puts a real-time resample in the source node (cheap, per-sample, and the shift worklet already lives in that path); creating the context at the file's rate moves the problem to the output device. The analysis wants its own rates regardless — the mel bank works at 22.05 kHz — so this is about playback fidelity, anddocs/research/navidrome-api-and-audio-engine.md§3.3's "bit-perfect" note is the prior art to read first. - How much demuxer to trust. Navidrome's Range behaviour, and how often real libraries are
fast-start, decide whether the head-only path is a
Rangerequest or a transcode request. - What
DECODED_CAPmeans once a decoded track is aFloat32Arraythe page owns rather than anAudioBufferthe browser owns — the cap is a count today, and 2.15 GiB per long mix is why it should be bytes.