Repository navigation
Expand file tree
/
Copy pathcore.js
More file actions
1512 lines (1400 loc) · 73.6 KB
/
Copy pathcore.js
File metadata and controls
1512 lines (1400 loc) · 73.6 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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* 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 '@audio/encode'
import convert, { parse as parseFmt } from 'pcm-convert'
import parseDuration from 'parse-duration'
import { resolveBuses } from './batch.js'
audio.version = '2.14.0'
/** Options as written short or long, the long kept: FFmpeg's `d` for duration (afade, acrossfade, atrim), and its
* crossfade filter's name, `xfade`, for crossfade. */
export function named(o) {
if (o == null || typeof o !== 'object' || (o.d === undefined && o.xfade === undefined)) return o
let { d, xfade, ...rest } = o
if (d !== undefined) rest.duration ??= d
if (xfade !== undefined) rest.crossfade ??= xfade
return rest
}
/** 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 = {}) {
// Worker-hosted engine — same call shape, runs in a Worker (import 'audio/worker' enables it)
if (opts.worker) {
let aw = globalThis[Symbol.for('audio.worker')]
if (!aw) throw new Error('audio: { worker } requires `import "audio/worker"` first — the worker facade stays out of the main bundle')
return aw(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(); scheduleEvict(a) }
let a = create([], sr, ch, 0, opts, null)
a.decoded = false
a.recording = false
a._.push = true // marks this instance as pushable — only these finalize on stop()
a._.acc = pageAccumulator({ pages: a.pages, notify, ondata: (...args) => emit(a, 'data', ...args) })
a._.waiters = waiters
stored(a, opts)
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(e => emit(first, 'error', e))
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)
// awaited, its pages are within the budget
if (a._.storing) {
a.ready = a._.storing.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(); scheduleEvict(a) }
// 'data' must not be observable before 'metadata' — queue until metadata fires, then flush in order.
let dataQueue = [], metaEmitted = false
let emitData = (...args) => metaEmitted ? emit(a, 'data', ...args) : dataQueue.push(args)
let a = create(pages, 0, 0, 0, { ...opts, source: ref }, null)
a._.waiters = waiters
a.decoded = false
const abort = a._.abort = new AbortController()
let readyResolve, readyReject
a._.ready = new Promise((r, j) => { readyResolve = r; readyReject = j })
a._.readyResolve = readyResolve
a._.ready.catch(() => {}) // suppress unhandled rejection
a.ready = (async () => {
try {
// persistent waits for its store, failing without one; auto decodes at once, its pages going to disk once it has one
let store = storeOf(a, opts)
if (store && opts.storage === 'persistent') { await store; if (a._.disposed) return true }
else store?.then(() => scheduleEvict(a), () => {})
let result = await decodeSource(source, { pages, notify, ondata: emitData, disposed: () => a._.disposed, signal: abort.signal })
if (a._.disposed) return true
a.sampleRate = result.sampleRate
a._.ch = result.channels
a._.fmtV = -1 // invalidate cached format
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; a._.bits = headerBits(result.format, result.header) }
emit(a, 'metadata', { sampleRate: result.sampleRate, channels: result.channels, estDuration: result.estDuration })
metaEmitted = true
for (let args of dataQueue.splice(0)) emit(a, 'data', ...args)
readyResolve()
a._.readyResolve = null
let final = await result.decoding
if (a._.disposed) return true
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).catch(() => {})
delete a.then; delete a.catch // clear thenable before resolve to prevent unwrap loop
return true
} catch (e) {
if (a._.disposed) return true
readyReject(e)
a._.readyResolve = null
emit(a, 'error', e)
throw e
} finally {
if (a._.abort === abort) a._.abort = null
}
})()
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) }
}
/** A copy `b` of a source `a` still arriving (a file decoding, a pushed stream) follows it (audio.from): it reads the
* pages as they land and has what `a` has, its length, stats, header and end, its rate and channels unless the copy
* asked for its own (`keep`), so it streams and edits live as `a` does. It shares `a`'s pages: disposing `b` drops
* its reference only; disposing `a` ends `b` too, as it ends `a`'s own streams. */
function follow(b, a, keep) {
b.pages = a.pages
let own = false
for (let k of ['len', 'acc', 'waiters', 'ready', 'estDur', 'header', 'format', 'bits', ...(keep.sr ? ['sr'] : []), ...(keep.ch ? ['ch'] : [])])
Object.defineProperty(b._, k, { get: () => a._[k], set() {}, enumerable: true, configurable: true })
Object.defineProperty(b._, 'disposed', { get: () => own || a._.disposed, set(v) { own = v }, enumerable: true, configurable: true })
Object.defineProperty(b, 'decoded', { get: () => a.decoded, set() {}, enumerable: true, configurable: true })
// the pages' store is `a`'s, set up after the copy may be made (storeOf): a page `a` lets go of comes back from it
Object.defineProperty(b, 'cache', { get: () => a.cache, set() {}, enumerable: true, configurable: true })
// its samples' stats, not what `a`'s edits make of them
Object.defineProperty(b, 'stats', { get: () => a.srcStats, set() {}, enumerable: true, configurable: true })
// the rate and channels arrive with the header: what was worked out from none is worked out again
if (!a._.sr) { let meta = () => { a.off('metadata', meta); b._.fmtV = b._.lenV = -1 }; a.on('metadata', meta) }
b.ready = a.ready.then(() => true)
b.ready.catch(() => {})
makeThenable(b)
}
/** 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)
// a page store ({ read(i), has(i), write(i, page) }, as cache.js's: pages kept on disk, a file's): its shape given,
// { length, channels, sampleRate, stats }, no page in memory till it is read, at most `budget` bytes of them after
if (typeof source?.read === 'function' && typeof source.has === 'function' && !source.pages) {
let { length = 0, channels = 1, sampleRate = 44100, stats = null } = opts
return create(Array(Math.ceil(length / audio.PAGE_SIZE)).fill(null), sampleRate, channels, length, { ...opts, cache: source }, stats)
}
if (source?.pages) {
// the copy holds the source's pages, not what its edits make of them: their stats, else one measured through its
// edits would be taken for its samples'
let b = 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, bitDepth: opts.bitDepth ?? source._.bits }, source.srcStats)
// a source still arriving: the copy follows it as it lands; a rate or channel count asked for stays the copy's
if (source._.waiters && !source.decoded) follow(b, source, { sr: !opts.sampleRate || opts.sampleRate === source._.sr, ch: !opts.channels || opts.channels === source._.ch })
// one arrived: its header, so the copy reads the file's own tags and markers as the source does
else Object.assign(b._, { header: source._.header, format: source._.format })
return b
}
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')
}
/** Stored sample depth of encoded audio bytes (their header): what `a.bitDepth` reports for a
* file source; for hosts that decode elsewhere (e.g. decodeAudioData) and build with audio.from. */
export const bitDepth = bytes => { let h = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes); return headerBits(detectType(h), h) }
/** Stored sample depth from a PCM container header: WAV `fmt ` bitsPerSample, AIFF `COMM`
* sampleSize (AIFC fl32/fl64 → 32/64), FLAC STREAMINFO bits-per-sample. Null otherwise. */
function headerBits(format, h) {
if (!h?.length) return null
let dv = new DataView(h.buffer, h.byteOffset, h.byteLength), id = o => String.fromCharCode(h[o], h[o + 1], h[o + 2], h[o + 3])
try {
if (format === 'flac') return id(0) === 'fLaC' ? ((h[20] & 1) << 4 | h[21] >> 4) + 1 : null
let le = format === 'wav', want = le ? 'fmt ' : format === 'aiff' ? 'COMM' : null
if (!want) return null
for (let o = 12; o + 8 <= h.length;) {
let size = dv.getUint32(o + 4, le)
if (id(o) === want) {
if (le) return dv.getUint16(o + 22, true)
let fl = size >= 22 ? id(o + 26).toLowerCase() : ''
return fl === 'fl32' ? 32 : fl === 'fl64' ? 64 : dv.getUint16(o + 14)
}
o += 8 + size + (size & 1)
}
} catch {}
return null
}
// ── Plugin Architecture ─────────────────────────────────────────────────
const fn = {}
audio.fn = fn // instance prototype (like $.fn)
audio.BLOCK_SIZE = 1024
audio.PAGE_SIZE = 1024 * audio.BLOCK_SIZE
/** The block of `bs` samples a time is in, `round` the way (floor: where a range starts; ceil: past where it ends), by its
* nearest sample: a time the library gave (a pause's end, k·bs/sr) lands on its block's edge, not a float's hair past
* it, which ceil reads as one more block. */
export const blockAt = (t, sr, bs, round = Math.floor) => round(Math.round(t * sr) / bs)
/** Full scale as PCM decodes (v/2^(bits-1)): 16-bit +32767 reads 32767/32768, so a sample this loud counts as clipped. */
export const FULL = 32767 / 32768
/** Internal protocol symbols for plugin overrides. */
export const LOAD = Symbol('load')
export const READ = Symbol('read')
/** Give the event loop a turn (I/O, timers, rendering, the messages waiting) between bursts of work. setTimeout(0)
* waits ≥1 ms in Node and ≥4 ms once nested in a browser; these return as soon as the loop has turned. Not
* scheduler.yield(): its continuation is queued ahead of the tasks already waiting, so a loop that yields with it
* keeps them waiting till it ends (a long file decoding in a worker answered nothing for the 11 s it took). */
export const yieldTask =
typeof setImmediate === 'function' ? () => new Promise(r => setImmediate(r)) :
typeof MessageChannel === 'function' ? () => new Promise(r => {
let mc = new MessageChannel() // one per turn, closed after: no open port holds a runtime alive
mc.port1.onmessage = () => { mc.port1.close(); r() }
mc.port2.postMessage(0)
}) :
() => new Promise(r => setTimeout(r, 0))
/** Resolve a channel option to concrete indices: null → all, n → [n], [..] → per-channel. */
export function resolveChannels(channel, total) {
let perCh = Array.isArray(channel)
let chs = channel != null ? (perCh ? channel : [channel]) : Array.from({ length: total }, (_, i) => i)
for (let c of chs) if (!Number.isInteger(c) || c < 0 || c >= total) throw new RangeError(`channel ${c}: the audio has ${total} channel${total === 1 ? '' : 's'}`)
return { chs, perCh }
}
/** The channels `channel` picks from a block, as resolveChannels reads it: all by default. */
export const pickChannels = (pcm, channel) => resolveChannels(channel, pcm.length).chs.map(c => pcm[c])
/** A streaming stat method that reads `{ channel }` as the block stats do: an array of channels answers per channel. */
export const perChannel = f => function (opts) {
return Array.isArray(opts?.channel) ? Promise.all(opts.channel.map(channel => f.call(this, { ...opts, channel }))) : f.call(this, opts)
}
/** Stream a range as the chosen channels' mean: what beats, notes, chords and key read. */
export async function* mono(inst, opts) {
opts = named(opts)
for await (let all of inst.stream({ at: opts?.at, duration: opts?.duration })) {
let pcm = pickChannels(all, opts?.channel), n = pcm[0]?.length
if (!n) continue
if (pcm.length === 1) { yield pcm[0]; continue }
let m = new Float32Array(n)
for (let ch of pcm) for (let i = 0; i < n; i++) m[i] += ch[i] / pcm.length
yield m
}
}
/** Emit event on instance. Snapshots listeners so a handler that (un)subscribes mid-emit
* cannot skip/duplicate others in this dispatch. */
export function emit(a, event, ...args) {
let arr = a._.ev[event]
if (arr) for (let cb of arr.slice()) cb(...args)
}
fn.on = function(event, cb) {
(this._.ev[event] ??= []).push(cb)
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.indexOf(cb); if (i >= 0) arr.splice(i, 1) }
return this
}
fn.dispose = function() {
this._.disposed = true // checked by in-flight decode/seek continuations to abort without mutating this instance
this.stop()
this._.abort?.abort()
this._.abort = null
this._.readyResolve?.()
this._.readyResolve = null
for (const url of this._.urls || []) URL.revokeObjectURL(url)
this._.urls = null
this._.ev = {}
this._.meters = null
this._.pcm = null
this._.plan = null
this._.wrc = null
this._.rsc = null
this._.srcStats = null
this._.header = null
this._.meta = null
this._.markers = null
this._.regions = null
this._.marks = null
this._.lru.clear()
this.edits.length = 0
this.block = null
// dropped, not emptied: a copy that follows this source (follow) may still read them
this.pages = []
this.stats = null
if (this._.waiters) for (let w of this._.waiters.splice(0)) w()
this._.waiters = null
this._.acc = null
this.cache = null
}
if (Symbol.dispose) fn[Symbol.dispose] = fn.dispose
const isOp = p => typeof p === 'function' && Object.hasOwn(p, 'params') && typeof p.params === 'object'
const isStat = p => p != null && typeof p === 'object' && typeof p.stat === 'string' && typeof p.compute === 'function'
const isCodec = p => p != null && typeof p === 'object' && typeof p.codec === 'string' && (typeof p.decode === 'function' || typeof p.encode === 'function')
/** Register plugins. Each receives audio. A contract plugin (a factory function
* with an own `params` object — see audiojs/compile CONTRACT.md) is hosted natively as
* an op; its declared `tail` composes a trailing pad so decays are not truncated.
* A stat plugin ({ stat: name, compute(channels, opts) }) registers as a.stat(name).
* A codec plugin ({ codec: fmt, test?, decode?, encode? }) extends what audio() can
* open and what save()/encode() can write. A string resolves through the
* audio.plugins registry (dynamic import — returns a promise); every atom-, stat- or
* codec-shaped export of the target registers. */
audio.use = function(...plugins) {
let loads = null
for (let p of plugins) {
if (typeof p === 'string') {
let spec = audio.plugins?.[p] ?? audio.atoms?.[p] // .atoms — deprecated ≤2.5 name
if (!spec) throw new Error(`audio.use: unknown plugin '${p}' — not in audio.plugins registry`)
;(loads ??= []).push(audio.import(spec).then(ns => {
for (let k of Object.keys(ns)) { if (isOp(ns[k])) useOp(ns[k]); else if (isStat(ns[k])) useStat(ns[k]); else if (isCodec(ns[k])) useCodec(ns[k]) }
}, e => { throw new Error(`audio.use('${p}'): install ${spec.split('/').slice(0, 2).join('/')} — ${e.message}`) }))
}
else if (isOp(p)) useOp(p)
else if (isStat(p)) useStat(p)
else if (isCodec(p)) useCodec(p)
else p(audio)
}
return loads ? Promise.all(loads).then(() => audio) : audio
}
/** Constant-power crossfade gains out of one signal into another that correlates ρ with it over the crossfade (Fink,
* Holters & Zölzer, "Signal-matched power-complementary cross-fading and dynamic processing", EURASIP JASP 2016):
* cos and sin over √(1 + 2ρ·cos·sin) at progress u ∈ [0, 1]: linear for one signal (ρ = 1), equal-power for unrelated
* ones (ρ = 0). */
export const xfade = (u, rho) => {
let a = u * Math.PI / 2, c = Math.cos(a), s = Math.sin(a), k = 1 / Math.sqrt(1 + 2 * rho * c * s)
return [c * k, s * k]
}
/** How alike two signals are over their first `n` samples, 0 to 1: their normalized correlation, out of phase as unrelated */
export function correlation(p, q, n) {
let pq = 0, pp = 0, qq = 0
for (let i = 0; i < n; i++) { let u = p[i] ?? 0, v = q[i] ?? 0; pq += u * v; pp += u * u; qq += v * v }
return pp && qq ? Math.max(0, Math.min(1, pq / Math.sqrt(pp * qq))) : 0
}
/** A whole-render op over a range: it reads all of its input, its output kept in the range alone, the input as it was
* outside it (one that renders in place, channel for channel; a time-stretch's range is its frames hook's). Each edge
* crossfades over 10 ms inside the range, from the input into what the op made and back, at the power their
* correlation there asks: a hard switch between the two clicks wherever they differ */
export function ranged(input, output, ctx) {
if ((ctx.at == null && ctx.duration == null) || output.length !== input.length) return
let n = input[0].length, at = ctx.at ?? 0, a = Math.max(0, Math.min(n, Math.round((at < 0 ? ctx.totalDuration + at : at) * ctx.sampleRate)))
let b = ctx.duration == null ? n : Math.min(n, a + Math.round(ctx.duration * ctx.sampleRate))
let x = Math.min(Math.round(0.01 * ctx.sampleRate), (b - a) >> 1)
for (let c = 0; c < output.length; c++) {
let i0 = input[c], o = output[c]
o.set(i0.subarray(0, a)); o.set(i0.subarray(b), b)
let ri = a > 0 ? correlation(i0.subarray(a), o.subarray(a), x) : 1, ro = b < n ? correlation(o.subarray(b - x), i0.subarray(b - x), x) : 1
for (let i = 0; i < x; i++) {
let u = (i + .5) / x
if (a > 0) { let [d, w] = xfade(u, ri); o[a + i] = d * i0[a + i] + w * o[a + i] }
if (b < n) { let [w, d] = xfade(u, ro), j = b - x + i; o[j] = w * o[j] + d * i0[j] }
}
}
}
/** What audio adds to a plugin it hosts, by the name the plugin registers: the op (or stat) as the plugin makes it →
* the one audio registers. A host can do what a plugin's contract can't: fn/auto.js renders @audio/chain's auto ahead
* of time, its denoise stage neural where @audio/neural-denoise is installed. */
audio.hosted = {}
/** How a registry plugin's module loads. A bundled page whose bundler cannot see `import(spec)` (a worker has no
* import map) supplies literal imports: audio.import = spec => loaders[spec]() */
audio.import = spec => import(spec)
/** Register a codec plugin: { codec: fmt, test?(bytes) → bool, decode?(bytes) →
* { channelData, sampleRate } | Promise, encode?(opts) → enc } (enc(chunk) →
* bytes, enc() → flush). test() sniffs headers where magic-byte detection draws
* a blank. A package may carry one half (decode-X / encode-X manifests) —
* registrations merge by format name. Codec atoms *extend*: bundled umbrella
* codecs win for formats they already serve (streaming decode stays streaming). */
function useCodec(m) {
let reg = (audio.codecs ??= {})
reg[m.codec] = { ...reg[m.codec], ...m }
}
/** Register a stat plugin: whole-signal analysis `compute(channels, { sampleRate, ...opts })`.
* The host reads the (ranged) PCM and hands it over — the batch shape every analysis
* kernel already is. Option values that are audio instances (e.g. similarity's `ref`)
* are pre-rendered to channel data. */
function useStat(m) {
if (!audio.stat) throw new Error('audio.use(stat): stat registry required — import "audio", not "audio/core.js"')
m = audio.hosted[m.stat]?.(m) ?? m
let name = m.stat
audio.stat(name, {}) // name registered; fn.stat dispatches to the instance method below
audio.fn[name] = async function(opts) {
let { at, duration, ...rest } = opts || {}
for (let k in rest) if (rest[k]?.pages && rest[k].read) rest[k] = await rest[k].read()
let pcm = await this.read(at != null || duration != null ? { at, duration } : undefined)
return m.compute(pcm, { sampleRate: this.sampleRate, ...rest })
}
}
/** Map a contract plugin (audio.js manifest factory) to an op descriptor. The contract is a convention, not a
* library — audio consumes it natively: params read off the factory, per-instance
* state on the proc ctx, smoothing left to engine sub-block automation (it already
* ramps patched values click-free), currentTime from blockOffset. */
function useOp(m) {
if (!audio.op) throw new Error('audio.use(module): op registry required — import "audio", not "audio/core.js"')
let specs = m.params || {}
let names = Object.keys(specs)
let id = m.id || (m.name || 'module').replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase()
let reg = d => audio.op(id, audio.hosted[id]?.(d) ?? d)
// tail: seconds, or fn(ctx) of the actual params (mirrors latency's fn form) — a
// feedback delay's decay depends on its feedback setting, not the declared maximum
let tail = m.tail || 0
// a param's `alias` is its former name: hosts still accept it (contract §Parameter metadata)
let given = (get, name) => get(name) ?? (specs[name].alias != null ? get(specs[name].alias) : undefined)
let snapParams = get => {
let s = {}
for (let name of names) {
let sp = specs[name], v = given(get, name) ?? sp.default
s[name] = sp.type === 'number' ? new Float32Array([v]) : v
}
return s
}
// Declared latency → plan-level plugin delay compensation (fn form: once per instance)
let latency = typeof m.latency === 'function'
? (o, sr) => m.latency({ sampleRate: sr, params: snapParams(n => o?.[n]) }) | 0
: m.latency | 0
let init = (ctx, maxBlock = audio.BLOCK_SIZE, width) => {
let snapshot = snapParams(name => ctx[name])
let mctx = {
sampleRate: ctx.sampleRate, maxBlockSize: maxBlock, maxChannels: 32,
render: 'offline', duration: ctx.totalDuration, currentTime: 0,
// declared layouts (contract §Buses) resolve against the input width; `layouts` option picks
params: snapshot, layouts: resolveBuses(m.channels, width == null ? [] : [width], ctx.layouts).layouts, events: undefined,
// events.out declaration validated; host routing of emissions is future work
emit(name) { if (!(name in (m.events?.out || {}))) throw new Error(`emit: "${name}" not declared in events.out`) }
}
let st = { mctx, live: {}, bufs: {} }
for (let name of names) if (specs[name].type === 'number') st.bufs[name] = new Float32Array(1)
st.process = m(mctx)
return st
}
let fill = (st, ctx) => {
for (let name of names) {
let sp = specs[name]
let v = given(n => ctx[n], name) ?? sp.default
if (sp.type === 'number') {
if (v < sp.min) v = sp.min
else if (v > sp.max) v = sp.max
st.bufs[name][0] = v
st.live[name] = st.bufs[name]
} else st.live[name] = sp.type === 'enum' && !sp.values.includes(v) ? sp.default : v
}
}
// Declared extra input buses (contract §channels) — bus 1 fed from ctx.key
// (an audio instance / Float32Array[]), rendered per block, rate-reconciled
let keyed = Array.isArray(m.channels?.inputs) && m.channels.inputs.length > 1
// its params as a call takes them: a keyed op's key first, the sound it reads (a.ducker(voice, { threshold }))
let args = keyed ? ['key', ...names] : names
// Declared fixed output count ≠ input (contract §channels, e.g. 2→5.1 upmix) →
// op-level `ch` hook; the plan pipeline sizes that stage's buffers to it
let busN = side => typeof side === 'number' ? side
: Array.isArray(side) && typeof side[0] === 'number' ? side[0] : null
let outN = busN(m.channels?.outputs)
let ch = outN != null && outN !== busN(m.channels?.inputs) ? () => outN : undefined
// Declared layouts (contract §Buses, e.g. mono → 'ambisonic-1'): the output width is the resolved layout's,
// unless both sides declare the same layouts (the width carries through)
let { inputs: li, outputs: lo } = m.channels ?? {}
if (resolveBuses(m.channels).layouts && JSON.stringify(li) !== JSON.stringify(lo))
ch = (n, o) => resolveBuses(m.channels, [n], o?.layouts).outputs[0]?.channels
let process = (input, output, ctx) => {
let st = ctx._am ??= init(ctx, undefined, input.length)
st.mctx.currentTime = ctx.blockOffset || 0
if (noteIn) feedEvents(st, ctx, input[0].length)
fill(st, ctx)
if (keyed && ctx.key != null && audio.renderAt) {
let n = input[0].length
let off = Math.round((ctx.blockOffset || 0) * ctx.sampleRate)
st.process([input, audio.renderAt(ctx.render, ctx.key, off, n, ctx.sampleRate)], [output], st.live)
} else st.process(keyed ? [input, undefined] : [input], [output], st.live)
}
// Per-block note feed for streaming instruments (contract §events): slice the
// compiled slots to [blockStart, blockEnd), times rebased block-relative. Slot
// objects are pooled per contract; binary search each block — streams can
// restart or seek, so no monotonic cursor.
let feedEvents = (st, ctx, frames) => {
if (ctx.notes && st.slots?.src !== ctx.notes)
st.slots = { src: ctx.notes, evs: noteSlots(ctx.notes, ctx.sampleRate), pool: [], view: [] }
if (!st.slots) { st.mctx.events = ctx.notes === undefined ? st.mctx.events : undefined; return }
let { evs, pool, view } = st.slots
let b0 = Math.round((ctx.blockOffset || 0) * ctx.sampleRate), b1 = b0 + frames
let lo = 0, hi = evs.length
while (lo < hi) { let mid = (lo + hi) >> 1; if (evs[mid].time < b0) lo = mid + 1; else hi = mid }
let n = 0
for (let i = lo; i < evs.length && evs[i].time < b1; i++, n++) {
let s = pool[n] ??= {}
let e = evs[i]
s.time = e.time - b0; s.type = e.type; s.kind = e.kind
s.pitch = e.pitch; s.velocity = e.velocity; s.channel = e.channel; s.id = e.id
view[n] = s
}
view.length = n
st.mctx.events = view
}
// Declared note input (contract §events) — the offline host's event source is a
// `notes` option: [{ time, midi | freq, duration?, velocity? }] compiled to the
// contract's pooled slots ({ time: sample, type: 'note', kind: 'on'|'off', pitch,
// velocity, channel, id }), sorted, on/off paired by id.
let noteIn = m.events?.in?.includes('note')
let noteSlots = (notes, sr) => {
let evs = []
for (let i = 0; i < notes.length; i++) {
let n = notes[i]
let pitch = n.midi ?? (n.freq != null ? 69 + 12 * Math.log2(n.freq / 440) : 69)
let on = Math.round((n.time ?? 0) * sr)
let velocity = n.velocity ?? 1
evs.push({ time: on, type: 'note', kind: 'on', pitch, velocity, channel: 0, id: i })
if (n.duration != null) evs.push({ time: on + Math.round(n.duration * sr), type: 'note', kind: 'off', pitch, velocity: 0, channel: 0, id: i })
}
return evs.sort((a, b) => a.time - b.time)
}
// streaming: false — the module needs the entire signal in one call; the plan
// engine materializes the timeline and hosts it as a whole-render op
if (m.streaming === false) {
// Declared tail on a whole-render plugin → plan pads the materialized input with
// that many seconds of silence so the decay renders instead of truncating (the
// plugin still sees equal frames in/out — both sides extended).
let wholeTail = typeof m.tail === 'function'
? (o, sr) => m.tail({ sampleRate: sr, params: snapParams(n => o?.[n]) })
: m.tail || 0
// Declared frames hook → structural output length (time-stretch class): the plan
// sizes the output buffers by it and continues from the result's actual length.
let frames = m.frames
? (n, o, sr) => m.frames(n, { sampleRate: sr, params: snapParams(k => o?.[k]) })
: undefined
return reg({
params: args, plugin: m, atom: m, ch, tail: wholeTail, frames,
whole(input, output, ctx) {
let st = init(ctx, input[0].length, input.length)
if (noteIn && ctx.notes) st.mctx.events = noteSlots(ctx.notes, ctx.sampleRate)
fill(st, ctx)
// a keyed module reads its key bus whole too, rendered over the same length
let key = keyed && ctx.key != null && audio.renderAt ? audio.renderAt(ctx.render, ctx.key, 0, input[0].length, ctx.sampleRate) : undefined
st.process(keyed ? [input, key] : [input], [output], st.live)
if (!frames) ranged(input, output, ctx)
}
})
}
if (!tail) return reg({ params: args, plugin: m, atom: m, latency, process, ch })
// Declared tail: expand into pad + hidden proc at compile time — the user edit stays
// one atomic entry (undo/serialize whole), the decay renders into the pad
audio.op('_' + id, { params: args, hidden: true, plugin: m, atom: m, latency, process, ch })
reg({
params: args, tail, plugin: m, atom: m, ch,
expand: (ctx) => {
let o = {}
for (let k of args) if (ctx[k] !== undefined) o[k] = ctx[k]
let t = typeof tail === 'function'
? tail({ sampleRate: ctx.sampleRate, params: snapParams(n => o[n]) })
: tail
return [['pad', { before: 0, after: t }], ['_' + id, o]]
}
})
}
// ── 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
keep: true, // preservesPitch
loop: false,
push: false, // true only for pushable (audio(null)) instances — gates fn.stop()'s finalize branch
disposed: false, // set by fn.dispose() — in-flight async continuations check this to abort
evicting: false, // non-reentrant guard for scheduleEvict
bits: opts.bitDepth ?? null, // stored sample depth of a PCM source (header), null when lossy/unknown
},
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._.fmt = null; a._.fmtV = -1 // effective sr/ch after edits (plan.js deriveFormat)
// Playback (getter/setter for interpolation & events)
Object.defineProperties(a, {
currentTime: {
get() {
// playing: what the speakers play now (fn/play.js)
let heard = this._.clock?.()
if (heard != null) return heard
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
},
// at a rate other than 1, the pitch kept (true, as a media element's) or following the speed, as a tape's
preservesPitch: {
get() { return this._.keep },
set(v) { v = !!v; if (this._.keep !== v) { this._.keep = v; emit(this, 'ratechange') } },
enumerable: true, configurable: true
},
loop: {
get() { return this._.loop },
set(v) { v = !!v; if (this._.loop !== v) { this._.loop = v; this._.onloop?.(v) } },
enumerable: true, configurable: true
},
})
a.playing = false; a.paused = false
a.ended = false; a.seeking = false
a.block = null
// Cache
a._.lru = new Set()
return a
}
function fromChannels(channelData, opts = {}) {
let sr = opts.sampleRate || 44100
let a = create(paginate(channelData), sr, channelData.length, channelData[0].length, opts, audio.statSession?.(sr).page(channelData).done())
stored(a, opts)
return a
}
/** Where pages go once the instance holds more than its `budget` of them (cache.js: the browser's own file system,
* OPFS): `storage: 'persistent'` asks for it, failing where there is none; 'auto' takes it where there is one, else
* keeps them in memory; a `cache` given is used as it is. Persistent or auto, the budget is the platform's
* (detectBudget) unless given. Null when there is nothing to set up. */
function storeOf(a, opts) {
let { storage } = opts
if (opts.cache || storage !== 'persistent' && storage !== 'auto') return null
return (async () => {
if (!audio.opfsCache && storage === 'persistent') throw new Error('Persistent storage requires cache module (import "./cache.js")')
let cache = await audio.opfsCache?.().catch(() => null)
if (!cache) {
if (storage === 'persistent') throw new Error('OPFS not available (required by storage: "persistent")')
return
}
let budget = opts.budget ?? await audio.detectBudget?.() ?? audio.DEFAULT_BUDGET ?? Infinity
if (a._.disposed) return
a.cache = cache
a.budget = budget
})()
}
/** An instance made from samples or pushed, storing as asked (storeOf): its store set up and its pages put within the
* budget in the background (`_.storing`), nothing that reads it waiting for that; failing, an 'error' */
function stored(a, opts) {
if (!opts.cache && opts.storage !== 'persistent' && opts.storage !== 'auto') return
a._.storing = Promise.resolve(storeOf(a, opts)).then(() => audio.evict?.(a))
a._.storing.catch(e => emit(a, 'error', e))
}
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 = named(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 },
/** Stored sample depth of the source (16, 24, 32 = float); null for lossy or generated audio. */
bitDepth: { get() { return this._.bits }, configurable: true },
/** Source stats (pre-edit snapshot) — used by resolve-stage ops like normalize/trim. */
// false where they were not known when its edits were measured (a stream still arriving): `stats` are the edits' then;
// a pushed stream's those it accumulated, so far while it arrives, whole once it is
srcStats: { get() { let acc = this._.acc; return (this._.srcStats ?? this.stats) || (acc && (this.decoded ? acc.whole : acc.stats)) || null }, configurable: true },
})
/** Resolve lazily loaded op modules (a descriptor's `load: () => import(...)` hook) for
* the ops an instance's edits name, so sync plan compilation finds them on `desc.mod`,
* then run each edit's asynchronous preparation (`prepare(a, index)`, e.g. model inference
* over the edit's input) before anything renders.
* Keeps atoms out of the bundle until an edit uses them. */
export async function loadOps(a) {
// an op planned before its module loaded (a plugin's tail and latency) plans again once it has; so does one whose
// preparation changes what the plan makes of it (how long an impulse response rings: prepare returns true)
let changed = false
for (let [type] of a.edits ?? []) { let d = audio.op?.(type); if (d?.load && !d.mod && (d.mod = await (d.loading ??= d.load()))) changed = true }
for (let i = 0; i < (a.edits?.length ?? 0); i++) if (await audio.op?.(a.edits[i][0])?.prepare?.(a, i) === true) changed = true
if (changed) a._.planV = a._.lenV = -1
// its edits as they are now prepared: what plans them synchronously may render through them (a mark placed, meta.js)
a._.prepared = a.version
}
/** What an edit takes long to make of its input (a model's run over it, in its preparation), by `key`: what names the
* model and its input's samples (vocals.js fingerprint), never a setting applied after it. Read from `audio.memo`, the
* store a host gives ({ get(key) → channels or null, set(key, channels) }: the editor keeps them in the browser), else
* made by make() and kept there. No store, made each time. Asked again while it is being made, or before the store
* holds it, the one making is shared: two tracks split from one sound run the model once. */
const making = new Map()
export function memo(key, make) {
if (making.has(key)) return making.get(key)
let store = audio.memo, storing = false
let made = (async () => {
try {
let kept = store && await Promise.resolve().then(() => store.get(key)).catch(() => null)
if (kept) return kept
let v = await make()
if (store) storing = Promise.resolve().then(() => store.set(key, v)).catch(() => {}).finally(() => making.delete(key))
return v
} finally { if (!storing) making.delete(key) }
})()
making.set(key, made)
return made
}
fn[LOAD] = async function() {
await loadOps(this)
if (this._.ready) await this._.ready
// Whole-render ops (streaming: false atoms) need the entire timeline — rendering
// mid-decode processes a partial (or empty) signal: read() returned 0 samples and
// save() crashed on a file source that hadn't finished decoding. Wait decode out.
if (!this.decoded && this.ready && this.edits?.some(e => audio.op?.(e[0])?.whole)) await this.ready
this._.acc?.drain()
}
/** Resolve once the whole source has arrived: decode done, or a pushed stream stopped. */
export async function arrived(a) {
if (a.ready) await a.ready
while (!a.decoded && a._.waiters && !a._.disposed) await new Promise(r => a._.waiters.push(r))
}
/** A time counted from the end (negative), resolved against the output's duration: known only once
* the source has arrived. Other times pass through. */
export async function fromEnd(a, at) {
if (!(at < 0)) return at
await arrived(a)
return Math.max(0, a.duration + at)
}
/** Concatenate a block stream into channel arrays. */
async function collect(blocks, nch) {
let parts = [], n = 0
for await (let b of blocks) { parts.push(b); n += b[0].length }
let out = Array.from({ length: parts[0]?.length ?? nch }, () => new Float32Array(n))
for (let i = 0, o = 0; i < parts.length; o += parts[i++][0].length) parts[i].forEach((c, k) => out[k].set(c, o))
return out
}
/** Default read — restores any evicted pages first (no-op if cache.js isn't loaded or a has no cache). */
fn[READ] = async function(offset, duration) {
if (audio.ensurePages) await audio.ensurePages(this, 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._.fmtV = -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
scheduleEvict(this)
return this
}
/** Stop recording and/or finalize pushable stream. Drain partial page, signal EOF to waiting streams.
* No-op on non-pushable — an ordinary file/URL decode also populates `_.acc` (streaming codec buffer)
* while mid-decode, and must not be finalized by a transport-level stop(). */
fn.stop = function() {
this.playing = false; this.paused = false; this.seeking = false
this._.cancelPlay?.()
if (this.recording) {
this.recording = false
this._.recording = null
if (this._._mic) { this._._mic(null); this._._mic = null }
}
if (this._.push && 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).
* `device`: an input by id or name (audio.devices()); `monitor`: the take through its edits as it comes in, to the
* default output (`true`) or one by id or name: input monitoring, as a DAW's through a track's inserts. */
fn.record = function(opts = {}) {
if (this._.disposed) throw new Error('audio: instance disposed')
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, { monitor, ...rest } = opts
const request = this._.recording = {}
let _rec = (async () => {
let { default: mic } = await import('@audio/mic')
if (self._.recording !== request) return
// small reads while monitoring: each is heard once it has come
let read = await mic({ sampleRate: sr, channels: ch, bitDepth: 16, ...monitor && { bufferSize: 10 }, ...rest })
if (self._.recording !== request) { read(null); return }
self._._mic = read
// a read hands over one block; the next is asked for as each comes, so none is missed
const take = (err, buf) => {
if (self._.recording !== request) return
if (err || !buf) return
self.push(new Int16Array(buf.buffer, buf.byteOffset, buf.byteLength / 2), 'int16')
read(take)
}
read(take)
if (monitor) await monitorOut(self, request, monitor)
})()
_rec.catch(error => {
if (self._.recording !== request) return
self.stop()
emit(self, 'error', error)
})
return this
}
/** The take's live edge through its edits to an output, block by block as it comes (its latency: the input's read,
* one engine block, the output's ring; and the edits' own lookahead), until recording stops. */
async function monitorOut(a, request, device) {
let { default: Speaker } = await import('@audio/speaker')
let ch = a.channels, write = await Speaker({ sampleRate: a.sampleRate, channels: ch, bitDepth: 32, bufferSize: 20, ...typeof device === 'string' && { device } })
try {