Repository navigation
Expand file tree
/
Copy pathstats.js
More file actions
546 lines (491 loc) · 25.5 KB
/
Copy pathstats.js
File metadata and controls
546 lines (491 loc) · 25.5 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
/**
* Stats engine — block-level stat computation + unified stat query.
* Self-registers on import — exposes statSession on audio, adds fn.stat.
*/
import audio, { parseTime, named, LOAD, resolveChannels, pacer, FULL, blockAt } from './core.js'
import { buildPlan, streamPlan, ensurePlan } from './plan.js'
// ── Stat descriptor registry ────────────────────────────────────
let statDefs = {}
/** Register/query stat: audio.stat(), audio.stat(name), audio.stat(name, descriptor|blockFn) */
audio.stat = function(name, desc) {
if (!arguments.length) return statDefs
if (arguments.length === 1) return statDefs[name]
if (typeof desc === 'function') desc = { block: desc }
statDefs[name] = desc
}
/** Period, in samples, of the grid a block field holds its place on: its descriptor's `period(sr)` (a field listed in
* `extra`), else none. */
const periodOf = (f, sr) => Object.values(statDefs).find(d => d.period && d.extra?.includes(f))?.period(sr)
/** A block function's value for one stat: a record { [name]: value } serves several stats from one pass. */
export const blockValue = (v, name) => v !== null && typeof v === 'object' && !Array.isArray(v) && !ArrayBuffer.isView(v) ? v[name] : v
/** The block functions measuring `names` (every registered stat when none), each called once a block for all the stats
* it serves: { fn, ctx, names }, `names` its fields, those `extra` lists too (fields no stat is named after), each field
* in one group only; `ctx` kept from block to block (a filter's state). Decode's session and the meter measure by them */
export function blockGroups(sr, names) {
let groups = new Map(), fields = new Set()
for (let [name, d] of Object.entries(audio.stat())) {
if (!d.block || names && !names.includes(name)) continue
let g = groups.get(d.block)
if (!g) groups.set(d.block, g = { fn: d.block, ctx: { sampleRate: sr }, names: [] })
for (let f of [name, ...d.extra ?? []]) if (!fields.has(f)) { fields.add(f); g.names.push(f) }
}
return [...groups.values()]
}
/** Whole blocks a block function's `many` measures at a call, at most: what it hands back stays small */
const RUN = 64
/** Create a stat computation session. ch inferred from first .page() call. `names`: those stats alone (with what their
* block functions carry), not every one registered. */
function statSession(sr, names) {
let fns, acc, ch, last = 0, rem = null, remLen = 0, total = 0
function init(c) {
ch = c
fns = blockGroups(sr, names)
acc = Object.create(null)
for (let g of fns) for (let f of g.names) acc[f] = Array.from({ length: ch }, () => [])
}
function record({ fn, ctx, names }, block) {
let r = fn(block, ctx)
for (let name of names) {
let v = blockValue(r, name), a = acc[name]
if (typeof v === 'number') for (let c = 0; c < ch; c++) a[c].push(v)
else for (let c = 0; c < ch; c++) a[c].push(v[c])
}
}
function processBlock(block) {
total += block[0].length
for (let g of fns) record(g, block)
}
/** m whole blocks of `page` from `off`, up to RUN at a time: a group whose block function measures a run at once (its
* `many`: each field a channel's values, a block each; null where it can't) in one call, the rest a block at a time */
function processRun(page, off, m) {
let BS = audio.BLOCK_SIZE
total += m * BS
for (let i0 = 0; i0 < m; i0 += RUN) {
let n = Math.min(RUN, m - i0), o0 = off + i0 * BS, run = null
for (let g of fns) {
let r = g.fn.many?.(run ??= Array.from({ length: ch }, (_, c) => page[c].subarray(o0, o0 + n * BS)), g.ctx, BS)
if (r) for (let name of g.names) for (let c = 0, v = r[name]; c < ch; c++) for (let i = 0, x = v[c], a = acc[name][c]; i < n; i++) a.push(x[i])
else for (let i = 0, o = o0; i < n; i++, o += BS) record(g, Array.from({ length: ch }, (_, c) => page[c].subarray(o, o + BS)))
}
}
}
return {
page(page) {
if (!acc) init(page.length)
let BS = audio.BLOCK_SIZE, off = 0, len = page[0].length
// Complete partial remainder from previous push
if (remLen > 0) {
let need = BS - remLen
if (len >= need) {
for (let c = 0; c < ch; c++) rem[c].set(page[c].subarray(0, need), remLen)
processBlock(rem)
off = need
remLen = 0
} else {
for (let c = 0; c < ch; c++) rem[c].set(page[c].subarray(0, len), remLen)
remLen += len
return this
}
}
// Process full blocks
let m = Math.floor((len - off) / BS)
if (m) { processRun(page, off, m); off += m * BS }
// Buffer remainder
if (off < len) {
if (!rem) rem = Array.from({ length: ch }, () => new Float32Array(BS))
for (let c = 0; c < ch; c++) rem[c].set(page[c].subarray(off))
remLen = len - off
}
return this
},
/** Flush any buffered partial block as a short final block. */
flush() {
if (remLen > 0) {
processBlock(Array.from({ length: ch }, (_, c) => rem[c].subarray(0, remLen)))
remLen = 0
}
},
delta() {
if (!acc) return
let firstKey = Object.keys(acc)[0]
if (!firstKey) return
let cur = acc[firstKey][0].length
if (cur <= last) return
let d = { fromBlock: last }
for (let name in acc) d[name] = acc[name].map(a => new Float32Array(a.slice(last)))
last = cur
return d
},
done() {
this.flush()
// length: samples the blocks cover, the last block possibly short
let out = { blockSize: audio.BLOCK_SIZE, length: total }
if (acc) for (let name in acc) out[name] = acc[name].map(a => new Float32Array(a))
return out
},
/** The stats so far, whole: as done() gives them, the buffered remainder a short final block, the session going on
* as it was (the remainder's block measured on copies of its state) */
whole() {
if (!acc) return null
let tail = remLen > 0 && rem.map(c => c.subarray(0, remLen)), last = Object.create(null)
if (tail) for (let { fn, ctx, names } of fns) { let r = fn(tail, structuredClone(ctx)); for (let name of names) last[name] = blockValue(r, name) }
let out = { blockSize: audio.BLOCK_SIZE, length: total + remLen }
for (let name in acc) out[name] = acc[name].map((a, c) => {
let x = new Float32Array(a.length + (tail ? 1 : 0))
x.set(a)
if (tail) x[a.length] = typeof last[name] === 'number' ? last[name] : last[name][c]
return x
})
return out
},
/** Return current accumulated stats without flushing remainder. */
snapshot() {
if (!acc) return null
let out = { blockSize: audio.BLOCK_SIZE, length: total, partial: true }
// Expose raw arrays to avoid O(N) allocation per chunk during progressive streaming
for (let name in acc) out[name] = acc[name]
return out
}
}
}
// ── Bin reduction ────────────────────────────────────────────────
/** Blocks [a, b) of bin i of n over blocks [from, to): n equal shares, each at least a block. */
function binAt(from, to, n, i) {
let bpp = (to - from) / n, a = from + Math.floor(i * bpp), b = Math.min(from + Math.floor((i + 1) * bpp), to)
return [a, b > a ? b : a + 1]
}
function binReduce(values, from, to, bins, reduce) {
if (bins <= 0 || to <= from) return new Float32Array(Math.max(0, bins))
from = Math.max(0, from); to = Math.min(to, values.length)
if (to <= from) return new Float32Array(bins)
let out = new Float32Array(bins)
for (let i = 0; i < bins; i++) out[i] = reduce(values, ...binAt(from, to, bins, i))
return out
}
const num = v => v === null || typeof v === 'number'
/** A stat over each of n bins of blocks [from, to), `of(a, b)` measuring blocks [a, b): a Float32Array, or one a
* channel where `of` gives the values of nch channels; null (nothing to measure) as NaN. Null as soon as a value is
* not a number. */
async function series(from, to, n, nch, of) {
let vals = []
for (let i = 0; i < n; i++) {
let v = await of(...binAt(from, to, n, i))
if (!num(v) && !(nch && Array.isArray(v) && v.length === nch && v.every(num))) return null
vals.push(v)
}
return Array.isArray(vals[0]) ? Array.from({ length: nch }, (_, c) => Float32Array.from(vals, v => v[c] ?? NaN))
: Float32Array.from(vals, v => v ?? NaN)
}
/** Remap source stats by segment layout (plan-only edits, no sample pipeline).
* Falls back to null if segments are too complex to remap cheaply. */
function remapStats(srcStats, plan, sr) {
let bs = srcStats.blockSize, segs = plan.segs, totalLen = plan.totalLen
let fields = Object.keys(srcStats).filter(k => k !== 'blockSize' && Array.isArray(srcStats[k]))
let ch = srcStats[fields[0]]?.length || 1
// Block stats a segment reads: the source's, or a stage's (baked prefix) derived from them
const from = ref => {
if (ref === undefined) return srcStats
if (ref._stats?.src !== srcStats) ref._stats = { src: srcStats, stats: audio.adaptStats(srcStats, ref, sr) }
return ref._stats.stats
}
// Check feasibility: self-ref (undefined), silence (null) or a derivable stage, rate ±1
for (let s of segs) {
let rate = s[3] || 1, ref = s[4]
if (s[6]) return null // envelope (crossfade): overlapping sums
if (ref !== undefined && ref !== null && !(ref.segs && from(ref)?.[fields[0]]?.length === ch)) return null // external ref
if (Math.abs(rate) !== 1) return null // resampled
if (s[0] % bs !== 0 || s[2] % bs !== 0) return null // unaligned — force recompute
// Reversing a short final block moves it to the front: none of the old block
// boundaries then match the output grid, so reversing block records is wrong.
if (rate < 0 && s[1] % bs !== 0) return null
// ending inside a block short of what it reads: that block's stats hold samples past the segment
if (ref !== null && (s[0] + s[1]) % bs !== 0 && s[0] + s[1] < from(ref).length) return null
}
// A field with a period holds its block's place on a grid of that many samples from the start of the stats: it moves
// only by whole periods, forward. Fields a derived stage dropped are dropped here too.
fields = fields.filter(f => {
let p = periodOf(f, sr)
return segs.every(s => s[4] === null || (!p || (s[3] || 1) > 0 && (s[2] - s[0]) % p === 0) && from(s[4])[f])
})
let outBlocks = Math.ceil(totalLen / bs)
let out = { blockSize: bs, length: totalLen }
for (let f of fields) out[f] = Array.from({ length: ch }, () => new Float32Array(outBlocks))
for (let s of segs) {
let srcOff = s[0], count = s[1], dstOff = s[2], rate = s[3] || 1, ref = s[4]
let dstBlockStart = Math.floor(dstOff / bs)
let dstBlockEnd = Math.ceil((dstOff + count) / bs)
if (ref === null) continue // silence — Float32Array already zeroed
let src = from(ref), srcBlockStart = Math.floor(srcOff / bs)
let srcBlocks = src[fields[0]][0].length
let rev = rate < 0
for (let i = dstBlockStart; i < dstBlockEnd && i < outBlocks; i++) {
let si = rev ? srcBlockStart + (dstBlockEnd - 1 - i) : srcBlockStart + (i - dstBlockStart)
if (si < 0 || si >= srcBlocks) continue
for (let f of fields) for (let c = 0; c < ch; c++) out[f][c][i] = src[f][c][si]
}
}
return out
}
// ── Self-register ────────────────────────────────────────────────
audio.statSession = statSession
/** Adapt source stats to a partial plan (segs + pipeline) for resolve-stage ops —
* algebraic remap + derive only; null when infeasible (caller decides fallback). */
audio.adaptStats = (src, plan, sr) => {
if (!src.blockSize) return null
let out = canDerivePipeline(plan.pipeline) && remapStats(src, plan, sr)
if (out && plan.pipeline.length) out = tryDeriveStats(out, plan.pipeline)
// resolve ops read any field: a derivation that dropped some can't stand in
if (out) for (let k in src) if (Array.isArray(src[k]) && !out[k]) return null
if (out && src.partial) out.partial = true
return out || null
}
/** Stream plan blocks into stat session, yielding event loop periodically to avoid blocking. */
async function streamStats(s, inst, plan, offset, duration) {
let pace = pacer()
// Keep fields/channel shape even when the plan yields no samples.
s.page(Array.from({ length: inst.channels }, () => new Float32Array(0)))
for (let chunk of streamPlan(inst, plan, offset, duration)) {
s.page(chunk)
await pace()
}
}
/** Clone block-level stats (deep copy of all Float32Arrays). */
function cloneStats(src) {
let out = { blockSize: src.blockSize, length: src.length }
for (let k in src) {
if (k === 'blockSize' || !Array.isArray(src[k])) continue
out[k] = src[k].map(a => new Float32Array(a))
}
return out
}
/** Check if pipeline ops can be derived algebraically from block stats. */
function canDerivePipeline(pipeline) {
for (let [type, opts] of pipeline) {
if (opts?.at != null || opts?.duration != null || opts?.channel != null) return false
let desc = audio.op(type)
// a mix under 1 blends output and input: no op's derivation holds for that
if (opts?.mix != null && opts.mix !== 1 && !desc?.params?.includes('mix')) return false
if (!desc?.deriveStats && !desc?.pointwise) return false
}
return true
}
/** Derive post-pipeline stats from source stats via algebraic transforms. */
function tryDeriveStats(srcStats, pipeline) {
let stats = cloneStats(srcStats)
for (let [type, opts] of pipeline) {
let desc = audio.op(type)
if (desc.deriveStats) {
if (desc.deriveStats(stats, opts || {}) === false) return null
} else if (desc.pointwise) {
derivePointwise(desc, stats, opts)
} else return null
reclip(stats)
}
return stats
}
// Fields a pointwise probe recomputes exactly (monotonic f: block extremes map to extremes).
const PROBED = new Set(['blockSize', 'length', 'partial', 'min', 'max', 'clipping'])
/** Auto-derive min/max/clipping for pointwise ops by probing process with edge values.
* Energy, mean square and DC of a nonlinear map aren't functions of block extremes:
* those fields are dropped, so a query that needs them renders instead of reading
* pre-op values (a clamp left loudness at its pre-clamp level). */
function derivePointwise(desc, stats, opts) {
for (let k in stats) if (!PROBED.has(k)) delete stats[k]
let ch = stats.min.length, n = stats.min[0]?.length || 0
if (!n) return
let { at, duration, channel, ...extra } = opts || {}
let ctx = { ...extra }
let outA = Array.from({ length: ch }, () => new Float32Array(n))
let outB = Array.from({ length: ch }, () => new Float32Array(n))
desc.process(stats.min.map(c => c.slice()), outA, ctx)
desc.process(stats.max.map(c => c.slice()), outB, ctx)
for (let c = 0; c < ch; c++) {
for (let i = 0; i < n; i++) {
stats.min[c][i] = Math.min(outA[c][i], outB[c][i])
stats.max[c][i] = Math.max(outA[c][i], outB[c][i])
}
}
}
/** A block clips where its derived extremes reach full scale; how many of its samples do, only its samples tell: there
* the count goes, so a query that counts renders (the clipping stat finds the blocks by their extremes); where no
* block reaches full scale, none clips */
function reclip(stats) {
if (!stats.clipping) return
let reach = stats.min.some((lo, c) => { let hi = stats.max[c]; for (let i = 0; i < lo.length; i++) if (lo[i] <= -FULL || hi[i] >= FULL) return true; return false })
if (reach) delete stats.clipping
else stats.clipping.forEach(cl => cl.fill(0))
}
/** Resolve block range from opts. Recomputes stats if edits are dirty, or if the
* cached (derived) stats lack a block field the query needs (`need`). */
export async function queryRange(inst, opts, need) {
await inst[LOAD]()
// Block stats land only after full decode — LOAD alone resolves at metadata
if (!inst.decoded && inst.ready) await inst.ready
opts = named(opts)
let at = parseTime(opts?.at), dur = parseTime(opts?.duration)
let hasRange = at != null || dur != null
let lacks = s => need?.some(f => !s?.[f])
// Block rounding must not turn an empty sample range into the final block.
let start = at < 0 ? Math.max(0, inst.duration + at) : at ?? 0
if (dur === 0 || start >= inst.duration) {
let stats = statSession(inst.sampleRate).page(Array.from({ length: inst.channels }, () => new Float32Array(0))).done()
return { stats, ch: inst.channels, sr: inst.sampleRate, from: 0, to: 0 }
}
// a range read from fields placed on a grid from the start of the stats (`period`): stats of the range itself
if (hasRange && need?.some(f => periodOf(f, inst.sampleRate))) {
let s = statSession(inst.sampleRate), plan = buildPlan(inst), atN = at != null && at < 0 ? inst.duration + at : at || 0
await ensurePlan(inst, plan, atN, dur)
await streamStats(s, inst, plan, atN, dur)
let stats = s.done(), first = Object.values(stats).find(v => v?.[0]?.length)
return { stats, ch: inst.channels, sr: inst.sampleRate, from: 0, to: first?.[0]?.length || 0 }
}
if (!inst.edits?.length && inst._.statsV !== inst.version && inst._.srcStats != null) {
// back to pristine (undo to zero edits) — restore the pre-edit snapshot, or measure again where there was none
inst.stats = inst._.srcStats || null
inst._.statsV = inst.version
}
if (!inst.stats || lacks(inst.stats) || inst.edits?.length && inst._.statsV !== inst.version) {
// the samples' own, before the edits replace `stats` (a pushed stream's once whole); false where unknown (one still
// arriving), never the edits'
if (inst._.srcStats == null) inst._.srcStats = (inst.decoded ? inst.srcStats : inst.stats) ?? false
let plan = buildPlan(inst), src = inst._.srcStats
// Fast path: remap by plan segs + derive pipeline algebraically (e.g. crop + gain + clamp)
let derived = src?.blockSize && canDerivePipeline(plan.pipeline) && remapStats(src, plan, inst.sampleRate)
if (derived && plan.pipeline.length) derived = tryDeriveStats(derived, plan.pipeline)
if (derived && !lacks(derived)) { inst.stats = derived; inst._.statsV = inst.version }
else if (hasRange) {
// Slow path scoped to range — avoid streaming whole timeline
let s = statSession(inst.sampleRate)
await ensurePlan(inst, plan, at || 0, dur)
await streamStats(s, inst, plan, at || 0, dur)
let stats = s.done(), first = Object.values(stats).find(v => v?.[0]?.length)
return { stats, ch: inst.channels, sr: inst.sampleRate, from: 0, to: first?.[0]?.length || 0 }
} else {
let s = statSession(inst.sampleRate); await ensurePlan(inst, plan); await streamStats(s, inst, plan); inst.stats = s.done()
inst._.statsV = inst.version
}
}
let sr = inst.sampleRate, bs = inst.stats?.blockSize
if (!bs) return { stats: inst.stats, ch: inst.channels, sr, from: 0, to: 0 }
let first = Object.values(inst.stats).find(v => v?.[0]?.length)
let blocks = first?.[0]?.length || 0
let atN = at != null && at < 0 ? inst.duration + at : at
let from = atN != null ? blockAt(atN, sr, bs) : 0
let to = dur != null ? blockAt((atN || 0) + dur, sr, bs, Math.ceil) : blocks
from = Math.max(0, Math.min(from, blocks))
to = Math.max(from, Math.min(to, blocks))
return { stats: inst.stats, ch: inst.channels, sr, from, to }
}
audio.fn.stat = async function(name, opts) {
// Array of stat names — parallel query, positional result
if (Array.isArray(name)) return Promise.all(name.map(n => this.stat(n, opts)))
let desc = audio.stat(name)
// registry stat plugins (truepeak, lra, …) load on first use
if (!desc && audio.plugins?.[name]) { await audio.use(name); desc = audio.stat(name) }
if (!desc) throw new Error(`Unknown stat: '${name}'`)
// what a stat reads from an optional package, loaded before it is read (beat.js)
await desc.load?.()
// `bins`: where, not only how much. A stat whose value is a number gives its value over each of n bins of the range,
// one block grid for all (binReduce's): a block stat reduces the bin's blocks, a query reads them, a method measures
// the bin's seconds; a null (nothing to measure) is NaN. A stat whose value is not a number, as its first bin's shows
// (events and regions carry their own times; a key; a vector, which spectrum and cepstrum size by `bins`), answers
// once for the whole range, opts as given.
// `d` as `duration` for every stat: a method reads the long name only
opts = named(opts)
let { bins, ...o } = opts ?? {}
if (bins != null && !(Number.isInteger(bins) && bins >= 0)) throw new RangeError(`bins ${bins}: a whole number, 0 or more`)
// Registered stat with instance method (streaming analysis: spectrum, cepstrum, silence, plugins, etc.)
if (!desc.query && !desc.reduce && !desc.block && typeof this[name] === 'function') {
if (bins == null) return this[name](opts)
await this[LOAD]()
if (!this.decoded && this.ready) await this.ready
// the range's ends as asked, the bins between on the block grid
let { at, duration, ...rest } = o, sr = this.sampleRate, bs = audio.BLOCK_SIZE, T = this.duration
at = parseTime(at); duration = parseTime(duration)
let t0 = at < 0 ? Math.max(0, T + at) : Math.min(at ?? 0, T), t1 = duration != null ? Math.min(T, t0 + duration) : T
let t = i => Math.min(t1, Math.max(t0, i * bs / sr)), nch = Array.isArray(rest.channel) && rest.channel.length
let from = blockAt(t0, sr, bs), to = blockAt(t1, sr, bs, Math.ceil)
// a method that reads the range in one pass (frames, each in its window) measures each bin's span of it
if (desc.spans) return this[name]({ ...rest, at: t0, duration: t1 - t0, spans: Array.from({ length: bins }, (_, i) => binAt(from, to, bins, i).map(t)) })
let v = await series(from, to, bins, nch, (a, b) => this[name]({ ...rest, at: t(a), duration: t(b) - t(a) }))
return v ?? this[name](opts)
}
// binned, a block stat reduces its own field, whatever its query reads
let need = desc.fields ?? (desc.block ? [name] : null)
if (bins != null && desc.block && desc.reduce && !need.includes(name)) need = [...need, name]
let { stats, ch, sr, from, to } = await queryRange(this, opts, need)
// Resolve channel selection once
let { chs, perCh } = resolveChannels(opts?.channel, ch)
let blockStats = stats[name], aggregate = desc.reduce
let reduce = (values, from, to) => aggregate(values, from, to, stats)
// Binned block stats: each channel's blocks reduced per bin, the channels averaged; a count (`count`: clipped samples)
// is every channel's, the channels added
if (bins != null && blockStats && aggregate) {
let reduce1 = c => binReduce(blockStats[c], from, to, bins, reduce)
if (perCh) return chs.map(reduce1)
if (chs.length === 1) return reduce1(chs[0])
let out = new Float32Array(bins)
for (let i = 0; i < bins; i++) {
let [a, b] = binAt(from, to, bins, i), sum = 0
for (let c of chs) sum += reduce(blockStats[c], a, b)
out[i] = desc.count ? sum : sum / chs.length
}
return out
}
// Derived stats — custom query
if (desc.query) {
let q = (a, b, op) => perCh ? chs.map(c => desc.query(stats, [c], a, b, sr, op)) : desc.query(stats, chs, a, b, sr, op)
if (bins == null) return q(from, to, opts)
return await series(from, to, bins, perCh && chs.length, (a, b) => q(a, b, o)) ?? q(from, to, opts)
}
// Raw block stats
if (!blockStats || !aggregate) throw new Error(`No block stat: '${name}'`)
// Scalar mode
if (perCh) return chs.map(c => reduce(blockStats[c], from, to))
if (chs.length === 1) return reduce(blockStats[chs[0]], from, to)
let vals = chs.map(c => reduce(blockStats[c], from, to))
return vals.reduce((a, b) => a + b, 0) / vals.length
}
/** The highest |sample| block stats hold over blocks [from, to) of channels `chs`, each channel's `dc` taken off first
* (peak, crest, db, a normalize's peak, the CLI's level as it plays) */
export function peakOf(stats, chs, from = 0, to = Infinity, dc) {
let v = 0
for (let c of chs) {
let mn = stats.min[c], mx = stats.max[c], d = dc?.[c] || 0
for (let i = from, e = Math.min(to, mn.length); i < e; i++) {
let a = Math.abs(mn[i] - d), b = Math.abs(mx[i] - d)
if (a > v) v = a
if (b > v) v = b
}
}
return v
}
// What counts as sound in block stats, for trim, shrink and silence: a level over a threshold, found from the blocks'
// floor when not given
export function autoThreshold(energies) {
let vals = energies.filter(e => e > 0)
if (!vals.length) return -40
vals.sort((a, b) => a - b)
let floor = vals[Math.floor(vals.length * 0.1)]
return Math.max(-80, Math.min(-20, 10 * Math.log10(floor) + 12))
}
/** Resolve dB threshold to linear. Found when db is null: 12 dB over the quietest tenth of the blocks (their floor),
* and 40 dB under their peak at most. Sound with no floor, a bell ringing on into the next strike, has a quietest tenth
* that is still sound: 12 dB over it read a tail at -22 dBFS as silence. */
export function resolveThreshold(stats, ch, from, to, db) {
if (db == null) {
let energies = [], peak = 0
for (let c = 0; c < ch; c++) for (let i = from; i < to; i++) {
energies.push(stats.energy[c][i])
peak = Math.max(peak, -stats.min[c][i], stats.max[c][i])
}
db = Math.min(autoThreshold(energies), 20 * Math.log10(peak || 1e-9) - 40)
}
return 10 ** (db / 20)
}
/** Check if block i is loud (any channel exceeds thresh). */
export let isLoud = (stats, i, ch, thresh) => {
for (let c = 0; c < ch; c++)
if (Math.max(Math.abs(stats.min[c][i]), Math.abs(stats.max[c][i])) > thresh) return true
return false
}