Repository navigation
Expand file tree
/
Copy pathcore.js
More file actions
1834 lines (1704 loc) · 98.8 KB
/
Copy pathcore.js
File metadata and controls
1834 lines (1704 loc) · 98.8 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, snap, hostCtx, fixed, idOf, paramState, setParam, valueAt, valuesAt, sourceAt, eachCall, noteEvents, notesIn, moveTransport, settingAt, buffersOf, channelsOf, widest, sideBuses, busIn, layoutChannels, what, accept } from './batch.js'
audio.version = '2.19.2'
/** 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
}
/** A timecode: HH:MM:SS.mmm, MM:SS.mmm or MM:SS */
export const TIMECODE = /^(\d+):(\d{1,2})(?::(\d{1,2}))?(?:\.(\d+))?$/
/** 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 }
let tc = v.match(TIMECODE)
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 edits = docEdits(source), a = audio(source.source, opts)
if (a.run) for (let e of 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
// the source's own failure, no edit's, though an edit's preparation meets it (blame)
a._.failed = e
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._.sr,
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)
// the sound whose samples it plays, at their rate and channels (checkpoint.js names a sound by it)
if (b._.sr === source._.sr && b._.ch === source._.ch) b._.root = source._.root ?? source
// 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
/** Seconds of an endless decay a render takes. A ring with no last sample (a reverb held open, a ladder at full
* resonance, an integrator: a processor's `tail` of Infinity) cannot be rendered whole; a `pad` before the edit gives
* another length */
audio.TAIL = 10
/** 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
// ── Documents ───────────────────────────────────────────────────────────
/** The form of a document (toJSON), its `schemaVersion`. JSON holds no ±Infinity or NaN: JSON.stringify writes null, read
* back as no value (a saved gain(-Infinity), silence, would come back at unity gain). Form 2 writes such a number
* { $number: 'Infinity' | '-Infinity' | 'NaN' }, as store.js writes a typed array { $bytes }; a document with no
* schemaVersion is the form audio 2.16 and earlier wrote, null in their place. Form 3's deepfilter and rnnoise take a
* limit of 0 as nothing taken and Infinity as none, where an earlier form's 0 was none (unlimited). A reader refuses a
* later form than its own: what it holds may mean what this reader cannot say. */
export const FORM = 3
const plain = v => v !== null && typeof v === 'object' && (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null)
const TAGS = ['Infinity', '-Infinity', 'NaN']
/** A number as a document writes it, and back (a JSON replacer's step and a reviver's, store.js): ±Infinity and NaN
* tagged, anything else as it is */
export const toNumber = v => typeof v === 'number' && !Number.isFinite(v) ? { $number: String(v) } : v
export const fromNumber = v => plain(v) && TAGS.includes(v.$number) && Object.keys(v).length === 1 ? Number(v.$number) : v
/** `v` with `f` applied to each value in its arrays and plain objects, `f` first (a sound, samples, a function are
* values, not walked): `v` itself where nothing changes, so nothing is made for an edit without such a value; a copy
* only along what does */
function remap(v, f) {
let x = f(v)
if (x !== v || v === null || typeof v !== 'object') return x
let w = null
// a finite number is as it is, in either direction: an array of them (a write's samples) is read, not called on
if (Array.isArray(v)) for (let i = 0; i < v.length; i++) {
let a = v[i], y = typeof a === 'number' && a - a === 0 ? a : remap(a, f)
if (!w && y !== a && !Object.is(y, a)) w = v.slice()
if (w) w[i] = y
}
else if (plain(v)) for (let k in v) {
let a = v[k], y = typeof a === 'number' && a - a === 0 ? a : remap(a, f)
if (!w && y !== a && !Object.is(y, a)) w = { ...v }
if (w) w[k] = y
}
return w ?? v
}
/** Edits as a document holds them: ±Infinity and NaN tagged (toJSON) */
export const jsonable = edits => remap(edits, toNumber)
/** What a document's edits run as (audio(doc), the CLI's --macro): its numbers read back (form 2: an earlier form wrote
* none, so an object so shaped there is the edit's own), a sound it holds (a mix's source, written as a document of
* its own, its sampleRate with it) a sound again, an earlier form's limit of none as form 3 says it (unlimited). A
* later form than FORM is refused, naming both. */
export function docEdits(doc) {
let n = doc.schemaVersion
if (n != null && !(Number.isInteger(n) && n >= 1 && n <= FORM)) throw new TypeError(`audio: the document is schemaVersion ${JSON.stringify(n)}; audio ${audio.version} reads schemaVersion ${FORM} and earlier`)
if (!Array.isArray(doc.edits)) return doc.edits
let number = n >= 2 ? fromNumber : v => v
return doc.edits.map(e => {
let name = Array.isArray(e) ? e[0] : e?.type ?? e?.name ?? e?.op
e = remap(e, v => {
if (!plain(v) || !Array.isArray(v.edits) || !('source' in v) || typeof v.sampleRate !== 'number') return number(v)
if (!v.source) throw new TypeError(`audio: ${name}: a sound made from samples, with no source to restore it from, is not in its document (a document holds a sound by its file)`)
return audio(v)
})
return n == null || n < 3 ? unlimited(e) : e
})
}
/** A limit an earlier form than 3 holds that meant none, as @audio/neural-denoise before 0.8 read it: deepfilter's 0,
* and rnnoise's 0 or under (its host clamped one under 0 to 0), by the number or as text in dB */
const NONE = {
deepfilter: v => v === 0,
rnnoise: v => { let d = typeof v === 'string' && v.trim() !== '' ? Number(v.replace(/\s*db$/i, '')) : v; return typeof d === 'number' && d <= 0 }
}
/** The edit `e` of an earlier form, its limit of none Infinity, which says none in form 3 (a value by place too, as an
* edit of an op not yet loaded holds it: { args }); an edit as [name, options] or, as the CLI's --macro reads one too,
* { type | name | op, ...options } */
function unlimited(e) {
let pair = Array.isArray(e), o = pair ? e[1] : e, name = pair ? e[0] : plain(e) ? e.type ?? e.name ?? e.op : null
let none = typeof name === 'string' && Object.hasOwn(NONE, name) && NONE[name], as = v => pair ? [e[0], v] : v
if (!none || !plain(o)) return e
if (o.limit !== undefined) return none(o.limit) ? as({ ...o, limit: Infinity }) : e
return Array.isArray(o.args) && none(o.args[0]) ? as({ ...o, args: [Infinity, ...o.args.slice(1)] }) : e
}
/** 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))
/** A long loop's turns: once `ms` of its work have passed, a task (yieldTask) to wait on, where what waits on the thread
* runs (a page's message, a newer run, Stop); before that, nothing. Blocks that come as settled promises give way to
* nothing without it. */
export const pacer = (ms = 8) => {
let t = performance.now()
return () => { if (performance.now() - t > ms) return yieldTask().then(() => { t = performance.now() }) }
}
/** 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'
/** A sound, as an option that feeds a processor's further input bus takes one (a key: plan.js render reads it): an audio
* instance, an AudioBuffer or planar channels, Float32Array[] */
const isSound = v => v != null && (!!v.pages || !!v.getChannelData || Array.isArray(v) && v[0] instanceof Float32Array)
/** The options every edit takes, read by the engine (plan.js: its range and its choice of channels), never a param's */
const EDIT_KEYS = ['at', 'duration', 'channel']
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')
/** Whether a name is taken: an op's, a stat's or a codec's, or an instance method's (an op's own method, which a
* registry op has before it loads, is not one: plan.js opMethods) */
const held = id => !!(audio.op?.(id) || audio.stat?.(id) || audio.codecs?.[id] || typeof audio.fn[id] === 'function' && audio.fn[id].op == null)
/** Register plugins. Each receives audio. A contract plugin (a factory function
* with an own `params` object — see audiojs/plugin 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) to its family's entry:
* the export that string names registers, and the family's others where nothing holds
* their names yet. */
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 => {
// a family's entry (@audio/<family>/audio) holds its members' manifests together: the one asked for registers,
// replacing what was under its name, as a module of one manifest did; a sibling only where nothing holds its
// name yet (an op, a stat, a codec, an instance method: a built-in's, or what a caller registered), so another
// member's load replaces nothing
for (let m of Object.values(ns)) {
let id = isOp(m) ? idOf(m) : isStat(m) ? m.stat : isCodec(m) ? m.codec : null
if (id == null || id !== p && held(id)) continue
if (isOp(m)) useOp(m); else if (isStat(m)) useStat(m); else useCodec(m)
}
}, 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 decay in seconds as a render takes it: an endless one audio.TAIL, none or a negative one 0 */
const decay = t => t === Infinity ? audio.TAIL : t > 0 ? t : 0
/** The registry's names whose processors keep a take's length: a package whose keywords say
* `restoration` or `pitch-shift`, the finer category the contract has a host read there. What rings past the end of a
* take a repair or a pitch shift renders is its own processing spread there (an STFT frame's gain over its samples, a
* grain's window), not sound the take had, and a take that comes back longer no longer lines up with what it was cut
* from, nor loops. audio.js names them; test/plugin-ops.js holds the list to the packages installed. The rule is the
* op's, by its name: the processor keeps the length whether the registry loads it or its manifest is handed in
* (audio.use(manifest), audio.op(name, manifest): hostOp) */
export const keeping = new Set()
/** The seconds of a processor's declared decay `t` an edit renders past its input, as its `tail` option says (`said`):
* true, all of it; false, none; a number, that many seconds. Unsaid: none for a processor that keeps a take's length
* (`keeps`), the whole decay for any other */
const ring = (t, said, keeps) => said === true ? decay(t) : said === false ? 0 : typeof said === 'number' ? decay(said)
: keeps ? 0 : decay(t)
/** An op's expand into the hidden op `name` that renders it, `o` its options, and its decay, `t` s, as a pad after it:
* the user's edit stays one (undo, serialize whole), the decay renders into the pad (a contract plugin's tail, convolve,
* a native plugin's or a WAM's). An endless decay (Infinity) renders audio.TAIL seconds */
export const tailed = (name, o, t) => (t = decay(t)) > 0 ? [['pad', { before: 0, after: t }], [name, o]] : [[name, o]]
/** 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, and a package's package.json (JSON, imported as JSON: an op that needs a version
* of its package reads it so). 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 => spec.endsWith('.json') ? import(spec, { with: { type: 'json' } }) : 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. One stat to a name: a stat plugin under a name another holds replaces it (a script
* run again defines it again); a built-in stat's, an op's or an instance method's name is not its to take. */
function useStat(m) {
if (!audio.stat) throw new Error('audio.use(stat): stat registry required — import "audio", not "audio/core.js"')
let name = m.stat, had = audio.stat(name), plugin = m
let taken = had && !had.plugin ? 'a built-in stat' : audio.op?.(name) ? 'an op' : !had && typeof audio.fn[name] === 'function' ? `an instance method (a.${name}())` : null
if (taken) throw new Error(`audio.use: '${name}' is ${taken}; register this stat under another name: audio.use({ ...stat, stat: 'my-${name}' })`)
m = audio.hosted[name]?.(m) ?? m
audio.stat(name, { plugin }) // 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 })
}
}
/** Register a contract plugin (an audio.js manifest's factory) as the op its id names (hostOp: one that keeps a take's
* length by that name, keeping, as the registry would host it, however it came). One op to a name: the
* same processor again is there already; a processor registered before under that id gives way to this one (a script
* run again in the editor defines its processor again); a built-in op's name is not its to take, and
* audio.op(name, processor) registers it under another. */
function useOp(m) {
if (!audio.op) throw new Error('audio.use(module): op registry required — import "audio", not "audio/core.js"')
// its op's name: its id, else its function's name; one with neither would take a name no call can mean
if (!m.id && !m.name) throw new Error('audio.use: a processor needs an id or a function name to register as an op (fn.id = \'my-op\')')
let id = idOf(m), had = audio.op(id)
if (had?.plugin === m) return
if (had && !had.plugin) throw new Error(`audio.use: '${id}' is a built-in op; register this processor under another name: audio.op('my-${id}', processor)`)
hostOp(m, id)
}
/** The options a processor's further input buses are fed by (contract § Channels): each bus's `name`, `key` where it has
* none */
const furtherOf = m => sideBuses(m.channels?.inputs).slice(1).map(b => b.name ?? 'key')
/** The params a call's positional arguments `a` map onto, in order (plan.js opMethod, audio.js autowire): op `d`'s, and
* where `d` hosts a processor with a further input bus and the first argument is a sound (isSound), that bus first:
* a.ducker(voice, -30) is key and threshold. Any other first argument is the first param: a.compressor(-30, 8) is
* threshold and ratio, its key given by option or none */
export function positional(d, a) {
let p = d?.params || [], bus = d?.plugin && isSound(a[0]) && furtherOf(d.plugin)[0]
return bus ? [bus, ...p] : p
}
/** Host a contract processor as op `name`: audio's own host of the contract (CONTRACT.md § What a host owes), its
* params read off the factory. The op resolves its values in time itself, not the engine (auto: 'own'): a call split
* where one jumps, at most 32 frames while one moves (batch.js eachCall, as toBatch and toStream do). Notes, the
* transport (`bpm`, `timeSignature`), buffers and further input buses come from the edit's options, emissions go to
* its `emitted(name, value, time)`. audio.use registers a processor under its id, audio.op(name, processor) under the
* caller's name; one hosted under the name of a registry op that keeps a take's length (keeping) keeps it: a.vocoder()
* is one op, a pitch shift, however its processor came. */
export function hostOp(m, name) {
let keeps = keeping.has(name)
// its op's method is how a call names it: an instance's own method under that name (read, save, clone) would answer;
// an op's method (another op's camelCase, plan.js opMethods) gives way to it
let method = audio.fn[name]
if (typeof method === 'function' && method.op == null && !audio.op(name)) throw new Error(`audio: '${name}' is an instance method (a.${name}()), so a processor under that name could not be called; register it under another: audio.op('my-${name}', processor)`)
let specs = m.params || {}, names = Object.keys(specs), id = idOf(m)
// Further input buses (contract § Channels): each fed a sound through the option its `name` gives, `key` where it has
// none; the first, too, by a call's first argument where that is a sound (positional)
let further = furtherOf(m)
// An edit's options as this op reads them, settled as the edit is made (plan.js normalizeEdit) or as the op loads
// after it (audio.js autowire): a value written with a unit in the unit its param declares ('10ms' to an attack in
// ms: 10); a value of another kind than its param's is an error (a.ducker(oneChannel, -30) would have rendered with
// the array for a threshold), and so is automation of a param read once, as the processor is built (restart), where
// the render would keep its first value throughout; a buffer of a channel count its declaration does not take, too,
// and a bus fed what is not a sound, which the render could not read
let settle = o => {
for (let name of names) {
let sp = specs[name], k = o[name] !== undefined ? name : sp.alias != null && o[sp.alias] !== undefined ? sp.alias : null
// an option every edit takes is the engine's, whatever a processor names so (haas's `channel`, left or right, is
// shadowed by the choice of channels, which `chosen` checks)
if (k == null || EDIT_KEYS.includes(name)) continue
o[k] = accept(sp, o[k], id, name)
}
for (let k of further) {
let v = o[k]
if (v != null && !isSound(v)) throw new TypeError(`${name}: ${k} is a sound its input bus reads (an audio instance, an AudioBuffer or Float32Array[]), not ${what(v)}`)
}
buffersOf(m, o)
chosen(o)
return o
}
let reg = d => (d.settle = settle, keeps && (d.keeps = true), audio.op(name, audio.hosted[name]?.(d) ?? d))
// 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)
// a buffer that has a rate (an audio instance) rendered whole at the op's rate, again only once it changed
let made = new WeakMap()
let readAt = sr => b => {
let k = made.get(b)
if (k?.sr !== sr || k.v !== b.version) {
let pcm = audio.render(b)
made.set(b, k = { sr, v: b.version, data: b.sampleRate === sr ? pcm : audio.renderAt((_, at, n) => pcm.map(c => c.subarray(at, at + n)), b, 0, Math.round(pcm[0].length * sr / b.sampleRate), sr) })
}
return k.data
}
// what a latency, tail or frames function reads (contract § Latency, tail): the values an edit gives, automation as
// it is at frame f (the start; for a tail, where the input ends and it begins), the buffers, and the transport of the
// edit's tempo (`bpm`, `timeSignature`, one for the render) at frame `end`: where the input ends for a tail, even a
// whole-signal processor's, whose values are its start's
let setting = (o, sr, f = 0, end = f) => settingAt(specs, name => sourceAt(given(n => o?.[n], name) ?? specs[name].default, f, sr), buffersOf(m, o, readAt(sr)), { bpm: o?.bpm, timeSig: o?.timeSignature }, end, sr)
// Declared latency → plan-level plugin delay compensation (fn form: once per instance)
let latency = typeof m.latency === 'function' ? (o, sr) => m.latency(setting(o, sr)) | 0 : m.latency | 0
// tail: seconds, or a function of the values in force (mirrors latency's fn form): a feedback delay's decay depends on
// its feedback setting, not the declared maximum. An endless one (Infinity) renders audio.TAIL seconds (decay). What
// of it an edit renders (ring, `t` its decay) its `tail` option says, unless a param of the processor's takes that
// name, as an op's own `mix` param takes the engine's mix
let tail = m.tail || 0, own = names.some(k => k === 'tail' || specs[k].alias === 'tail')
let rung = (o, t) => ring(t, own ? undefined : o?.tail, keeps)
// An instance, built where its block loop starts (frame f) or for the one call of a whole render: its values from
// the edit, its widest bus from those it reads and writes, declared layouts resolved against the input width (a
// `layouts` option picks), its buffers read
let init = (ctx, f, maxBlock, input, output) => {
let sr = ctx.sampleRate, state = paramState(specs, ctx, id)
// what each input bus carries (batch.js busIn): bus 0 and a further one fed, their count; one fed by nothing, none
let keys = further.map(k => ctx[k] == null ? undefined : channelsOf(ctx[k])), res = resolveBuses(m.channels, [input.length, ...keys], ctx.layouts, id)
let carry = res.inputs.map((b, i) => i && keys[i - 1] == null ? 0 : b.channels)
let mctx = hostCtx(m, {
sampleRate: sr, maxBlockSize: maxBlock, maxChannels: widest(carry[0] ?? input.length, output.length, carry.slice(1)), duration: ctx.totalDuration,
params: snap(specs, name => valueAt(state[name], f, sr)), buffers: buffersOf(m, ctx, readAt(sr)),
layouts: res.layouts,
}, (name, args, time) => ctx.emitted?.(name, args[0], time))
return { mctx, state, live: {}, process: m(mctx), pool: [], view: [], evs: null, notes: undefined, carry, keep: [] }
}
// the edit's notes as note events, compiled once for each notes option
let noteIn = m.events?.in?.includes('note')
let notesOf = (st, ctx) => {
if (st.evs == null || st.notes !== ctx.notes) st.notes = ctx.notes, st.evs = ctx.notes ? noteEvents(ctx.notes, ctx.sampleRate) : []
return st.evs
}
// the input buses of a block of n frames from frame f, each with the channels it carries and its samples finite
// (batch.js busIn: one channel copied to a bus of more, a NaN or Infinity made 0 in the instance's scratch): bus 0,
// and each further one its option feeds (rendered, the rate reconciled), none where nothing does
let bus = (x, st, i) => busIn(x, st.carry[i], id, i, st.keep[i] ??= [])
let buses = (input, ctx, f, n, st) => [bus(input, st, 0), ...further.map((k, i) => ctx[k] != null && audio.renderAt ? bus(audio.renderAt(ctx.render, ctx[k], f, n, ctx.sampleRate), st, i + 1) : [])]
// 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. The same fixed count on both sides (a
// stereo processor) widens a mono sound to it, one channel feeding it copied (busIn): a width that changes only there
// (chKeeps), a range or a mix refused there alone. Any other width stays: a choice of its count (`channel`) runs in
// place, another count is refused at the render
let busN = side => typeof side === 'number' ? side
: Array.isArray(side) && typeof side[0] === 'number' ? side[0] : null
let decl = typeof m.channels === 'object' && !Array.isArray(m.channels) ? m.channels : { inputs: m.channels, outputs: m.channels }
let outN = busN(decl.outputs), inN = busN(decl.inputs), chKeeps = outN != null && outN === inN
let ch = outN == null ? undefined : chKeeps ? n => n === 1 ? outN : n : () => outN
// 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, id).outputs[0]?.channels
// An edit on chosen channels (`channel`: their numbers) hands its op those alone, in and out, a stage as a whole
// render (plan.js applyProcs, compilePlan), the sound's width kept (widthOf), so
// a processor that takes or makes a fixed count on bus 0 runs there only on a choice of that many: another is an error
// at the call (settle), naming the op, both counts and what to do instead
let [in0] = sideBuses(decl.inputs), [out0] = sideBuses(decl.outputs)
let count = b => b?.layouts ? b.layouts.map(layoutChannels).join(' or ') : b?.count === 'any' ? null : b?.count
let fits = (k, layouts) => {
try { let r = resolveBuses(m.channels, [k], layouts); return (r.inputs[0]?.channels ?? k) === k && (r.outputs[0]?.channels ?? k) === k }
catch { return false } // none of its layouts has k channels
}
let chosen = o => {
let picked = [o.channel ?? []].flat(), k = picked.length
if (!k || picked.some(c => typeof c !== 'number') || fits(k, o.layouts)) return
// a generator (no input bus 0) takes none: a choice holds what it makes
let i = in0 ? count(in0) ?? k : null, u = count(out0) ?? i ?? k, n = c => `${c} channel${c === 1 ? '' : 's'}`, fit = (i ?? u) === u && typeof u === 'number' ? u : 0
throw new RangeError(`${name}: it ${i == null ? `makes ${n(u)}` : i === u ? `takes ${n(i)}` : `takes ${n(i)} and makes ${u}`}, and channel: ${JSON.stringify(o.channel)} chooses ${k}; an op on chosen channels reads and writes those alone: ${fit ? `choose ${fit} (channel: [${Array.from({ length: fit }, (_, c) => c).join(', ')}]) or leave channel out` : 'leave channel out'}`)
}
// A block of the timeline from frame f: the values patched into the edit since the last one (a live edit) are new
// sources, a restart param's excepted (it is the instance's: a change of it rebuilds it, plan.js pipelineSig); then
// one call for each stretch its values hold, ctx's time, transport and notes set for it
let process = (input, output, ctx) => {
let n = input[0].length, sr = ctx.sampleRate, f = Math.round((ctx.blockOffset || 0) * sr)
let st = ctx._am ??= init(ctx, f, audio.BLOCK_SIZE, input, output)
for (let name of names) {
let p = st.state[name], v = given(k => ctx[k], name) ?? specs[name].default
if (v !== p.src && !fixed(p.spec)) setParam(p, v, id, name)
}
let ins = buses(input, ctx, f, n, st), outs = [output], evs = noteIn && notesOf(st, ctx)
eachCall(st.state, st.live, f, n, sr, (i0, i1) => {
st.mctx.currentTime = (f + i0) / sr
moveTransport(st.mctx.transport, ctx.bpm, ctx.timeSignature, f + i0, sr)
if (evs) st.mctx.events = notesIn(evs, f + i0, i1 - i0, st.pool, st.view)
if (i0 === 0 && i1 === n) st.process(ins, outs, st.live)
else st.process(ins.map(b => b.map(c => c.subarray(i0, i1))), [output.map(c => c.subarray(i0, i1))], st.live)
})
}
// 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).
// A tail function is handed the transport where the input ends, its `n` frames (plan.js tailN); what of it the
// edit renders is read at the render (rung: an endless one audio.TAIL then)
let wholeTail = tail ? (o, sr, n) => rung(o, typeof tail === 'function' ? tail(setting(o, sr, 0, n)) : 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, setting(o, sr)) : undefined
return reg({
params: names, plugin: m, atom: m, ch, chKeeps, tail: wholeTail, frames,
// one call of the whole signal (none of 0 frames), its values as they are at its start
whole(input, output, ctx) {
let n = input[0].length, sr = ctx.sampleRate
if (!n) return
let st = init(ctx, 0, Math.max(n, output[0]?.length ?? 0), input, output)
valuesAt(st.state, st.live, 0, sr)
moveTransport(st.mctx.transport, ctx.bpm, ctx.timeSignature, 0, sr)
if (noteIn) st.mctx.events = notesIn(notesOf(st, ctx), 0, n, st.pool, st.view)
// a keyed module reads its key bus whole too, rendered over the same length
st.process(buses(input, ctx, 0, n, st), [output], st.live)
if (!frames) ranged(input, output, ctx)
}
})
}
if (!tail) return reg({ params: names, plugin: m, atom: m, latency, process, ch, chKeeps, auto: 'own' })
// Declared tail: expand into pad + hidden proc at compile time (tailed), the options the host reads handed on, a
// param's former name (alias) among them
let aliases = names.map(n => specs[n].alias).filter(k => k != null)
let taken = [...new Set([...names, ...aliases, ...further, ...Object.keys(m.buffers || {}), 'layouts', 'notes', 'bpm', 'timeSignature', 'emitted'])]
audio.op('_' + name, { params: names, hidden: true, plugin: m, atom: m, latency, process, ch, chKeeps, auto: 'own' })
// its latency said as the hidden op's, for what reads it off the op (the plan compensates the hidden op it renders)
reg({
params: names, tail, plugin: m, atom: m, ch, chKeeps, latency,
expand: (ctx) => {
let o = {}, sr = ctx.sampleRate
for (let k of taken) if (ctx[k] !== undefined) o[k] = ctx[k]
return tailed('_' + name, o, rung(ctx, typeof tail === 'function' ? tail(setting(o, sr, Math.round(ctx.totalDuration * sr))) : tail))
}
})
}
// ── 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 (deck.js playback)
let heard = this._.play?.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._.play?.loop(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 => { a._.failed = 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))