/** Main-thread side of the classifier worker: one call per take, a fresh * worker each time so a hung custom algorithm dies with its worker when * the next classification starts. */ import type { ClfRequest, ClfResponse } from './algo.worker.ts'; import type { Detection, TrainingArrays } from './types.ts'; let current: Worker | null = null; let nextId = 1; export function classifyInWorker( source: string, x: Float32Array, fs: number, training: TrainingArrays, ): Promise<{ detections: Detection[]; logs: string[] }> { current?.terminate(); const worker = new Worker(new URL('./algo.worker.ts', import.meta.url), { type: 'module' }); current = worker; const id = nextId++; const req: ClfRequest = { id, source, x, fs, training }; return new Promise((resolve, reject) => { worker.onmessage = (e: MessageEvent) => { if (e.data.id !== id) return; worker.terminate(); if (current === worker) current = null; if (e.data.ok && e.data.detections) resolve({ detections: e.data.detections, logs: e.data.logs }); else reject(new Error(e.data.error ?? 'classifier failed')); }; worker.onerror = (e) => { worker.terminate(); if (current === worker) current = null; reject(new Error(e.message || 'classifier worker failed')); }; worker.postMessage(req); }); }