# Analyzers: what they measure and how to read them

## Contents
1. Tools
2. Reading the default report
3. Lenses
4. Expectations (`--expect`)
5. Reading the spectrogram PNG
6. Comparing and batch variety
7. Loop check
8. Known blind spots

## 1. Tools

| Command | Use |
|---|---|
| `analyze.mjs f.wav [--lens a,b] [--png [out.png]] [--zoom t0,t1] [--expect '{…}'\|@file.json] [--paths] [--brief] [--json]` | everything about one file; `--brief` = one line per file for batches; `--paths` lists every numeric path |
| `compare.mjs ref.wav cand.wav` | what differs: shape distance, envelope, loudness, brightness, band balance |
| `compare.mjs --variety a.wav b.wav …` | pairwise distance matrix of a set |
| `loopcheck.mjs bed.wav [--png] [--preview]` | seam, evenness, internal repetition; `--preview` writes the loop three times in a row |

In code: `sd.analyze(buf, { lens })`, `sd.formatReport(rep)`, `sd.checkExpectations(rep, exp)`, `sd.compare(a, b)`,
`sd.variety(bufs)`, `sd.loopStats(buf)`, `sd.spectrogramPng(buf, { t0, t1 })`, or simply `sd.save(path, buf, { lens, expect })`.
WAV is read natively; other formats need `ffmpeg` on PATH.

## 2. Reading the default report

```
LEVEL  peak · true peak · RMS · crest · LUFS momentary-max / integrated / LRA
ENV    attack · peak time · -20 dB after · T60 (fit) · sustain · head/tail silence   + loudness sparkline
SPEC   centroid · 85 % rolloff · slope dB/oct · noisiness · extension (lowest–highest audible band)
BANDS  sub 20–60 · bass 60–250 · lowMid 250–500 · mid 500–2k · presence 2–6k · air 6–20k   (dB re total)
PEAKS  prominent partials with note names · harmonicity
TIME   heat map: rows = bands, columns = time, one shade = 10 dB   + centroid sparkline
EVENTS onsets (count, rate, times) · spacing CV · repetition period
MOD    envelope modulation depth: swell <2 Hz · syllabic 2–8 · flutter 8–20 · rough 20–150 · kurtosis · level drift
PITCH  voiced share · median f0 · range · trend   + f0 contour
STEREO correlation (low/high) · width · balance · mono-sum loss · ITD   + pan-over-time sparkline
DEFECTS objective faults
```

- **LUFS momentary-max** is the loudness figure for one-shots; **integrated** for anything over a few seconds.
  Peak says nothing about loudness: a click and a boom can share a peak and differ by 20 LU.
- **Crest** (peak − RMS): > 18 dB very transient, 10–14 dB dense, < 8 dB squashed or steady noise.
- **attack** is 10→90 % of the first rise. < 5 ms reads as a hit, 10–50 ms as a soft onset, > 100 ms as a swell.
- **T60 (fit)**: the fit value tells how exponential the decay is. Near 1 = single clean decay (one object, one
  room). Low fit = several stages or events; then read the sparkline instead of the number.
- **noisiness** compares the spectrum with its own smoothed shape: ≈0 pure partials, ≈1 noise of any colour.
  It is long-term: a sweeping tone smears into "noise"; check `PITCH` and the picture for glides.
- **slope**: white 0, pink −3, brown −6 dB/oct; most natural broadband sounds sit between −3 and −6.
  Steeper = distant/muffled, flatter or positive = harsh/hissy.
- **TIME** is the most useful block. Read each row as "what this band does": a sub row that outlasts everything
  = weight; an air row only at the start = a crisp transient; diagonal structure across rows = a sweep.
- **EVENTS**: onset times are accurate to about a millisecond. `spacing CV` ≈ 0 means metronomic, 0.3–0.6
  natural irregularity, shrinking gaps = bouncing/accelerando (see the listed times).
- **MOD**: `syllabic` high = speech-like or wave-like pulsing; `rough` high = buzzing, growl, engine, tension.
  **kurtosis**: ≈0 smooth hiss, 3–30 separate grains, > 50 sparse clicks.
- **STEREO**: correlation 1 = dual mono, 0.3–0.8 natural width, < 0 phase trouble. `mono-sum loss` shows what
  a mono speaker loses. The pan sparkline should show the movement you programmed.

## 3. Lenses

Add the lens of the family you are working in; each prints only what matters there.

| Lens | Prints | Read it for |
|---|---|---|
| `impact` | T60 in low/mid/high bands, transient share, mode count | material and size: metal = long everywhere; wood/plastic = short and much shorter up high; equal decays in all bands = synthetic |
| `texture` | kurtosis, local crest, level drift, centroid drift, onset rate, swell/rough | grainy vs smooth, static vs alive. Sand/rain/fire/crowd |
| `speech` | syllable rate, pauses, voiced share, f0 median/range, syllabic depth, articulation | speech-likeness. Natural speech: 3–7 syll/s, voiced 40–70 %, range 4–12 st, articulation > 0.25 oct |
| `spatial` | closest-approach time, level arc, brightness change, Doppler start/end pitch → implied speed, pan path | whether motion reads as motion: shift (cents) and speed should match the scene |
| `cinematic` | hit time (onset of the largest energy step), energy climax, build monotonicity, brightness trend, pre-hit dip, tail, low-end duration | sync and shape of trailer gestures. `hitTime` is what must sit on the cut |
| `tonal` | partial list with notes, f0, stability, glide | pitched material, tuning layers to each other |
| `loop` | seam click, level/spectral step, evenness, internal repetition | quick loop sanity (full view: `loopcheck.mjs`). With this lens `DEFECTS` judges the seam instead of the file edges (a loop starts and ends mid-waveform by design) |

