// THE PLAY VIEW'S SOUND, as arithmetic (umtool/docs/knobs.md, "Play the cut"; // the engine is components/projects/review/playEngine/). Every clip's sound is // decoded (the bench's /api/report/audio: ffmpeg's decode of the window, so // the samples are the ones the build cuts) and scheduled back to back on ONE // AudioContext: each clip starts at its segment's first second on the cut's // clock and stops at its footage's last, sample-exact, and the whole view's // clock -- the rail, the tally, the stamps, the finale, a note's anchor -- is // that context's time mapped through the plan. These are the numbers: where // each clip's sound sits on the cut's clock, what its level does over it (the // crossfade's ramps, room's muted edges, the loudness gain, the clip's own // audio knobs, the mute mark, a locked edge's silence), and, from a cut second and a speed, when each // node starts, at what offset into its buffer, for how long, with which // gain breakpoints. Pure: no Web Audio, so it is unit-tested // (playSchedule.test.mjs) and the engine only applies it. // // CLOCKS: `t` is the cut's (Play's) second; `src` a source second; a name // ending in `Wall` is the listener's seconds from the moment playback starts // (cut seconds divided by the speed). import { MUTE_FADE } from "umtool-report-to-video/mute"; import { GAP_FADE, gappedLength, keptSpans, offsetIn } from "umtool-report-to-video/gaps"; import { ROOM } from "yt-dlp-transcript-common/lib/report/look.mjs"; /** Room's afade at a muted edge (the build's roomAudioFilter): the look's own number. */ export const ROOM_FADE = ROOM.fade; const fin = (v) => typeof v === "number" && Number.isFinite(v); const r6 = (v) => Math.round(v * 1e6) / 1e6; /** * A piecewise-linear level, as [[t, g], ...] sorted by t (cut seconds); flat * before the first and after the last point. The product of several is * sampled at the union of their points -- exact for one ramp at a time, * within a few percent where two ramps overlap. * * @typedef {Array<[number, number]>} Envelope */ /** An envelope's level at t. */ export function levelAt(env, t) { if (!env.length) return 1; if (t <= env[0][0]) return env[0][1]; for (let i = 1; i < env.length; i += 1) { const [t1, g1] = env[i]; if (t <= t1) { const [t0, g0] = env[i - 1]; return t1 > t0 ? g0 + ((g1 - g0) * (t - t0)) / (t1 - t0) : g1; } } return env[env.length - 1][1]; } /** The product of envelopes, sampled at every point of each (clamped to [from, to]). */ export function multiply(envs, from, to) { const ts = new Set([from, to]); for (const e of envs) for (const [t] of e) if (t > from && t < to) ts.add(t); return [...ts].sort((a, b) => a - b).map((t) => [r6(t), r6(envs.reduce((g, e) => g * levelAt(e, t), 1))]); } /** A rise from 0 at `a` to 1 at `b` (a fade in), or a fall when `down`. */ const ramp = (a, b, down = false) => (b > a ? [[a, down ? 1 : 0], [b, down ? 0 : 1]] : [[a, down ? 0 : 1]]); /** * Where each clip's sound sits on the cut's clock and what its level does. * * from / to the cut seconds it sounds over: its segment's start to its * source's end (the encode's last part-frame and a carrying * clip's hold are silent, as the build pads them) * src the source second at `from` (an `audio.offset` reads the * sound that much earlier: later against the picture) * env its level: the crossfades (a linear ramp over each * overlap, acrossfade's `tri`), room's muted head and * tail, the clip's fadeIn / fadeOut, the mute mark * gain a constant multiplier: the loudness gain and the clip's * own `audio.gain`, in dB, as amplitude * * A clip with GAPS (`clip.gaps`, gaps.mjs) is several spans, one per piece * that plays, abutting on the cut's clock: each reads its own source seconds, * with the build's GAP_FADE out at the end of the piece before a join and in * at the start of the piece after it -- a jump in the sound with no click. * * @param {{ items: Array<{ id: string, start: number, end: number, clip: null | { * sourceFrom: number, sourceTo: number, playEnd: number, hold: number, * sound?: [number, number], gainDb?: number, audio?: Record, muteFrom?: number, soundFrom?: number, * gaps?: Array<{ from: number, to: number }> } }> }} plan * `piece` is the span's place among its clip's (0 for a clip with no gaps): * what its decode is looked up by (decodesOf). * * @returns {Array<{ id: string, index: number, piece: number, from: number, to: number, src: number, srcTo: number, env: Envelope, gain: number }>} */ export function audioSpans(plan) { const items = plan?.items ?? []; const out = []; items.forEach((it, i) => { const c = it.clip; if (!c || !(c.playEnd > it.start)) return; const from = it.start; // Its source's length: the encode pads a segment to whole frames with SILENCE (apad), and a hold is silent too. // Less its gaps: they never play. const gaps = c.gaps?.length ? c.gaps : null; const to = Math.min(c.playEnd, it.start + Math.max(0, gaps ? gappedLength(c.sourceFrom, c.sourceTo, gaps) : c.sourceTo - c.sourceFrom)); if (!(to > from)) return; const prev = items[i - 1]; const next = items[i + 1]; const dIn = prev ? Math.max(0, prev.end - it.start) : 0; const dOut = next ? Math.max(0, it.end - next.start) : 0; const envs = []; // The crossfades: up over the overlap with the clip before, down over the one after (on the segment, hold included). if (dIn > 0) envs.push(ramp(from, from + dIn)); if (dOut > 0) envs.push(ramp(it.end - dOut, it.end, true)); const at = (src) => from + offsetIn(src, c.sourceFrom, gaps); // Room: heard over [sound[0], sound[1]] only -- a fade in ending at its start, a fade out from its end. if (Array.isArray(c.sound) && fin(c.sound[0]) && fin(c.sound[1])) { const [sa, sb] = c.sound; if (sa > c.sourceFrom + 1e-6) envs.push(ramp(at(sa) - ROOM_FADE, at(sa))); if (sb < c.sourceTo - 1e-6) envs.push(ramp(at(sb), at(sb) + ROOM_FADE, true)); } // The clip's own fades, at its segment's edges (clip-audio.mjs). const a = c.audio ?? {}; if (fin(a.fadeIn) && a.fadeIn > 0) envs.push(ramp(from, from + Math.min(a.fadeIn, to - from))); if (fin(a.fadeOut) && a.fadeOut > 0) envs.push(ramp(to - Math.min(a.fadeOut, to - from), to, true)); // The mute mark: silent from it on, the fade ending AT it. // A locked end is one too (the route sends the build's rule, mute.mjs soundOnSegment). if (fin(c.muteFrom)) envs.push(ramp(at(/** @type {number} */ (c.muteFrom)) - MUTE_FADE, at(/** @type {number} */ (c.muteFrom)), true)); // A locked start: silent before it, the fade rising FROM it (the build's soundFromAudioFilter). if (fin(c.soundFrom)) envs.push(ramp(at(/** @type {number} */ (c.soundFrom)), at(/** @type {number} */ (c.soundFrom)) + MUTE_FADE)); const db = (fin(c.gainDb) ? /** @type {number} */ (c.gainDb) : 0) + (fin(a.gain) ? a.gain : 0); const shift = fin(a.offset) ? a.offset / 1000 : 0; if (!gaps) { out.push({ id: it.id, index: i, piece: 0, from, to, src: r6(c.sourceFrom - shift), srcTo: r6(c.sourceFrom - shift + (to - from)), env: multiply(envs, from, to), gain: r6(10 ** (db / 20)), }); return; } // One span per piece that plays; the joins faded out and in (the build's gapFilterParts). const pieces = keptSpans(c.sourceFrom, c.sourceTo, gaps) .map((p) => ({ src: p.from, a: at(p.from), b: Math.min(to, at(p.to)) })) .filter((p) => p.b > p.a + 1e-6); pieces.forEach((p, k) => { const d = Math.min(GAP_FADE, (p.b - p.a) / 2); const joins = []; if (k > 0) joins.push(ramp(p.a, p.a + d)); if (k < pieces.length - 1) joins.push(ramp(p.b - d, p.b, true)); out.push({ id: it.id, index: i, piece: k, from: r6(p.a), to: r6(p.b), src: r6(p.src - shift), srcTo: r6(p.src - shift + (p.b - p.a)), env: multiply([...envs, ...joins], p.a, p.b), gain: r6(10 ** (db / 20)), }); }); }); return out; } /** * What to start, from cut second `t` at `rate`: for each span not yet over, * its delay from the moment playback starts (`atWall`), the source second * its buffer is read from, how long it plays (`durWall`), and its envelope * on the same wall clock (the first point is the level AT its start, so a * seek into a ramp starts mid-ramp). Hard cuts abut exactly: one span's * `atWall + durWall` is the next one's `atWall`. * * @param {ReturnType} spans * @param {number} t * @param {number} [rate] * @param {{ until?: number }} [opts] only spans starting before this cut second */ export function scheduleFrom(spans, t, rate = 1, { until = Infinity } = {}) { const r = rate > 0 ? rate : 1; const out = []; for (const s of spans) { if (s.to <= t + 1e-9 || s.from >= until) continue; const begin = Math.max(t, s.from); const env = multiply([s.env], begin, s.to).map(([x, g]) => [r6((x - t) / r), g]); out.push({ id: s.id, index: s.index, piece: s.piece ?? 0, atWall: r6((begin - t) / r), durWall: r6((s.to - begin) / r), src: r6(s.src + (begin - s.from)), srcTo: s.srcTo, env, gain: s.gain, }); } return out; } /** The cut second at context time `now`, for a playback started at `ctxStart` from cut second `t0`. */ export const cutTimeAtCtx = (t0, ctxStart, now, rate = 1) => t0 + Math.max(0, now - ctxStart) * (rate > 0 ? rate : 1); /** * One span's decode (the engine's are decodesOf, below: per kept piece, and * found by what they cover). Which span of a clip's source to decode for Play: its whole sound * (offset included) and a little either side, so a seek and a crossfade read * inside one buffer. Bounded: a clip is seconds, never a recording. * * @param {{ src: number, srcTo: number }} span * @param {{ pad?: number, max?: number }} [opts] */ export function decodeSpanOf(span, { pad = 0.25, max = 120 } = {}) { const from = Math.max(0, span.src - pad); return { from: Math.round(from * 1000) / 1000, to: Math.round(Math.min(span.srcTo + pad, from + max) * 1000) / 1000 }; } /** * How far the render may move a clip's OUTER edge from the manifest's (s): * render.snapWindow's default (1.6, snap.mjs SNAP_DEFAULTS) and the snap's * tail (0.18), rounded up. While the render's edges are being measured * (useRenderCuts `measuring`) a clip's sound is decoded this much wider at * its two ends, so the decode on the manifest's edges is the one the render's * play from too -- found by what it covers (bankTrim.mjs coveringSlot), not * asked for again. A cut that snaps further (a wider `snapWindow`, a montage's * phrase cut) asks again for what it does not cover. */ export const EDGE_SLACK = 2; /** Kept pieces of a gapped clip less than this far apart (source s) are decoded as one. */ export const MERGE_GAP = 1; const msDown = (v) => Math.floor(v * 1000 + 1e-6) / 1000; const msUp = (v) => Math.ceil(v * 1000 - 1e-6) / 1000; /** * WHAT TO DECODE FOR ONE CLIP'S SOUND: for each of its spans (audioSpans, one * per kept piece, in order), the source seconds its node reads (`need`) and * the span to ask the audio route for when no decode held covers them * (`ask`). A clip with gaps is decoded PER PIECE -- never its gaps: a clip * that keeps 25 s of an 88 s span decodes 25 s and the pads -- except that * pieces under `merge` apart share one decode (one request, not several * for a few hundred ms saved). Each decode is the pieces' sound and `pad` * either side (a seek and a crossfade read inside it), the clip's outer two * edges `slack` more (EDGE_SLACK while the render's edges are measured, else * 0); all of it inside the cached window (`within`: the route clamps to it * too), at most `max` long. * * @param {Array<{ src: number, srcTo: number }>} spans the clip's, in order * @param {{ pad?: number, slack?: number, merge?: number, max?: number, within?: { from: number, to: number } | null }} [opts] * @returns {Array<{ need: { from: number, to: number }, ask: { from: number, to: number } }>} one per span */ export function decodesOf(spans, { pad = 0.25, slack = 0, merge = MERGE_GAP, max = 120, within = null } = {}) { const lo = within && fin(within.from) ? within.from : 0; const hi = within && fin(within.to) ? within.to : Infinity; const clamp = (v) => Math.min(hi, Math.max(lo, v)); /** @type {number[][]} */ const groups = []; spans.forEach((s, k) => { const g = groups[groups.length - 1]; if (g && s.src - spans[g[g.length - 1]].srcTo < merge) g.push(k); else groups.push([k]); }); const out = new Array(spans.length); groups.forEach((g, n) => { const a = spans[g[0]]; const b = spans[g[g.length - 1]]; const from = msDown(clamp(Math.max(0, a.src - pad - (n === 0 ? slack : 0)))); const to = msUp(Math.min(clamp(b.srcTo + pad + (n === groups.length - 1 ? slack : 0)), from + max)); for (const k of g) { const s = spans[k]; const nf = clamp(s.src); out[k] = { need: { from: r6(nf), to: r6(Math.max(nf, clamp(s.srcTo))) }, ask: { from, to } }; } }); return out; }