Select the tear on level, waveform or spectrogram; 10–20 kHz analysis band
- One analysis band (default 10–20 kHz) for energy, tear detection, level,
background and spectrum normalisation; the separate spectrum band is gone.
- Tear range and close-up merged: level, waveform and spectrogram share a
zoomable time axis and the range can be dragged on any of them.
- Optional zero-phase band-pass view of the waveform.
8 changed files+261−220
README.mdmodified+2−3View file
@@ -25,13 +25,12 @@ Open the printed localhost URL in Chrome. Everything runs in the browser; record
2525 ## What it does
2626
2727 - **Record**: a list of samples, each one tear at whatever speed you choose, sorted slowest first by measured tear duration. Add a new sample, re-record or delete one, and give it an optional name and notes. Capture is raw: Chrome's echo cancellation, noise suppression and auto gain are off, and samples come straight from the audio graph via an AudioWorklet at the mic's own sample rate (32-bit float, no compression). For each sample:
28- - **Tear range**: found automatically; drag across the level plot to mark it again, drag its edges, or type start/end times. Play the tear (with a moving playhead) or the whole recording.
28+ - **Tear range**: level in the analysis band, waveform (raw, or filtered to the analysis band) and spectrogram on one zoomable time axis. The range is found automatically; drag across any of the three plots to mark it again, drag its edges, or type start/end times. Play the tear (with a moving playhead) or the whole recording.
2929 - **Results**: duration, speed, energy, mean power, peak/clipping, level above background.
30- - **Close-up**: waveform and spectrogram, with zoom buttons, to look for individual clicks.
3130 - **Frequency makeup**: the tear's energy spectrum against the background.
3231 - **Compare**: all samples, coloured by tear duration (stronger = faster): energy vs tear duration, loudness (mean power) vs duration, spectra of all speeds overlaid (optionally shape only), a table and CSV export.
3332
34-Two frequency bands (set under Analysis settings): the **energy band**, default 15–20 kHz, is used for total energy, finding the tear, the level-over-time plot and the background comparison, because lower frequencies carry much more room and handling noise. The **spectrum band**, default 100 Hz–20 kHz, is the range over which spectra are shown and compared.
33+Analysis band (set under Analysis settings), default 10–20 kHz: used for total energy, finding the tear, the level plot, the optional filtered waveform, the background comparison and normalising spectra, because lower frequencies carry much more room and handling noise. Spectra are still drawn over the full range for context.
3534
3635 The “What this can tell you” tab in the app explains the method and its limits.
3736
scripts/check-analysis.tsmodified+12−2View file
@@ -1,5 +1,5 @@
11 // Sanity checks for the analysis, run with `npm test`.
2-import { analyze, detectSegment, DEFAULT_SETTINGS, energyBand, bandLevels, smoothLog } from "../src/analysis/analyze.ts";
2+import { analyze, detectSegment, DEFAULT_SETTINGS, energyBand, bandLevels, bandpass, smoothLog } from "../src/analysis/analyze.ts";
33 import { syntheticTear } from "../src/audio/synthetic.ts";
44 import { decodeWav, encodeWavFloat32 } from "../src/audio/wav.ts";
55
@@ -43,6 +43,16 @@ const fs = 48000;
4343 check("band level of white noise", Math.abs(mean / (p * 5 / 24) - 1) < 0.05, `${(mean / p).toFixed(4)} vs ${(5 / 24).toFixed(4)}`);
4444 }
4545
46+// Band-pass: a 15 kHz tone passes, a 1 kHz tone is removed
47+{
48+ const n = 48000;
49+ const tone = (f: number) => Float32Array.from({ length: n }, (_, i) => Math.sin((2 * Math.PI * f * i) / fs));
50+ const rms = (v: Float32Array) => Math.sqrt(v.slice(4800, -4800).reduce((a, x) => a + x * x, 0) / (v.length - 9600));
51+ const pass = rms(bandpass(tone(15000), fs, { lo: 10000, hi: 20000 })) / rms(tone(15000));
52+ const stop = rms(bandpass(tone(1000), fs, { lo: 10000, hi: 20000 })) / rms(tone(1000));
53+ check("band-pass keeps 15 kHz, removes 1 kHz", Math.abs(pass - 1) < 0.01 && stop < 1e-3, `pass ${pass.toFixed(4)}, stop ${stop.toExponential(1)}`);
54+}
55+
4656 // Synthetic tears: same clicks at different durations
4757 const results: { T: number; energyDb: number; shapeDb: number[] }[] = [];
4858 for (const T of [0.3, 1, 3, 10]) {
@@ -51,7 +61,7 @@ for (const T of [0.3, 1, 3, 10]) {
5161 check(`detect segment T=${T}`, !!seg && Math.abs(seg.start - 1) < 0.08 && Math.abs(seg.end - (1 + T)) < 0.08, seg ? `${seg.start.toFixed(3)}–${seg.end.toFixed(3)}` : "none");
5262 if (!seg) continue;
5363 const a = analyze(x, fs, seg, DEFAULT_SETTINGS);
54- const shape = smoothLog(a.freqs, a.netEsd.map((v) => v / a.shapeEnergy), 1000, 20000, 1 / 3).v.map((v) => 10 * Math.log10(v));
64+ const shape = smoothLog(a.freqs, a.netEsd.map((v) => v / a.energy), 1000, 20000, 1 / 3).v.map((v) => 10 * Math.log10(v));
5565 results.push({ T, energyDb: 10 * Math.log10(a.energy), shapeDb: shape });
5666 console.log(` T=${T}s energy=${(10 * Math.log10(a.energy)).toFixed(2)} dB snr=${a.snrDb.toFixed(1)} dB peak=${a.peakDbfs.toFixed(1)} dBFS`);
5767 }
src/App.tsxmodified+4−10View file
@@ -54,7 +54,7 @@ export function App() {
5454 storeSettings(s);
5555 };
5656
57- // Ranges found automatically follow the energy band: re-detect them when it changes.
57+ // Ranges found automatically follow the analysis band: re-detect them when it changes.
5858 // Ranges set by hand are left alone.
5959 const { energyLow, energyHigh } = settings;
6060 useEffect(() => {
@@ -328,22 +328,16 @@ function SettingsPanel({ settings, setSettings }: { settings: AnalysisSettings;
328328 return (
329329 <div className="settings card">
330330 <div className="settings-row">
331- <b>Energy band</b>
331+ <b>Analysis band</b>
332332 {field("energyLow", "from", "Hz")}
333333 {field("energyHigh", "to", "Hz")}
334- <span className="muted small">Used for total energy, finding the tear, the level-over-time plot and the background comparison.</span>
335- </div>
336- <div className="settings-row">
337- <b>Spectrum band</b>
338- {field("shapeLow", "from", "Hz")}
339- {field("shapeHigh", "to", "Hz")}
340- <span className="muted small">The frequency range shown when comparing spectra.</span>
334+ <span className="muted small">Used for total energy, finding the tear, the level plot, the filtered waveform and the background comparison.</span>
341335 </div>
342336 <div className="settings-row">
343337 {field("sheetLengthIn", "Tear length", "in")}
344338 <button
345339 className="primary"
346- disabled={!changed || d.energyHigh <= d.energyLow || d.shapeHigh <= d.shapeLow || d.sheetLengthIn <= 0}
340+ disabled={!changed || d.energyHigh <= d.energyLow || d.sheetLengthIn <= 0}
347341 onClick={() => setSettings(d)}
348342 >
349343 Apply
src/analysis/analyze.tsmodified+42−15View file
@@ -6,21 +6,17 @@ export interface Segment {
66 }
77
88 export interface AnalysisSettings {
9- // Energy band: total energy, tear detection, level over time and the background comparison.
10- // High frequencies, where the tear stands far above room and handling noise.
9+ // Analysis band: total energy, tear detection, level over time, the filtered waveform, the
10+ // background comparison and spectrum normalisation. High frequencies, where the tear stands
11+ // far above room and handling noise.
1112 energyLow: number; // Hz
1213 energyHigh: number; // Hz
13- // Spectrum band: the frequency range over which spectra are shown and compared.
14- shapeLow: number; // Hz
15- shapeHigh: number; // Hz
1614 sheetLengthIn: number; // length of the tear, inches
1715 }
1816
1917 export const DEFAULT_SETTINGS: AnalysisSettings = {
20- energyLow: 15000,
18+ energyLow: 10000,
2119 energyHigh: 20000,
22- shapeLow: 100,
23- shapeHigh: 20000,
2420 sheetLengthIn: 11,
2521 };
2622
@@ -206,14 +202,13 @@ export interface Analysis {
206202 noiseEsd: Float64Array | null; // background PSD × segment duration (what background alone would contribute)
207203 netEsd: Float64Array; // max(esd - noiseEsd, 0)
208204 noiseSeconds: number; // how much background audio the noise estimate is based on
209- energyRaw: number; // in the energy band, FS^2·s
205+ energyRaw: number; // in the analysis band, FS^2·s
210206 energyNoise: number;
211207 energy: number; // energyRaw - energyNoise
212- shapeEnergy: number; // background-subtracted energy in the spectrum band (for normalising shapes)
213208 snrDb: number; // 10 log10(energyRaw / energyNoise)
214209 peakDbfs: number; // in the segment
215210 nearClip: number; // samples with |x| >= 0.99 in the segment
216- backgroundDbfs: number | null; // RMS level of background in the energy band
211+ backgroundDbfs: number | null; // RMS level of background in the analysis band
217212 }
218213
219214 export function analyze(
@@ -267,9 +262,6 @@ export function analyze(
267262 }
268263 const energy = energyRaw - energyNoise;
269264
270- const [sLo, sHi] = bins(settings.shapeLow, settings.shapeHigh);
271- let tot = 0;
272- for (let k = sLo; k <= sHi; k++) tot += netEsd[k];
273265
274266 let peak = 0;
275267 let nearClip = 0;
@@ -300,7 +292,6 @@ export function analyze(
300292 energyRaw,
301293 energyNoise,
302294 energy,
303- shapeEnergy: tot * df,
304295 snrDb: noiseEsd ? 10 * Math.log10(energyRaw / Math.max(energyNoise, 1e-30)) : Infinity,
305296 peakDbfs: 20 * Math.log10(Math.max(peak, 1e-10)),
306297 nearClip,
@@ -384,3 +375,39 @@ export function spectrogram(x: Float32Array, fs: number, nfft = 1024, maxCols =
384375 }
385376 return { cols, bins, dt: hop / fs, t0: nfft / 2 / fs, df: fs / nfft, db, maxDb };
386377 }
378+
379+// ---------- band-pass filter ----------
380+
381+// Zero-phase band-pass via FFT of the whole signal, with raised-cosine edges (`taper` Hz wide)
382+// to limit ringing. Timing is preserved exactly, which matters for lining up with the raw signal.
383+export function bandpass(x: Float32Array, fs: number, band: Band, taper = 500): Float32Array {
384+ let n = 1;
385+ while (n < x.length) n *= 2;
386+ const re = new Float64Array(n);
387+ const im = new Float64Array(n);
388+ re.set(x);
389+ fft(re, im);
390+ const gain = (f: number) => {
391+ const lo = band.lo;
392+ const hi = Math.min(band.hi, fs / 2);
393+ if (f < lo - taper / 2 || f > hi + taper / 2) return 0;
394+ if (f < lo + taper / 2) return 0.5 - 0.5 * Math.cos((Math.PI * (f - (lo - taper / 2))) / taper);
395+ if (f > hi - taper / 2) return 0.5 - 0.5 * Math.cos((Math.PI * (hi + taper / 2 - f)) / taper);
396+ return 1;
397+ };
398+ for (let k = 0; k <= n / 2; k++) {
399+ const g = gain((k * fs) / n);
400+ re[k] *= g;
401+ im[k] *= g;
402+ if (k > 0 && k < n / 2) {
403+ re[n - k] *= g;
404+ im[n - k] *= g;
405+ }
406+ }
407+ // inverse FFT via conjugation
408+ for (let k = 0; k < n; k++) im[k] = -im[k];
409+ fft(re, im);
410+ const out = new Float32Array(x.length);
411+ for (let i = 0; i < x.length; i++) out[i] = re[i] / n;
412+ return out;
413+}
src/components/About.tsxmodified+6−6View file
@@ -18,7 +18,7 @@ export function About({ settings }: { settings: AnalysisSettings }) {
1818 <h2>What is measured</h2>
1919 <ul>
2020 <li>
21- <b>Tear segment</b>: found automatically as the loudest stretch well above the background in the energy band (gaps under 0.6 s are bridged). Check it on the Record tab and adjust it if it is wrong. Duration and speed ({settings.sheetLengthIn} in ÷ duration) come from this segment.
21+ <b>Tear segment</b>: found automatically as the loudest stretch well above the background in the analysis band (gaps under 0.6 s are bridged). Check it on the Record tab and adjust it if it is wrong. Duration and speed ({settings.sheetLengthIn} in ÷ duration) come from this segment.
2222 </li>
2323 <li>
2424 <b>Energy spectral density</b> of the tear: Welch average of 2048-point Hann-windowed spectra over the segment, times its duration. Units are digital
@@ -29,10 +29,10 @@ export function About({ settings }: { settings: AnalysisSettings }) {
2929 dominate), scaled to the tear's duration and subtracted.
3030 </li>
3131 <li>
32- <b>Sound energy</b>: the background-subtracted spectrum summed over the <b>energy band</b>, {fmtHz(settings.energyLow)} –{" "}
33- {fmtHz(settings.energyHigh)}. Lower frequencies carry much more room and handling noise, so energy, the automatic tear range and the level-over-time
34- plot all use only this band. Spectra are shown and compared over the wider <b>spectrum band</b>, {fmtHz(settings.shapeLow)} –{" "}
35- {fmtHz(settings.shapeHigh)}. Both bands can be changed under Analysis settings.
32+ <b>Sound energy</b>: the background-subtracted spectrum summed over the <b>analysis band</b>, {fmtHz(settings.energyLow)} –{" "}
33+ {fmtHz(settings.energyHigh)}. Lower frequencies carry much more room and handling noise, so energy, the automatic tear range, the level plot and
34+ the filtered waveform all use only this band. Spectra are still shown over the full range for context. The band can be changed under Analysis
35+ settings.
3636 </li>
3737 </ul>
3838
@@ -44,7 +44,7 @@ export function About({ settings }: { settings: AnalysisSettings }) {
4444 is bigger than many of the effects you may be looking for.
4545 </li>
4646 <li>
47- <b>The mic colours the sound.</b> A laptop microphone has its own frequency response and records little above about 20 kHz, so the top of the energy band is near the limit of what it captures. Spectra show the sound as
47+ <b>The mic colours the sound.</b> A laptop microphone has its own frequency response and records little above about 20 kHz, so the top of the analysis band is near the limit of what it captures. Spectra show the sound as
4848 that mic hears it. That is fine for comparing speeds against each other, but not for absolute spectra.
4949 </li>
5050 <li>
src/components/CompareView.tsxmodified+9−9View file
@@ -100,7 +100,7 @@ export function CompareView({ recs, settings, onOpen }: Props) {
100100 <p className="caption">
101101 Energy spectrum of each tear, background removed.
102102 {normalize
103- ? " Each curve is divided by its total energy over the plotted range, so only the shape is compared."
103+ ? " Each curve is divided by its energy in the analysis band (shaded), so the curves line up there and only differences in shape remain."
104104 : " If tears at all speeds contain the same clicks, the curves should lie on top of each other."}
105105 </p>
106106 <SpectraOverlay rows={rows} normalize={normalize} smoothing={smoothing} settings={settings} />
@@ -268,13 +268,13 @@ function Scatter({
268268
269269 function SpectraOverlay({ rows, normalize, smoothing, settings }: { rows: Row[]; normalize: boolean; smoothing: number; settings: AnalysisSettings }) {
270270 const fsMin = rows.length ? Math.min(...rows.map((r) => r.a.fs)) : 48000;
271- const fLo = Math.max(20, settings.shapeLow);
272- const fHi = Math.min(settings.shapeHigh, fsMin / 2);
271+ const fLo = 20;
272+ const fHi = fsMin / 2;
273273
274274 const lines = useMemo(
275275 () =>
276276 rows.map((r) => {
277- const scale = normalize ? 1 / r.a.shapeEnergy : 1;
277+ const scale = normalize ? 1 / r.a.energy : 1;
278278 const sm = smoothLog(r.a.freqs, r.a.netEsd.map((v) => v * scale), fLo, fHi, smoothing);
279279 return { name: rowName(r), dur: r.a.duration, f: sm.f, db: sm.v.map((v) => (v > 0 ? 10 * Math.log10(v) : NaN)) };
280280 }),
@@ -290,8 +290,8 @@ function SpectraOverlay({ rows, normalize, smoothing, settings }: { rows: Row[];
290290
291291 const draw = useCallback(
292292 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
293- if (!normalize) {
294- // mark the energy band
293+ {
294+ // mark the analysis band
295295 ctx.fillStyle = th.seg;
296296 const bl = s.x(Math.max(settings.energyLow, fLo));
297297 const bh = s.x(Math.min(settings.energyHigh, fHi));
@@ -322,7 +322,7 @@ function SpectraOverlay({ rows, normalize, smoothing, settings }: { rows: Row[];
322322 }}
323323 ariaLabel="Energy spectra of the tears, overlaid"
324324 />
325- <Legend rows={rows} lines extra={normalize ? undefined : "shaded: energy band"} />
325+ <Legend rows={rows} lines extra="shaded: analysis band" />
326326 </>
327327 );
328328 }
@@ -401,7 +401,7 @@ function exportCsv(rows: Row[], settings: AnalysisSettings) {
401401 const head = [
402402 "name", "notes", "recorded", "source", "sample_rate", "tear_start_s", "tear_end_s", "range_set_by_hand", "duration_s", "speed_in_per_s",
403403 "energy_db", "energy_raw_db", "background_db", "above_background_db", "peak_dbfs", "near_clip_samples",
404- "energy_band_low_hz", "energy_band_high_hz", "spectrum_band_low_hz", "spectrum_band_high_hz", "sheet_length_in",
404+ "band_low_hz", "band_high_hz", "sheet_length_in",
405405 ];
406406 const q = (v: unknown) => {
407407 const s = String(v ?? "");
@@ -414,7 +414,7 @@ function exportCsv(rows: Row[], settings: AnalysisSettings) {
414414 m.label, m.notes, new Date(m.createdAt).toISOString(), m.source, m.sampleRate, a.segment.start.toFixed(4), a.segment.end.toFixed(4), m.segmentManual,
415415 a.duration.toFixed(4), a.speedInPerSec.toFixed(4), db10(a.energy).toFixed(3), db10(a.energyRaw).toFixed(3), db10(a.energyNoise).toFixed(3),
416416 a.snrDb.toFixed(2), a.peakDbfs.toFixed(2), a.nearClip,
417- settings.energyLow, settings.energyHigh, settings.shapeLow, settings.shapeHigh, settings.sheetLengthIn,
417+ settings.energyLow, settings.energyHigh, settings.sheetLengthIn,
418418 ]
419419 .map(q)
420420 .join(","),
src/components/TearView.tsxmodified+185−174View file
@@ -1,6 +1,6 @@
11 import { useCallback, useEffect, useMemo, useRef, useState } from "react";
22 import { CanvasPlot, drawLine, readTheme, type PointerInfo, type Scales, type Theme } from "./CanvasPlot.tsx";
3-import { bandLevels, detectSegment, energyBand, smoothLog, spectrogram, type Analysis, type AnalysisSettings, type Segment } from "../analysis/analyze.ts";
3+import { bandLevels, bandpass, detectSegment, energyBand, smoothLog, spectrogram, type Analysis, type AnalysisSettings, type Segment } from "../analysis/analyze.ts";
44 import type { RecordingMeta } from "../storage/db.ts";
55 import { play, stop as stopPlay, usePlayhead } from "../audio/player.ts";
66 import { db10, fmtHz, fmtSec, getAnalysis, getAudio } from "../model.ts";
@@ -60,7 +60,23 @@ export function TearView({ meta, settings, onUpdate }: Props) {
6060 onUpdate({ ...meta, segment: s, segmentManual: true });
6161 };
6262
63- // ---------- tear range (whole recording) ----------
63+ // ---------- shared time view (level, waveform, spectrogram) ----------
64+ const [view, setView] = useState<[number, number]>([0, dur]);
65+ useEffect(() => setView([0, meta.length / meta.sampleRate]), [meta.id, meta.length, meta.sampleRate]);
66+ const clampView = (a: number, b: number): [number, number] => {
67+ const w = Math.min(dur, Math.max(b - a, 0.002));
68+ let s = Math.max(0, a);
69+ if (s + w > dur) s = dur - w;
70+ return [s, s + w];
71+ };
72+ const zoom = (f: number, around = (view[0] + view[1]) / 2) => setView(clampView(around - (around - view[0]) * f, around + (view[1] - around) * f));
73+ const fitTear = () => {
74+ if (!seg) return;
75+ const m = Math.max(0.05, 0.08 * (seg.end - seg.start));
76+ setView(clampView(seg.start - m, seg.end + m));
77+ };
78+
79+ // ---------- selecting the tear range (on any of the three plots) ----------
6480 const drag = useRef<{ kind: "start" | "end" | "new"; anchor: number; px0: number; before: Segment | null } | null>(null);
6581 const edgeAt = (p: PointerInfo): "start" | "end" | null => {
6682 if (!seg) return null;
@@ -70,7 +86,7 @@ export function TearView({ meta, settings, onUpdate }: Props) {
7086 return ds <= de ? "start" : "end";
7187 };
7288 const clampT = (t: number) => Math.min(Math.max(t, 0), dur);
73- const rangeHandlers = {
89+ const timeHandlers = {
7490 onPointer: (type: "down" | "move" | "up", p: PointerInfo) => {
7591 if (type === "down") {
7692 drag.current = { kind: edgeAt(p) ?? "new", anchor: clampT(p.xv), px0: p.px, before: seg };
@@ -89,13 +105,69 @@ export function TearView({ meta, settings, onUpdate }: Props) {
89105 const d = drag.current;
90106 drag.current = null;
91107 if (d.kind === "new" && Math.abs(p.px - d.px0) <= 3) return; // a plain click changes nothing
92- if (seg && seg.end - seg.start >= 0.01) commitSeg(seg);
108+ if (seg && seg.end - seg.start >= 0.005) commitSeg(seg);
93109 else setSeg(d.before);
94110 }
95111 },
112+ // pinch (or ctrl + scroll) zooms, sideways two-finger scroll moves along; plain scrolling scrolls the page
113+ onWheel: (p: PointerInfo, ev: WheelEvent) => {
114+ if (ev.ctrlKey) {
115+ zoom(Math.exp(ev.deltaY * 0.01), Math.min(Math.max(p.xv, view[0]), view[1]));
116+ return true;
117+ }
118+ if (Math.abs(ev.deltaX) > Math.abs(ev.deltaY)) {
119+ const shift = (ev.deltaX / (p.scales.right - p.scales.left)) * (view[1] - view[0]);
120+ setView(clampView(view[0] + shift, view[1] + shift));
121+ return true;
122+ }
123+ return false;
124+ },
125+ onDoubleClick: () => setView([0, dur]),
96126 cursor: (p: PointerInfo) => (edgeAt(p) ? "ew-resize" : "crosshair"),
97127 };
98128
129+ // shading (or dimming, on the spectrogram), edges with grab handles, playhead
130+ const drawSelection = (ctx: CanvasRenderingContext2D, s: Scales, th: Theme, onImage: boolean) => {
131+ const ink = onImage ? "#ffffff" : th.ink;
132+ if (seg) {
133+ const a = s.x(seg.start);
134+ const b = s.x(seg.end);
135+ if (onImage) {
136+ ctx.fillStyle = "rgba(0,0,0,0.45)";
137+ ctx.fillRect(s.left, s.top, a - s.left, s.bottom - s.top);
138+ ctx.fillRect(b, s.top, s.right - b, s.bottom - s.top);
139+ }
140+ for (const px of [a, b]) {
141+ ctx.strokeStyle = ink;
142+ ctx.lineWidth = 2;
143+ ctx.beginPath();
144+ ctx.moveTo(px, s.top);
145+ ctx.lineTo(px, s.bottom);
146+ ctx.stroke();
147+ ctx.fillStyle = ink;
148+ ctx.beginPath();
149+ ctx.roundRect(px - 4, (s.top + s.bottom) / 2 - 12, 8, 24, 3);
150+ ctx.fill();
151+ }
152+ }
153+ if (playhead !== null) {
154+ ctx.strokeStyle = ink;
155+ ctx.lineWidth = 2;
156+ ctx.setLineDash([3, 3]);
157+ ctx.beginPath();
158+ ctx.moveTo(s.x(playhead), s.top);
159+ ctx.lineTo(s.x(playhead), s.bottom);
160+ ctx.stroke();
161+ ctx.setLineDash([]);
162+ }
163+ };
164+ const shadeSeg = (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
165+ if (!seg) return;
166+ ctx.fillStyle = th.seg;
167+ ctx.fillRect(s.x(seg.start), s.top, s.x(seg.end) - s.x(seg.start), s.bottom - s.top);
168+ };
169+
170+ // ---------- level in the analysis band ----------
99171 const levelRange = useMemo<[number, number]>(() => {
100172 if (!levels) return [-100, 0];
101173 const dbs = Array.from(levels.power, (p) => db10(p)).sort((a, b) => a - b);
@@ -103,132 +175,71 @@ export function TearView({ meta, settings, onUpdate }: Props) {
103175 return [Math.max(-140, Math.floor((lo - 6) / 10) * 10), 0];
104176 }, [levels]);
105177
106- const drawPlayhead = (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
107- if (playhead === null) return;
108- ctx.strokeStyle = th.ink;
109- ctx.lineWidth = 2;
110- ctx.beginPath();
111- ctx.moveTo(s.x(playhead), s.top);
112- ctx.lineTo(s.x(playhead), s.bottom);
113- ctx.stroke();
114- };
115-
116- const drawRange = useCallback(
178+ const drawLevel = useCallback(
117179 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
118- if (seg) {
119- const a = s.x(seg.start);
120- const b = s.x(seg.end);
121- ctx.fillStyle = th.seg;
122- ctx.fillRect(a, s.top, b - a, s.bottom - s.top);
123- }
180+ shadeSeg(ctx, s, th);
124181 if (levels) {
125182 const { frameSec, power } = levels;
126- const perPx = Math.max(1, Math.floor(power.length / ((s.right - s.left) * 2)));
183+ const i0 = Math.max(0, Math.floor(view[0] / frameSec) - 1);
184+ const i1 = Math.min(power.length, Math.ceil(view[1] / frameSec) + 1);
185+ const step = Math.max(1, Math.floor((i1 - i0) / ((s.right - s.left) * 2)));
127186 const xs: number[] = [];
128187 const ys: number[] = [];
129- for (let i = 0; i < power.length; i += perPx) {
188+ for (let i = i0; i < i1; i += step) {
130189 let m = 0;
131- for (let j = i; j < Math.min(i + perPx, power.length); j++) m = Math.max(m, power[j]);
132- xs.push((i + perPx / 2) * frameSec);
190+ for (let j = i; j < Math.min(i + step, i1); j++) m = Math.max(m, power[j]);
191+ xs.push((i + step / 2) * frameSec);
133192 ys.push(db10(m));
134193 }
135194 drawLine(ctx, s, xs, ys, mainColor(th), 1.5);
136195 }
137- if (seg) {
138- // edges with grab handles
139- for (const t of [seg.start, seg.end]) {
140- const px = s.x(t);
141- ctx.strokeStyle = th.ink;
142- ctx.lineWidth = 2;
143- ctx.beginPath();
144- ctx.moveTo(px, s.top);
145- ctx.lineTo(px, s.bottom);
146- ctx.stroke();
147- ctx.fillStyle = th.ink;
148- ctx.beginPath();
149- ctx.roundRect(px - 4, (s.top + s.bottom) / 2 - 12, 8, 24, 3);
150- ctx.fill();
151- }
152- }
153- drawPlayhead(ctx, s, th);
196+ drawSelection(ctx, s, th, false);
154197 },
155198 // eslint-disable-next-line react-hooks/exhaustive-deps
156- [levels, seg, playhead],
199+ [levels, view, seg, playhead],
157200 );
158201
159- // ---------- close-up ----------
160- const fit = useCallback(
161- (s: Segment | null): [number, number] => {
162- if (!s) return [0, dur];
163- const m = Math.max(0.05, 0.08 * (s.end - s.start));
164- return [Math.max(0, s.start - m), Math.min(dur, s.end + m)];
165- },
166- [dur],
167- );
168- const [view, setView] = useState<[number, number]>(() => fit(meta.segment));
169- useEffect(() => setView(fit(meta.segment)), [meta.id, meta.segment, fit]);
170- const clampView = (a: number, b: number): [number, number] => {
171- const w = Math.min(dur, Math.max(b - a, 0.002));
172- let s = Math.max(0, a);
173- if (s + w > dur) s = dur - w;
174- return [s, s + w];
175- };
176- const zoom = (f: number, around = (view[0] + view[1]) / 2) => setView(clampView(around - (around - view[0]) * f, around + (view[1] - around) * f));
177- const pan = useRef<{ px0: number; view0: [number, number] } | null>(null);
178- const closeHandlers = {
179- onPointer: (type: "down" | "move" | "up", p: PointerInfo) => {
180- if (type === "down") pan.current = { px0: p.px, view0: view };
181- else if (type === "move" && pan.current) {
182- const d = pan.current;
183- const dt = ((p.px - d.px0) / (p.scales.right - p.scales.left)) * (d.view0[1] - d.view0[0]);
184- setView(clampView(d.view0[0] - dt, d.view0[1] - dt));
185- } else pan.current = null;
186- },
187- // pinch on a trackpad (or ctrl + scroll) zooms; plain scrolling scrolls the page
188- onWheel: (p: PointerInfo, ev: WheelEvent) => {
189- if (!ev.ctrlKey) return false;
190- zoom(Math.exp(ev.deltaY * 0.01), Math.min(Math.max(p.xv, view[0]), view[1]));
191- return true;
192- },
193- onDoubleClick: () => setView(fit(seg)),
194- cursor: () => "grab",
195- };
196-
197- const drawEdges = (ctx: CanvasRenderingContext2D, s: Scales, color: string) => {
198- if (!seg) return;
199- ctx.strokeStyle = color;
200- ctx.lineWidth = 1.5;
201- ctx.setLineDash([5, 4]);
202- ctx.beginPath();
203- for (const t of [seg.start, seg.end]) {
204- ctx.moveTo(s.x(t), s.top);
205- ctx.lineTo(s.x(t), s.bottom);
202+ // ---------- waveform (raw or band-passed) ----------
203+ const [filtered, setFilteredState] = useState(() => {
204+ try {
205+ return localStorage.getItem("rsa-filter-wave") === "1";
206+ } catch {
207+ return false;
208+ }
209+ });
210+ const setFiltered = (v: boolean) => {
211+ setFilteredState(v);
212+ try {
213+ localStorage.setItem("rsa-filter-wave", v ? "1" : "0");
214+ } catch {
215+ /* ignore */
206216 }
207- ctx.stroke();
208- ctx.setLineDash([]);
209217 };
218+ const xf = useMemo(() => (x && filtered ? bandpass(x, fs, { lo: energyLow, hi: energyHigh }) : null), [x, fs, filtered, energyLow, energyHigh]);
219+ const wave = filtered ? xf : x;
210220
211221 const waveMax = useMemo(() => {
212- if (!x) return 1;
222+ if (!wave) return 1;
213223 let m = 0;
214- for (let i = 0; i < x.length; i++) m = Math.max(m, Math.abs(x[i]));
215- return Math.max(m * 1.05, 1e-4);
216- }, [x]);
224+ for (let i = 0; i < wave.length; i++) m = Math.max(m, Math.abs(wave[i]));
225+ return Math.max(m * 1.05, 1e-6);
226+ }, [wave]);
217227
218228 const drawWave = useCallback(
219229 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
220- if (x) {
230+ shadeSeg(ctx, s, th);
231+ if (wave) {
221232 const color = mainColor(th);
222233 const a = Math.max(0, Math.floor(view[0] * fs));
223- const b = Math.min(x.length, Math.ceil(view[1] * fs));
234+ const b = Math.min(wave.length, Math.ceil(view[1] * fs));
224235 const px = s.right - s.left;
225236 const perPx = (b - a) / px;
226237 if (perPx < 2) {
227238 const xs: number[] = [];
228239 const ys: number[] = [];
229- for (let i = Math.max(0, a - 1); i < Math.min(x.length, b + 1); i++) {
240+ for (let i = Math.max(0, a - 1); i < Math.min(wave.length, b + 1); i++) {
230241 xs.push(i / fs);
231- ys.push(x[i]);
242+ ys.push(wave[i]);
232243 }
233244 drawLine(ctx, s, xs, ys, color, 1.5);
234245 if (perPx < 0.15) {
@@ -243,7 +254,7 @@ export function TearView({ meta, settings, onUpdate }: Props) {
243254 let lo = Infinity;
244255 let hi = -Infinity;
245256 for (let i = i0; i < i1; i++) {
246- const v = x[i];
257+ const v = wave[i];
247258 if (v < lo) lo = v;
248259 if (v > hi) hi = v;
249260 }
@@ -253,13 +264,13 @@ export function TearView({ meta, settings, onUpdate }: Props) {
253264 }
254265 }
255266 }
256- drawEdges(ctx, s, th.ink2);
257- drawPlayhead(ctx, s, th);
267+ drawSelection(ctx, s, th, false);
258268 },
259269 // eslint-disable-next-line react-hooks/exhaustive-deps
260- [x, view, fs, seg, playhead],
270+ [wave, view, fs, seg, playhead],
261271 );
262272
273+ // ---------- spectrogram ----------
263274 const drawSpec = useCallback(
264275 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
265276 if (spec && specImage) {
@@ -272,19 +283,22 @@ export function TearView({ meta, settings, onUpdate }: Props) {
272283 const dx1 = s.x(spec.t0 + sx1 * spec.dt);
273284 if (sx1 > sx0) ctx.drawImage(specImage, sx0, 0, sx1 - sx0, spec.bins, dx0, s.top, dx1 - dx0, s.bottom - s.top);
274285 }
275- drawEdges(ctx, s, "#ffffff");
276- if (playhead !== null) {
277- ctx.strokeStyle = "#ffffff";
278- ctx.lineWidth = 2;
279- ctx.beginPath();
280- ctx.moveTo(s.x(playhead), s.top);
281- ctx.lineTo(s.x(playhead), s.bottom);
282- ctx.stroke();
286+ // analysis band edges
287+ ctx.strokeStyle = "rgba(255,255,255,0.7)";
288+ ctx.lineWidth = 1;
289+ ctx.setLineDash([6, 4]);
290+ ctx.beginPath();
291+ for (const f of [energyLow, energyHigh]) {
292+ if (f >= fs / 2) continue;
293+ ctx.moveTo(s.left, s.y(f));
294+ ctx.lineTo(s.right, s.y(f));
283295 }
284- void th;
296+ ctx.stroke();
297+ ctx.setLineDash([]);
298+ drawSelection(ctx, s, th, true);
285299 },
286300 // eslint-disable-next-line react-hooks/exhaustive-deps
287- [spec, specImage, view, seg, playhead],
301+ [spec, specImage, view, seg, playhead, energyLow, energyHigh],
288302 );
289303
290304 // ---------- spectrum ----------
@@ -305,7 +319,7 @@ export function TearView({ meta, settings, onUpdate }: Props) {
305319 const drawSpectrum = useCallback(
306320 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
307321 if (!specLines) return;
308- // the energy band
322+ // the analysis band
309323 ctx.fillStyle = th.seg;
310324 const bl = s.x(settings.energyLow);
311325 const bh = s.x(Math.min(settings.energyHigh, fHi));
@@ -327,11 +341,11 @@ export function TearView({ meta, settings, onUpdate }: Props) {
327341
328342 const a = analysis;
329343 const warnings: string[] = [];
330- if (!seg) warnings.push("No tear was found automatically. Drag across the plot below to mark it.");
344+ if (!seg) warnings.push("No tear was found automatically. Drag across the plots below to mark it.");
331345 if (a && a.nearClip > 0) warnings.push(`${a.nearClip} samples in the tear are at or near full scale (clipping). The energy is underestimated; consider re-recording further from the microphone.`);
332346 if (a && !a.noiseEsd) warnings.push("There is not enough quiet before or after the tear to measure the background, so nothing was subtracted. Leave about a second of quiet at each end.");
333347 else if (a && a.snrDb < 10)
334- warnings.push(`In the energy band (${bandLabel}) the tear is only ${a.snrDb.toFixed(1)} dB above the background, so the energy depends on how well the background is estimated.`);
348+ warnings.push(`In the analysis band (${bandLabel}) the tear is only ${a.snrDb.toFixed(1)} dB above the background, so the energy depends on how well the background is estimated.`);
335349 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.");
336350
337351 const th = readTheme(document.documentElement);
@@ -349,8 +363,7 @@ export function TearView({ meta, settings, onUpdate }: Props) {
349363 <div>
350364 <h3>Tear range</h3>
351365 <p className="caption">
352- Sound level in the energy band ({bandLabel}) over the whole recording. Drag across the plot to mark where the tear is. Drag a dark edge to
353- adjust it. Everything below uses only this range.
366+ Drag across any of the three plots to mark where the tear is; drag a dark edge to adjust it. Everything else on this page uses only this range.
354367 </p>
355368 </div>
356369 <div className="toolbar">
@@ -365,27 +378,70 @@ export function TearView({ meta, settings, onUpdate }: Props) {
365378 </button>
366379 </div>
367380 </div>
381+ <div className="plot-head">
382+ <div className="toolbar">
383+ <button onClick={() => zoom(0.5)}>+ Zoom in</button>
384+ <button onClick={() => zoom(2)}>− Zoom out</button>
385+ <button disabled={!seg} onClick={fitTear}>
386+ Fit tear
387+ </button>
388+ <button onClick={() => setView([0, dur])}>Whole recording</button>
389+ <span className="muted small">
390+ Showing {fmtSec(view[0])}–{fmtSec(view[1])}. Pinch to zoom, two-finger swipe sideways to move along.
391+ </span>
392+ </div>
393+ </div>
368394 <CanvasPlot
369- height={150}
370- xRange={[0, dur]}
395+ height={130}
396+ xRange={view}
371397 yRange={levelRange}
372398 xLabel="time (s)"
373- yLabel={`level ${bandLabel} (dBFS)`}
374- draw={drawRange}
399+ yLabel={`level ${bandLabel}`}
400+ hideXTicks
401+ draw={drawLevel}
375402 hover={(p) => {
376- const lines = [`${p.xv.toFixed(2)} s`];
403+ const lines = [`${p.xv.toFixed(3)} s`];
377404 if (levels) {
378405 const i = Math.floor(p.xv / levels.frameSec);
379- if (i >= 0 && i < levels.power.length) lines.push(`${db10(levels.power[i]).toFixed(1)} dBFS`);
406+ if (i >= 0 && i < levels.power.length) lines.push(`${db10(levels.power[i]).toFixed(1)} dBFS in ${bandLabel}`);
380407 }
381408 return { lines };
382409 }}
383- ariaLabel="Sound level over the whole recording, with the tear range"
384- {...rangeHandlers}
410+ ariaLabel={`Sound level in ${bandLabel} over time, with the tear range`}
411+ {...timeHandlers}
412+ />
413+ <CanvasPlot
414+ height={150}
415+ xRange={view}
416+ yRange={[-waveMax, waveMax]}
417+ xLabel="time (s)"
418+ yLabel={filtered ? `waveform ${bandLabel}` : "waveform"}
419+ hideXTicks
420+ draw={drawWave}
421+ hover={(p) => ({ lines: [`${p.xv.toFixed(4)} s`] })}
422+ ariaLabel="Waveform, with the tear range"
423+ {...timeHandlers}
385424 />
425+ <CanvasPlot
426+ height={220}
427+ xRange={view}
428+ yRange={[0, fs / 2]}
429+ xLabel="time (s)"
430+ yLabel="frequency (Hz)"
431+ draw={drawSpec}
432+ hover={(p) => ({ lines: [`${p.xv.toFixed(3)} s`, fmtHz(p.yv)] })}
433+ ariaLabel="Spectrogram, with the tear range"
434+ {...timeHandlers}
435+ />
436+ <div className="range-row">
437+ <label className="toolbar">
438+ <input type="checkbox" checked={filtered} onChange={(e) => setFiltered(e.target.checked)} /> Show the waveform filtered to the analysis band ({bandLabel})
439+ </label>
440+ <span className="muted small">Spectrogram: brighter is louder; dashed lines mark the analysis band.</span>
441+ </div>
386442 <RangeInputs seg={seg} dur={dur} onCommit={commitSeg} />
387443 <div className="range-row">
388- <span className="muted small">{meta.segmentManual ? "Range set by hand." : "Range found automatically."}</span>
444+ <span className="muted small">{meta.segmentManual ? "Range set by hand." : `Range found automatically from the level in ${bandLabel}.`}</span>
389445 <button
390446 disabled={!x}
391447 onClick={() => {
@@ -406,51 +462,6 @@ export function TearView({ meta, settings, onUpdate }: Props) {
406462 <Stats a={a} settings={settings} bandLabel={bandLabel} />
407463 </section>
408464
409- <section className="card">
410- <div className="plot-head">
411- <div>
412- <h3>Close-up</h3>
413- <p className="caption">Drag to move along. Pinch (or ctrl + scroll) to zoom. Dashed lines mark the tear range.</p>
414- </div>
415- <div className="toolbar">
416- <button onClick={() => zoom(0.5)} aria-label="Zoom in">
417- + Zoom in
418- </button>
419- <button onClick={() => zoom(2)} aria-label="Zoom out">
420- − Zoom out
421- </button>
422- <button onClick={() => setView(fit(seg))}>Fit tear</button>
423- <button onClick={() => setView([0, dur])}>Whole recording</button>
424- </div>
425- </div>
426- <CanvasPlot
427- height={160}
428- xRange={view}
429- yRange={[-waveMax, waveMax]}
430- xLabel="time (s)"
431- yLabel="waveform"
432- hideXTicks
433- draw={drawWave}
434- hover={(p) => ({ lines: [`${p.xv.toFixed(4)} s`] })}
435- ariaLabel="Waveform close-up"
436- {...closeHandlers}
437- />
438- <CanvasPlot
439- height={230}
440- xRange={view}
441- yRange={[0, fs / 2]}
442- xLabel="time (s)"
443- yLabel="frequency (Hz)"
444- draw={drawSpec}
445- hover={(p) => ({ lines: [`${p.xv.toFixed(3)} s`, fmtHz(p.yv)] })}
446- ariaLabel="Spectrogram close-up"
447- {...closeHandlers}
448- />
449- <p className="caption">
450- Showing {fmtSec(view[0])}–{fmtSec(view[1])}. Spectrogram: 1024-point windows; brighter is louder, spanning the top 90 dB of this recording.
451- </p>
452- </section>
453-
454465 <section className="card">
455466 <div className="plot-head">
456467 <div>
@@ -487,7 +498,7 @@ export function TearView({ meta, settings, onUpdate }: Props) {
487498 <i className="swatch dashed" /> background alone, over the same duration
488499 </span>
489500 <span>
490- <i className="swatch shade" /> energy band ({bandLabel})
501+ <i className="swatch shade" /> analysis band ({bandLabel})
491502 </span>
492503 </div>
493504 </section>
src/model.tsmodified+1−1View file
@@ -29,7 +29,7 @@ export function durationColor(d: number | null, th: Theme): string {
2929
3030 // ---------- settings ----------
3131
32-const SETTINGS_KEY = "rsa-settings-v2";
32+const SETTINGS_KEY = "rsa-settings-v3";
3333
3434 export function loadSettings(): AnalysisSettings {
3535 try {