/ proof-of-concept / instrawave-compose
Sign in
proof-of-concept / instrawave-compose
instrawave-compose / src / store.ts
176 lines · 6.8 KBCodeBlameHistory
9f20d5bTuning audition, instrument geometry editor with 3D view, full browser persistenceJeremy Magland 2 * Persistence. Small structured state lives in localStorage: voices with
3 * their training-clip descriptions and cached features, per-instrument
4 * geometry overrides, the take's events, and UI knobs. Bulk audio and
5 * binary data live in IndexedDB: training-clip audio, the take's audio,
6 * and the bakes (the drum's is a couple of hundred MB, which is exactly
7 * why it is worth keeping). The stores can drift only in harmless
8 * directions: a clip whose audio is missing cannot be re-edited but keeps
9 * classifying, and a bake whose key no longer matches is ignored.
11import type { Binding } from './render/types.ts';
13export interface TrainHit { vec: number[]; peakDb: number; }
14export interface TrainClip {
15 id: string;
16 sr: number;
17 sens: number; // the sensitivity the onsets were detected with
18 onsets: number[]; // seconds
19 excluded: number[]; // indices into onsets
20 hits: TrainHit[]; // features of the included onsets, cached
22export interface Voice {
23 id: string;
24 name: string;
25 color: string;
26 binding: Binding;
27 clips: TrainClip[];
28 loose: TrainHit[]; // hits learned from takes; they belong to no clip
31 id: string; t: number; voiceId: string; gain: number;
32 peakDb: number; vec: number[] | null; // null for hand-added hits
33 s0: number; s1: number; // sample bounds in the take clip; -1 if hand-added
36/** The pooled training set a voice contributes to classification. */
37export function trainPool(v: Voice): TrainHit[] {
38 return [...v.clips.flatMap((c) => c.hits), ...v.loose];
41const KEY = 'instrawave-compose/v2';
42const KEY_V1 = 'instrawave-compose/v1';
9f20d5bTuning audition, instrument geometry editor with 3D view, full browser persistenceJeremy Magland 43const KEY_IW = 'instrawave-compose/iw';
44const KEY_TAKE = 'instrawave-compose/take';
45const KEY_UI = 'instrawave-compose/ui';
9f20d5bTuning audition, instrument geometry editor with 3D view, full browser persistenceJeremy Magland 47function read<T>(key: string): T | null {
9f20d5bTuning audition, instrument geometry editor with 3D view, full browser persistenceJeremy Magland 49 const raw = localStorage.getItem(key);
50 return raw ? (JSON.parse(raw) as T) : null;
51 } catch {
52 return null;
53 }
56export function loadVoices(): Voice[] {
57 const doc = read<{ voices: Voice[] }>(KEY);
58 if (doc) return doc.voices;
59 // v1 stored a flat training list and a synth preset per voice.
60 const v1 = read<{ voices: { id: string; name: string; color: string; preset: string; train: TrainHit[] }[] }>(KEY_V1);
61 if (v1) {
62 const voices: Voice[] = v1.voices.map((v) => ({
63 id: v.id, name: v.name, color: v.color,
64 binding: { kind: 'synth', preset: v.preset as ('kick' | 'snare' | 'hat' | 'tom') },
65 clips: [], loose: v.train,
66 }));
67 localStorage.setItem(KEY, JSON.stringify({ voices }));
68 localStorage.removeItem(KEY_V1);
69 return voices;
70 }
74export function saveVoices(voices: Voice[]): void {
75 localStorage.setItem(KEY, JSON.stringify({ voices }));
9f20d5bTuning audition, instrument geometry editor with 3D view, full browser persistenceJeremy Magland 78/** Per-instrument geometry and accuracy overrides. */
79export function loadIwOverrides(): Record<string, Record<string, number>> {
80 return read(KEY_IW) ?? {};
82export function saveIwOverrides(o: Record<string, Record<string, number>>): void {
83 localStorage.setItem(KEY_IW, JSON.stringify(o));
86export function loadTakeHits(): TakeHit[] | null {
87 return read(KEY_TAKE);
89export function saveTakeHits(hits: TakeHit[]): void {
90 localStorage.setItem(KEY_TAKE, JSON.stringify(hits));
93export interface UiState { takeSens: number; captureSens: number; }
94export function loadUi(): UiState {
95 return read(KEY_UI) ?? { takeSens: 0.6, captureSens: 0.6 };
97export function saveUi(ui: UiState): void {
98 localStorage.setItem(KEY_UI, JSON.stringify(ui));
9f20d5bTuning audition, instrument geometry editor with 3D view, full browser persistenceJeremy Magland 102 for (const k of [KEY, KEY_IW, KEY_TAKE, KEY_UI]) localStorage.removeItem(k);
9f20d5bTuning audition, instrument geometry editor with 3D view, full browser persistenceJeremy Magland 105// ---- bulk data in IndexedDB ---------------------------------------------------
838af43Per-instrument render cache in IndexedDB and .wav downloadJeremy Magland 107const STORES = ['clips', 'takes', 'bakes', 'bakemeta', 'renders'] as const;
109let dbPromise: Promise<IDBDatabase> | null = null;
110function db(): Promise<IDBDatabase> {
111 return (dbPromise ??= new Promise((resolve, reject) => {
838af43Per-instrument render cache in IndexedDB and .wav downloadJeremy Magland 112 const req = indexedDB.open('instrawave-compose', 3);
114 for (const s of STORES) {
115 if (!req.result.objectStoreNames.contains(s)) req.result.createObjectStore(s);
116 }
117 };
bd6f329Editable persistent trainings, multi-select exclusion, playback pulses, instrawave bindingsJeremy Magland 118 req.onsuccess = () => resolve(req.result);
119 req.onerror = () => reject(req.error);
120 }));
9f20d5bTuning audition, instrument geometry editor with 3D view, full browser persistenceJeremy Magland 123function op<T>(store: string, mode: IDBTransactionMode, fn: (s: IDBObjectStore) => IDBRequest<T>): Promise<T> {
bd6f329Editable persistent trainings, multi-select exclusion, playback pulses, instrawave bindingsJeremy Magland 124 return db().then((d) => new Promise<T>((resolve, reject) => {
9f20d5bTuning audition, instrument geometry editor with 3D view, full browser persistenceJeremy Magland 125 const req = fn(d.transaction(store, mode).objectStore(store));
bd6f329Editable persistent trainings, multi-select exclusion, playback pulses, instrawave bindingsJeremy Magland 126 req.onsuccess = () => resolve(req.result);
127 req.onerror = () => reject(req.error);
128 }));
131export function putClipAudio(id: string, samples: Float32Array, sr: number): Promise<unknown> {
9f20d5bTuning audition, instrument geometry editor with 3D view, full browser persistenceJeremy Magland 132 return op('clips', 'readwrite', (s) => s.put({ samples, sr }, id));
134export function getClipAudio(id: string): Promise<{ samples: Float32Array; sr: number } | null> {
9f20d5bTuning audition, instrument geometry editor with 3D view, full browser persistenceJeremy Magland 135 return op<{ samples: Float32Array; sr: number } | undefined>('clips', 'readonly', (s) => s.get(id))
138export function deleteClipAudio(id: string): Promise<unknown> {
9f20d5bTuning audition, instrument geometry editor with 3D view, full browser persistenceJeremy Magland 139 return op('clips', 'readwrite', (s) => s.delete(id));
142export function putTakeAudio(samples: Float32Array, sr: number): Promise<unknown> {
143 return op('takes', 'readwrite', (s) => s.put({ samples, sr }, 'take'));
145export function getTakeAudio(): Promise<{ samples: Float32Array; sr: number } | null> {
146 return op<{ samples: Float32Array; sr: number } | undefined>('takes', 'readonly', (s) => s.get('take'))
147 .then((r) => r ?? null);
150/** Bake bytes and their key are separate stores so staleness can be
151 * checked without deserializing hundreds of MB. */
152export async function putBake(name: string, key: string, bytes: Uint8Array): Promise<void> {
153 await op('bakes', 'readwrite', (s) => s.put(bytes, name));
154 await op('bakemeta', 'readwrite', (s) => s.put(key, name));
156export function getBakeKey(name: string): Promise<string | null> {
157 return op<string | undefined>('bakemeta', 'readonly', (s) => s.get(name)).then((r) => r ?? null);
159export function getBakeBytes(name: string): Promise<Uint8Array | null> {
160 return op<Uint8Array | undefined>('bakes', 'readonly', (s) => s.get(name)).then((r) => r ?? null);
838af43Per-instrument render cache in IndexedDB and .wav downloadJeremy Magland 163/** A rendered instrument track at the mix rate, keyed by the instrument
164 * and stamped with the exact events, tuning, and bake key it was rendered
165 * from; a matching signature means the GPU has nothing to redo. */
166export function putRender(name: string, sig: string, data: Float32Array): Promise<unknown> {
167 return op('renders', 'readwrite', (s) => s.put({ sig, data }, name));
169export function getRender(name: string): Promise<{ sig: string; data: Float32Array } | null> {
170 return op<{ sig: string; data: Float32Array } | undefined>('renders', 'readonly', (s) => s.get(name))
171 .then((r) => r ?? null);
9f20d5bTuning audition, instrument geometry editor with 3D view, full browser persistenceJeremy Magland 174export async function clearBulk(): Promise<void> {
175 for (const s of STORES) await op(s, 'readwrite', (st) => st.clear());
↑↓ move↵openescclose