// A composition played through the streaming system. The composition provides its layout, its // score (in the score worker, by id) and a view that draws from the score's data at the // playhead; this turns them into a Piece for the album shell: play, stop, seek, buffering status, // and author edits (live settings apply at once; others recompute the performance from the // current moment, with the same seed). import type { AudioEngine } from "../core/audio.ts"; import type { Piece } from "../core/composition.ts"; import type { ParamSpec, Params } from "../core/params.ts"; import { randomSeed } from "../core/rng.ts"; import type { FrameStore } from "./frames.ts"; import type { Layout } from "./layout.ts"; import { Performance } from "./performance.ts"; export interface View { /** Draw at piece time t from the score's data (null before the first play: a preview). */ draw(t: number, store: FrameStore | null, playing: boolean): void; /** seconds of drawing data to keep before the playhead (trails, fading points) */ keep(P: Params): number; readouts?(t: number, store: FrameStore | null): Record; dispose?(): void; } export interface StreamDef { id: string; schema: ParamSpec[]; layout(P: Params): Layout; /** length before the score knows its end */ estimateLength(P: Params): number; view(el: HTMLElement, params: () => Params): View; } const RESTART_DELAY = 400; // ms after the last non-live edit export function createStreamPiece(def: StreamDef, el: HTMLElement, params: () => Params): Piece { const view = def.view(el, params); const fixedKeys = def.schema.filter((s) => !s.live).map((s) => s.key); const fixedKey = (P: Params) => JSON.stringify(fixedKeys.map((k) => P[k])); let audio: AudioEngine | null = null; let perf: Performance | null = null; let perfKey = ""; let store: FrameStore | null = null; // what's drawn (kept after a stop) let stoppedAt = 0; let lastEnd: number | null = null; let seed = 0; let restartAt = 0; let notice: string | null = null; // drawing data is also trimmed on a timer: animation frames stop while the page is hidden const trimTimer = window.setInterval(() => store?.trim(piece.now() - view.keep(params())), 1000); function open(a: AudioEngine, offset: number, keepSeed: boolean) { const P = params(); perf?.dispose(); audio = a; if (!keepSeed || !seed) seed = (P.seed as number) > 0 ? Math.round(P.seed as number) : randomSeed(); perf = new Performance(a.ctx, a.input, def.id, P, seed, Math.max(0, offset), def.layout(P), def.estimateLength(P)); perfKey = fixedKey(P); store = perf.store; lastEnd = null; notice = null; restartAt = 0; } function stop() { if (!perf) return; stoppedAt = perf.time(); if (perf.endT !== null) lastEnd = perf.endT; perf.dispose(); perf = null; } const piece: Piece = { get playing() { return perf !== null; }, async start(a, offset) { open(a, offset, false); await perf!.ready; }, stop, seek(t) { if (audio) open(audio, t, true); }, draw() { const P = params(); if (perf) { if (perf.state === "error") { notice = "something went wrong computing this piece; try play again"; stop(); } else if (perf.state === "ended") { const end = perf.endT ?? perf.time(); stop(); stoppedAt = end; piece.onEnded?.(); } else { perf.update(P); // a change to the performance itself: recompute from here, with the same seed if (fixedKey(P) !== perfKey) { const now = performance.now(); if (!restartAt) restartAt = now + RESTART_DELAY; else if (now >= restartAt && audio) open(audio, perf.time(), true); } else restartAt = 0; } } const t = piece.now(); store?.trim(t - view.keep(P)); view.draw(t, store, perf?.state === "playing"); }, now: () => (perf ? perf.time() : stoppedAt), length: () => perf?.endT ?? lastEnd ?? def.estimateLength(params()), status: () => ({ buffering: perf !== null && (perf.state === "loading" || perf.state === "buffering"), fill: perf?.fill ?? 0 }), notice: () => notice, readouts() { const t = piece.now(); return { time: `${t.toFixed(1)} / ${piece.length().toFixed(1)} s`, buffer: perf ? `${perf.state}, ${perf.ahead.toFixed(1)} s ahead, ${perf.rebuffers} pause${perf.rebuffers === 1 ? "" : "s"}` : "–", "seed used": seed ? String(seed) : "–", ...(store?.info(t) ?? {}), ...(view.readouts?.(t, store) ?? {}), }; }, dispose() { stop(); window.clearInterval(trimTimer); view.dispose?.(); el.replaceChildren(); }, }; if (import.meta.env.DEV) (globalThis as { __piece?: Piece }).__piece = piece; // for tests in the dev server return piece; }