Dev.to WebDev 🛠 Dev 👁 0 📖 5 min read

How We Eliminated the 44ms Chrome WebCodecs AAC Priming Offset in Pure JavaScript

When we built Audio Visualizer Online — a zero-upload browser studio that renders 1080p audio-reactive MP4 music videos at 4–5× real time using Canvas 2D, WebCodecs (VideoEncoder + AudioEncoder), and mp4-muxer — everythi

When we built Audio Visualizer Online — a zero-upload browser studio that renders 1080p audio-reactive MP4 music videos at 4–5× real time using Canvas 2D, WebCodecs (VideoEncoder + AudioEncoder), and mp4-muxer — everything looked crisp in our first lab tests. A 3-minute 1080p track rendered in 35.9 seconds without downloading a 35 MB ffmpeg.wasm binary or turning on COOP/COEP headers.

Then we ran an audio-visual beat-alignment test with synthetic click transients at 250 ms, 1000 ms, and 2500 ms, decoded the exported MP4 with FFmpeg, and measured the waveform onsets.

Every single audio hit arrived 44 milliseconds late — and the container audio stream ran slightly past 3.000s.

Here is why that happens in Chrome's WebCodecs AudioEncoder, why mp4-muxer alone cannot fix it, and the zero-dependency pure-JavaScript fix we shipped (and open-sourced under MIT) to lock MP4 exports to 0.0 ms beat-sync accuracy.

Why WebCodecs AAC Exports Drift by ~44ms

AAC-LC (mp4a.40.2) is a frame-based transform codec operating on 1,024-sample MDCT frames. To initialize its filter bank without edge artifacts, every OS AAC encoder prepends encoder priming silence before sample 0 of your PCM input, and zero-pads the final partial frame at the end:

  • macOS CoreAudio (Chrome on macOS): typically 2,112 samples (44.0 ms at 48 kHz)
  • Windows Media Foundation / FDK-AAC: often 1,024 – 2,112 samples depending on OS & build

When you pass WebCodecs AudioData starting at timestamp: 0 into AudioEncoder and feed the resulting EncodedAudioChunks into an MP4 muxer, the muxer writes the raw compressed AAC frames into mdat, without knowing how many priming samples the host OS encoder prepended.

So when FFmpeg, Chrome, Premiere Pro, or QuickTime plays that MP4 back:

  1. Sample 0 of the decoded AAC stream is priming silence, pushing your actual kick drum from t = 250 ms to t = 294 ms.
  2. Your video frames (rendered deterministically from exact PCM sample positions) flash on the beat at 250 ms — 44 ms (1.3 frames at 30 fps) ahead of the audio.
  3. Trailing zero-padding stretches the audio track past your video's 3.000s duration.

Step 1: Measure Exact Host Priming Delay in ~12ms

Hardcoding 2112 works on macOS CoreAudio, but breaks on Linux or Windows codecs that prepend 1024 or 1600 samples.

Instead, we run a tiny self-calibrating loopback probe once per (sampleRate, channels) pair and cache the result:

  1. Synthesize an 8192-sample buffer containing a clean Hann-windowed dual-sine burst (1000 Hz + 2300 Hz) starting at sample offset 2048.
  2. Encode that buffer through AudioEncoder (mp4a.40.2).
  3. Immediately decode the encoded chunks through AudioDecoder.
  4. Cross-correlate the decoded PCM against the reference burst to find the exact integer sample lag (bestLag).

On desktop Chrome / macOS, this probe takes ~12 milliseconds and consistently returns 2112 samples.

export async function measureAacPrimingSamples(sr, ch = 2, bitrate = 192_000) {
  if (typeof AudioEncoder === "undefined" || typeof AudioDecoder === "undefined") return null;
  const N = 8192, B0 = 2048, BL = 1024;
  const f1 = Math.min(1000, sr * 0.15), f2 = Math.min(2300, sr * 0.3);
  const ref = new Float32Array(N);
  let eng = 0;
  for (let i = 0; i < BL; i++) {
    const v = (0.5 - 0.5 * Math.cos((2 * Math.PI * i) / (BL - 1))) * 0.6 *
      (Math.sin((2 * Math.PI * f1 * i) / sr) + 0.5 * Math.sin((2 * Math.PI * f2 * i) / sr));
    ref[B0 + i] = v;
    if (!(i & 1)) eng += v * v;
  }
  // Encode via AudioEncoder -> decode via AudioDecoder -> cross-correlate lag 0..4096
  // Full standalone MIT implementation:
  // https://gist.github.com/soler-yang/97a995945fa4e2e8bd9ddc6c81751294
}

