// The energy hum, in the score: one held note of a sustained sound whose timbre follows the energy, // with a fade-in at the start and a fade-out that ends with the piece. Its overall level is the // output's live level (humLevel); the score sends the fades, the loudness-follow and the timbre. import type { Params } from "../../core/params.ts"; import { LIVE_TARGETS, targetRange, targetValue } from "../../instruments/sounds.ts"; import { log, pow } from "../../physics/dmath.ts"; import type { ScoreSink } from "../../stream/score.ts"; const CONTROL_DT = 0.05; // s of piece time between control updates export class HumScore { private started = false; private next = 0; private sent: Record = {}; private P: Params; private stem: number; private sink: ScoreSink; constructor(P: Params, stem: number, sink: ScoreSink) { this.P = P; this.stem = stem; this.sink = sink; } /** e: normalized energy at piece time t; end: piece time everything has faded (null until known). */ update(t: number, e: number, end: number | null) { const { P, sink, stem } = this; if (!sink.emitting || t < this.next) return; this.next = t + CONTROL_DT; if (!this.started) { this.started = true; sink.cmd(stem, { t, type: "gain", value: 0, tau: 0 }); sink.cmd(stem, { t, type: "noteOn", note: P.humPitch as number, vel: 1 }); } const peak = P.energyPeak as number; const rel = Math.max(0, Math.min(1, e / peak)); const e0 = Math.min(P.energyStart as number, 0.999 * peak); const colorBase = P.humColorMode === "log" ? Math.max(0, Math.min(1, log(Math.max(e, 1e-12) / e0) / log(peak / e0))) : rel; const fadeIn = P.humFadeIn as number, fadeOut = P.humFadeOut as number; const fade = Math.max(0, Math.min(1, fadeIn > 0 ? t / fadeIn : 1, end !== null && fadeOut > 0 ? (end - t) / fadeOut : 1)); const follow = P.humFollow as number; sink.cmd(stem, { t, type: "gain", value: fade * (1 - follow + follow * rel), tau: 0.08, normalize: P.humNormalize as boolean }); // timbre: the mapped settings, sent when they move noticeably const color = pow(colorBase, P.humColorCurve as number); const params: Record = {}; let changed = false; for (const i of [1, 2]) { const target = P[`humTarget${i}`] as string; if (target === "none" || !LIVE_TARGETS.includes(target)) continue; const from = P[`humFrom${i}`] as number, to = P[`humTo${i}`] as number; const v = targetValue(target, from + (to - from) * color, pow); if (!Number.isFinite(v)) continue; params[target] = v; if (this.sent[target] === undefined || Math.abs(v - this.sent[target]) > 0.002 * targetRange(target)) changed = true; } if (changed) { this.sent = params; sink.cmd(stem, { t, type: "params", params }); } } }