/ simulated_instruments / cymbal2
Sign in
simulated_instruments / cymbal2
cymbal2 / webapp / src / hooks / useRenderer.ts
120 lines · 3.8 KBBlameHistoryRaw
1// Hook owning the render worker. Unlike the sibling cymbal app there is no
2// debounced auto-preview: a cymbal2 render is a full time-domain integration
3// and takes from under a minute (preview) to minutes (full quality) in the
4// browser, so renders are explicit. A request in flight can be cancelled,
5// which tears the worker down and builds a fresh one.
7import { useCallback, useEffect, useRef, useState } from 'react';
8import type { Cymbal2Params } from '../params';
9import type { MFile } from '../mfiles';
10import type { ErrorMessage, ProgressMessage, RenderResponse } from '../worker/renderWorker';
12export interface RenderError {
13 message: string;
14 file?: string;
15 line?: number;
18export interface RenderState {
19 result: RenderResponse | null;
20 error: RenderError | null;
21 busy: boolean;
22 stage: string;
23 elapsedS: number;
26export function useRenderer(params: Cymbal2Params, mfiles: MFile[]) {
27 const workerRef = useRef<Worker | null>(null);
28 const nextId = useRef(1);
29 const inFlight = useRef<number | null>(null);
30 const startedAt = useRef(0);
31 const [state, setState] = useState<RenderState>({
32 result: null,
33 error: null,
34 busy: false,
35 stage: '',
36 elapsedS: 0,
37 });
39 const attachHandlers = useCallback((worker: Worker) => {
40 worker.onmessage = (ev: MessageEvent<RenderResponse | ProgressMessage | ErrorMessage>) => {
41 const msg = ev.data;
42 if (msg.type === 'progress') {
43 const pct = msg.stage === 'integrate' && msg.frac > 0.1
44 ? ` ${Math.round(((msg.frac - 0.1) / 0.85) * 100)}%`
45 : '';
46 setState((s) => ({ ...s, stage: msg.stage + pct }));
47 return;
48 }
49 inFlight.current = null;
50 if (msg.type === 'error') {
51 // A failed render leaves nothing playable: the previous result is
52 // dropped, so Play and Download cannot hand back audio that no
53 // longer corresponds to the code or parameters on screen.
54 setState((s) => ({
55 ...s,
56 result: null,
57 error: { message: msg.message, file: msg.file, line: msg.line },
58 busy: false,
59 stage: '',
60 }));
61 return;
62 }
63 setState((s) => ({ ...s, result: msg, error: null, busy: false, stage: '' }));
64 };
65 }, []);
67 const makeWorker = useCallback(() => {
68 const worker = new Worker(new URL('../worker/renderWorker.ts', import.meta.url), {
69 type: 'module',
70 });
71 attachHandlers(worker);
72 workerRef.current = worker;
73 return worker;
74 }, [attachHandlers]);
76 useEffect(() => {
77 const worker = makeWorker();
78 return () => {
79 worker.terminate();
80 workerRef.current = null;
81 inFlight.current = null;
82 };
83 }, [makeWorker]);
85 // elapsed-time ticker while a render is in flight
86 useEffect(() => {
87 if (!state.busy) return;
88 const t = setInterval(
89 () => setState((s) => ({ ...s, elapsedS: (performance.now() - startedAt.current) / 1000 })),
90 250,
91 );
92 return () => clearInterval(t);
93 }, [state.busy]);
95 const render = useCallback(
96 (quality: 'preview' | 'full') => {
97 const worker = workerRef.current;
98 if (!worker || inFlight.current !== null) return;
99 const id = nextId.current++;
100 inFlight.current = id;
101 startedAt.current = performance.now();
102 setState((s) => ({ ...s, busy: true, stage: 'starting', elapsedS: 0 }));
103 worker.postMessage({ type: 'render', id, params, mfiles, quality });
104 },
105 [params, mfiles],
106 );
108 const cancel = useCallback(() => {
109 const worker = workerRef.current;
110 if (worker) worker.terminate();
111 inFlight.current = null;
112 makeWorker();
113 setState((s) => ({ ...s, busy: false, stage: '', elapsedS: 0 }));
114 }, [makeWorker]);
116 const renderPreview = useCallback(() => render('preview'), [render]);
117 const renderFull = useCallback(() => render('full'), [render]);
119 return { ...state, renderPreview, renderFull, cancel };
↑↓ move↵openescclose