Step 2: Patch ISO/IEC 14496-12 edts/elst + Apple TN2258 roll

Once muxer.finalize() gives you the finalized MP4 Uint8Array, we patch the moov box in-memory in ~0.3 ms:

  1. Locate the audio track (trak whose mdia > hdlr has handler type 'soun').
  2. Insert edts > elst right after tkhd:
    • segment_duration = exact unpadded audio duration in mvhd timescale ticks (this trims trailing AAC padding automatically).
    • media_time = Math.round((primingSamples / sampleRate) * audioTimescale) (tells every compliant player to skip exact priming samples).
    • media_rate = 0x00010000 (1.0).
  3. Insert Apple TN2258 sgpd + sbgp ('roll', roll_distance = -1) at the end of stbl:
    • Apple AVFoundation / CoreAudio requires the -1 sample pre-roll group to prime the MDCT overlap-add buffer from the previous AAC packet before skipping to media_time.
  4. Update parent box sizes (moov, trak, mdia, minf, stbl) and clamp mvhd + audio tkhd durations.
  5. Shift stco / co64 chunk offsets across ALL tracks when moov precedes mdat (fastStart: "in-memory"):
    • Because inserting edts + sgpd/sbgp grows moov by dT bytes, every byte offset pointing into mdat shifts right by +dT. Skipping this step corrupts fastStart MP4s!
import { measureAacPrimingSamples, patchMp4AudioEditList } from "./mp4-aac-priming-sync.js";

const primingPromise = measureAacPrimingSamples(sampleRate, numChannels, 192_000);
// ... encode video + audio frames ...
const [, , priming] = await Promise.all([
  videoEncoder.flush(),
  audioEncoder.flush(),
  primingPromise
]);
muxer.finalize();

let mp4Bytes = new Uint8Array(target.buffer);
if (priming !== null) {
  mp4Bytes = patchMp4AudioEditList(mp4Bytes, priming, audioDurSec, videoDurSec, sampleRate);
}

Before & After Verification (FFprobe + PCM Onset Check)

Testing a 3.000-second stereo clip with synthetic click transients at 250 ms, 1000 ms, and 2500 ms:

Metric Raw WebCodecs + mp4-muxer With patchMp4AudioEditList
Click #1 decoded onset 294.0 ms (+44.0 ms late) 250.0 ms (0.0 ms delta)
Click #2 decoded onset 1044.0 ms (+44.0 ms late) 1000.0 ms (0.0 ms delta)
Click #3 decoded onset 2544.0 ms (+44.0 ms late) 2500.0 ms (0.0 ms delta)
Container duration (ffprobe) 3.048 s (trailing AAC pad) 3.000 s
Extra runtime overhead — ~12 ms once + < 1 ms per export
Extra dependencies / WASM — 0 bytes WASM, 0 deps

Two More Container Traps We Fixed Along the Way

While hardening our multi-format local exporter, we hit two closely related browser container issues and included pure-JS fixes for both in the same MIT toolkit:

  1. Chromium MediaRecorder WebM missing Duration: Chromium writes WebM streams without an EBML Duration (0x4489) element, causing NLEs and seek bars to show N/A / Infinity. Our patchWebmDuration() injects the 8-byte IEEE-754 Float64 duration directly into Segment > Info and updates VINT sizes.
  2. True 32-bit RGBA transparent overlays without FFmpeg.wasm: For video editors who want transparent audio waveforms over footage without chroma-keying, our 4 KB pure-JS PNG-in-MOV writer emits canonical QuickTime atoms (ftyp qt, png depth 32, fiel, pasp 1:1, edts/elst, co64, 16-bit PCM sowt) that import with straight alpha in Premiere Pro, After Effects, and DaVinci Resolve. (One subtle macOS gotcha we documented in our NLE Transparent Audio Visualizer Guide: modern macOS AVFoundation dropped legacy 'png ' QuickTime decoding, so Final Cut Pro users should use Green Screen MP4 or transcode locally to ProRes 4444.)

Open-Source Code & Live Demo

Everything described above is open-sourced under the MIT license with zero dependencies and Node unit tests (npm test):

If you're building with WebCodecs AudioEncoder and ran into beat drift or fastStart stco offset bugs, I'd love to compare notes in the comments!

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.