/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / stream / piece.ts
133 lines · 4.9 KBCodeBlameHistory
75ca48aOverhaul playback: background-computed, buffered, one clockJeremy Magland 1// A composition played through the streaming system. The composition provides its layout, its
2// score (in the score worker, by id) and a view that draws from the score's data at the
3// playhead; this turns them into a Piece for the album shell: play, stop, seek, buffering status,
4// and author edits (live settings apply at once; others recompute the performance from the
5// current moment, with the same seed).
7import type { AudioEngine } from "../core/audio.ts";
8import type { Piece } from "../core/composition.ts";
9import type { ParamSpec, Params } from "../core/params.ts";
10import { randomSeed } from "../core/rng.ts";
11import type { FrameStore } from "./frames.ts";
12import type { Layout } from "./layout.ts";
13import { Performance } from "./performance.ts";
15export interface View {
16 /** Draw at piece time t from the score's data (null before the first play: a preview). */
17 draw(t: number, store: FrameStore | null, playing: boolean): void;
18 /** seconds of drawing data to keep before the playhead (trails, fading points) */
19 keep(P: Params): number;
20 readouts?(t: number, store: FrameStore | null): Record<string, string>;
21 dispose?(): void;
24export interface StreamDef {
25 id: string;
26 schema: ParamSpec[];
27 layout(P: Params): Layout;
28 /** length before the score knows its end */
29 estimateLength(P: Params): number;
30 view(el: HTMLElement, params: () => Params): View;
33const RESTART_DELAY = 400; // ms after the last non-live edit
35export function createStreamPiece(def: StreamDef, el: HTMLElement, params: () => Params): Piece {
36 const view = def.view(el, params);
37 const fixedKeys = def.schema.filter((s) => !s.live).map((s) => s.key);
38 const fixedKey = (P: Params) => JSON.stringify(fixedKeys.map((k) => P[k]));
40 let audio: AudioEngine | null = null;
41 let perf: Performance | null = null;
42 let perfKey = "";
43 let store: FrameStore | null = null; // what's drawn (kept after a stop)
44 let stoppedAt = 0;
45 let lastEnd: number | null = null;
46 let seed = 0;
47 let restartAt = 0;
48 let notice: string | null = null;
49 // drawing data is also trimmed on a timer: animation frames stop while the page is hidden
50 const trimTimer = window.setInterval(() => store?.trim(piece.now() - view.keep(params())), 1000);
52 function open(a: AudioEngine, offset: number, keepSeed: boolean) {
53 const P = params();
54 perf?.dispose();
55 audio = a;
56 if (!keepSeed || !seed) seed = (P.seed as number) > 0 ? Math.round(P.seed as number) : randomSeed();
57 perf = new Performance(a.ctx, a.input, def.id, P, seed, Math.max(0, offset), def.layout(P), def.estimateLength(P));
58 perfKey = fixedKey(P);
59 store = perf.store;
60 lastEnd = null;
61 notice = null;
62 restartAt = 0;
63 }
65 function stop() {
66 if (!perf) return;
67 stoppedAt = perf.time();
68 if (perf.endT !== null) lastEnd = perf.endT;
69 perf.dispose();
70 perf = null;
71 }
73 const piece: Piece = {
74 get playing() {
75 return perf !== null;
76 },
77 async start(a, offset) {
78 open(a, offset, false);
79 await perf!.ready;
80 },
81 stop,
82 seek(t) {
83 if (audio) open(audio, t, true);
84 },
85 draw() {
86 const P = params();
87 if (perf) {
88 if (perf.state === "error") {
89 notice = "something went wrong computing this piece; try play again";
90 stop();
91 } else if (perf.state === "ended") {
92 const end = perf.endT ?? perf.time();
93 stop();
94 stoppedAt = end;
95 piece.onEnded?.();
96 } else {
97 perf.update(P);
98 // a change to the performance itself: recompute from here, with the same seed
99 if (fixedKey(P) !== perfKey) {
100 const now = performance.now();
101 if (!restartAt) restartAt = now + RESTART_DELAY;
102 else if (now >= restartAt && audio) open(audio, perf.time(), true);
103 } else restartAt = 0;
104 }
105 }
106 const t = piece.now();
107 store?.trim(t - view.keep(P));
108 view.draw(t, store, perf?.state === "playing");
109 },
110 now: () => (perf ? perf.time() : stoppedAt),
111 length: () => perf?.endT ?? lastEnd ?? def.estimateLength(params()),
112 status: () => ({ buffering: perf !== null && (perf.state === "loading" || perf.state === "buffering"), fill: perf?.fill ?? 0 }),
113 notice: () => notice,
114 readouts() {
115 const t = piece.now();
116 return {
117 time: `${t.toFixed(1)} / ${piece.length().toFixed(1)} s`,
118 buffer: perf ? `${perf.state}, ${perf.ahead.toFixed(1)} s ahead, ${perf.rebuffers} pause${perf.rebuffers === 1 ? "" : "s"}` : "–",
119 "seed used": seed ? String(seed) : "–",
120 ...(store?.info(t) ?? {}),
121 ...(view.readouts?.(t, store) ?? {}),
122 };
123 },
124 dispose() {
125 stop();
126 window.clearInterval(trimTimer);
127 view.dispose?.();
128 el.replaceChildren();
129 },
130 };
131 if (import.meta.env.DEV) (globalThis as { __piece?: Piece }).__piece = piece; // for tests in the dev server
132 return piece;
↑↓ move↵openescclose