-
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathcore.js
More file actions
701 lines (641 loc) · 27.9 KB
/
core.js
File metadata and controls
701 lines (641 loc) · 27.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
/**
* audio core — paged audio container with plugin architecture.
*
* audio.fn — instance prototype (like $.fn)
* audio.stat — stat descriptor registration/query (block, reduce, query)
* audio.use — plugin registration
*/
import decode from 'audio-decode'
import getType from 'audio-type'
import encode from 'encode-audio'
import convert, { parse as parseFmt } from 'pcm-convert'
import parseDuration from 'parse-duration'
audio.version = '2.2.0'
/** Parse time value: number passthrough, string via parse-duration or timecode. */
export function parseTime(v) {
if (v == null) return v
if (typeof v === 'number') { if (!Number.isFinite(v)) throw new Error(`Invalid time: ${v}`); return v }
// Timecode: HH:MM:SS.mmm, MM:SS.mmm, or MM:SS
let tc = v.match(/^(\d+):(\d{1,2})(?::(\d{1,2}))?(?:\.(\d+))?$/)
if (tc) {
let [, a, b, c, frac] = tc
let s = c != null ? +a * 3600 + +b * 60 + +c : +a * 60 + +b
if (frac) s += +('0.' + frac)
return s
}
let s = parseDuration(v, 's')
if (s != null && isFinite(s)) return s
throw new Error(`Invalid time: ${v}`)
}
// ── Entry Points ─────────────────────────────────────────────────────────
/** Create audio from any source. Sync — returns instance immediately.
* Thenable: `await audio('file.mp3')` waits for full decode.
* Edits can be chained before decode completes. */
export default function audio(source, opts = {}) {
// No source → pushable instance (tape recorder — push, record, stop)
if (source == null) {
let sr = opts.sampleRate || 44100, ch = opts.channels || 1
let waiters = []
let notify = () => { for (let w of waiters.splice(0)) w() }
let a = create([], sr, ch, 0, opts, null)
a.decoded = false
a.recording = false
a._.acc = pageAccumulator({ pages: a.pages, notify, ondata: (...args) => emit(a, 'data', ...args) })
a._.waiters = waiters
return a
}
// Restore from serialized document
if (source && typeof source === 'object' && !Array.isArray(source) && source.edits) {
if (!source.source) throw new TypeError('audio: cannot restore document without source reference')
let a = audio(source.source, opts)
if (a.run) for (let e of source.edits) a.run(e)
return a
}
// Concat from array of sources
if (Array.isArray(source) && source.length && !(source[0] instanceof Float32Array)) {
let instances = source.map(s => s?.pages ? s : audio(s, opts))
let first = instances[0].clip ? instances[0].clip() : audio.from(instances[0])
if (!first.insert) throw new Error('audio([...]): concat requires insert plugin — import "audio" instead of "audio/core.js"')
let xf = opts?.crossfade
for (let i = 1; i < instances.length; i++) {
let d = Array.isArray(xf) ? xf[i - 1] : xf
if (d && first.crossfade) first.crossfade(instances[i], d, opts?.curve)
else first.insert(instances[i])
}
let loading = instances.filter(s => !s.decoded)
if (loading.length) {
first.ready = Promise.all(loading.map(s => s.ready)).then(() => { delete first.then; delete first.catch; return true })
first.ready.catch(() => {})
makeThenable(first)
}
return first
}
// From AudioBuffer
if (source?.getChannelData && source?.numberOfChannels) return audio.from(source, opts)
// From PCM arrays or silence duration
if (Array.isArray(source) && source[0] instanceof Float32Array || typeof source === 'number') {
let a = audio.from(source, opts)
if (audio.evict && a.cache && a.budget !== Infinity) {
a.ready = audio.evict(a).then(() => { delete a.then; delete a.catch; return true })
a.ready.catch(() => {})
makeThenable(a)
}
return a
}
// From encoded source (file, URL, buffer)
let ref = typeof source === 'string' ? source : source instanceof URL ? source.href : null
let pages = [], waiters = []
let notify = () => { for (let w of waiters.splice(0)) w() }
let a = create(pages, 0, 0, 0, { ...opts, source: ref }, null)
a._.waiters = waiters
a.decoded = false
let readyResolve, readyReject
a._.ready = new Promise((r, j) => { readyResolve = r; readyReject = j })
a._.ready.catch(() => {}) // suppress unhandled rejection
a.ready = (async () => {
try {
if (opts.storage === 'persistent') {
if (!audio.opfsCache) throw new Error('Persistent storage requires cache module (import "./cache.js")')
try { opts = { ...opts, cache: await audio.opfsCache(), budget: opts.budget ?? audio.DEFAULT_BUDGET ?? Infinity } }
catch { throw new Error('OPFS not available (required by storage: "persistent")') }
a.cache = opts.cache
a.budget = opts.budget
}
let result = await decodeSource(source, { pages, notify, ondata: (...args) => emit(a, 'data', ...args) })
a.sampleRate = result.sampleRate
a._.ch = result.channels
a._.chV = -1 // invalidate cached channels
if (result.acc) a._.acc = result.acc
if (result.estDuration) a._.estDur = result.estDuration
if (result.header) { a._.header = result.header; a._.format = result.format }
emit(a, 'metadata', { sampleRate: result.sampleRate, channels: result.channels, estDuration: result.estDuration })
readyResolve()
let final = await result.decoding
a._.len = final.length
a._.lenV = -1
a.stats = final.stats
if (final.header) { a._.header = final.header; a._.metaDone = false }
a.decoded = true
notify()
audio.evict?.(a)
delete a.then; delete a.catch // clear thenable before resolve to prevent unwrap loop
return true
} catch (e) {
readyReject(e)
emit(a, 'error', e)
throw e
}
})()
a.ready.catch(() => {}) // suppress unhandled rejection; errors surface through LOAD or await
makeThenable(a)
return a
}
/** Make instance thenable — await resolves after full decode. Self-removing to prevent infinite unwrap. */
function makeThenable(a) {
a.then = function(resolve, reject) {
return a.ready.then(() => { delete a.then; delete a.catch; return a }).then(resolve, reject)
}
a.catch = function(reject) { return a.then(null, reject) }
}
/** Sync creation from PCM data, AudioBuffer, audio instance, function, or seconds of silence. */
audio.from = function(source, opts = {}) {
if (Array.isArray(source) && source[0] instanceof Float32Array) return fromChannels(source, opts)
if (typeof source === 'number') return fromSilence(source, opts)
if (typeof source === 'function') return fromFunction(source, opts)
if (source?.pages) {
return create([...source.pages], opts.sampleRate ?? source.sampleRate,
opts.channels ?? source._.ch, source._.len,
{ source: source.source, storage: source.storage, cache: source.cache, budget: opts.budget ?? source.budget }, source.stats)
}
if (source?.getChannelData) {
let chs = Array.from({ length: source.numberOfChannels }, (_, i) => new Float32Array(source.getChannelData(i)))
return fromChannels(chs, { sampleRate: source.sampleRate, ...opts })
}
// Typed array with format conversion
if (ArrayBuffer.isView(source) && opts.format) {
let fmt = parseFmt(opts.format)
let ch = fmt.channels || opts.channels || 1
let sr = fmt.sampleRate || opts.sampleRate || 44100
let src = { ...fmt, channels: ch }
if (ch > 1 && src.interleaved == null) src.interleaved = true
let pcm = convert(source, src, { dtype: 'float32', interleaved: false, channels: ch })
let perCh = pcm.length / ch
let chs = Array.from({ length: ch }, (_, c) => pcm.subarray(c * perCh, (c + 1) * perCh))
return fromChannels(chs, { sampleRate: sr })
}
throw new TypeError('audio.from: expected Float32Array[], AudioBuffer, audio instance, function, or number')
}
// ── Plugin Architecture ─────────────────────────────────────────────────
const fn = {}
audio.fn = fn // instance prototype (like $.fn)
audio.BLOCK_SIZE = 1024
audio.PAGE_SIZE = 1024 * audio.BLOCK_SIZE
/** Internal protocol symbols for plugin overrides. */
export const LOAD = Symbol('load')
export const READ = Symbol('read')
/** Emit event on instance. */
export function emit(a, event, ...args) {
let arr = a._.ev[event]
if (arr) for (let cb of arr) cb(...args)
}
fn.on = function(event, cb, opts) {
if (opts == null) { (this._.ev[event] ??= []).push(cb); return this }
let o = typeof opts === 'string' || Array.isArray(opts) ? { type: opts } : opts
let wrap = (...args) => cb(...args)
wrap._cb = cb; wrap._opts = o
;(this._.ev[event] ??= []).push(wrap)
return this
}
fn.off = function(event, cb) {
if (!event) { this._.ev = {}; return this }
if (!cb) { delete this._.ev[event]; return this }
let arr = this._.ev[event]
if (arr) { let i = arr.findIndex(e => e === cb || e._cb === cb); if (i >= 0) arr.splice(i, 1) }
return this
}
fn.dispose = function() {
this.stop()
this._.ev = {}
this._.meters = null
this._.pcm = null
this._.plan = null
this.pages.length = 0
this.stats = null
this._.waiters = null
this._.acc = null
}
if (Symbol.dispose) fn[Symbol.dispose] = fn.dispose
/** Register plugins. Each receives audio. */
audio.use = function(...plugins) {
for (let p of plugins) p(audio)
}
// ── Instance ─────────────────────────────────────────────────────────────
function create(pages, sampleRate, ch, length, opts = {}, stats) {
let a = Object.create(fn)
a.pages = pages
a.source = opts.source ?? null
a.storage = opts.storage || 'memory'
a.cache = opts.cache || null
a.budget = opts.budget ?? Infinity
a.stats = stats
a.decoded = true
a.ready = Promise.resolve(true)
Object.defineProperty(a, '_', {
value: {
sr: sampleRate, // source sample rate
ch, // source channel count
len: length, // source sample length
waiters: null, // decode notify queue (null when not streaming)
ev: {}, // instance event listeners
ct: 0, ctStamp: 0, // currentTime wall-clock interpolation
vol: 1, muted: false, // volume 0..1 linear with change events
rate: 1, // playbackRate
},
writable: false, enumerable: false, configurable: false
})
// History (edit pipeline)
a.edits = []
a.version = 0
a._.pcm = null; a._.pcmV = -1
a._.plan = null; a._.planV = -1
a._.statsV = -1
a._.lenC = a._.len; a._.lenV = 0
a._.chC = a._.ch; a._.chV = 0
a._.srC = a._.sr; a._.srV = 0
// Playback (getter/setter for interpolation & events)
Object.defineProperties(a, {
currentTime: {
get() {
if (this.playing && !this.paused) {
let t = this._.ct + (performance.now() - this._.ctStamp) / 1000 * (this._.rate || 1)
let d = this.duration
return d > 0 ? Math.min(t, d) : t
}
return this._.ct
},
set(v) { this._.ct = v; this._.ctStamp = performance.now() },
enumerable: true, configurable: true
},
volume: {
get() { return this._.vol },
set(v) { v = Math.max(0, Math.min(1, +v || 0)); if (this._.vol !== v) { this._.vol = v; emit(this, 'volumechange') } },
enumerable: true, configurable: true
},
muted: {
get() { return this._.muted },
set(v) { v = !!v; if (this._.muted !== v) { this._.muted = v; emit(this, 'volumechange') } },
enumerable: true, configurable: true
},
playbackRate: {
get() { return this._.rate },
set(v) { v = Math.max(0.0625, Math.min(16, +v || 1)); if (this._.rate !== v) { this._.rate = v; emit(this, 'ratechange') } },
enumerable: true, configurable: true
},
})
a.playing = false; a.paused = false
a.ended = false; a.seeking = false
a.loop = false; a.block = null
// Cache
a._.lru = new Set()
return a
}
function fromChannels(channelData, opts = {}) {
let sr = opts.sampleRate || 44100
return create(paginate(channelData), sr, channelData.length, channelData[0].length, opts, audio.statSession?.(sr).page(channelData).done())
}
function fromSilence(seconds, opts = {}) {
let sr = opts.sampleRate || 44100, ch = opts.channels || 1
return fromChannels(Array.from({ length: ch }, () => new Float32Array(Math.round(seconds * sr))), { ...opts, sampleRate: sr })
}
function fromFunction(fn, opts = {}) {
let sr = opts.sampleRate || 44100, ch = opts.channels || 1
let dur = opts.duration
if (dur == null) throw new TypeError('audio.from(fn): duration required')
let len = Math.round(dur * sr)
let chs = Array.from({ length: ch }, () => new Float32Array(len))
for (let i = 0; i < len; i++) {
let v = fn(i / sr, i)
if (typeof v === 'number') for (let c = 0; c < ch; c++) chs[c][i] = v
else for (let c = 0; c < ch; c++) chs[c][i] = v[c] ?? 0
}
return fromChannels(chs, { sampleRate: sr })
}
Object.defineProperties(fn, {
sampleRate: { get() { return this._.sr }, set(v) { this._.sr = v }, enumerable: true, configurable: true },
length: { get() { return this._.len }, configurable: true },
duration: { get() { return this.length / this.sampleRate }, configurable: true },
channels: { get() { return this._.ch }, configurable: true },
/** Source stats (pre-edit snapshot) — used by resolve-stage ops like normalize/trim. */
srcStats: { get() { return this._.srcStats || this.stats || this._.acc?.stats }, configurable: true },
})
fn[LOAD] = async function() {
if (this._.ready) await this._.ready; this._.acc?.drain()
}
fn[READ] = function(offset, duration) { return readPages(this, offset, duration) }
/** Push PCM data into a pushable instance. Accepts Float32Array[], Float32Array, or typed array with format. */
fn.push = function(data, fmt) {
let acc = this._.acc
if (!acc) throw new Error('push: instance is not pushable — create with audio()')
let ch = this._.ch, sr = this.sampleRate
let chData
if (Array.isArray(data) && data[0] instanceof Float32Array) chData = data
else if (data instanceof Float32Array) chData = [data]
else if (ArrayBuffer.isView(data)) {
let f = fmt || {}
let srcFmt = typeof f === 'string' ? f : f.format || 'int16'
let nch = f.channels || ch
let src = { dtype: srcFmt, channels: nch }
if (nch > 1) src.interleaved = true
let pcm = convert(data, src, { dtype: 'float32', interleaved: false, channels: nch })
let perCh = pcm.length / nch
chData = Array.from({ length: nch }, (_, c) => pcm.subarray(c * perCh, (c + 1) * perCh))
}
else throw new TypeError('push: expected Float32Array[], Float32Array, or typed array')
// Sync channel count on first push, validate on subsequent
if (!this._.ch) { this._.ch = chData.length; this._.chV = -1 }
else if (chData.length !== this._.ch) throw new TypeError(`push: expected ${this._.ch} channels, got ${chData.length}`)
acc.push(chData, (fmt && fmt.sampleRate) || sr)
this._.len = acc.length
this._.lenV = -1
return this
}
/** Stop recording and/or finalize pushable stream. Drain partial page, signal EOF to waiting streams. No-op on non-pushable. */
fn.stop = function() {
this.playing = false; this.paused = false; this.seeking = false
if (this._._wake) this._._wake()
if (this.recording) {
this.recording = false
if (this._._mic) { this._._mic(null); this._._mic = null }
}
if (this._.acc && !this.decoded) {
this._.acc.drain()
this.decoded = true
if (this._.waiters) for (let w of this._.waiters.splice(0)) w()
}
return this
}
/** Start recording from mic. Pushes PCM chunks until .stop(). Requires audio-mic (npm i audio-mic). */
fn.record = function(opts = {}) {
if (!this._.acc) throw new Error('record: instance is not pushable — create with audio()')
if (this.recording) return this
this.recording = true
this.decoded = false
let self = this, sr = this.sampleRate, ch = this._.ch
let _rec = (async () => {
let { default: mic } = await import('audio-mic')
let read = mic({ sampleRate: sr, channels: ch, bitDepth: 16, ...opts })
self._._mic = read
read((err, buf) => {
if (!self.recording) return
if (err || !buf) return
self.push(new Int16Array(buf.buffer, buf.byteOffset, buf.byteLength / 2), 'int16')
})
})()
_rec.catch(() => {}) // suppress unhandled rejection; surfaces through .ready/.stop
return this
}
fn.seek = function(t) {
t = Math.max(0, t)
this.seeking = true
this.currentTime = t
if (this.cache) {
let page = Math.floor(t * this.sampleRate / audio.PAGE_SIZE)
;(async () => {
for (let i = Math.max(0, page - 1); i <= Math.min(page + 2, this.pages.length - 1); i++)
if (this.pages[i] === null && await this.cache.has(i)) this.pages[i] = await this.cache.read(i)
})().catch(() => {})
}
if (this.playing) { this._._seekTo = t; if (this._._wake) this._._wake() }
else this.seeking = false
return this
}
fn.read = async function(opts) {
if (typeof opts !== 'object' || opts === null) opts = {}
let { at, duration, format, channel, meta } = opts
at = parseTime(at); duration = parseTime(duration)
await this[LOAD]()
let pcm = await this[READ](at, duration)
if (channel != null) pcm = [pcm[channel]]
if (!format) return channel != null ? pcm[0] : pcm
let converted = encode[format] ? await encode[format](pcm, { sampleRate: this.sampleRate, ...meta }) : pcm.map(ch => convert(ch, 'float32', format))
return channel != null ? (Array.isArray(converted) ? converted[0] : converted) : converted
}
// ── Pages ────────────────────────────────────────────────────────────────
/** Split channels into pages of PAGE_SIZE samples. */
function paginate(channelData) {
let len = channelData[0].length, pages = []
for (let off = 0; off < len; off += audio.PAGE_SIZE)
pages.push(channelData.map(ch => ch.subarray(off, Math.min(off + audio.PAGE_SIZE, len))))
return pages
}
/** Walk pages of instance a, calling visitor(page, channel, start, end) for each overlapping page. */
export function walkPages(a, c, srcOff, len, visitor) {
let pages = a.pages, PS = audio.PAGE_SIZE, lru = a._.lru
let p0 = Math.floor(srcOff / PS), pos = p0 * PS
for (let p = p0; p < pages.length && pos < srcOff + len; p++) {
let pg = pages[p], pLen = pg ? pg[0].length : PS
if (pos + pLen > srcOff && pg) {
let s = Math.max(srcOff - pos, 0), e = Math.min(srcOff + len - pos, pLen)
if (lru && lru._last !== p) { lru.delete(p); lru.add(p); lru._last = p }
visitor(pg, c, s, e, Math.max(pos - srcOff, 0))
}
pos += pLen
}
// Read from accumulator partial buffer if it extends beyond emitted pages
let acc = a._.acc
if (acc && pos < srcOff + len) {
let partial = acc.partial
if (partial) {
let s = Math.max(srcOff - pos, 0), e = Math.min(srcOff + len - pos, partial[0].length)
if (e > s) visitor(partial, c, s, e, Math.max(pos - srcOff, 0))
}
}
}
/** Copy channel c from a's pages into target buffer. */
export function copyPages(a, c, srcOff, len, target, tOff) {
walkPages(a, c, srcOff, len, (pg, ch, s, e, off) => target.set(pg[ch].subarray(s, e), tOff + off))
}
/** Read range from source pages (no edits). */
export function readPages(a, offset, duration) {
let sr = a.sampleRate, ch = a._.ch
let s = offset != null ? Math.min(Math.max(Math.round(offset * sr), 0), a._.len) : 0
let len = duration != null ? Math.round(duration * sr) : a._.len - s
len = Math.min(Math.max(len, 0), a._.len - s)
let out = Array.from({ length: ch }, () => new Float32Array(len))
for (let c = 0; c < ch; c++) copyPages(a, c, s, len, out[c], 0)
return out
}
// ── Decode ───────────────────────────────────────────────────────────────
/** Resolve source to ArrayBuffer. */
async function resolveSource(source) {
if (source instanceof ArrayBuffer) return source
if (source instanceof Uint8Array) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength)
if (source instanceof URL) return resolveSource(source.href)
if (typeof source === 'string') {
if (/^(https?|data|blob):/.test(source) || typeof window !== 'undefined')
return (await fetch(source)).arrayBuffer()
if (source.startsWith('file:')) {
let { fileURLToPath } = await import('url')
source = fileURLToPath(source)
}
let { readFile } = await import('fs/promises')
let buf = await readFile(source)
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
}
throw new TypeError('audio: unsupported source type')
}
/** Detect format + prepare source. */
async function detectSource(source) {
if (source instanceof ArrayBuffer || source instanceof Uint8Array) {
let bytes = source instanceof ArrayBuffer
? new Uint8Array(source)
: source.byteOffset || source.byteLength !== source.buffer.byteLength
? new Uint8Array(source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength))
: new Uint8Array(source.buffer)
return { format: getType(bytes), bytes }
}
if (typeof source === 'string' && !/^(https?|data|blob):/.test(source) && typeof window === 'undefined') {
let path = source
if (source.startsWith('file:')) { let { fileURLToPath } = await import('url'); path = fileURLToPath(source) }
let { open, stat } = await import('fs/promises')
let fh = await open(path, 'r')
let hdr = new Uint8Array(12)
await fh.read(hdr, 0, 12, 0)
await fh.close()
let format = getType(new Uint8Array(hdr))
let fileSize = (await stat(path)).size
let { createReadStream } = await import('fs')
return { format, reader: createReadStream(path), fileSize }
}
let buf = await resolveSource(source)
let bytes = new Uint8Array(buf)
return { format: getType(bytes), bytes }
}
/** Universal page accumulator — push(chData, sampleRate) interface.
* Used by decodeSource and audio() push instances. This IS the universal source adapter. */
function pageAccumulator(opts = {}) {
let { pages = [], notify, ondata } = opts
let sr = 0, ch = 0, totalLen = 0, pagePos = 0
let pageBuf = null, session
function emit(page) {
pages.push(page)
totalLen += page[0].length
notify?.()
}
return {
pages,
get sampleRate() { return sr },
get channels() { return ch },
get length() { return totalLen + pagePos },
get partial() { return pagePos > 0 ? pageBuf.map(c => c.subarray(0, pagePos)) : null },
get partialLen() { return pagePos },
get stats() { return session?.snapshot?.() ?? null },
push(chData, sampleRate) {
if (!pageBuf) {
sr = sampleRate; ch = chData.length
pageBuf = Array.from({ length: ch }, () => new Float32Array(audio.PAGE_SIZE))
session = audio.statSession?.(sr)
}
session?.page(chData)
let srcPos = 0, chunkLen = chData[0].length
while (srcPos < chunkLen) {
let n = Math.min(chunkLen - srcPos, audio.PAGE_SIZE - pagePos)
for (let c = 0; c < ch; c++) pageBuf[c].set(chData[c].subarray(srcPos, srcPos + n), pagePos)
srcPos += n; pagePos += n
if (pagePos === audio.PAGE_SIZE) {
emit(pageBuf)
pageBuf = Array.from({ length: ch }, () => new Float32Array(audio.PAGE_SIZE))
pagePos = 0
}
}
if (ondata) {
let delta = session?.delta()
if (delta) ondata({ delta, offset: (totalLen + pagePos) / sr, sampleRate: sr, channels: ch, pages })
}
notify?.()
},
/** Flush partial page into pages array. Non-destructive — accumulator stays open. */
drain() {
if (pagePos > 0) {
emit(pageBuf.map(c => c.slice(0, pagePos)))
pageBuf = Array.from({ length: ch }, () => new Float32Array(audio.PAGE_SIZE))
pagePos = 0
}
},
done() {
if (pagePos > 0) emit(pageBuf.map(c => c.slice(0, pagePos)))
session?.flush()
if (ondata && session) {
let delta = session.delta()
if (delta) ondata({ delta, offset: totalLen / sr, sampleRate: sr, channels: ch, pages })
}
return { stats: session?.done(), length: totalLen }
}
}
}
/** Estimate duration from file size, format, sampleRate, channels. */
function estimateDuration(fileSize, format, sampleRate, channels) {
if (!fileSize || !sampleRate || !channels) return null
if (format === 'wav') return Math.max(0, (fileSize - 44) / (sampleRate * channels * 2)) // 16-bit PCM
if (format === 'flac') return fileSize / (sampleRate * channels * 0.7) // ~56% compression typical
if (format === 'mp3') return fileSize / (128000 / 8) // assume 128kbps
if (format === 'ogg' || format === 'opus') return fileSize / (96000 / 8) // assume 96kbps
return null
}
/** Decode any source into pages + stats. Pages fill progressively. */
async function decodeSource(source, opts = {}) {
let { format, bytes, reader, fileSize } = await detectSource(source)
// Non-streaming fallback
if (!format || !decode[format]) {
if (!bytes) bytes = new Uint8Array(await resolveSource(source))
let { channelData, sampleRate } = await decode(bytes.buffer || bytes)
let pages = opts.pages || []
let ps = paginate(channelData)
for (let p of ps) { pages.push(p); opts.notify?.() }
let stats = audio.statSession?.(sampleRate)?.page(channelData)?.done() ?? null
let header = bytes.subarray(0, Math.min(bytes.length, 256 * 1024))
return { pages, sampleRate, channels: channelData.length, header, format, decoding: Promise.resolve({ stats, length: channelData[0].length }) }
}
// Streaming decode
let dec = await decode[format]()
let t = performance.now()
let yieldLoop = () => {
let now = performance.now()
if (now - t > 8) { t = now; return new Promise(r => setTimeout(r, 0)) }
}
let firstResolve
let origNotify = opts.notify
let firstReady = new Promise(r => { firstResolve = r })
let acc = pageAccumulator({
pages: opts.pages,
ondata: opts.ondata,
notify: () => { origNotify?.(); if (firstResolve) { let f = firstResolve; firstResolve = null; f() } }
})
// Accumulate first ~256KB for meta parsing (ID3v2, FLAC blocks, WAV chunks before `data`).
let HEADER_CAP = 256 * 1024, headerChunks = [], headerLen = 0, headerDone = false, headerBytes = null
let addHeader = buf => {
if (headerDone || !headerChunks) return
headerChunks.push(buf)
headerLen += buf.length
if (headerLen >= HEADER_CAP) headerDone = true
}
let flushHeader = () => {
if (headerBytes) return headerBytes
if (!headerChunks) return new Uint8Array(0)
headerBytes = new Uint8Array(headerLen)
let pos = 0
for (let c of headerChunks) { headerBytes.set(c, pos); pos += c.length }
headerChunks = null
return headerBytes
}
let decoding = (async () => {
try {
if (reader) {
for await (let chunk of reader) {
let buf = chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk)
addHeader(buf)
let r = await dec(buf)
if (r.channelData.length) acc.push(r.channelData, r.sampleRate)
await yieldLoop()
}
} else {
addHeader(bytes)
let FEED = 64 * 1024
for (let off = 0; off < bytes.length; off += FEED) {
let r = await dec(bytes.subarray(off, Math.min(off + FEED, bytes.length)))
if (r.channelData.length) acc.push(r.channelData, r.sampleRate)
await yieldLoop()
}
}
let flushed = await dec()
if (flushed.channelData.length) acc.push(flushed.channelData, flushed.sampleRate)
let final = acc.done()
final.header = flushHeader()
return final
} catch (e) { if (firstResolve) { let f = firstResolve; firstResolve = null; f() }; throw e }
})()
await firstReady
if (!acc.sampleRate) throw new Error('audio: decoded no audio data')
let estDuration = estimateDuration(fileSize || bytes?.length, format, acc.sampleRate, acc.channels)
return { pages: acc.pages, sampleRate: acc.sampleRate, channels: acc.channels, header: flushHeader(), format, decoding, acc, estDuration }
}