import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { CanvasPlot, drawLine, readTheme, type PointerInfo, type Scales, type Theme } from "./CanvasPlot.tsx"; import { detectSegment, frameLevels, smoothLog, spectrogram, type Analysis, type AnalysisSettings, type Segment } from "../analysis/analyze.ts"; import type { RecordingMeta } from "../storage/db.ts"; import { encodeWavFloat32 } from "../audio/wav.ts"; import { colorFor, db10, download, fmtDate, fmtHz, fmtSec, getAnalysis, getAudio, groupStyle, PRESET_LABELS, safeName } from "../model.ts"; import { magma } from "../colormap.ts"; interface Props { meta: RecordingMeta; all: RecordingMeta[]; settings: AnalysisSettings; onUpdate: (m: RecordingMeta) => void; onDelete: (m: RecordingMeta) => void; } const SMOOTHING: [string, number][] = [ ["none", 0], ["1/24 octave", 1 / 24], ["1/12 octave", 1 / 12], ["1/6 octave", 1 / 6], ["1/3 octave", 1 / 3], ]; let playCtx: AudioContext | null = null; let playing: AudioBufferSourceNode | null = null; function play(x: Float32Array, fs: number, a: number, b: number) { stopPlay(); playCtx ??= new AudioContext(); const s = Math.max(0, Math.floor(a * fs)); const e = Math.min(x.length, Math.ceil(b * fs)); const buf = playCtx.createBuffer(1, Math.max(1, e - s), fs); buf.copyToChannel(x.subarray(s, e) as Float32Array, 0); const src = playCtx.createBufferSource(); src.buffer = buf; src.connect(playCtx.destination); src.start(); playing = src; } function stopPlay() { try { playing?.stop(); } catch { /* already stopped */ } playing = null; } export function RecordingView({ meta, all, settings, onUpdate, onDelete }: Props) { const [x, setX] = useState(null); const [analysis, setAnalysis] = useState(null); const dur = meta.length / meta.sampleRate; const [view, setView] = useState<[number, number]>([0, dur]); const [seg, setSeg] = useState(meta.segment); const [smoothing, setSmoothing] = useState(1 / 12); const [notes, setNotes] = useState(meta.notes); const [label, setLabel] = useState(meta.label); useEffect(() => { let live = true; setX(null); setView([0, meta.length / meta.sampleRate]); setNotes(meta.notes); setLabel(meta.label); getAudio(meta.id).then((a) => live && setX(a)); return () => { live = false; stopPlay(); }; }, [meta.id, meta.length, meta.sampleRate, meta.notes, meta.label]); useEffect(() => setSeg(meta.segment), [meta.segment]); useEffect(() => { let live = true; setAnalysis(null); getAnalysis(meta, settings).then((a) => live && setAnalysis(a)); return () => { live = false; }; }, [meta, settings]); const fs = meta.sampleRate; const levels = useMemo(() => (x ? frameLevels(x, fs, 0.005) : null), [x, fs]); const spec = useMemo(() => (x ? spectrogram(x, fs) : null), [x, fs]); const specImage = useMemo(() => (spec ? spectrogramImage(spec) : null), [spec]); const commitSeg = (s: Segment | null) => { onUpdate({ ...meta, segment: s, segmentManual: true }); }; // ---------- shared time-axis interaction ---------- const drag = useRef<{ kind: "start" | "end" | "pan"; px0: number; view0: [number, number] } | null>(null); const edgeAt = (p: PointerInfo): "start" | "end" | null => { if (!seg) return null; if (Math.abs(p.px - p.scales.x(seg.start)) < 7) return "start"; if (Math.abs(p.px - p.scales.x(seg.end)) < 7) return "end"; return null; }; const clampView = (a: number, b: number): [number, number] => { const w = Math.min(dur, Math.max(b - a, 0.002)); let s = Math.max(0, a); if (s + w > dur) s = dur - w; return [s, s + w]; }; const timeHandlers = { onWheel: (p: PointerInfo, ev: WheelEvent) => { if (Math.abs(ev.deltaX) > Math.abs(ev.deltaY)) { const shift = (ev.deltaX / (p.scales.right - p.scales.left)) * (view[1] - view[0]); setView(clampView(view[0] + shift, view[1] + shift)); return; } const f = Math.exp(ev.deltaY * 0.0025); const t = Math.min(Math.max(p.xv, view[0]), view[1]); setView(clampView(t - (t - view[0]) * f, t + (view[1] - t) * f)); }, onPointer: (type: "down" | "move" | "up", p: PointerInfo) => { if (type === "down") { drag.current = { kind: edgeAt(p) ?? "pan", px0: p.px, view0: view }; } else if (type === "move" && drag.current) { const d = drag.current; if (d.kind === "pan") { const dt = ((p.px - d.px0) / (p.scales.right - p.scales.left)) * (d.view0[1] - d.view0[0]); setView(clampView(d.view0[0] - dt, d.view0[1] - dt)); } else if (seg) { const t = Math.min(Math.max(p.xv, 0), dur); setSeg(d.kind === "start" ? { start: Math.min(t, seg.end - 0.005), end: seg.end } : { start: seg.start, end: Math.max(t, seg.start + 0.005) }); } } else if (type === "up") { if (drag.current && drag.current.kind !== "pan" && seg) commitSeg(seg); drag.current = null; } }, onDoubleClick: () => setView([0, dur]), cursor: (p: PointerInfo) => (edgeAt(p) ? "ew-resize" : "grab"), }; const drawSeg = useCallback( (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => { if (!seg) return; const a = s.x(seg.start); const b = s.x(seg.end); ctx.fillStyle = th.seg; ctx.fillRect(a, s.top, b - a, s.bottom - s.top); ctx.strokeStyle = th.ink2; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.moveTo(a, s.top); ctx.lineTo(a, s.bottom); ctx.moveTo(b, s.top); ctx.lineTo(b, s.bottom); ctx.stroke(); }, [seg], ); const { slot } = groupStyle(meta.label, all); const mainColor = (th: Theme) => colorFor(slot, th.series, th.ink2); const levelRange = useMemo<[number, number]>(() => { if (!levels) return [-100, 0]; const dbs = Array.from(levels.power, (p) => db10(p)).sort((a, b) => a - b); const lo = dbs[Math.floor(dbs.length * 0.01)] ?? -100; return [Math.max(-140, Math.floor((lo - 6) / 10) * 10), 0]; }, [levels]); const drawLevel = useCallback( (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => { drawSeg(ctx, s, th); if (!levels) return; const { frameSec, power } = levels; const i0 = Math.max(0, Math.floor(view[0] / frameSec) - 1); const i1 = Math.min(power.length, Math.ceil(view[1] / frameSec) + 1); const step = Math.max(1, Math.floor((i1 - i0) / ((s.right - s.left) * 2))); const xs: number[] = []; const ys: number[] = []; for (let i = i0; i < i1; i += step) { let m = 0; for (let j = i; j < Math.min(i + step, i1); j++) m = Math.max(m, power[j]); xs.push((i + step / 2) * frameSec); ys.push(db10(m)); } drawLine(ctx, s, xs, ys, mainColor(th), 1.5); }, // eslint-disable-next-line react-hooks/exhaustive-deps [levels, view, drawSeg, slot], ); const waveMax = useMemo(() => { if (!x) return 1; let m = 0; for (let i = 0; i < x.length; i++) m = Math.max(m, Math.abs(x[i])); return Math.max(m * 1.05, 1e-4); }, [x]); const drawWave = useCallback( (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => { drawSeg(ctx, s, th); if (!x) return; const color = mainColor(th); const a = Math.max(0, Math.floor(view[0] * fs)); const b = Math.min(x.length, Math.ceil(view[1] * fs)); const px = s.right - s.left; const perPx = (b - a) / px; if (perPx < 2) { const xs: number[] = []; const ys: number[] = []; for (let i = Math.max(0, a - 1); i < Math.min(x.length, b + 1); i++) { xs.push(i / fs); ys.push(x[i]); } drawLine(ctx, s, xs, ys, color, 1.5); if (perPx < 0.15) { ctx.fillStyle = color; for (let i = 0; i < xs.length; i++) ctx.fillRect(s.x(xs[i]) - 1.5, s.y(ys[i]) - 1.5, 3, 3); } return; } ctx.fillStyle = color; for (let c = 0; c < px; c++) { const i0 = a + Math.floor(c * perPx); const i1 = Math.min(b, a + Math.floor((c + 1) * perPx)); let lo = Infinity; let hi = -Infinity; for (let i = i0; i < i1; i++) { const v = x[i]; if (v < lo) lo = v; if (v > hi) hi = v; } if (lo > hi) continue; const y0 = s.y(hi); const y1 = s.y(lo); ctx.fillRect(s.left + c, y0, 1, Math.max(1, y1 - y0)); } }, // eslint-disable-next-line react-hooks/exhaustive-deps [x, view, fs, drawSeg, slot], ); const drawSpec = useCallback( (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => { if (spec && specImage) { const c0 = (view[0] - spec.t0) / spec.dt; const c1 = (view[1] - spec.t0) / spec.dt; ctx.imageSmoothingEnabled = c1 - c0 < s.right - s.left; const sx0 = Math.max(0, c0); const sx1 = Math.min(spec.cols, c1); const dx0 = s.x(spec.t0 + sx0 * spec.dt); const dx1 = s.x(spec.t0 + sx1 * spec.dt); if (sx1 > sx0) ctx.drawImage(specImage, sx0, 0, sx1 - sx0, spec.bins, dx0, s.top, dx1 - dx0, s.bottom - s.top); } if (seg) { ctx.strokeStyle = th.surface; ctx.lineWidth = 1.5; ctx.setLineDash([4, 3]); ctx.beginPath(); for (const t of [seg.start, seg.end]) { ctx.moveTo(s.x(t), s.top); ctx.lineTo(s.x(t), s.bottom); } ctx.stroke(); ctx.setLineDash([]); } }, [spec, specImage, view, seg], ); // ---------- spectrum ---------- const fLo = 20; const fHi = fs / 2; const specLines = useMemo(() => { if (!analysis) return null; const tear = smoothLog(analysis.freqs, analysis.esd, fLo, fHi, smoothing); const bg = analysis.noiseEsd ? smoothLog(analysis.freqs, analysis.noiseEsd, fLo, fHi, smoothing) : null; return { f: tear.f, tear: tear.v.map(db10), bg: bg ? bg.v.map(db10) : null }; }, [analysis, smoothing, fHi]); const specRange = useMemo<[number, number]>(() => { if (!specLines) return [-160, -60]; const top = Math.max(...specLines.tear.filter(Number.isFinite)); return [Math.floor((top - 80) / 10) * 10, Math.ceil((top + 3) / 10) * 10]; }, [specLines]); const drawSpectrum = useCallback( (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => { if (!specLines) return; // grey out what lies outside the analysis band ctx.fillStyle = th.seg; const bl = s.x(settings.bandLow); const bh = s.x(Math.min(settings.bandHigh, fHi)); ctx.fillRect(s.left, s.top, bl - s.left, s.bottom - s.top); ctx.fillRect(bh, s.top, s.right - bh, s.bottom - s.top); if (specLines.bg) drawLine(ctx, s, specLines.f, specLines.bg, th.muted, 2, [5, 4]); drawLine(ctx, s, specLines.f, specLines.tear, mainColor(th), 2); }, // eslint-disable-next-line react-hooks/exhaustive-deps [specLines, settings, fHi, slot], ); const specHover = (p: PointerInfo) => { if (!specLines) return null; let best = 0; for (let i = 1; i < specLines.f.length; i++) if (Math.abs(Math.log(specLines.f[i] / p.xv)) < Math.abs(Math.log(specLines.f[best] / p.xv))) best = i; const lines = [fmtHz(specLines.f[best]), `tear: ${specLines.tear[best].toFixed(1)} dB`]; if (specLines.bg) lines.push(`background: ${specLines.bg[best].toFixed(1)} dB`); return { lines, x: specLines.f[best], y: specLines.tear[best] }; }; const timeHover = (p: PointerInfo) => { const lines = [`${p.xv.toFixed(p.xv < 10 ? 3 : 2)} s`]; if (levels) { const i = Math.floor(p.xv / levels.frameSec); if (i >= 0 && i < levels.power.length) lines.push(`level: ${db10(levels.power[i]).toFixed(1)} dBFS (5 ms RMS)`); } return { lines }; }; // ---------- actions ---------- const saveNotes = () => notes !== meta.notes && onUpdate({ ...meta, notes }); const saveLabel = (l: string) => { setLabel(l); if (l.trim() && l !== meta.label) onUpdate({ ...meta, label: l.trim() }); }; const autoDetect = () => { if (!x) return; const s = detectSegment(x, fs); onUpdate({ ...meta, segment: s, segmentManual: false }); }; const exportWav = () => { if (!x) return; const d = new Date(meta.createdAt).toISOString().replace(/[:]/g, "-").slice(0, 19); download(encodeWavFloat32(x, fs), `${d}_${safeName(meta.label)}_${meta.id.slice(0, 6)}.wav`); }; const a = analysis; const warnings: string[] = []; if (!seg) warnings.push("No tear was found automatically. Zoom so the tear fills the view and press “Use visible range as tear”."); if (a && a.nearClip > 0) warnings.push(`${a.nearClip} samples in the tear are at or near full scale (clipping). The energy is underestimated and the spectrum is distorted.`); if (a && !a.noiseEsd) warnings.push("Not enough quiet audio before or after the tear to estimate the background, so nothing was subtracted."); else if (a && a.snrDb < 10) warnings.push(`The tear is only ${a.snrDb.toFixed(1)} dB above the background in the analysis band; the energy estimate is sensitive to the background subtraction.`); if (seg && (seg.start < 0.05 || seg.end > dur - 0.05)) warnings.push("The tear touches the start or end of the recording and may be cut off."); return (
setLabel(e.target.value)} onBlur={(e) => saveLabel(e.target.value)} onKeyDown={(e) => e.key === "Enter" && (e.target as HTMLInputElement).blur()} aria-label="Speed label" /> {meta.source === "mic" ? "microphone" : meta.source} {fmtDate(meta.createdAt)} · {fmtSec(dur)} · {fs} Hz{meta.fileName ? ` · ${meta.fileName}` : ""}