/ proof-of-concept / instrawave-compose
Sign in
proof-of-concept / instrawave-compose
instrawave-compose / src / store.ts
184 lines · 7.1 KBBlameHistoryRaw
1/**
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.
10 */
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 volume: number; // playback level, applied at mix time; never renders
28 clips: TrainClip[];
29 loose: TrainHit[]; // hits learned from takes; they belong to no clip
31export interface TakeHit {
32 id: string; t: number; voiceId: string; gain: number;
33 peakDb: number; vec: number[] | null; // null for hand-added hits
34 s0: number; s1: number; // sample bounds in the take clip; -1 if hand-added
37/** The pooled training set a voice contributes to classification. */
38export function trainPool(v: Voice): TrainHit[] {
39 return [...v.clips.flatMap((c) => c.hits), ...v.loose];
42const KEY = 'instrawave-compose/v2';
43const KEY_V1 = 'instrawave-compose/v1';
44const KEY_IW = 'instrawave-compose/iw';
45const KEY_TAKE = 'instrawave-compose/take';
46const KEY_UI = 'instrawave-compose/ui';
48function read<T>(key: string): T | null {
49 try {
50 const raw = localStorage.getItem(key);
51 return raw ? (JSON.parse(raw) as T) : null;
52 } catch {
53 return null;
54 }
57export function loadVoices(): Voice[] {
58 const doc = read<{ voices: Voice[] }>(KEY);
59 if (doc) {
60 for (const v of doc.voices) v.volume ??= 1; // pre-volume stores
61 return doc.voices;
62 }
63 // v1 stored a flat training list and a synth preset per voice.
64 const v1 = read<{ voices: { id: string; name: string; color: string; preset: string; train: TrainHit[] }[] }>(KEY_V1);
65 if (v1) {
66 const voices: Voice[] = v1.voices.map((v) => ({
67 id: v.id, name: v.name, color: v.color,
68 binding: { kind: 'synth', preset: v.preset as ('kick' | 'snare' | 'hat' | 'tom') },
69 volume: 1,
70 clips: [], loose: v.train,
71 }));
72 localStorage.setItem(KEY, JSON.stringify({ voices }));
73 localStorage.removeItem(KEY_V1);
74 return voices;
75 }
76 return [];
79export function saveVoices(voices: Voice[]): void {
80 localStorage.setItem(KEY, JSON.stringify({ voices }));
83/** Per-instrument geometry and accuracy overrides. */
84export function loadIwOverrides(): Record<string, Record<string, number>> {
85 return read(KEY_IW) ?? {};
87export function saveIwOverrides(o: Record<string, Record<string, number>>): void {
88 localStorage.setItem(KEY_IW, JSON.stringify(o));
91export function loadTakeHits(): TakeHit[] | null {
92 return read(KEY_TAKE);
94export function saveTakeHits(hits: TakeHit[]): void {
95 localStorage.setItem(KEY_TAKE, JSON.stringify(hits));
98export interface UiState { takeSens: number; captureSens: number; }
99export function loadUi(): UiState {
100 return read(KEY_UI) ?? { takeSens: 0.6, captureSens: 0.6 };
102export function saveUi(ui: UiState): void {
103 localStorage.setItem(KEY_UI, JSON.stringify(ui));
106export function clearStore(): void {
107 for (const k of [KEY, KEY_IW, KEY_TAKE, KEY_UI]) localStorage.removeItem(k);
110// ---- bulk data in IndexedDB ---------------------------------------------------
112const STORES = ['clips', 'takes', 'bakes', 'bakemeta', 'renders'] as const;
114let dbPromise: Promise<IDBDatabase> | null = null;
115function db(): Promise<IDBDatabase> {
116 return (dbPromise ??= new Promise((resolve, reject) => {
117 const req = indexedDB.open('instrawave-compose', 3);
118 req.onupgradeneeded = () => {
119 for (const s of STORES) {
120 if (!req.result.objectStoreNames.contains(s)) req.result.createObjectStore(s);
121 }
122 };
123 req.onsuccess = () => resolve(req.result);
124 req.onerror = () => reject(req.error);
125 }));
128function op<T>(store: string, mode: IDBTransactionMode, fn: (s: IDBObjectStore) => IDBRequest<T>): Promise<T> {
129 return db().then((d) => new Promise<T>((resolve, reject) => {
130 const req = fn(d.transaction(store, mode).objectStore(store));
131 req.onsuccess = () => resolve(req.result);
132 req.onerror = () => reject(req.error);
133 }));
136export function putClipAudio(id: string, samples: Float32Array, sr: number): Promise<unknown> {
137 return op('clips', 'readwrite', (s) => s.put({ samples, sr }, id));
139export function getClipAudio(id: string): Promise<{ samples: Float32Array; sr: number } | null> {
140 return op<{ samples: Float32Array; sr: number } | undefined>('clips', 'readonly', (s) => s.get(id))
141 .then((r) => r ?? null);
143export function deleteClipAudio(id: string): Promise<unknown> {
144 return op('clips', 'readwrite', (s) => s.delete(id));
147export function putTakeAudio(samples: Float32Array, sr: number): Promise<unknown> {
148 return op('takes', 'readwrite', (s) => s.put({ samples, sr }, 'take'));
150export function getTakeAudio(): Promise<{ samples: Float32Array; sr: number } | null> {
151 return op<{ samples: Float32Array; sr: number } | undefined>('takes', 'readonly', (s) => s.get('take'))
152 .then((r) => r ?? null);
155/** Bake bytes and their key are separate stores so staleness can be
156 * checked without deserializing hundreds of MB. */
157export async function putBake(name: string, key: string, bytes: Uint8Array): Promise<void> {
158 await op('bakes', 'readwrite', (s) => s.put(bytes, name));
159 await op('bakemeta', 'readwrite', (s) => s.put(key, name));
161export function getBakeKey(name: string): Promise<string | null> {
162 return op<string | undefined>('bakemeta', 'readonly', (s) => s.get(name)).then((r) => r ?? null);
164export function getBakeBytes(name: string): Promise<Uint8Array | null> {
165 return op<Uint8Array | undefined>('bakes', 'readonly', (s) => s.get(name)).then((r) => r ?? null);
168/** A rendered instrument track at the mix rate, keyed by the instrument
169 * and stamped with the exact events, tuning, and bake key it was rendered
170 * from; a matching signature means the GPU has nothing to redo. */
171export function putRender(name: string, sig: string, data: Float32Array): Promise<unknown> {
172 return op('renders', 'readwrite', (s) => s.put({ sig, data }, name));
174export function getRender(name: string): Promise<{ sig: string; data: Float32Array } | null> {
175 return op<{ sig: string; data: Float32Array } | undefined>('renders', 'readonly', (s) => s.get(name))
176 .then((r) => r ?? null);
178export function deleteRender(name: string): Promise<unknown> {
179 return op('renders', 'readwrite', (s) => s.delete(name));
182export async function clearBulk(): Promise<void> {
183 for (const s of STORES) await op(s, 'readwrite', (st) => st.clear());
↑↓ move↵openescclose