Repository navigation
Expand file tree
/
Copy pathplan.js
More file actions
1905 lines (1741 loc) · 98.9 KB
/
Copy pathplan.js
File metadata and controls
1905 lines (1741 loc) · 98.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
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
/**
* Plan — non-destructive edit pipeline.
* Intercepts create/run/read/stream to track and materialize edits.
*/
import audio, { readPages, copyPages, walkPages, missed, parseTime, named, fromEnd, LOAD, READ, emit, resolveChannels, pickChannels, xfade, correlation, arrived, fingerprint, hostOp, positional, blame, jsonable, FORM } from './core.js'
import { isCurve, fixed, what } from './batch.js'
let fn = audio.fn
let ops = {}
// ── Segments: [from, count, to, rate?, ref?, interp?, env?] ──────
// interp: optional `(src, target, tOff, n, rate, phase) => void` for custom
// interpolation. May expose `.margin` (samples of context needed each side).
// Falls back to built-in linear when omitted.
// env: fade envelope, flat pairs [p0, p1, …] of fade phase at the segment's start and
// end, linear in between; gain Π sin(p·π/2). An envelope segment is summed into the
// output instead of written: a fade-out and a fade-in over the same span are an
// equal-power crossfade (cos² + sin² = 1), the DAW clip-fade model.
export function seg(from, count, to, rate, ref, interp, env) {
let s = [from, count, to]
if (rate != null && rate !== 1) s[3] = rate
if (ref !== undefined) s[4] = ref
if (interp) s[5] = interp
if (env) s[6] = env
return s
}
/** The sub-range [at, at + n) (output coords) of segment s, written at `to`: same source,
* ref and interpolation, envelope cut to the sub-range. Time-scaling ops pass the new
* `count` and `rate`; `flip` reverses the read (rate sign and envelope direction). */
export function subSeg(s, at, n, to, count = n, rate = s[3], flip = false) {
let e = s[6], env
if (e) {
let u = (at - s[2]) / s[1], v = (at + n - s[2]) / s[1]
env = []
for (let k = 0; k < e.length; k += 2) {
let a = e[k] + (e[k + 1] - e[k]) * u, b = e[k] + (e[k + 1] - e[k]) * v
env.push(flip ? b : a, flip ? a : b)
}
}
return seg(segSrcStart(s, at, n), count, to, flip ? -(rate || 1) : rate, s[4], s[5], env)
}
/** An envelope segment cut to where it dominates (gain ≥ √½, the equal-power midpoint),
* as a plain segment (null if never): the span where its source, not its crossfade
* partner's, is what's heard. Marker/region projection maps through this. */
export function dominant(s) {
let e = s[6], N = 64, i0 = -1, i1 = -1
if (!e) return s
for (let i = 0; i < N; i++) {
let u = (i + 0.5) / N, g = 1
for (let k = 0; k < e.length; k += 2) g *= Math.sin((e[k] + (e[k + 1] - e[k]) * u) * Math.PI / 2)
if (g >= Math.SQRT1_2 - 1e-9) { if (i0 < 0) i0 = i; i1 = i + 1 }
}
if (i0 < 0) return null
let a = s[2] + Math.round(i0 / N * s[1]), b = s[2] + Math.round(i1 / N * s[1])
return b > a ? subSeg(s, a, b - a, a).slice(0, 6) : null
}
/** Fade a rebased span of segments (output [0, len)) from phase p0 to p1: 1 → 0 fades
* out, 0 → 1 fades in; composes with any envelope already there. */
export function fadeSegs(segs, len, p0, p1) {
return segs.map(s => {
let n = s.slice(), u = s[2] / len, v = (s[2] + s[1]) / len
n[6] = [...(s[6] || []), p0 + (p1 - p0) * u, p0 + (p1 - p0) * v]
return n
})
}
/** Source start sample for the sub-range [iStart, iStart+n) of segment sg (output coords).
* Reversed segments (rate < 0) read tail-first, so the sub-range anchors at the far end. */
export function segSrcStart(sg, iStart, n) {
let rate = sg[3] || 1, absR = Math.abs(rate)
return rate < 0
? sg[0] + (sg[1] - (iStart - sg[2]) - n) * absR
: sg[0] + (iStart - sg[2]) * absR
}
/** Slice segments to the output range [off, off+len), rebased to 0. Rate-sign correct. */
export function sliceSegs(segs, off, len) {
let r = [], end = off + len
for (let s of segs) {
let a = Math.max(s[2], off), b = Math.min(s[2] + s[1], end)
if (a < b) r.push(subSeg(s, a, b - a, a - off))
}
return r
}
/** Rewrite the [at, at+len) output range of segs through fn(subSegs), shifting the tail. */
export function spliceSegs(segs, at, len, fn) {
let total = planLen(segs)
at = Math.max(0, Math.min(at, total))
len = Math.max(0, Math.min(len ?? total - at, total - at))
if (!len) return segs
let mid = fn(sliceSegs(segs, at, len))
let midLen = planLen(mid)
let r = sliceSegs(segs, 0, at)
for (let s of mid) { let n = s.slice(); n[2] += at; r.push(n) }
for (let s of sliceSegs(segs, at + len, total - at - len)) { let n = s.slice(); n[2] += at + midLen; r.push(n) }
return r
}
// ── Edit array: ['type', opts] ─────────────────────────────────────
// Normalized shape: compact tuple with options object only.
// e[0] = type, e[1] = opts (named params + range opts + extras)
// ── Range Helpers ────────────────────────────────────────────────
/** Normalize an offset in samples: negative = from-end, clamp to [0, total]. dflt used when offset is null. */
export function planOffset(offset, total, dflt = 0) {
let s = offset ?? dflt
if (s < 0) s = total + s
return Math.min(Math.max(0, s), total)
}
/** An edit's own dry/wet where its op has none: `mix`, how much of its output is heard, 1 (all of it, the default) to 0
* (its input as it came), a number, a curve {t, v} or t => share over its input's time. Null where it is all of it, or
* the op's own param (an effect's dry/wet). */
function ownMix(desc, o) {
let m = o?.mix
return m == null || m === 1 || desc?.params?.includes('mix') ? null : m
}
/** A mix the engine can take: a share 0..1, a curve or a function, on an op that keeps the timeline and the channels
* (the output and the input line up sample for sample; an op whose width depends on what it hosts, chKeeps, is
* checked where it compiles), on chosen channels as widthOf has it. Throws what is wrong. */
function mixable(name, m, desc, channel) {
if (!(typeof m === 'function' || isCurve(m) || m >= 0 && m <= 1)) throw new RangeError(`${name}: mix is a share, 0 to 1, a curve { t, v } or t => share, not ${JSON.stringify(m)}`)
if (m !== 1 && (desc?.plan || reshapes(desc, channel) || desc?.frames)) throw new TypeError(`${name}: mix blends an edit's output with its input, so it is for edits that keep the timeline and the channels`)
}
/** Whether an edit of op `desc` on `channel` runs in place: on chosen channels a processor audio hosts that keeps the
* timeline reads and writes those alone (core.js hostOp refuses a choice of a count it does not take and make) */
const inPlace = (desc, channel) => channel != null && !!desc?.plugin && !desc.frames
/** Whether an edit of op `desc` on `channel` changes the channel count whatever it is fed (an op whose width depends on
* what it hosts, chKeeps, changes it only on some: renderWidth): what a call refuses a range or a mix for */
const reshapes = (desc, channel) => !!desc?.ch && !desc.chKeeps && !inPlace(desc, channel)
/** The channels an edit of op `desc` leaves of `n`, `ctx` what its width hook reads: the hook's, but one in place
* (inPlace) leaves them as they are */
function widthOf(desc, n, channel, ctx) {
return desc?.ch && !inPlace(desc, channel) ? desc.ch(n, ctx) || n : n
}
/** The channels edit `[type, o]` leaves of `n` where it renders, as a stage (initProcs) or whole: an op whose width
* depends on what it hosts (chKeeps: a plugin) takes a range or a mix only where it keeps the width; refused, it is
* named as written (a hidden op renders the edit of the op it is named after: _haas, a tailed processor's, haas's),
* with the way through: the sound made as wide first */
function renderWidth(type, desc, n, o, ctx) {
let w = widthOf(desc, n, o.channel, ctx)
if (w !== n && desc.chKeeps && (o.at != null || o.duration != null || ownMix(desc, o) != null)) {
let as = desc.hidden ? type.replace(/^_/, '') : type, why = o.at != null || o.duration != null ? 'a range keeps the channel count, and this changes it' : 'mix blends the output with the input, and this changes the channel count'
throw new TypeError(`${as}: ${why} (${n} → ${w}); make the sound ${w === 2 ? 'stereo' : `${w} channels`} first: a.remix(${w})`)
}
return w
}
/** Compute [start, end] sample range from a process ctx (at/duration) over a buffer of given len. */
export function opRange(ctx, len) {
let sr = ctx.sampleRate
// ctx.at is block-relative (the engine passes at − blockOffset). When unset, the op
// anchors at absolute 0 — i.e. blockOffset samples before this block — otherwise a
// position-dependent op (mix/write/crossfade source offset) restarts every block.
let s = ctx.at != null ? Math.round(ctx.at * sr) : -Math.round((ctx.blockOffset || 0) * sr)
return [s, ctx.duration != null ? s + Math.round(ctx.duration * sr) : len]
}
/** An op's range on the timeline, in samples: [a0, a1), as the engine hands it over (`at` relative to this block), for
* an op that keeps state across blocks; a duration alone from 0, as opRange reads it; unranged, the whole timeline. */
export function rangeOf(ctx) {
let sr = ctx.sampleRate
if (ctx.at == null && ctx.duration == null) return [-Infinity, Infinity]
let a0 = ctx.at != null ? Math.round((ctx.at + (ctx.blockOffset || 0)) * sr) : 0
return [a0, ctx.duration != null ? Math.max(a0, 0) + Math.round(ctx.duration * sr) : Infinity]
}
// ── Op Registration ─────────────────────────────────────────────
function isOpts(v) {
// a breakpoint curve {t, v} is a positional param value, not an options bag
return v != null && typeof v === 'object' && !Array.isArray(v) && !ArrayBuffer.isView(v) && !v.pages && !v.getChannelData && !isCurve(v)
}
/** Map positional args to named params on ctx. */
function mapParams(params, args, ctx) {
if (params) for (let i = 0; i < params.length && i < args.length; i++) {
if (params[i].startsWith('...')) { ctx[params[i].slice(3)] = args.slice(i); break } // rest: the remaining args
ctx[params[i]] = args[i]
}
}
/** Normalize edit options: parse time fields and sample aliases. A time no render can hold (±Infinity, NaN, as a number
* or as text) refused naming op `type` (finite) */
function normalizeOpts(opts, sr, type) {
let o = isOpts(opts) ? { ...named(opts) } : {}
if (o.at != null) o.at = time(type, 'at', o.at)
if (o.duration != null) o.duration = time(type, 'duration', o.duration)
if (o.offset != null) { o.at = finite(type, 'offset', o.offset) / sr; delete o.offset }
if (o.length != null) { o.duration = finite(type, 'length', o.length) / sr; delete o.length }
return o
}
const time = (type, k, v) => typeof v === 'number' || numeric(v) ? (finite(type, k, v), parseTime(v)) : parseTime(v)
// ── Values a render can hold ─────────────────────────────────────
/** The ops this package registers, marked by audio.js once its modules have run: their edits' values are judged at the
* call (judge); an op the user registers, or one in place of a built-in, takes what it is given */
export const builtin = new WeakSet()
/** The longest a sound can be, in samples: its positions are whole sample counts in doubles, exact to 2^53 − 1, which
* is also the longest a typed array can be (ECMA-262 ToIndex) */
export const LONGEST = Number.MAX_SAFE_INTEGER
/** Text a number is written in (' -Infinity', '1e999', '0.5'); a word ('linear', 'inf', '300hz') is not */
const numeric = v => typeof v === 'string' && v.trim() !== '' && !Number.isNaN(+v)
/** What option `k` of op `d` takes beyond finite numbers, as the op declares it (`nonfinite`: option → { value: what it
* means }, or true for an option it does not read as a number, samples or a function's own; a function of the option
* and the options giving either; true for the whole op) */
const means = (d, k, o) => { let nf = d?.nonfinite; return typeof nf === 'function' ? nf(k, o) : nf === true || nf?.[k] }
/** What an option takes, as a refusal says it: of a value itself, or of one an array or an object of it holds */
const takes = (ok, held) => `${held ? 'holds finite numbers' : 'is a finite number'}${ok && ok !== true ? Object.entries(ok).map(([v, m]) => ` or ${v} (${m})`).join('') : ''}`
/** The one form every value no render can hold is refused in: `op: option is what it takes, not the value` (a value it
* holds: `op: option holds finite numbers, not the value`), text quoted, `why` after it (where, in a function) */
export const refuse = (type, k, what, v, why = '') => new RangeError(`${type}: ${k} ${what}, not ${typeof v === 'string' ? `'${v}'` : String(v)}${why}`)
/** `v` as option `k` of op `type` reads it: a number, text as the number it is (Number), finite or a value the op declares
* (`ok`, from means), else refused. An op that reads text later than the call (a filter's freq) refuses it where it
* reads it, by this */
export function finite(type, k, v, ok, why = '', held = false) {
let n = typeof v === 'number' ? v : Number(v)
if (Number.isFinite(n) || ok && ok !== true && String(n) in ok) return n
throw refuse(type, k, takes(ok, held), v, why)
}
/** An edit's values judged at the call, after its options are normalized (its times parsed, values by position placed):
* every number in them, text that is one, a curve's points, through arrays and plain objects; a sound, samples (a
* typed array), a function and a word are not read here (a function's values are, as the render reads them:
* applyProcs). Nothing is made: a value is read once, in place */
function judge(type, o) {
let d = ops[type]
if (!builtin.has(d) || d.nonfinite === true) return
for (let k in o) if (k !== 'args') { let ok = means(d, k, o); if (ok !== true) read(type, k, o[k], ok) }
// values by position (a.run(['pad', { args: [1] }])), read as the params they are placed in once the edit runs
if (Array.isArray(o.args)) {
let p = positional(d, o.args)
for (let i = 0; i < o.args.length; i++) {
let k = p[Math.min(i, p.length - 1)]?.replace(/^\.\.\./, '') ?? 'args', ok = means(d, k, o)
if (ok !== true) read(type, k, o.args[i], ok)
}
}
}
// a value nested deeper than DEEP is not read: an object that holds itself (an app's own among an op's options) stops
// there, nothing made to tell it
const DEEP = 32
function read(type, k, v, ok, depth = 0) {
if (typeof v === 'number') return finite(type, k, v, ok, '', depth > 0)
if (typeof v === 'string') return numeric(v) && finite(type, k, v, ok, '', depth > 0)
if (v === null || typeof v !== 'object' || ArrayBuffer.isView(v) || v.pages || v.getChannelData || depth > DEEP) return
if (isCurve(v)) return points(type, k, v.t, ok) || points(type, k, v.v, ok)
if (Array.isArray(v)) { for (let i = 0; i < v.length; i++) read(type, k, v[i], ok, depth + 1); return }
let p = Object.getPrototypeOf(v)
if (p === Object.prototype || p === null) for (let j in v) read(type, k, v[j], ok, depth + 1)
}
// A curve's points, plain or typed: each a finite number. A curve is interpolated in its values' own unit, so a point at
// -Infinity dB holds the segment to it at -Infinity from its start: no fade, and no meaning of the op's
function points(type, k, xs, ok) {
for (let i = 0; i < xs.length; i++) {
let x = xs[i], n = typeof x === 'number' ? x : Number(x)
if (Number.isFinite(n)) continue
let m = ok && ok !== true && ok[String(n)]
throw refuse(type, k, 'is a curve of finite numbers', x, m ? ` (${m}: ${n} as the value itself, a fade to ramp to it)` : '')
}
}
/** The length the timeline holds after edit `type` (its options `o`), `n` samples: past LONGEST, or not a number, an error
* naming the op and the options that made it, where the length is derived (its first length, duration or read) */
function long(n, type, o) {
if (n <= LONGEST) return
let ks = Object.keys(o).filter(k => !['at', 'duration', 'channel'].includes(k) && (typeof o[k] === 'number' || typeof o[k] === 'string' || ArrayBuffer.isView(o[k])))
throw new RangeError(`${type}: ${ks.join(', ') || 'its options'} ${ks.length > 1 ? 'are values' : 'is a value'} that keep${ks.length > 1 ? '' : 's'} the sound within ${LONGEST} samples, not ${ks.map(k => shown(o[k])).join(', ')}`)
}
// An edit as its refusal shows it: an array's items in turn, options as { … }, any other value as batch.js `what` names
// it (a number as written, a string quoted, a sound by its kind, not its samples)
const shown = v => Array.isArray(v) ? `[${v.map(shown).join(', ')}]` : isOpts(v) ? '{ … }' : what(v)
/** Normalize an edit to compact ['type', opts] storage form. Accepts ['type'] or ['type', opts], anything else an
* error showing that form. An op whose options name another op to do it (`via`: a stretch's method, its algorithm's
* own op) gives that op's edit in its place: the edit is that op's from then on, its module the only one loaded for
* it (audio.js autowire). An op that settles its options (`settle`: a contract plugin's units and fixed params) does
* so here, so a wrong one throws at the call. */
function normalizeEdit(edit, sr, call = false) {
// a trailing undefined is one not passed, as a method's argument is: ['gain', { value: -6 }, undefined] is the edit
// without it
if (Array.isArray(edit)) {
let n = edit.length
while (n > 1 && edit[n - 1] === undefined) n--
if (n < edit.length) edit = edit.slice(0, n)
}
let [type, opts] = Array.isArray(edit) ? edit : []
// after the name, one object of options: values past it or in its place would be dropped and the op render its
// defaults (a.run(['compressor', -30, 8])); values by position go in it as `args`, mapped as a call's arguments are,
// and the error shows that form only for an op that takes them (one with params, or a registry op not loaded yet):
// autowire maps `args` onto params alone, so ['reverse', { args: [5] }] would drop the 5 as silently
if (typeof type !== 'string' || edit.length > 2 || opts != null && !isOpts(opts)) {
let vals = typeof type === 'string' ? edit.slice(1) : [], takes = !ops[type] || ops[type].params?.length > 0
throw new TypeError(`audio.run: an edit is [name] or [name, options]${takes && vals.length && !vals.some(isOpts) ? `, values by position in options.args: ['${type}', { args: ${shown(vals)} }]` : ''}, not ${shown(edit)}`)
}
let o = normalizeOpts(opts || {}, sr, type)
// the edit a call makes, judged as it is called (an edit an op emits is the op's own)
if (call) judge(type, o)
ops[type]?.settle?.(o)
return ops[type]?.via?.(o) ?? [type, o]
}
// A whole op's range rendered: read with 100 ms either side, set back with 10 ms crossfades
const SEAM_CONTEXT = 0.1, SEAM = 0.01
/** Channel `c` with its range [s0, s1) in place of `m`, the range as an op made it (`n` samples long): each seam
* crossfaded from the audio as it was, which goes on past the range's start and comes in before its end, at the
* constant power the two signals' correlation there asks (out of phase, as unrelated), so neither clicks nor swells */
function seamed(c, m, n, s0, s1, sr) {
let y = new Float32Array(c.length - (s1 - s0) + n), x = Math.min(Math.round(SEAM * sr), n >> 1, s1 - s0)
y.set(c.subarray(0, s0)); y.set(m, s0); y.set(c.subarray(s1), s0 + n)
let ri = correlation(c.subarray(s0), m, x), ro = correlation(m.subarray(n - x), c.subarray(s1 - x), x)
for (let i = 0; i < x; i++) {
let [di, mi] = xfade((i + .5) / x, ri), [mo, dout] = xfade((i + .5) / x, ro)
y[s0 + i] = di * c[s0 + i] + mi * (m[i] ?? 0)
y[s0 + n - x + i] = mo * (m[n - x + i] ?? 0) + dout * c[s1 - x + i]
}
return y
}
/** A range of a whole signal `n` samples long, [a, b) in samples, as `at` (negative: from the end) and `duration` say */
export function spanOf(n, at, duration, sr) {
let a = at == null ? 0 : Math.max(0, Math.min(n, Math.round((at < 0 ? n / sr + at : at) * sr)))
return [a, duration == null ? n : Math.min(n, a + Math.round(duration * sr))]
}
/** Detect functions deeply so non-serializable edits can be omitted from JSON.
* Own keys only; audio-instance refs serialize via their own toJSON, typed arrays as data. */
function hasFunction(v, seen = new Set()) {
if (typeof v === 'function') return true
if (!v || typeof v !== 'object') return false
if (v.pages || ArrayBuffer.isView(v)) return false
if (seen.has(v)) return false
seen.add(v)
if (Array.isArray(v)) return v.some(x => hasFunction(x, seen))
for (let k of Object.keys(v)) if (hasFunction(v[k], seen)) return true
return false
}
/** Register/query op: audio.op(name, descriptor|process|processor). A contract processor (a function with its own
* `params`) is hosted under the name given (core.js hostOp), replacing what had it, as any op given a name does */
audio.op = function(name, arg1, arg2, arg3) {
if (!arguments.length) return ops
if (arguments.length === 1) return ops[name]
if (arguments.length === 2 && typeof arg1 === 'function' && Object.hasOwn(arg1, 'params') && typeof arg1.params === 'object') return hostOp(arg1, name)
// Normalize to descriptor object
let desc
if (typeof arg1 !== 'function') {
desc = arg1
} else {
let plan, opts
if (typeof arg2 === 'function') { plan = arg2; opts = arg3 }
else opts = arg2
desc = { process: arg1 }
if (plan) desc.plan = plan
if (opts) Object.assign(desc, opts)
}
if (!desc.hidden) opMethods(name)
ops[name] = desc
}
/** Op `name` as an instance method, made once: a[name](), unless the instance has a method of its own by that name;
* another op's camelCase there (below) gives way to the op of the name. A name a script cannot write after a dot (a
* dashed id: a['transient-shaper']()) is the same method under its camelCase too (a.transientShaper(), the edit
* recorded under the name), unless that is a method already (an instance's own, another op's) */
export function opMethods(name) {
if (!fn[name] || fn[name].op != null && fn[name].op !== name) fn[name] = opMethod(name)
let alias = name.replace(/-+(.)/g, (_, c) => c.toUpperCase())
if (alias !== name && /^[A-Za-z_$][\w$]*$/.test(alias) && !fn[alias]) fn[alias] = fn[name]
}
/** Instance method for op `name`. Positional args map to the op's params at call time (a
* `...rest` param takes the remaining ones; a sound first, a keyed processor's key: core.js positional); an op not
* registered yet (a registry plugin still to load) keeps them as `args`, mapped once it loads. More positional args
* than params is an error, not a silent drop: an op without params takes options only. */
export function opMethod(name) {
let method = function(...a) {
// an argument passed as undefined is one not passed (options handed on by a caller that has none)
while (a.length && a.at(-1) === undefined) a.pop()
let hasOpts = a.length && isOpts(a.at(-1))
let o = hasOpts ? { ...named(a.pop()) } : {}
let d = ops[name]
if (d) {
let p = positional(d, a)
if (!p.at(-1)?.startsWith('...') && a.length > p.length)
throw new TypeError(p.length ? `${name}: expected at most ${p.length} argument${p.length === 1 ? '' : 's'} (${p.join(', ')}), got ${a.length}` : `${name}: takes options ({ at, duration, … }), not positional arguments`)
mapParams(p, a, o)
}
else if (a.length) o.args = a
// NaN refused at the call: a built-in's values by the shared check (judge) where it reads them; an option it does not
// read (a native plugin's own parameter, a function's own option) and another op's (a registry processor, the
// user's) as given
for (let k in o) if (typeof o[k] === 'number' && Number.isNaN(o[k]) && (!builtin.has(d) || means(d, k, o) === true)) throw new RangeError(`${name}: ${k} is NaN`)
if (reshapes(d, o.channel) && (o.at != null || o.duration != null)) throw new TypeError(`${name}: range options not supported for channel-changing ops`)
if (o.mix != null && !d?.params?.includes('mix')) mixable(name, o.mix, d, o.channel)
return this.run([name, o])
}
method.op = name // an op's method, not an instance's own (read, save): a processor may take the name of the one only
return method
}
// ── Edit Tracking ───────────────────────────────────────────────
/** Push an edit, bump version, notify. */
export function pushEdit(a, edit) {
a.edits.push(edit)
a.version++
emit(a, 'change')
}
/** Pop an edit, bump version, notify. */
export function popEdit(a) {
let e = a.edits.pop()
if (e) { a.version++; emit(a, 'change') }
return e
}
// ── Virtual Length/Channels ─────────────────────────────────────
/** The registry ops whose processors can change a sound's width, each with the width it makes: a function of the width
* given, a count of its own, or 0 where none is known before it loads (audio.js names them). Asked before one has
* loaded, the sound's `channels` is the width the op will make, and an error, as its length is, only where that is
* not known */
export const widening = new Map()
/** Effective output format after all edits — the single home for folding the
* edit list through op `.sr`/`.ch` hooks (lightweight: no segments, no resolve). */
function deriveFormat(a) {
if (a._.fmtV === a.version) return a._.fmt
let sr = a._.sr, ch = a._.ch, known = true, unknown = []
for (let [i, [type, o = {}]] of a.edits.entries()) try {
let desc = ops[type]
// an op not loaded yet (a registry plugin before the first read) is passed as keeping the format, the width too
// unless it changes it (on chosen channels it runs in place): then the width it makes of this one, and where that
// is not known before it loads, the op named
if (!desc) {
known = false
let w = o.channel == null ? widening.get(type) : undefined
// a count of its own is the width whatever came before it
if (typeof w === 'function') ch = w(ch); else if (w) ch = w, unknown = []; else if (w === 0 && !unknown.includes(type)) unknown.push(type)
continue
}
if (desc.sr) sr = desc.sr(sr, o) || sr
if (desc.ch) { let { at, duration, channel, ...extra } = o; ch = widthOf(desc, ch, channel, extra) }
// an edit that sets the width outright (a remix to a count or a list of channels) makes it known again
if (desc.sets?.(o)) unknown = []
} catch (e) { throw blame(e, a, i) }
// loading changes no version, so an answer before it is not kept
a._.fmt = { sr, ch, unknown }; a._.fmtV = known ? a.version : -1
return a._.fmt
}
Object.defineProperties(fn, {
sampleRate: {
get() { return this.edits?.length ? deriveFormat(this).sr : this._.sr },
set(v) { this._.sr = v; this._.fmtV = -1 },
enumerable: true, configurable: true
},
// kept by the edits, the length and the sounds the edits read: one inserted and cropped later shortens this one too
length: { get() {
let rv = refVersion(this)
if (this._.lenV === this.version && this._.lenL === this._.len && this._.lenR === rv) return this._.lenC
let len = this.edits.length ? lengthOf(this) : this._.len
this._.lenC = len; this._.lenV = this.version; this._.lenL = this._.len; this._.lenR = rv
return len
}, configurable: true },
channels: {
get() {
if (!this.edits?.length) return this._.ch
let { ch, unknown } = deriveFormat(this)
if (unknown.length) throw new Error(`${unknown.join(', ')}: can change the channel count, and ${unknown.length > 1 ? 'are' : 'is'} not loaded until the first read (await audio.use(${unknown.map(n => `'${n}'`).join(', ')}) to know it before)`)
return ch
},
configurable: true
},
})
// ── Read ───────────────────────────────────────────────────────────────
/** Ensure cache pages for the source ranges a plan will access. */
export async function ensurePlan(a, plan, offset, duration, visiting = new Set()) {
if (!audio.ensurePages || duration === 0) return
if (visiting.has(a)) throw new Error('audio: circular source reference')
visiting.add(a)
// a sound an edit takes failing as its pages come (its plan, a page from its store): that edit's
const restore = async (ref, at, duration) => {
try { await (ref.edits.length ? ensurePlan(ref, buildPlan(ref), at, duration, visiting) : audio.ensurePages(ref, at, duration)) }
catch (e) { throw blame(e, a, holderOf(a, ref)) }
}
// A stage (baked prefix) is a plan over the same instance — recurse without re-entering a
const prime = async (plan, offset, duration) => {
let { segs, sr, latency = 0 } = plan
let s = Math.round((offset || 0) * sr)
let e = duration != null ? s + Math.round(duration * sr) : plan.totalLen
e = Math.min(e + latency, plan.totalLen) // latency cursors read ahead
// Match streamPlan's warm-up, including pages before the requested range.
if (plan.pipeline.length) s = warmStart(s, s + latency, plan.warmup)
// Pull sources (mix/crossfade) use seconds; segment refs use source samples.
if (plan.pulls) for (let p of plan.pulls) {
let S = s / sr, E = e / sr
let o1 = Math.max(S, p.at), o2 = Math.min(E, p.at + p.ref.duration)
if (o2 > o1) await restore(p.ref, o1 - p.at, o2 - o1)
}
for (let sg of segs) {
let iStart = Math.max(s, sg[2]), iEnd = Math.min(e, sg[2] + sg[1])
if (iStart >= iEnd) continue
let rate = sg[3] || 1, absR = Math.abs(rate), n = iEnd - iStart
let margin = (sg[5] && sg[5].margin) || 0
let srcStart = segSrcStart(sg, iStart, n)
let srcLen = n * absR + 1 + 2 * margin
let target = sg[4] === null ? null : sg[4] || a
if (target?.segs) await prime(target, Math.max(0, srcStart - margin) / target.sr, srcLen / target.sr)
else if (target) {
let rate = target.sampleRate
let at = Math.max(0, srcStart - margin) / rate, duration = srcLen / rate
if (target === a) await audio.ensurePages(target, at, duration)
else await restore(target, at, duration)
}
}
}
try { await prime(plan, offset, duration) } finally { visiting.delete(a) }
}
/** Visit every audio instance referenced by edit opts (insert/mix/crossfade sources). */
function eachRef(a, cb) {
for (let edit of a.edits) {
let o = edit[1]
if (!o) continue
for (let k in o) if (o[k]?.pages) cb(o[k])
}
}
/** The edit of `a` whose options hold the sound `ref` (a mix's source, an insert's, a key), -1 where none does (the
* clipboard a paste reads): a failure of that sound is that edit's (core.js blame) */
const holderOf = (a, ref) => a.edits.findIndex(([, o]) => o && Object.values(o).includes(ref))
/** The index in a.edits of the edit a pipeline entry renders: the entry itself, or the edit whose expand or resolve
* emitted it (`origin`: a tailed processor's hidden op, a normalize's gain); -1 for none, which blame leaves be */
const origin = new WeakMap()
const editOf = (a, ed) => a.edits.indexOf(origin.get(ed) ?? ed)
/** Await full decode of every referenced source — a ref's length/PCM must be
* settled before its plan segment or ctx.render pull reads from it. */
export async function loadRefs(a) {
let refs = []
eachRef(a, r => refs.push(r))
for (let r of refs) try { if (r.ready) await r.ready; await r[LOAD]() } catch (e) { throw blame(e, a, holderOf(a, r)) }
}
fn[READ] = async function(offset, duration) {
if (!this.edits.length) {
if (audio.ensurePages) await audio.ensurePages(this, offset, duration)
return readPages(this, offset, duration)
}
await this[LOAD]()
// A clipboard snapshot must include the complete input, even before decode settles.
if (!this.decoded && this.edits.some(e => e[0] === 'copy' || e[0] === 'cut')) await this.ready
await loadRefs(this)
let plan = buildPlan(this)
let s = Math.round((offset || 0) * plan.sr)
let e = duration != null ? s + Math.round(duration * plan.sr) : plan.totalLen
if (e - s > MAX_FLAT_SIZE) throw new Error(`Audio too large for flat read (${((e - s) / 1e6).toFixed(0)}M samples). Use streaming.`)
await ensurePlan(this, plan, offset, duration)
return readPlan(this, plan, offset, duration)
}
// ── Stream ─────────────────────────────────────────────────────
fn[Symbol.asyncIterator] = fn.stream = async function*(opts) {
opts = named(opts)
let offset = parseTime(opts?.at), duration = parseTime(opts?.duration)
if (this._.disposed) return
if (this._.ready) await this._.ready
offset = await fromEnd(this, offset)
if (this._.disposed) return
await loadRefs(this)
let a = this, sr = a.sampleRate, BS = audio.BLOCK_SIZE
let live = !!a._.waiters && !a.decoded
if (!live) await a[LOAD]()
let startSample = offset ? Math.round(offset * sr) : 0
let endSample = duration != null ? startSample + Math.round(duration * sr) : Infinity
let durExplicit = duration != null
let builtLen = 0, plan = null, procs = null, outPos = startSample, ensured = false
let lastVer = a.version
let T = 0 // pipeline latency — outPos runs in cursor space, T ahead of the timeline
let nch = a._.ch
let bufA = Array.from({ length: nch }, () => new Float32Array(BS))
let xf = null, sigP = '', yielded = false // an edit's crossfade (the old render going out), pipeline signature
while (!a._.disposed && outPos < endSample + T) {
let acc = a._.acc
let avail = a.decoded ? a._.len : acc ? acc.length : a._.len
// Rebuild the plan when new source data arrives, on the one-time post-decode pass,
// or when edits were pushed mid-stream (live parameter/op changes during playback)
// (an edit during a crossfade waits for it to finish: ~20 ms)
if (avail > builtLen || (a.decoded && !ensured) || (a.version !== lastVer && !xf)) {
let verChanged = plan != null && a.version !== lastVer, old = plan, warm = null
lastVer = a.version
builtLen = Math.max(builtLen, avail)
// whole, the plan its length was read by, if it was (a resolve that measured the signal is not measured twice)
plan = a.decoded && builtLen === a._.len ? buildPlan(a) : compilePlan(a, builtLen, a.decoded)
let sig = pipelineSig(plan.pipeline), width = plan.ch ?? nch
// procs for this plan from timeline sample t (warmed up below, once its pages are there)
const fresh = t => {
nch = width; T = plan.latency; sigP = sig
bufA = Array.from({ length: nch }, () => new Float32Array(BS))
procs = initProcs(a, plan.pipeline, plan.totalLen / sr, sr, nch)
outPos = t + T
warm = t
}
if (procs && yielded && verChanged && (plan.latency !== T || width !== nch || sig !== sigP || !sameTimeline(old.segs, plan.segs))) {
// An edit that changes what renders here (a cut, an insert, an op added or removed, a new latency or width):
// the old render goes on for ~20 ms beside the new one, warmed up at the same place, and crossfades into it
// (linear: the same sound, changed)
let n = Math.min(2048, Math.round(sr * 0.02))
xf = { plan: old, procs, pos: outPos, buf: bufA, n, left: n }
fresh(outPos - T)
} else if (procs && yielded && (width !== nch || sig !== sigP)) fresh(outPos - T)
else if (!procs || width !== nch || sig !== sigP) {
// First compile, or a pipeline settled before anything streamed. Warm up before the latency-delayed start,
// never after the requested one: a stage delayed by T must see input from startSample, or a latency past
// the warm-up loses the first T − warm-up samples
nch = width; T = plan.latency; sigP = sig
bufA = Array.from({ length: nch }, () => new Float32Array(BS))
procs = initProcs(a, plan.pipeline, plan.totalLen / sr, sr, nch)
outPos = (startSample > 0 || T > 0) && procs.length ? warmStart(startSample, startSample + T, plan.warmup) : startSample
} else {
// Latency refined as the source arrives — keep content continuity: cursor c ↦ c + ΔT
if (plan.latency !== T) { outPos += plan.latency - T; T = plan.latency }
// Same structure, values refined — patch ctx in place (ramped in applyProcs)
if (procs.length) patchProcs(procs, plan.pipeline)
}
if (verChanged) await loadRefs(a)
// A live source's end moves: ops placed from it follow (their output is held back until final)
if (!a.decoded) {
let td = plan.totalLen / sr
for (let p of procs) { p.ctx.totalDuration = td; if (p.origAt != null && p.origAt < 0) p.at = td + p.origAt }
}
if (a.decoded && (!ensured || verChanged)) {
ensured = true
if (endSample === Infinity || (verChanged && !durExplicit)) endSample = plan.totalLen
let td = plan.totalLen / sr
for (let p of procs) {
p.ctx.totalDuration = td
if (p.origAt != null && p.origAt < 0) p.at = td + p.origAt
}
await ensurePlan(a, plan, offset, duration)
let seen = new Set()
for (let s of plan.segs) if (s[4]?.pages && !seen.has(s[4])) try { seen.add(s[4]); await s[4][LOAD]() } catch (e) { throw blame(e, a, holderOf(a, s[4])) }
}
// new procs mid-stream: warmed up over what precedes the timeline position, which has rendered already
if (warm != null && procs.length) for (let p = warmStart(warm, outPos, plan.warmup); p < outPos;) {
let len = Math.min(BS, outPos - p)
for (let b of bufA) b.fill(0, 0, len)
renderBlock(a, plan.segs, p, len, bufA)
applyProcs(a, len < BS ? bufA.map(b => b.subarray(0, len)) : bufA, procs, p, sr)
p += len
}
}
if (a._.disposed) return
if (!plan || outPos >= plan.totalLen + T) {
if (a.decoded) break
await new Promise(r => a._.waiters.push(r))
continue
}
// Cursor bounds: pre-decode the limit gates determinism; post-decode cursors may
// run T past totalLen to flush lookahead delay lines (renders as silence)
let bound = a.decoded ? plan.totalLen + T : Math.min(plan.limit, plan.totalLen)
// the latency pre-roll too: nothing is processed past what is settled, or a stateful op
// builds on a placement the rest of the input still moves
let blockEnd = Math.min(outPos < startSample + T ? startSample + T : endSample + T, bound)
let len = Math.min(BS, blockEnd - outPos)
if (len <= 0) { if (a.decoded) break; await new Promise(r => a._.waiters.push(r)); continue }
let needed = maxSrcSample(plan.segs, outPos, outPos + len)
if (needed > builtLen && !a.decoded) {
await new Promise(r => a._.waiters.push(r))
continue
}
if (!rendered(a, plan, outPos, len, bufA)) { await ensurePlan(a, plan, outPos / sr, len / sr); rendered(a, plan, outPos, len, bufA) }
let src = len < BS ? bufA.map(b => b.subarray(0, len)) : bufA
let out = procs.length ? applyProcs(a, src, procs, outPos, sr) : src
if (xf) {
// the old render over the same stretch of the timeline, fading out as the new one fades in
let ob = xf.buf
if (!rendered(a, xf.plan, xf.pos, len, ob)) { await ensurePlan(a, xf.plan, xf.pos / sr, len / sr); rendered(a, xf.plan, xf.pos, len, ob) }
let os = len < BS ? ob.map(b => b.subarray(0, len)) : ob
let oo = xf.procs.length ? applyProcs(a, os, xf.procs, xf.pos, sr) : os, k = xf.n - xf.left
for (let c = 0; c < out.length; c++) {
let o = oo[c % oo.length], y = out[c]
for (let i = 0; i < len; i++) { let t = Math.min(1, (k + i + 1) / xf.n); y[i] = o[i] * (1 - t) + y[i] * t }
}
xf.pos += len
if ((xf.left -= len) <= 0) xf = null
}
if (outPos >= startSample + T) { yielded = true; yield out.map(b => b.slice(0, len)) }
outPos += len
}
}
// A block of a stream rendered into `buf`: false where it met a page let go of since its pages were ensured (another
// reader's eviction, a store set up only now), read as silence, for the stream to restore it and render it again
function rendered(a, plan, pos, len, buf) {
let m = missed
for (let b of buf) b.fill(0, 0, len)
renderBlock(a, plan.segs, pos, len, buf)
return missed === m
}
// ── API ────────────────────────────────────────────────────────
fn.undo = function(n = 1) {
if (!this.edits.length) return n === 1 ? null : []
let removed = []
for (let i = 0; i < n && this.edits.length; i++) removed.push(popEdit(this))
return n === 1 ? removed[0] : removed
}
fn.run = function(...edits) {
let sr = this.sampleRate
for (let e of edits) {
// its values judged before its place is asked: a paste's before its clipboard
let ed = normalizeEdit(e, sr, true)
if (ed[0] === 'paste' && !this.edits.some(e => e[0] === 'copy' || e[0] === 'cut')) throw new Error('paste: clipboard is empty; call copy() or cut() first')
pushEdit(this, ed)
}
return this
}
fn.toJSON = function() {
let left = [], edits = this.edits.filter(e => hasFunction(e[1]) ? (left.push(e[0]), false) : true)
// a function does not serialize: the edits that hold one are left out, said once a call (a curve { t, v } is kept)
if (left.length) console.warn(`audio: toJSON leaves out ${left.length} edit${left.length > 1 ? 's' : ''} holding a function, which does not serialize: ${[...new Set(left)].join(', ')} (automation written as a curve { t, v } is kept)`)
return { source: this.source, edits: jsonable(edits), sampleRate: this.sampleRate, channels: known(this, 'channels'), duration: known(this, 'duration'), schemaVersion: FORM }
}
/** What the edits make of a sound's width or length, as the document says it: null where it cannot be said before a read
* (a length that a trim decides from a render through spectral, whose module loads at the first read; a width a
* registry op picks; an align, whose lag is found as it prepares): the edits are the document, these its summary */
function known(a, key) {
try { return a[key] } catch { return null }
}
fn.clone = function() {
let b = audio.from(this, { sampleRate: this._.sr }), _ = this._
for (let [type, opts] of this.edits) pushEdit(b, [type, opts ? { ...opts } : {}])
// its tags and marks too: the copy plays the same samples through the same edits, so they keep to them as they are
if (_.metaDone) Object.assign(b._, { metaDone: true, meta: _.meta && { ..._.meta }, markers: _.markers?.map(m => ({ ...m })), regions: _.regions?.map(r => ({ ...r })) })
if (_.marks?.length) b._.marks = _.marks.map(m => ({ ...m }))
return b
}
// ── Render Engine ──────────────────────────────────────────────
const MAX_FLAT_SIZE = 2 ** 29
// Blocks rendered before a seek point to warm up stateful ops (filters, vocoders)
const WARMUP = 8
/** Get sample length from any source type. */
export function srcLen(s) {
return Array.isArray(s) ? s[0].length : s?.getChannelData ? s.length : s._.len
}
/** Source length expressed in target-rate samples. */
export function refLen(source, sr) {
let len = Array.isArray(source) ? source[0].length : source.length
let ssr = source?.sampleRate
return ssr && ssr !== sr ? Math.round(len * sr / ssr) : len
}
/** Render n target-rate samples at srcOff (target coords) from a source,
* resampling when the source's sample rate differs. */
audio.renderAt = renderAt // sidechain bus reads in core's useOp (no core→plan import)
audio.render = render // a buffer (an audio instance) read whole there too
export function renderAt(render, source, srcOff, n, sr) {
let ssr = source?.sampleRate
let ratio = ssr && ssr !== sr ? ssr / sr : 1
if (ratio === 1) return render(source, srcOff, n)
let src = render(source, Math.floor(srcOff * ratio), Math.ceil(n * ratio) + 1)
return src.map(ch => { let o = new Float32Array(n); resample(ch, o, 0, n, ratio, srcOff * ratio % 1); return o })
}
/** Render all edits into flat PCM, or read a slice. For ctx.render in PCM ops. */
export function render(a, offset, count) {
// Raw Float32Array[]
if (Array.isArray(a) && a[0] instanceof Float32Array) {
return offset != null ? a.map(ch => ch.subarray(offset, offset + count)) : a
}
// AudioBuffer: a slice as views of its channels, as Float32Array[] gives one (the readers of a block, a key's, a mix's
// source's, never write it; a copy of every channel whole for each block made a key's read grow with the square of
// its length); the whole as copies
if (a?.getChannelData && !a.pages) {
if (offset != null) return Array.from({ length: a.numberOfChannels }, (_, i) => a.getChannelData(i).subarray(offset, offset + count))
return Array.from({ length: a.numberOfChannels }, (_, i) => new Float32Array(a.getChannelData(i)))
}
if (offset != null) return readRange(a, offset, count)
if (a._.pcm && a._.pcmV === a.version) return a._.pcm
if (!a.edits.length) { let r = readPages(a); a._.pcm = r; a._.pcmV = a.version; return r }
let plan = buildPlan(a)
let virtualLen = planLen(plan.segs)
if (virtualLen > MAX_FLAT_SIZE) throw new Error(`Audio too large for flat render (${(virtualLen / 1e6).toFixed(0)}M samples). Use streaming.`)
let r = readPlan(a, plan)
a._.pcm = r; a._.pcmV = a.version
return r
}
export function planLen(segs) { let m = 0; for (let s of segs) m = Math.max(m, s[2] + s[1]); return m }
/** How a plan op transforms the safe output boundary during incremental decode: of `limit` input samples, the output
* that is final, as the op's `limit` hook says; one without keeps it */
function adjustLimit(limit, type, ctx) {
if (limit <= 0) return 0
return audio.op(type)?.limit?.(limit, ctx) ?? limit
}
/** Build plan ctx for a plan hook or adjustLimit. */
function mkPlanCtx(total, sr, offset, length, extra) {
return { total, sampleRate: sr, offset, length, ...extra }
}
/** Declared latency of a pipeline op in samples — number, or fn(opts, sr) for
* param-dependent lookahead. The render loop runs cursors this far ahead of the
* requested timeline so delayed output lands aligned (plugin delay compensation). */
function procLatency(desc, o, sr) {
let l = desc?.latency
return (typeof l === 'function' ? Math.round(l(o || {}, sr)) : l) || 0
}
/** Declared warm-up of a pipeline op in samples: input it needs before an output position to
* get that position right (context before a repaired range, a frame's left half). A render
* that starts mid-timeline begins this far earlier; number, or fn(opts, sr). */
function procWarmup(desc, o, sr) {
let w = desc?.warmup
return (typeof w === 'function' ? Math.round(w(o || {}, sr)) : w) || 0
}
/** Declared holdback of a pipeline op in samples: output before the plan's current end it can't
* finalize until the end is known (a fade-out's length); number, or fn(opts, sr, total). */
function procHoldback(desc, o, sr, total) {
let h = desc?.holdback
return (typeof h === 'function' ? Math.round(h(o || {}, sr, total)) : h) || 0
}
/** First input sample for output from s, with the latency-shifted cursor sc: the fixed warm-up
* blocks before the cursor, the plan's declared warm-up before s, never past s. */
const warmStart = (s, sc, warmup = 0) => Math.max(0, Math.min(s, s - warmup, sc - audio.BLOCK_SIZE * WARMUP))
/** Stats a resolve-stage op (edit `index`) sees: source stats remapped through the
* structural segs + pipeline accumulated so far, so trim/normalize measure output space,
* not source space. Algebraic remap when possible; otherwise the prefix renders into stats
* as a stage. Its output below the limit is settled, so each compile renders only what
* newly settled: a live stream accumulates them as it goes (partial until final), and the
* timeline is never rendered twice for them. */
function resolveCtxStats(a, index, st) {
let src = a.srcStats, { segs, pipeline, sr } = st
if (src) {
// the source itself, whole: a crop from 0 keeps the first segment's start but not its length
if (!pipeline.length && segs.length === 1 && segs[0][0] === 0 && segs[0][2] === 0 && segs[0][1] === a._.len && !segs[0][3] && segs[0][4] === undefined) return src
let adapted = audio.adaptStats?.(src, st, sr)
if (adapted) return adapted
}
// none known (a copy of a stream measured through its edits): the prefix renders into stats, as one that can't adapt
if (!audio.statSession) return null
let edit = a.edits[index], all = a._.rstats ??= new WeakMap(), c = all.get(edit), rv = refVersion(a)
if (!c || c.rv !== rv || c.prefix.length !== index || c.prefix.some((e, i) => e !== a.edits[i]))
all.set(edit, c = { prefix: a.edits.slice(0, index), rv, pos: 0, hl: 0 })
// what was rendered holds while the timeline only grows and the stage keeps its shape
if (!c.st || c.st.sr !== sr || c.st.ch !== st.ch || c.st.latency !== st.latency ||
pipelineSig(c.st.pipeline) !== pipelineSig(pipeline) || !sameTimeline(c.st.segs, segs)) {
c.procs = null; c.st = null
c.session = audio.statSession(sr); c.done = 0; c.stats = null
}
if (c.stats) return c.stats
st.outCh = stageWidth(a, pipeline, st.ch, st.totalLen / sr, sr)
st.cur = c
let settled = st.final ? st.totalLen : Math.max(0, Math.min(st.limit, st.totalLen) - st.latency)
for (let n; (n = Math.min(1 << 16, settled - c.done)) > 0; c.done += n) c.session.page(readStage(a, st, c.done, n))
return st.final ? (c.stats = c.session.done()) : c.session.snapshot()
}
/** Compile edit list into plan segments + pipeline for a given source length.
* final=true when source is fully decoded — all positions are determined. */
function compilePlan(a, len, final, measure = false) {
let sr = a._.sr, ch = a._.ch
let segs = [[0, len, 0]], pipeline = [], limit = len, pulls = [], latency = 0, warmup = 0, clipboard
// Share pages, never a full PCM copy; the edit prefix replays the processed audio
// and preserves format derivation and ordinary ref/cache behavior.
const snapshot = index => {
let ref = inputOf(a, index)
return ref
}
// Pipeline push that also registers ctx.render pull sources (mix/crossfade)
// so ensurePlan can prime their pages alongside segment refs.
let pushProc = ed => {
pipeline.push(ed)
latency += procLatency(ops[ed[0]], ed[1], sr)
warmup = Math.max(warmup, procWarmup(ops[ed[0]], ed[1], sr))
let o = ed[1]
if (o) for (let k in o) if (o[k]?.pages) pulls.push({ ref: o[k], at: o.at ?? 0 })
// While the end is unknown, output that depends on it waits, and only that much: a range
// counted from the end, or the op's declared holdback (a fade-out's length)
if (!final) {
let t = planLen(segs), hb = procHoldback(ops[ed[0]], o, sr, t)
// a range from the end is placed only at the end: until then the op must not reach it,
// nor the context it reads before it (warm-up)
if (o?.at < 0) hb = Math.max(hb, Math.round(-o.at * sr) + procWarmup(ops[ed[0]], o, sr))
if (hb) limit = Math.min(limit, Math.max(0, t - hb))
}
}
// A structural op works on the audio as processed so far: pending pipeline ops bake
// into a stage — a nested plan the timeline reads as its source — so later splices
// neither pass through them nor shift their ranges, fades and automation time.
let index = 0, bakes = 0
let bake = () => {
if (!pipeline.length) return
let st = { segs, pipeline, totalLen: planLen(segs), sr, ch, latency, warmup, pulls, limit }
st.outCh = stageWidth(a, pipeline, ch, st.totalLen / sr, sr)
st.cur = stageCursor(a, index, bakes++)
segs = [seg(0, st.totalLen, 0, undefined, st)]
ch = st.outCh
clear()
}
// a fresh pipeline, after a stage baked or a whole op rendered
let clear = () => { pipeline = []; pulls = []; latency = 0; warmup = 0 }
// a structural op: the pipeline so far baked, the segments rewritten, the safe boundary moved as the op says (limit)
let restructure = (op, type, at, duration, extra) => {
bake()
let pctx = mkPlanCtx(planLen(segs), sr, at != null ? Math.round(at * sr) : null, duration != null ? Math.round(duration * sr) : null, extra)
// the timeline it rewrites, for what reads it as it was (a stretch's vocoder, at its own rate)
pctx.input = timelineOf(a, segs, ch)
segs = op.plan(segs, pctx)
// where the length is derived: one the timeline cannot hold refused, naming the edit that made it
long(planLen(segs), ...a.edits[index])
if (!final) limit = adjustLimit(limit, type, pctx)
}
// an op that sets the rate from here on (resample)
let rerate = (op, o) => { let ns = op?.sr?.(sr, o); if (ns) sr = ns }
// a whole op's declared decay, in samples: rendered past the end of its input, `n` samples (a hosted processor's tail
// function is handed the transport there)
let tailN = (op, o, n) => Math.round((typeof op.tail === 'function' ? op.tail(o, sr, n) : op.tail || 0) * sr)
// Apply edits emitted by an expand/resolve hook: structural → segment rewrite,
// otherwise pipeline. Inherits the parent edit's range and mix unless overridden.
let applyEmitted = (emitted, at, duration, channel, mix) => {
let edits = Array.isArray(emitted) && typeof emitted[0] !== 'string' ? emitted : [emitted]
for (let re of edits) {
re = normalizeEdit(re, sr)
let [rType, rOpts = {}] = re, rOp = ops[rType]
let o = { ...rOpts }
o.at ??= at; o.duration ??= duration; o.channel ??= channel
// the mix is the processor's: a structural edit it emits (a tail's pad) changes the timeline, not the sound
if (mix != null && !rOp?.plan) o.mix ??= mix
re = [rType, o]
origin.set(re, a.edits[index])
if (rOp?.whole) throw new Error(`audio: whole-render op '${rType}' cannot be emitted by expand/resolve`)
if (o.mix != null && !rOp?.params?.includes('mix')) mixable(rType, o.mix, rOp, o.channel)
if (typeof rOp?.plan === 'function') {
let { at: rAt, duration: rDur, channel: rCh, ...rExtra } = o
restructure(rOp, rType, rAt, rDur, rExtra)
} else {