Skip to content

Commit 39e02ad

Browse files
committed
Fix large stereo issue
1 parent 25114d8 commit 39e02ad

2 files changed

Lines changed: 33 additions & 3 deletions

File tree

packages/encode-mp3/mp3-encode.js

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,31 @@ export default async function mp3(opts) {
2727

2828
encoder.configure(cfg)
2929

30+
// WASM encoder has ~320MB/channel buffer limit.
31+
// Chunk large inputs in 1152*1024 (~1.18M) sample blocks.
32+
const CHUNK = 1152 * 1024
33+
3034
return { encode, flush, free }
3135

3236
function encode(ch) {
33-
// returned buffer is owned by encoder — must copy
34-
let raw = encoder.encode(ch)
35-
return new Uint8Array(raw)
37+
let n = ch[0].length
38+
if (n <= CHUNK) {
39+
let raw = encoder.encode(ch)
40+
return new Uint8Array(raw)
41+
}
42+
let parts = []
43+
for (let i = 0; i < n; i += CHUNK) {
44+
let end = Math.min(i + CHUNK, n)
45+
let slice = ch.map(c => c.subarray(i, end))
46+
let raw = encoder.encode(slice)
47+
if (raw.length) parts.push(new Uint8Array(raw))
48+
}
49+
let total = 0
50+
for (let p of parts) total += p.length
51+
let out = new Uint8Array(total)
52+
let off = 0
53+
for (let p of parts) { out.set(p, off); off += p.length }
54+
return out
3655
}
3756

3857
function flush() {

packages/encode-mp3/test.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,14 @@ t('VBR mode', async () => {
2929
let buf = enc.flush()
3030
ok(buf.length > 0)
3131
})
32+
33+
t('large stereo (30min 48kHz)', async () => {
34+
let sr = 48000, dur = 1800, n = sr * dur
35+
let ch = new Float32Array(n)
36+
for (let i = 0; i < n; i++) ch[i] = 0.3 * Math.sin(2 * Math.PI * 440 * i / sr)
37+
let enc = await mp3({ sampleRate: sr, channels: 2, bitrate: 128 })
38+
let out = enc.encode([ch, new Float32Array(ch)])
39+
ok(out.length > 0, 'has encoded data: ' + (out.length / 1e6).toFixed(1) + 'MB')
40+
let final = enc.flush()
41+
ok(out.length + final.length > 1e6, 'total > 1MB')
42+
})

0 commit comments

Comments
 (0)