import { readFileSync } from 'fs' import decode, { decoder, gapless } from './decode-aac.js' import { parseMeta } from './meta.js' let pass = 0, fail = 0 function ok(cond, msg) { if (cond) { pass++; console.log(' ok', msg) } else { fail++; console.log(' FAIL', msg) } } function near(a, b, tol = 0.02) { return Math.abs(a - b) < tol } function rms(f32) { let s = 0; for (let i = 0; i < f32.length; i++) s += f32[i] * f32[i]; return Math.sqrt(s / f32.length) } let m4a = readFileSync(new URL('lena.m4a', import.meta.resolve('audio-lena'))) let aac = readFileSync(new URL('lena.aac', import.meta.resolve('audio-lena'))) // ---- M4A decode ---- console.log('M4A decode') { let r = await decode(m4a) ok(r.channelData.length === 2, 'stereo') ok(r.sampleRate === 44100, 'sampleRate 44100') ok(near(r.channelData[0].length / r.sampleRate, 12.28, 0.05), 'duration ~12.28s') ok(rms(r.channelData[0]) > 0.05, 'has audio content') // verify no NaN/Inf let bad = 0 for (let ch of r.channelData) for (let i = 0; i < ch.length; i++) if (!isFinite(ch[i])) bad++ ok(bad === 0, 'no NaN/Inf in output') } // ---- ADTS decode ---- console.log('ADTS decode') { let r = await decode(aac) ok(r.channelData.length >= 1, 'has channels (' + r.channelData.length + ')') ok(r.sampleRate === 44100, 'sampleRate 44100') ok(r.channelData[0].length > 100000, 'has samples (' + r.channelData[0].length + ')') ok(rms(r.channelData[0]) > 0.05, 'has audio content') // no NaN let bad = 0 for (let i = 0; i < r.channelData[0].length; i++) if (!isFinite(r.channelData[0][i])) bad++ ok(bad === 0, 'no NaN/Inf') } // ---- Stereo separation ---- console.log('stereo separation') { let r = await decode(m4a) let diff = 0 for (let i = 0; i < Math.min(1000, r.channelData[0].length); i++) diff += Math.abs(r.channelData[0][i] - r.channelData[1][i]) ok(diff > 0.001, 'L/R channels differ') } // ---- Sequential determinism ---- console.log('sequential determinism') { let r1 = await decode(m4a) let r2 = await decode(m4a) ok(r1.channelData[0].length === r2.channelData[0].length, 'same length') ok(r1.sampleRate === r2.sampleRate, 'same sampleRate') let maxDiff = 0 for (let i = 0; i < r1.channelData[0].length; i++) maxDiff = Math.max(maxDiff, Math.abs(r1.channelData[0][i] - r2.channelData[0][i])) ok(maxDiff === 0, 'identical output') } // ---- Concurrent decoders ---- console.log('concurrent decoders') { let [r1, r2] = await Promise.all([decode(m4a), decode(m4a)]) ok(r1.channelData[0].length === r2.channelData[0].length, 'same length') } // ---- Lifecycle ---- console.log('lifecycle') { // decode after free throws let d = await decoder() d.free() let threw = false try { d.decode(new Uint8Array(m4a)) } catch { threw = true } ok(threw, 'decode after free throws') // double free is safe d = await decoder() d.decode(new Uint8Array(m4a)) d.free() d.free() ok(true, 'double free ok') // flush returns EMPTY d = await decoder() d.decode(new Uint8Array(m4a)) let f = d.flush() ok(f.channelData.length === 0, 'flush returns EMPTY') d.free() } // ---- M4A streaming (moov split across chunks, non-faststart layout) ---- // Regression: github #44 — init fired on partial moov → garbage stsz/stco → 0 frames. console.log('M4A streaming') { let ref = await decode(m4a) for (let chunkSize of [16384, 4096, 1024, 256]) { let dec = await decoder() let chunks = [] for (let off = 0; off < m4a.length; off += chunkSize) { let r = dec.decode(m4a.subarray(off, Math.min(off + chunkSize, m4a.length))) if (r.channelData.length) chunks.push(r.channelData[0]) } let f = dec.flush() if (f.channelData.length) chunks.push(f.channelData[0]) dec.free() let total = chunks.reduce((s, c) => s + c.length, 0) ok(total === ref.channelData[0].length, 'chunk=' + chunkSize + ' count matches (' + total + ')') let stream = new Float32Array(total), pos = 0 for (let c of chunks) { stream.set(c, pos); pos += c.length } let maxDiff = 0 for (let i = 0; i < total; i++) maxDiff = Math.max(maxDiff, Math.abs(stream[i] - ref.channelData[0][i])) ok(maxDiff === 0, 'chunk=' + chunkSize + ' content identical') } } // ---- M4A streaming, faststart layout (moov before mdat) ---- // Regression: github #45 — when init parses moov early with no room for first frame, // _left stayed null and subsequent chunks misaligned, yielding 0 frames. console.log('M4A streaming (faststart)') { // Build faststart variant: ftyp + moov + mdat, with stco offsets rewritten. let r32 = (b, o) => (b[o] << 24 | b[o + 1] << 16 | b[o + 2] << 8 | b[o + 3]) >>> 0 let w32 = (b, o, v) => { b[o] = (v >>> 24) & 255; b[o + 1] = (v >>> 16) & 255; b[o + 2] = (v >>> 8) & 255; b[o + 3] = v & 255 } let src = new Uint8Array(m4a), boxes = {}, off = 0 while (off < src.length - 8) { let sz = r32(src, off) let t = String.fromCharCode(src[off + 4], src[off + 5], src[off + 6], src[off + 7]) boxes[t] = { off, sz } off += sz } let moov = src.slice(boxes.moov.off, boxes.moov.off + boxes.moov.sz) let mdat = src.subarray(boxes.mdat.off, boxes.mdat.off + boxes.mdat.sz) let newMdatOff = boxes.ftyp.sz + moov.length let delta = newMdatOff - boxes.mdat.off for (let i = 0; i < moov.length - 4; i++) { let t = String.fromCharCode(moov[i], moov[i + 1], moov[i + 2], moov[i + 3]) if (t === 'stco') { let n = r32(moov, i + 8) for (let k = 0; k < n; k++) w32(moov, i + 12 + k * 4, r32(moov, i + 12 + k * 4) + delta) } } let fast = new Uint8Array(boxes.ftyp.sz + moov.length + mdat.length) fast.set(src.subarray(0, boxes.ftyp.sz), 0) fast.set(moov, boxes.ftyp.sz) fast.set(mdat, newMdatOff) let ref = await decode(fast) ok(ref.channelData[0].length > 0, 'faststart whole-file decodes') // 64-byte chunks: moov spans many chunks AND first frame can't fit at init time. for (let chunkSize of [16384, 1024, 256, 64]) { let dec = await decoder() let chunks = [] for (let off = 0; off < fast.length; off += chunkSize) { let r = dec.decode(fast.subarray(off, Math.min(off + chunkSize, fast.length))) if (r.channelData.length) chunks.push(r.channelData[0]) } let f = dec.flush() if (f.channelData.length) chunks.push(f.channelData[0]) dec.free() let total = chunks.reduce((s, c) => s + c.length, 0) ok(total === ref.channelData[0].length, 'chunk=' + chunkSize + ' count matches (' + total + ')') let stream = new Float32Array(total), pos = 0 for (let c of chunks) { stream.set(c, pos); pos += c.length } let maxDiff = 0 for (let i = 0; i < total; i++) maxDiff = Math.max(maxDiff, Math.abs(stream[i] - ref.channelData[0][i])) ok(maxDiff === 0, 'chunk=' + chunkSize + ' content identical') } } // ---- M4A with a chapter track ---- // Regression: github #48 — a second non-audio trak (QuickTime chapter/text track, // e.g. ffmpeg-copied Logic Pro markers) clobbered the audio trak's stsz/stco/stsc // in the flat moov parse → 0 frames. Tables must come from the audio trak only. console.log('M4A chapter track') { let chaptered = readFileSync(new URL('./fixtures/chaptered.m4a', import.meta.url)) // phase-independent pitch estimate (AAC priming shifts the signal): zero-crossing rate let freq = (ch, sr) => { let a = ch.subarray(4096, ch.length - 1024), z = 0 for (let i = 1; i < a.length; i++) if ((a[i - 1] < 0) !== (a[i] < 0)) z++ return z * sr / (2 * a.length) } let r = await decode(chaptered) ok(r.channelData.length === 2, 'stereo') ok(r.sampleRate === 44100, 'sampleRate 44100') ok(near(r.channelData[0].length / r.sampleRate, 2.0, 0.1), 'duration ~2s (' + (r.channelData[0].length / r.sampleRate).toFixed(2) + 's)') ok(rms(r.channelData[0]) > 0.05, 'has audio content') ok(near(freq(r.channelData[0], r.sampleRate) / 440, 1, 0.05), 'ch0 ≈ 440Hz') ok(near(freq(r.channelData[1], r.sampleRate) / 660, 1, 0.05), 'ch1 ≈ 660Hz') // chunked feed goes through the same trak selection on the streaming path let dec = await decoder(), total = 0 for (let off = 0; off < chaptered.length; off += 1024) { let c = dec.decode(chaptered.subarray(off, Math.min(off + 1024, chaptered.length))) if (c.channelData.length) total += c.channelData[0].length } dec.free() ok(total === r.channelData[0].length, 'chunked count matches (' + total + ')') } // ---- ADTS streaming (partial frame buffering) ---- console.log('ADTS streaming') { let ref = await decode(aac) for (let chunkSize of [100, 300]) { let dec = await decoder() let chunks = [] for (let off = 0; off < aac.length; off += chunkSize) { let r = dec.decode(aac.subarray(off, Math.min(off + chunkSize, aac.length))) if (r.channelData.length) chunks.push(r.channelData[0]) } let f = dec.flush() if (f.channelData.length) chunks.push(f.channelData[0]) dec.free() let total = chunks.reduce((s, c) => s + c.length, 0) ok(total === ref.channelData[0].length, 'chunk=' + chunkSize + ' count matches (' + total + ')') // verify content matches one-shot let stream = new Float32Array(total), pos = 0 for (let c of chunks) { stream.set(c, pos); pos += c.length } let maxDiff = 0 for (let i = 0; i < total; i++) maxDiff = Math.max(maxDiff, Math.abs(stream[i] - ref.channelData[0][i])) ok(maxDiff === 0, 'chunk=' + chunkSize + ' content identical (maxDiff=' + maxDiff + ')') } } // ---- Edge cases ---- console.log('edge cases') { // empty input let d = await decoder() let r = d.decode(new Uint8Array(0)) let tail = d.flush() ok(!(r instanceof Promise) && !(tail instanceof Promise), 'decode and flush return values') ok(r.channelData.length === 0, 'empty input → EMPTY') d.free() // null input d = await decoder() r = d.decode(null) ok(r.channelData.length === 0, 'null input → EMPTY') d.free() // garbage input d = await decoder() let garbage = new Uint8Array(1000) crypto.getRandomValues(garbage) try { r = d.decode(garbage) ok(r.channelData.length === 0, 'garbage → EMPTY or error') } catch { ok(true, 'garbage → threw (ok)') } d.free() // truncated M4A (ftyp header only) d = await decoder() r = d.decode(new Uint8Array(m4a.subarray(0, 500))) ok(r.channelData.length === 0, 'truncated M4A → EMPTY') d.free() // ArrayBuffer input let input = m4a.buffer.slice(m4a.byteOffset, m4a.byteOffset + m4a.length) r = await decode(input) ok(r.channelData.length === 2, 'ArrayBuffer input works') d = await decoder() r = d.decode(input) d.free() ok(r.channelData.length === 2, 'decoder accepts ArrayBuffer') } // ---- Performance ---- console.log('performance') { // warmup await decode(m4a) let t0 = performance.now(), N = 10 for (let i = 0; i < N; i++) await decode(m4a) let ms = (performance.now() - t0) / N ok(ms < 200, 'M4A decode < 200ms (' + ms.toFixed(1) + 'ms)') console.log(' ' + ms.toFixed(1) + 'ms/decode (249KB, 12.3s audio)') } // ===== ALAC (Apple Lossless) — afconvert fixtures, 16 + 24 bit ===== console.log('ALAC') { let sine = (n, f, sr = 44100) => Array.from({ length: n }, (_, i) => Math.sin(2 * Math.PI * f * i / sr)) let corr = (a, b) => { let n = Math.min(a.length, b.length), sa = 0, sb = 0, sab = 0 for (let i = 0; i < n; i++) { sa += a[i] * a[i]; sb += b[i] * b[i]; sab += a[i] * b[i] } return sab / Math.sqrt(sa * sb) } for (let [name, nCh] of [['alac_mono', 1], ['alac_stereo', 2], ['alac24_mono', 1], ['alac24_stereo', 2]]) { let r = await decode(readFileSync(new URL('./fixtures/' + name + '.m4a', import.meta.url))) ok(r.sampleRate === 44100, name + ': sampleRate 44100') ok(r.channelData.length === nCh, name + ': ' + nCh + 'ch') ok(r.channelData[0].length === 22050, name + ': sample count') ok(corr(r.channelData[0], sine(r.channelData[0].length, 440)) > 0.99, name + ': ch0 ≈ 440Hz') if (nCh === 2) ok(corr(r.channelData[1], sine(r.channelData[1].length, 660)) > 0.99, name + ': ch1 ≈ 660Hz') } } // ===== metadata (iTunes ilst tags) ===== console.log('M4A metadata') { let { meta, sampleRate } = parseMeta(readFileSync(new URL('./fixtures/tagged.m4a', import.meta.url))) ok(sampleRate === 44100, 'sampleRate from mp4a box') ok(meta.title === 'Lena Sine', 'title (©nam)') ok(meta.artist === 'audiojs', 'artist (©ART)') ok(meta.album === 'Fixtures', 'album (©alb)') ok(meta.year === '2026', 'year (©day)') ok(meta.genre === 'Test', 'genre (©gen)') ok(meta.track === '3', 'track (trkn)') ok(meta.pictures.length === 1 && meta.pictures[0].mime === 'image/png', 'cover art (covr)') ok(parseMeta(new Uint8Array([0, 0, 0, 8, 1, 2, 3, 4])) === null, 'non-MP4 → null') } // ---- gapless: iTunSMPB (Apple's afconvert) ---- // A 44137-sample chirp (100 Hz up 1950 Hz/s, 0.4 peak) through AudioToolbox AAC-LC: 2112 samples of priming, 855 // of padding, per its iTunSMPB. FAAD2 withholds 1024; the rest is trimmed, so the output is the source's length, // on its first sample. Before, it came 1088 samples late and 2048 longer. console.log('gapless') { let src = Float32Array.from({ length: 44137 }, (_, i) => { let t = i / 44100; return 0.4 * Math.sin(2 * Math.PI * (100 * t + 1950 * t * t)) }) let fx = readFileSync(new URL('./fixtures/gapless-itunsmpb.m4a', import.meta.url)) for (let [name, r] of [['whole', await decode(fx)], ['chunked', await (async () => { let dec = await decoder(), parts = [] for (let i = 0; i < fx.length; i += 1000) { let c = dec.decode(fx.subarray(i, i + 1000)); if (c.channelData.length) parts.push(c.channelData[0]) } dec.free() let out = new Float32Array(parts.reduce((n, p) => n + p.length, 0)), o = 0 for (let p of parts) { out.set(p, o); o += p.length } return { channelData: [out] } })()]]) { let out = r.channelData[0], best = -Infinity, lag = 0 for (let d = -2500; d <= 2500; d++) { let s = 0; for (let i = 5000; i < 35000; i++) s += src[i] * (out[i + d] || 0); if (s > best) best = s, lag = d } ok(out.length === src.length, `${name}: length ${out.length} = ${src.length}`) ok(lag === 0, `${name}: no lag (${lag})`) } } // ---- gapless: the edit list's one media edit (ISO/IEC 14496-12 §8.6.6) ---- // An empty edit (media_time -1, a delay) beside it keeps its window; several media edits cut or repeat the media, // which no trim presents: no window, the track decodes whole console.log('gapless edit list') { let box = (n, f) => { let b = new Uint8Array(n); f(new DataView(b.buffer)); return b } let elst = (...e) => box(8 + 12 * e.length, v => { v.setUint32(4, e.length); e.forEach(([d, m], i) => { v.setUint32(8 + 12 * i, d); v.setInt32(12 + 12 * i, m); v.setUint32(16 + 12 * i, 0x10000) }) }) let mdhd = box(24, v => v.setUint32(12, 44100)), mvhd = box(24, v => v.setUint32(12, 1000)) ok(gapless({ elst: elst([1000, 2112]), mdhd, mvhd })?.start === 2112 / 44100, 'one media edit: its window') ok(gapless({ elst: elst([500, -1], [1000, 2112]), mdhd, mvhd })?.start === 2112 / 44100, 'an empty edit, then the media edit: its window') ok(gapless({ elst: elst([500, 2112], [500, 30000]), mdhd, mvhd }) === null, 'two media edits: no window') } // ---- ADTS channel order ---- // 3.0 tones (L 220, R 330, C 440 Hz) through ffmpeg's AAC: channel configuration 3 codes C L R, out in SMPTE order. // A 0xFF inside a leading ID3v2 tag is no ADTS header: the configuration comes from the first verified sync. // ffmpeg -f lavfi -i "aevalsrc=0.3*sin(2*PI*220*t)|0.3*sin(2*PI*330*t)|0.3*sin(2*PI*440*t):s=48000:d=0.2:c=3.0" \ // -c:a aac -b:a 64k -fflags +bitexact -flags +bitexact -f adts tones-3ch.aac console.log('ADTS channel order') { let adts = readFileSync(new URL('./fixtures/tones-3ch.aac', import.meta.url)) let id3 = Uint8Array.from([0x49, 0x44, 0x33, 3, 0, 0, 0, 0, 0, 16, 0x54, 0x58, 0x58, 0x58, 0, 0, 0, 6, 0, 0, 0, 0xFF, 0, 0, 0, 0]) let mag = (d, f, sr) => { let re = 0, im = 0; for (let i = 0; i < d.length; i++) { let p = 2 * Math.PI * f * i / sr; re += d[i] * Math.cos(p); im -= d[i] * Math.sin(p) } return Math.hypot(re, im) / d.length } for (let [name, buf] of [['ADTS', adts], ['ID3 + ADTS', Buffer.concat([id3, adts])]]) { let r = await decode(buf), tones = r.channelData.map(d => [220, 330, 440].sort((a, b) => mag(d, b, r.sampleRate) - mag(d, a, r.sampleRate))[0]) ok(tones.join() === '220,330,440', `${name}: L R C (${tones})`) } } console.log(`\n${pass + fail} tests, ${pass} passed, ${fail} failed`) if (fail) process.exit(1)