## 4. Expectations

`--expect` takes JSON mapping a path to `[min, max]`, `{ "min": … }`, `{ "max": … }` or `{ "near": x, "tol": y }`.
`--paths` prints every available path with its current value. Common ones:

```
level.lufsI  level.lufsMmax  level.truePeakDb  level.crestDb  level.lra
envelope.attackMs  envelope.t60  envelope.peakTime  envelope.headSilence  envelope.effectiveDuration
spectrum.centroid  spectrum.rolloff85  spectrum.slopeDbOct  spectrum.noisiness  spectrum.fLow  spectrum.fHigh
spectrum.bands.sub|bass|lowMid|mid|presence|air      spectrum.peakCount
events.count  events.rate  events.ioiCv  events.firstOnset  events.period  events.periodStrength
modulation.swell|syllabic|flutter|rough  texture.kurtosis  texture.levelStdDb
pitch.median  pitch.rangeSt  pitch.slopeStPerSec  pitch.voicedRatio
stereo.correlation  stereo.widthDb  stereo.monoLossDb  defects.count
lenses.impact.lowT60|midT60|highT60|transientShare        lenses.speech.syllableRate|f0RangeSt|articulationOct
lenses.spatial.shiftCents|impliedSpeed|closestTime        lenses.cinematic.hitTime|buildMonotonicity|tailSeconds
lenses.loop.seamClickDb|evennessDb|repeatStrength
```

Exit code is 2 when any expectation fails, so a render script can gate on it. Write wide ranges: an
expectation states what must be true for the brief, not what the first render happened to measure.

## 5. Reading the spectrogram PNG

Top: waveform per channel (blue L, orange R). Middle: log-frequency spectrogram, 20 Hz–20 kHz, bright = loud,
84 dB range. Bottom: level in dB. `--zoom 2.9,3.2` re-renders a time range at full width.

- **Vertical line** = click/transient (all frequencies at once). Expected at hits; unexpected ones are bugs
  (discontinuity, hard gate, parameter jump).
- **Horizontal lines** = steady partials (modes, hum, whistles). Evenly spaced = harmonic; irregular = metal.
  Lines that fade right-to-left at different speeds = natural modal decay.
- **Diagonal lines** = glides: Doppler, risers, sirens, bubbles (short up-ticks), speech formants.
- **Vertical stripes repeating** = pulsing/AM: engine firing, creak, tension riser, crickets.
- **Cloud without structure** = noise; where it sits and how its top edge moves is the filter sweep.
- **Hard horizontal ceiling** = band-limiting (a low-pass, a low sample-rate source). Often the reason
  something feels "dull".
- **Mirror-image streaks near the top** = aliasing (naive oscillators, heavy distortion without oversampling).
- **Pre-ringing or smear before a hit** = a linear-phase/STFT process or reversed reverb — fine if intended.
- A **stripe at 0 Hz edge / waveform sitting off-centre** = DC offset.

## 6. Comparing and batch variety

`compare` normalizes level and duration and reports them separately, then measures how different the
time-frequency *shape* is. Orientation: < 1.5 dB near-identical · 1.5–4 same sound, different take · 4–8
related · > 8 different sounds. The band line tells where the difference is.

Use it for: candidate vs. reference; version N vs. N−1 (did the edit do what you meant, and only that?);
resynthesis vs. original; kernel offline vs. the same graph in Web Audio.

`--variety` prints the full matrix and three spreads (loudness, duration, brightness). Round-robin variations
of one asset: aim ≈ 1.5–5 dB apart with < 2 LU loudness spread. A family of distinct assets: > 5 dB between
members, or the family will blur.

## 7. Loop check

Flags: a click at the wrap (compared with the loop's own busiest moments, so a crackling fire is not accused of
clicking); a level or tone step across the seam that is larger than the body's own movement; a strong internal
repetition shorter than half the loop (a "tell"); uneven loudness (one salient moment that will mark every pass);
loops under ~8 s. `--png` shows the last and first half-second joined — the seam is in the middle of the picture;
you should not be able to find it.

## 8. Known blind spots

- **Masking and loudness of layers inside a mix** are not modelled: a layer can measure present and be inaudible
  under another. Check layers solo and in context (`compare` with/without).
- **Pitch tracking** assumes one voice; on chords or noisy tones it reports the strongest periodicity.
- **Long-term statistics hide short events**: one 20 ms defect does not move `SPEC`. The `TIME` map, onsets
  and the PNG are where short things show.
- **Perceived spaciousness, "punch", "warmth"** are constructs of several cues; use the handles in
  `workflow.md` §2 rather than hunting one number.
- **Speech lens** measures prosody-likeness, not intelligibility or voice quality.
- Numbers are stable to roughly ±0.5 dB / ±3 %; do not iterate on differences smaller than that.
