Modern Apps git

← Modern-Apps.git

tuner: score chords against chroma and playable voicings, smoothed by an HMM

Commit
53030affd07fbe85d2703cb8804df9695fb415f7
Author
Vayun Mathur <[email protected]>
When
2026-11-01 18:27 UTC (1 month ago)
Parents
587a0af
The Chord tab named chords by first committing to an exact note set per frame
(harmonic sieve) and matching it against templates, so one missed or extra
pitch class lost the name. On Record-3 (real ukulele, C/Am/F) it named 14 of
145 frames correctly.

ChordExtractor.CHROMA_HMM (now the default) scores every root x quality, plus
single-note and no-chord states, directly against a tuning-compensated chroma
and against the instrument's own voicings from VoicingGenerator, then filters
the result with an online HMM so evidence builds up across a strum. Tier-B
honesty rules are unchanged; same-root rivals (C vs Cmaj7) are now shown as
Ambiguous even with a bass. The sieve still supplies the displayed note set.

- Record-3: 42/145 frames correct (was 14), 2 wrong
- Synthetic strummed progressions: guitar 83% vs 73%, ukulele 88% vs 83%
- ~1.4 ms per frame on JVM; template bank built lazily on the analysis thread

Adds StrumSynth + ChordProgressionEvalTest (synthetic labelled progressions,
streamed exactly as TunerViewModel does) and a CHROMA_HMM row in
RealAudioHarnessTest. ChordDetector.setInstrument now takes the Instrument.

Diff

tuner/AGENTS.md
diff --git a/tuner/AGENTS.md b/tuner/AGENTS.mdindex 2f062873db..ec242948ad 100644--- a/tuner/AGENTS.md+++ b/tuner/AGENTS.md@@ -13,9 +13,9 @@ _Install: ./install tuner (dev by default)._  ## Overview **Purpose:** Precise offline chromatic tuner (guitar/ukulele/piano) — sub-cent meter, 415–466 Hz reference, wrong-string warnings, honest uncertainty. No network permission.-**Key features:** Raw-mic `AudioCapture` → `domain/` DSP chain (YIN + FFT/Constant-Q + harmonic sieve/NNLS + phase-slope) → `PitchDetector` → meter/note/chord UI with fret diagrams + piano keyboard; instrument profiles in `data/`.+**Key features:** Raw-mic `AudioCapture` → `domain/` DSP chain (YIN + phase-slope for notes; Constant-Q → chroma + voicing templates → HMM for chords, harmonic sieve for the displayed note set) → meter/note/chord UI with fret diagrams + piano keyboard; instrument profiles in `data/`. **Entry points:** `Route` → `MainActivity.kt` → `Navigation.kt` → `ui/NoteScreen.kt` → `platform/TunerViewModel.kt` → `domain/PitchDetector.kt`.-**Gotchas:** Chord detection is not built yet (metadata says so) — don't assume `ChordDetector` is wired; mic latency varies by device, keep the capture path lean.+**Gotchas:** `ChordDetector` defaults to `ChordExtractor.CHROMA_HMM`; SIEVE/NNLS stay selectable only for `RealAudioHarnessTest` comparisons. Chord accuracy is measured by `ChordProgressionEvalTest` (synthetic, `build/chord-eval-report.txt`) and `RealAudioHarnessTest` (Record-3, `build/real-audio-report.txt`) — re-run both when touching chord constants. Mic latency varies by device, keep the capture path lean.  ## Key files ### Root — entry + navigation@@ -36,7 +36,10 @@ _Install: ./install tuner (dev by default)._ - com/vayunmathur/tuner/domain/TuningOffset.kt - com/vayunmathur/tuner/domain/PresentationHold.kt - com/vayunmathur/tuner/domain/Tonality.kt-- com/vayunmathur/tuner/domain/ChordDetector.kt — not yet wired (see Gotchas)+- com/vayunmathur/tuner/domain/ChordDetector.kt+- com/vayunmathur/tuner/domain/Chroma.kt+- com/vayunmathur/tuner/domain/ChordTemplates.kt+- com/vayunmathur/tuner/domain/ChordHmm.kt - com/vayunmathur/tuner/domain/ChordNaming.kt - com/vayunmathur/tuner/domain/ChordPresenter.kt - com/vayunmathur/tuner/domain/VoicingGenerator.kt
tuner/src/main/java/com/vayunmathur/tuner/domain/ChordDetector.kt
diff --git a/tuner/src/main/java/com/vayunmathur/tuner/domain/ChordDetector.kt b/tuner/src/main/java/com/vayunmathur/tuner/domain/ChordDetector.ktindex 86390992a6..ddb10e0ccb 100644--- a/tuner/src/main/java/com/vayunmathur/tuner/domain/ChordDetector.kt+++ b/tuner/src/main/java/com/vayunmathur/tuner/domain/ChordDetector.kt@@ -1,12 +1,19 @@ package com.vayunmathur.tuner.domain  import com.vayunmathur.tuner.data.DEFAULT_PARTIALS+import com.vayunmathur.tuner.data.Instrument -/** Which note extractor the Chord tab runs. See [ChordDetector]. */+/** Which extractor the Chord tab runs. See [ChordDetector]. */ enum class ChordExtractor {     /**-     * Greedy harmonic sieve over a closed candidate set. The default, on measured evidence --     * see [HarmonicSieve] for the numbers.+     * Chords scored directly against chroma and playable voicings, smoothed by an HMM - no note+     * set is committed to before naming. The default; see [ChordTemplates] and [ChordHmm].+     */+    CHROMA_HMM,++    /**+     * Greedy harmonic sieve over a closed candidate set, named by [ChordNaming]. Still runs under+     * [CHROMA_HMM] to supply the displayed note set. See [HarmonicSieve] for its numbers.      */     SIEVE, @@ -21,12 +28,13 @@ enum class ChordExtractor { }  /**- * The Chord tab's pipeline: CQT, a tonality gate, note extraction, temporal stabilisation, then- * naming (TUNER_SPEC C.2).+ * The Chord tab's pipeline: CQT, a tonality gate, then either direct chord scoring with HMM+ * smoothing ([ChordExtractor.CHROMA_HMM], the default) or note extraction, temporal+ * stabilisation and naming (TUNER_SPEC C.2).  *- * Extraction is [ChordExtractor.SIEVE] by default. NNLS was the original design and is still- * reachable through [extractor], but it produced 1.89 notes on a tonal frame of Record-3 against- * the sieve's 3.32 - and a triad needs three, so it was rarely naming anything at all.+ * The note-first paths lost on real audio because a name needed the exact note set in a single+ * frame: the sieve named 14 of 145 Record-3 frames correctly, NNLS none. They stay reachable+ * through [extractor] so `RealAudioHarnessTest` keeps measuring the comparison.  *  * The CQT is still computed on every frame even under the sieve, because two things other than  * extraction need it: the [Tonality] gate reads spectral flatness off the raw frame, and@@ -44,47 +52,52 @@ class ChordDetector(     sampleRate: Double,     soundingRange: IntRange = NoteSalience.FULL_RANGE,     partials: List<Double> = DEFAULT_PARTIALS,-    private val extractor: ChordExtractor = ChordExtractor.SIEVE,+    private val extractor: ChordExtractor = ChordExtractor.CHROMA_HMM,     /**      * The tonality gate's flatness threshold. Exposed so `RealAudioHarnessTest` can sweep it      * against real audio rather than against the synthetic corpus, which cannot say anything      * useful about where it belongs.      */-    private val maxFlatness: Double = Tonality.MAX_FLATNESS,+    private val maxFlatness: Double =+        if (extractor == ChordExtractor.CHROMA_HMM) Tonality.CHROMA_MAX_FLATNESS else Tonality.MAX_FLATNESS,     polyphony: Int = HarmonicSieve.MAX_NOTES,     relativeFloor: Double = HarmonicSieve.RELATIVE_FLOOR,+    /** Supplies the playable voicings [ChordExtractor.CHROMA_HMM] scores against; null for none. */+    instrument: Instrument? = null, ) {     private val constantQ = ConstantQ(sampleRate)     private val sieve = HarmonicSieve(sampleRate, soundingRange, partials, polyphony, relativeFloor)     private val tuning = TuningOffset()     private var confirmed = NoteSalience(soundingRange, partials)     private var provisional = NoteSalience(soundingRange, partials, PROVISIONAL_FIRST_BIN)-    private var range = soundingRange     private var profile = partials-    private var maxNotes = polyphony+    private var voicingSource = instrument     private val history = ArrayDeque<Set<Int>>() +    /** Built on first use rather than in [setInstrument], which the UI calls on the main thread. */+    private var templates: ChordTemplates? = null+    private var hmm: ChordHmm? = null+    private var evidence = DoubleArray(0)+     /**-     * Narrows the dictionary to the notes an instrument can sound (see `Instrument.soundingRange`)-     * and rebuilds its atoms from that instrument's measured partials (`Instrument.partials`).+     * Narrows the analysis to what [instrument] can sound and rebuilds everything derived from its+     * measured partials and voicings.      *-     * Rebuilding is a fraction of a millisecond and only happens when the user picks a different-     * instrument, so this is a setter rather than a new detector: the CQT kernel bank and-     * [requiredSamples] do not depend on either, and the caller's capture buffer is sized from-     * the latter.+     * A setter rather than a new detector: the CQT kernel bank and [requiredSamples] do not depend+     * on the instrument, and the caller's capture buffer is sized from the latter.      */-    fun setInstrument(-        soundingRange: IntRange,-        partials: List<Double>,-        polyphony: Int = HarmonicSieve.MAX_NOTES,-    ) {-        if (soundingRange == range && partials == profile && polyphony == maxNotes) return-        range = soundingRange+    fun setInstrument(instrument: Instrument) {+        if (instrument == voicingSource) return+        val range = instrument.soundingRange+        val partials = instrument.partials+        val polyphony = instrument.polyphony         profile = partials-        maxNotes = polyphony-        sieve.setInstrument(soundingRange, partials, polyphony)-        confirmed = NoteSalience(soundingRange, partials)-        provisional = NoteSalience(soundingRange, partials, PROVISIONAL_FIRST_BIN)+        voicingSource = instrument+        sieve.setInstrument(range, partials, polyphony)+        confirmed = NoteSalience(range, partials)+        provisional = NoteSalience(range, partials, PROVISIONAL_FIRST_BIN)+        templates = null+        hmm = null         reset()     } @@ -98,6 +111,7 @@ class ChordDetector(     fun reset() {         history.clear()         tuning.reset()+        hmm?.reset()     }      /**@@ -109,10 +123,9 @@ class ChordDetector(      * taken from pitch order would hard-gate the tier-B vocabulary onto the wrong root and      * produce confidently wrong slash chords.      *-     * Note that `bassNoteOf` is separately vacuous above F3 today, so on a ukulele - whose+     * Note that the bass search stops at G3 (F3 on the note-first paths), so on a ukulele - whose      * lowest possible note is C4 - this changes nothing yet. It is here so that raising that-     * ceiling, which is the obvious fix to the guitar-derived constant, cannot silently break-     * the re-entrant case.+     * ceiling cannot silently break the re-entrant case.      */     fun analyse(         samples: DoubleArray,@@ -122,8 +135,11 @@ class ChordDetector(         val magnitudes = constantQ.magnitudes(samples)         tuning.observe(magnitudes)         val firstBin = if (tier == ChordTier.PROVISIONAL) PROVISIONAL_FIRST_BIN else 0+        if (extractor == ChordExtractor.CHROMA_HMM) {+            return chromaReading(magnitudes, samples, tier, firstBin, bassInformsRoot)+        }         val picked = when (extractor) {-            ChordExtractor.SIEVE -> sieveNotes(magnitudes, samples, firstBin)+            ChordExtractor.SIEVE, ChordExtractor.CHROMA_HMM -> sieveNotes(magnitudes, samples, firstBin)             ChordExtractor.NNLS -> nnlsNotes(magnitudes, tier, firstBin)         } ?: run {             history.clear()@@ -137,6 +153,152 @@ class ChordDetector(         return ChordNaming.name(stable, bass, tier)     } +    /**+     * Scores every chord against this frame's chroma, folds that into the HMM, and reads the+     * posterior back out under the same honesty rules [ChordNaming] enforces.+     *+     * The sieve still runs, but only for [ChordReading.notes]: the display has to show what was+     * heard, and a voicing is a suggestion, never a measurement. A gated frame returns silence as+     * before but does not wipe the HMM - it pushes it towards no-chord, so a single gate dropout+     * in a decay costs one frame of evidence rather than the whole strum.+     */+    private fun chromaReading(+        magnitudes: DoubleArray,+        samples: DoubleArray,+        tier: ChordTier,+        firstBin: Int,+        bassInformsRoot: Boolean,+    ): ChordReading {+        val bank = templates ?: ChordTemplates(profile, voicingSource).also {+            templates = it+            evidence = DoubleArray(it.states.size)+        }+        val model = hmm ?: ChordHmm(bank.states.size).also { hmm = it }++        val picked = sieveNotes(magnitudes, samples, firstBin)+        if (picked == null) {+            history.clear()+            evidence.fill(-SILENCE_EVIDENCE)+            evidence[bank.noChord] = 0.0+            model.update(evidence)+            return silence(tier)+        }+        val notes = stabilise(picked).ifEmpty { picked }++        val withBass = tier == ChordTier.CONFIRMED && bassInformsRoot+        val frame = Chroma.of(magnitudes, tuning.cents, firstBin, withBass)+        val bass = frame.bassMidi?.let { pitchClassOf(it) }+        bank.logLikelihoods(frame, firstBin / BINS_PER_SEMITONE, bass, evidence)+        model.update(evidence)+        return interpret(bank, model.posterior, notes, frame, bass, tier)+    }++    private fun interpret(+        bank: ChordTemplates,+        posterior: DoubleArray,+        notes: List<DetectedNote>,+        frame: ChromaFrame,+        bass: Int?,+        tier: ChordTier,+    ): ChordReading {+        var best = 0+        for (s in posterior.indices) if (posterior[s] > posterior[best]) best = s+        val bassConfidence = frame.bassConfidence.toFloat()+        fun reading(label: ChordLabel, alternates: List<ChordCandidate>, confidence: Double, presentation: ChordPresentation) =+            ChordReading(notes, bass, bassConfidence, label, alternates, confidence.toFloat(), tier, presentation)++        return when (val state = bank.states[best]) {+            ChordState.NoChord -> notesOnly(notes, frame, tier)+            is ChordState.Note -> reading(+                ChordLabel.SingleNote(+                    notes.filter { pitchClassOf(it.midi) == state.pitchClass }.minOfOrNull { it.midi }+                        ?: strongestMidiOf(frame, state.pitchClass),+                ),+                emptyList(),+                posterior[best],+                ChordPresentation.UNCERTAIN,+            )+            is ChordState.Named -> namedReading(bank, posterior, best, state.name, bass, ::reading)+        }+    }++    private fun namedReading(+        bank: ChordTemplates,+        posterior: DoubleArray,+        best: Int,+        name: ChordName,+        bass: Int?,+        reading: (ChordLabel, List<ChordCandidate>, Double, ChordPresentation) -> ChordReading,+    ): ChordReading {+        val alternates = posterior.indices+            .filter { it != best && bank.states[it] is ChordState.Named }+            .filter { posterior[it] >= ALTERNATE_RATIO * posterior[best] }+            .sortedByDescending { posterior[it] }+            .take(MAX_ALTERNATES)+            .map { ChordCandidate((bank.states[it] as ChordState.Named).name, posterior[it].toFloat()) }++        val named = ChordNaming.withSlash(name, bass)+        val bassBacked = bass != null && bass == name.root+        val gated = name.quality.tier == QualityTier.B && !bassBacked+        // A bass only settles rivals on another root: it cannot tell C from Cmaj7.+        val sameRoot = alternates.firstOrNull { it.name.root == name.root }+        val contested = if (bassBacked) sameRoot != null else alternates.isNotEmpty()+        if (gated || contested) {+            // A tier-B winner's rival is its pitch-class twin - Am7 for C6 - even when the twin+            // scored below the alternate ratio, because only the bass could ever separate them.+            val rival = (if (bassBacked) sameRoot else alternates.firstOrNull())+                ?: twinOf(bank, posterior, name)?.let { ChordCandidate(it.first, it.second.toFloat()) }+            if (rival != null) {+                val confidence = posterior[best] + rival.confidence+                if (confidence < ChordNaming.NAMING_THRESHOLD) {+                    return reading(ChordLabel.Unnamed, emptyList(), confidence, ChordPresentation.NOTES_ONLY)+                }+                return reading(ChordLabel.Ambiguous(named, rival.name), alternates, confidence, ChordPresentation.AMBIGUOUS)+            }+            if (gated) return reading(ChordLabel.Unnamed, emptyList(), posterior[best], ChordPresentation.NOTES_ONLY)+        }++        val confidence = posterior[best]+        return when {+            confidence < ChordNaming.NAMING_THRESHOLD ->+                reading(ChordLabel.Unnamed, emptyList(), confidence, ChordPresentation.NOTES_ONLY)+            confidence >= ChordNaming.CONFIDENT_THRESHOLD ->+                reading(ChordLabel.Chord(named), alternates, confidence, ChordPresentation.CONFIDENT)+            else -> reading(ChordLabel.Chord(named), alternates, confidence, ChordPresentation.UNCERTAIN)+        }+    }++    private fun twinOf(bank: ChordTemplates, posterior: DoubleArray, name: ChordName): Pair<ChordName, Double>? {+        var twin: Pair<ChordName, Double>? = null+        for (s in posterior.indices) {+            val other = (bank.states[s] as? ChordState.Named)?.name ?: continue+            if (other.root == name.root || other.pitchClasses != name.pitchClasses) continue+            if (twin == null || posterior[s] > twin.second) twin = other to posterior[s]+        }+        return twin+    }++    /** No chord fits: the note set is still the measurement, so it is shown without a name. */+    private fun notesOnly(notes: List<DetectedNote>, frame: ChromaFrame, tier: ChordTier): ChordReading {+        if (notes.isEmpty()) return silence(tier)+        val distinct = notes.map { pitchClassOf(it.midi) }.toSet()+        if (distinct.size <= 2) {+            return ChordNaming.name(notes, frame.bassMidi?.let { DetectedNote(it, frame.bassConfidence) }, tier)+        }+        return ChordReading(+            notes, null, 0f, ChordLabel.Unnamed, emptyList(), 0f, tier, ChordPresentation.NOTES_ONLY,+        )+    }++    private fun strongestMidiOf(frame: ChromaFrame, pitchClass: Int): Int {+        var best = LOWEST_NOTE_MIDI + pitchClass+        for (n in frame.semitones.indices) {+            val midi = LOWEST_NOTE_MIDI + n+            if (pitchClassOf(midi) == pitchClass && frame.semitones[n] > frame.semitones[best - LOWEST_NOTE_MIDI]) best = midi+        }+        return best+    }+     /**      * Sieve extraction, gated on flatness and on the sieve's own absolute peak.      *@@ -218,5 +380,13 @@ class ChordDetector(         const val PROVISIONAL_FIRST_BIN = 2 * CQT_BINS_PER_OCTAVE         const val HISTORY_FRAMES = 3         const val REQUIRED_FRAMES = 2+        const val BINS_PER_SEMITONE = CQT_BINS_PER_OCTAVE / 12++        /** Log-likelihood a gated frame takes off every state but no-chord. */+        const val SILENCE_EVIDENCE = 4.0++        /** A chord within this posterior ratio of the winner is shown alongside it. */+        const val ALTERNATE_RATIO = 0.6+        const val MAX_ALTERNATES = 2     } }
tuner/src/main/java/com/vayunmathur/tuner/domain/ChordHmm.kt
diff --git a/tuner/src/main/java/com/vayunmathur/tuner/domain/ChordHmm.kt b/tuner/src/main/java/com/vayunmathur/tuner/domain/ChordHmm.ktnew file mode 100644index 0000000000..3fb48f15b3--- /dev/null+++ b/tuner/src/main/java/com/vayunmathur/tuner/domain/ChordHmm.kt@@ -0,0 +1,44 @@+package com.vayunmathur.tuner.domain++import kotlin.math.exp++/**+ * Online forward filtering over [stateCount] states with a sticky diagonal.+ *+ * Forward only, so it adds no latency: each hop's posterior uses the past and the present frame.+ * What it buys over per-frame decisions is accumulation - a strum's decay tail, too weak on its+ * own to separate C from C5, keeps the C it was confidently given a few hops earlier unless the+ * new evidence actually argues for something else.+ *+ * Transitions are uniform off the diagonal, which makes each step O(states).+ */+internal class ChordHmm(private val stateCount: Int, private val stay: Double = STAY) {+    val posterior = DoubleArray(stateCount) { 1.0 / stateCount }++    fun reset() {+        posterior.fill(1.0 / stateCount)+    }++    fun update(logLikelihood: DoubleArray) {+        val leave = (1.0 - stay) / (stateCount - 1)+        var peak = Double.NEGATIVE_INFINITY+        for (v in logLikelihood) if (v > peak) peak = v+        var total = 0.0+        for (s in 0 until stateCount) {+            // Sum over predecessors collapses because every off-diagonal weight is the same.+            val prior = posterior[s] * stay + (1.0 - posterior[s]) * leave+            posterior[s] = prior * exp(logLikelihood[s] - peak)+            total += posterior[s]+        }+        if (total <= 0.0) {+            reset()+            return+        }+        for (s in 0 until stateCount) posterior[s] /= total+    }++    private companion object {+        /** Per 85 ms hop. Swept against 0.7..0.97; see `ChordTemplates` for how flat that was. */+        const val STAY = 0.95+    }+}
tuner/src/main/java/com/vayunmathur/tuner/domain/ChordNaming.kt
diff --git a/tuner/src/main/java/com/vayunmathur/tuner/domain/ChordNaming.kt b/tuner/src/main/java/com/vayunmathur/tuner/domain/ChordNaming.ktindex 0031e58737..04f522bacf 100644--- a/tuner/src/main/java/com/vayunmathur/tuner/domain/ChordNaming.kt+++ b/tuner/src/main/java/com/vayunmathur/tuner/domain/ChordNaming.kt@@ -330,7 +330,7 @@ object ChordNaming {         }         .toList() -    private fun withSlash(bestName: ChordName, bassPitchClass: Int?): ChordName {+    internal fun withSlash(bestName: ChordName, bassPitchClass: Int?): ChordName {         // A slash chord only when the bass is confident and is a chord tone other than the         // root. When it is not confident, omit the slash rather than guess an inversion.         val slash = bassPitchClass
tuner/src/main/java/com/vayunmathur/tuner/domain/ChordTemplates.kt
diff --git a/tuner/src/main/java/com/vayunmathur/tuner/domain/ChordTemplates.kt b/tuner/src/main/java/com/vayunmathur/tuner/domain/ChordTemplates.ktnew file mode 100644index 0000000000..2251246bc6--- /dev/null+++ b/tuner/src/main/java/com/vayunmathur/tuner/domain/ChordTemplates.kt@@ -0,0 +1,156 @@+package com.vayunmathur.tuner.domain++import com.vayunmathur.tuner.data.Instrument+import kotlin.math.ln+import kotlin.math.pow+import kotlin.math.roundToInt+import kotlin.math.sqrt++/** What one HMM state stands for. Chords first, then bare pitch classes, then silence. */+internal sealed interface ChordState {+    data class Named(val name: ChordName) : ChordState+    data class Note(val pitchClass: Int) : ChordState+    data object NoChord : ChordState+}++/**+ * Per-frame evidence for every [ChordState], scored directly against [ChromaFrame] rather than+ * against a picked note set.+ *+ * Two views of the same frame, summed:+ * - a pitch-class template per chord with the instrument's partials folded in, so the octave and+ *   twelfth of each tone are expected rather than read as extra notes;+ * - on a fretted instrument, the best fit over the shapes [VoicingGenerator] says are playable,+ *   rendered at their real pitches. That brings in register and re-entrancy - a ukulele F sounds+ *   C lowest - without trusting pitch order, and gives no credit to voicings no hand can make.+ *+ * Bare-note states exist so a single plucked string is not read as the major triad its own+ * overtones resemble.+ */+internal class ChordTemplates(partials: List<Double>, instrument: Instrument?) {+    val states: List<ChordState> = buildList {+        for (root in 0..11) for (quality in ChordQuality.entries) add(ChordState.Named(ChordName(root, quality)))+        for (pitchClass in 0..11) add(ChordState.Note(pitchClass))+        add(ChordState.NoChord)+    }+    val noChord: Int = states.lastIndex++    private val harmonics: List<Pair<Int, Double>> = partials.take(MAX_HARMONICS).mapIndexedNotNull { index, amplitude ->+        if (amplitude <= 0.0) return@mapIndexedNotNull null+        val h = index + 1+        (12.0 * ln(h.toDouble()) / ln(2.0)).roundToInt() to (amplitude / partials[0]).pow(HARMONIC_EXPONENT)+    }++    private val chroma: Array<DoubleArray> = Array(noChord) { pitchChroma(pitchClassesOf(states[it])) }++    private val shapes: Array<List<DoubleArray>> = Array(noChord) { shapesFor(states[it], instrument) }+    private val useShapes = shapes.any { it.isNotEmpty() }++    /** Fills [out] with one log-likelihood per state. */+    fun logLikelihoods(frame: ChromaFrame, firstNote: Int, bassPitchClass: Int?, out: DoubleArray) {+        val frameNorm = norm(frame.semitones, firstNote)+        val trebleMax = frame.treble.max()+        for (s in 0 until noChord) {+            var score = dot(frame.treble, chroma[s])+            if (useShapes) {+                var best = 0.0+                if (frameNorm > 0.0) {+                    for (shape in shapes[s]) {+                        val shapeNorm = norm(shape, firstNote)+                        if (shapeNorm <= 0.0) continue+                        val fit = dot(frame.semitones, shape) / (frameNorm * shapeNorm)+                        if (fit > best) best = fit+                    }+                }+                score = CHROMA_WEIGHT * score + (1 - CHROMA_WEIGHT) * best+            }+            when (val state = states[s]) {+                is ChordState.Named -> {+                    // Tier B': a false Caug on a beginner's C is far worse than a missed real one.+                    val strict = state.name.quality.strictInterval+                    if (strict != null &&+                        frame.treble[pitchClassOf(state.name.root + strict)] <= ChordNaming.STRICT_TONE * trebleMax+                    ) {+                        score = 0.0+                    }+                    score -= COMPLEXITY_COST * state.name.quality.complexity+                    if (bassPitchClass == state.name.root) score += BASS_BONUS+                }+                is ChordState.Note -> if (bassPitchClass == state.pitchClass) score += BASS_BONUS+                ChordState.NoChord -> Unit+            }+            out[s] = SHARPNESS * score+        }+        out[noChord] = SHARPNESS * NO_CHORD_SCORE+    }++    private fun pitchClassesOf(state: ChordState): Set<Int> = when (state) {+        is ChordState.Named -> state.name.pitchClasses+        is ChordState.Note -> setOf(state.pitchClass)+        ChordState.NoChord -> emptySet()+    }++    private fun pitchChroma(pitchClasses: Set<Int>): DoubleArray {+        val out = DoubleArray(12)+        for (pc in pitchClasses) for ((offset, weight) in harmonics) out[pitchClassOf(pc + offset)] += weight+        Chroma.normalise(out)+        return out+    }++    private fun shapesFor(state: ChordState, instrument: Instrument?): List<DoubleArray> {+        if (instrument == null || instrument.strings.isEmpty()) return emptyList()+        return when (state) {+            is ChordState.Named -> VoicingGenerator.generate(instrument, state.name).map { render(it.soundingMidi) }+            is ChordState.Note -> instrument.soundingRange.filter { pitchClassOf(it) == state.pitchClass }.map { render(listOf(it)) }+            ChordState.NoChord -> emptyList()+        }+    }++    private fun render(midis: List<Int>): DoubleArray {+        val out = DoubleArray(NOTE_COUNT)+        for (midi in midis) {+            for ((offset, weight) in harmonics) {+                val n = midi + offset - LOWEST_NOTE_MIDI+                if (n in 0 until NOTE_COUNT) out[n] += weight+            }+        }+        return out+    }++    private fun dot(a: DoubleArray, b: DoubleArray): Double {+        var sum = 0.0+        for (i in a.indices) sum += a[i] * b[i]+        return sum+    }++    private fun norm(values: DoubleArray, from: Int): Double {+        var sum = 0.0+        for (i in from until values.size) sum += values[i] * values[i]+        return sqrt(sum)+    }++    private companion object {+        /** Past the eighth partial the folded pitch classes are mostly noise. */+        private const val MAX_HARMONICS = 8++        /**+         * Partial weights are flattened because the chroma is log-compressed: a partial at 0.18 of+         * the fundamental reads as far more than 0.18 of it after compression.+         *+         * This and the constants below were swept together against Record-3 and the synthetic+         * progressions in `ChordProgressionEvalTest`; every neighbouring value moved either by+         * about two points, so none of them is finely balanced.+         */+        private const val HARMONIC_EXPONENT = 0.75++        private const val CHROMA_WEIGHT = 0.5+        private const val COMPLEXITY_COST = 0.03+        private const val BASS_BONUS = 0.06++        /** A tonal frame whose best template fits worse than this is better explained as no chord. */+        private const val NO_CHORD_SCORE = 0.55++        /** Converts a cosine score to a log-likelihood; higher makes each frame more decisive. */+        private const val SHARPNESS = 30.0+    }+}
tuner/src/main/java/com/vayunmathur/tuner/domain/Chroma.kt
diff --git a/tuner/src/main/java/com/vayunmathur/tuner/domain/Chroma.kt b/tuner/src/main/java/com/vayunmathur/tuner/domain/Chroma.ktnew file mode 100644index 0000000000..6773afa061--- /dev/null+++ b/tuner/src/main/java/com/vayunmathur/tuner/domain/Chroma.kt@@ -0,0 +1,126 @@+package com.vayunmathur.tuner.domain++import kotlin.math.ln+import kotlin.math.sqrt++/**+ * One frame of chord evidence read off the CQT, with no note decisions made.+ *+ * The sieve has to commit to an exact note set before anything is named, so one missed or one+ * extra pitch class costs the name. These are soft saliences instead: the chord scorer weighs+ * every hypothesis against them and the HMM accumulates them across a strum.+ */+internal class ChromaFrame(+    /** Whitened log salience per semitone for MIDI [LOWEST_NOTE_MIDI] upwards; zero below the tier. */+    val semitones: DoubleArray,+    /** [semitones] folded to pitch classes, L2-normalised (all zero for an empty frame). */+    val treble: DoubleArray,+    /** Lowest strong note in the bass register, or null when there is none or it was not asked for. */+    val bassMidi: Int?,+    /** Salience of [bassMidi] relative to the frame's strongest semitone, 0 when null. */+    val bassConfidence: Double,+)++internal object Chroma {+    /**+     * [firstBin] masks the bins the provisional tier has not filled yet. [tuningCents] slides the+     * semitone grid onto the instrument rather than penalising a flat one for sitting between bins.+     */+    fun of(magnitudes: DoubleArray, tuningCents: Double, firstBin: Int, withBass: Boolean): ChromaFrame {+        require(magnitudes.size == CQT_BINS) { "expected $CQT_BINS bins" }+        val semitones = semitoneSalience(whiten(magnitudes, firstBin), tuningCents, firstBin)++        val treble = DoubleArray(12)+        for (n in semitones.indices) treble[pitchClassOf(LOWEST_NOTE_MIDI + n)] += semitones[n]+        normalise(treble)++        val bass = if (withBass) lowestStrongNote(semitones) else null+        return ChromaFrame(semitones, treble, bass?.first, bass?.second ?: 0.0)+    }++    /**+     * Level-normalised log compression, then the local mean subtracted.+     *+     * Normalising by the frame's own peak first is what makes the compression actually compress:+     * a quiet decay tail at -24 dBFS has CQT magnitudes around 0.03, where `ln(1 + m)` is linear.+     */+    private fun whiten(magnitudes: DoubleArray, firstBin: Int): DoubleArray {+        val out = DoubleArray(CQT_BINS)+        var peak = 0.0+        for (i in firstBin until CQT_BINS) if (magnitudes[i] > peak) peak = magnitudes[i]+        if (peak <= 0.0) return out+        val log = DoubleArray(CQT_BINS) { if (it < firstBin) 0.0 else ln(1.0 + COMPRESSION * magnitudes[it] / peak) }+        for (i in firstBin until CQT_BINS) {+            val from = maxOf(firstBin, i - WHITENING_HALF_WIDTH)+            val to = minOf(CQT_BINS - 1, i + WHITENING_HALF_WIDTH)+            var mean = 0.0+            for (k in from..to) mean += log[k]+            mean /= (to - from + 1)+            out[i] = (log[i] - mean).coerceAtLeast(0.0)+        }+        return out+    }++    /**+     * The strongest of the three bins around each tuned semitone centre.+     *+     * Three bins a semitone, so the windows `[3n - 1, 3n + 1]` partition the axis and two adjacent+     * notes can never claim the same bin, while still absorbing ±33 cents of residual mistuning and+     * string inharmonicity.+     */+    private fun semitoneSalience(white: DoubleArray, tuningCents: Double, firstBin: Int): DoubleArray {+        val shift = tuningCents * CQT_BINS_PER_OCTAVE / 1200.0+        return DoubleArray(NOTE_COUNT) { n ->+            val centre = n * BINS_PER_SEMITONE + shift+            if (centre < firstBin) {+                0.0+            } else {+                maxOf(sample(white, centre - 1), sample(white, centre), sample(white, centre + 1))+            }+        }+    }++    private fun sample(values: DoubleArray, position: Double): Double {+        if (position < 0.0 || position > values.size - 1) return 0.0+        val low = position.toInt()+        val high = minOf(low + 1, values.size - 1)+        val t = position - low+        return values[low] * (1 - t) + values[high] * t+    }++    /**+     * The bass is the lowest *strong* note, not the strongest low one: in a C chord voiced C3 E3 G3+     * all three are equally strong, and only pitch order says which is underneath.+     */+    private fun lowestStrongNote(semitones: DoubleArray): Pair<Int, Double>? {+        val peak = semitones.max()+        if (peak <= 0.0) return null+        for (n in 0..(BASS_CEILING_MIDI - LOWEST_NOTE_MIDI)) {+            val value = semitones[n]+            if (value < BASS_FRACTION * peak) continue+            if (n > 0 && semitones[n - 1] > value) continue+            if (semitones[n + 1] > value) continue+            return (LOWEST_NOTE_MIDI + n) to value / peak+        }+        return null+    }++    fun normalise(values: DoubleArray) {+        var norm = 0.0+        for (v in values) norm += v * v+        norm = sqrt(norm)+        if (norm > 0.0) for (i in values.indices) values[i] /= norm+    }++    private const val BINS_PER_SEMITONE = CQT_BINS_PER_OCTAVE / 12++    /** Dynamic range of the log stage: 40 dB below the frame's peak maps to about 0. */+    private const val COMPRESSION = 100.0++    private const val WHITENING_HALF_WIDTH = CQT_BINS_PER_OCTAVE++    /** G3. A guitar's bass sits at or below this in every common shape, barre chords included. */+    private const val BASS_CEILING_MIDI = 55++    private const val BASS_FRACTION = 0.5+}
tuner/src/main/java/com/vayunmathur/tuner/domain/HarmonicSieve.kt
diff --git a/tuner/src/main/java/com/vayunmathur/tuner/domain/HarmonicSieve.kt b/tuner/src/main/java/com/vayunmathur/tuner/domain/HarmonicSieve.ktindex 9318d4aafa..849c83287b 100644--- a/tuner/src/main/java/com/vayunmathur/tuner/domain/HarmonicSieve.kt+++ b/tuner/src/main/java/com/vayunmathur/tuner/domain/HarmonicSieve.kt@@ -8,8 +8,13 @@ import kotlin.math.roundToInt import kotlin.math.sqrt  /**- * The Chord tab's note extractor: FFT, score only the pitches the instrument can sound, take the- * strongest, subtract its measured partials, repeat.+ * The note extractor behind [ChordExtractor.SIEVE], and the source of the displayed note set+ * under [ChordExtractor.CHROMA_HMM]: FFT, score only the pitches the instrument can sound, take+ * the strongest, subtract its measured partials, repeat.+ *+ * It no longer decides chord names by default. Naming from its note set needed every pitch class+ * in a single frame and scored 14/145 on Record-3; scoring chords directly against chroma with+ * HMM smoothing scores 42/145 on the same recording (see `RealAudioHarnessTest`).  *  * This replaced NNLS as the primary extractor on measured evidence, not on preference. The  * argument for the deconvolution is that a note's overtone series is itself a chord, so a plain
tuner/src/main/java/com/vayunmathur/tuner/domain/Tonality.kt
diff --git a/tuner/src/main/java/com/vayunmathur/tuner/domain/Tonality.kt b/tuner/src/main/java/com/vayunmathur/tuner/domain/Tonality.ktindex 1950e28c9b..6350aeb3bb 100644--- a/tuner/src/main/java/com/vayunmathur/tuner/domain/Tonality.kt+++ b/tuner/src/main/java/com/vayunmathur/tuner/domain/Tonality.kt@@ -73,6 +73,14 @@ data class Tonality(          */         const val MAX_FLATNESS: Double = 0.40 +        /**+         * The gate for `ChordExtractor.CHROMA_HMM`. The note-first extractors name every frame they+         * pass on its own; the HMM weighs a marginal frame as weak evidence instead. On Record-3,+         * loosening its gate from 0.40 to 0.60 took correct frames from 33 to 42 with wrong ones+         * unchanged at 2. Still below the 0.709 of the most tonal noise measured here.+         */+        const val CHROMA_MAX_FLATNESS: Double = 0.60+         /**          * In the units [NoteSalience.subtractBackground] produces - log-magnitude above a local          * mean - so this is an absolute floor on how far a note stands out of its own
tuner/src/main/java/com/vayunmathur/tuner/platform/TunerViewModel.kt
diff --git a/tuner/src/main/java/com/vayunmathur/tuner/platform/TunerViewModel.kt b/tuner/src/main/java/com/vayunmathur/tuner/platform/TunerViewModel.ktindex acfd61a83b..de345883ab 100644--- a/tuner/src/main/java/com/vayunmathur/tuner/platform/TunerViewModel.kt+++ b/tuner/src/main/java/com/vayunmathur/tuner/platform/TunerViewModel.kt@@ -86,11 +86,7 @@ class TunerViewModel(application: Application) : AndroidViewModel(application) {      init {         // Not foldable into the field initialiser: `chord` is constructed before `state` exists.-        chord.setInstrument(-            state.instrument.soundingRange,-            state.instrument.partials,-            state.instrument.polyphony,-        )+        chord.setInstrument(state.instrument)     }      private fun initialState(): TunerUiState {@@ -187,7 +183,7 @@ class TunerViewModel(application: Application) : AndroidViewModel(application) {         val instrument = state.instruments.firstOrNull { it.id == id } ?: return         smoother.reset()         noteHold.reset()-        chord.setInstrument(instrument.soundingRange, instrument.partials, instrument.polyphony)+        chord.setInstrument(instrument)         resetChord()         state = state.copy(             instrument = instrument,
tuner/src/test/java/com/vayunmathur/tuner/domain/ChordProgressionEvalTest.kt
diff --git a/tuner/src/test/java/com/vayunmathur/tuner/domain/ChordProgressionEvalTest.kt b/tuner/src/test/java/com/vayunmathur/tuner/domain/ChordProgressionEvalTest.ktnew file mode 100644index 0000000000..44e2955170--- /dev/null+++ b/tuner/src/test/java/com/vayunmathur/tuner/domain/ChordProgressionEvalTest.kt@@ -0,0 +1,234 @@+package com.vayunmathur.tuner.domain++import com.vayunmathur.tuner.data.Instrument+import com.vayunmathur.tuner.data.InstrumentCatalog+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Streams labelled synthetic progressions through the detector exactly as `TunerViewModel` does -+ * same hop, same tier schedule, same [ChordPresenter] - and scores what the user would see.+ *+ * `build/chord-eval-report.txt` is the full comparison. The assertions are relative (the shipping+ * extractor must beat the sieve it replaced) plus floors set below the measured numbers, because+ * absolute accuracy on a synthetic corpus is a ceiling, not a prediction. See [StrumSynth].+ */+class ChordProgressionEvalTest {+    private val catalog = InstrumentCatalog.parse(File("src/main/assets/instruments.json").readText())+    private val guitar = catalog.byId("guitar-standard")+    private val ukulele = catalog.byId("ukulele-gcea")++    private fun c(root: Int, quality: ChordQuality = ChordQuality.MAJOR) = ChordName(root, quality)+    private val minor = ChordQuality.MINOR++    private val guitarProgressions = listOf(+        listOf(c(7), c(2), c(4, minor), c(0)),+        listOf(c(0), c(9, minor), c(5), c(7)),+        listOf(c(9, minor), c(2, minor), c(4, ChordQuality.DOMINANT_SEVENTH), c(9, minor)),+        listOf(c(2, ChordQuality.MINOR_SEVENTH), c(7, ChordQuality.DOMINANT_SEVENTH), c(0, ChordQuality.MAJOR_SEVENTH), c(9, minor)),+        listOf(c(9), c(4), c(6, minor), c(2)),+        listOf(c(4), c(9), c(11, ChordQuality.DOMINANT_SEVENTH), c(4)),+    )++    private val ukuleleProgressions = listOf(+        listOf(c(0), c(7), c(9, minor), c(5)),+        listOf(c(5), c(0), c(2, minor), c(10)),+        listOf(c(7, ChordQuality.DOMINANT_SEVENTH), c(0), c(9, minor), c(2, minor)),+        listOf(c(9), c(2), c(4, ChordQuality.DOMINANT_SEVENTH), c(9)),+    )++    private class Metrics {+        var frames = 0+        var shownCorrect = 0+        var shownOffered = 0+        var rawCorrect = 0+        var shownChanges = 0+        var chordChanges = 0+        val latenciesMs = ArrayList<Double>()+        var missed = 0+        var tierBAlone = 0+        val confusions = HashMap<String, Int>()++        fun add(other: Metrics) {+            frames += other.frames+            shownCorrect += other.shownCorrect+            shownOffered += other.shownOffered+            rawCorrect += other.rawCorrect+            shownChanges += other.shownChanges+            chordChanges += other.chordChanges+            latenciesMs += other.latenciesMs+            missed += other.missed+            tierBAlone += other.tierBAlone+            for ((key, count) in other.confusions) confusions[key] = (confusions[key] ?: 0) + count+        }++        fun rate(part: Int) = if (frames == 0) 0.0 else part.toDouble() / frames+        val medianLatency: Double get() = latenciesMs.sorted().let { if (it.isEmpty()) Double.NaN else it[it.size / 2] }++        fun row(label: String) = "  %-28s frames %4d  shown-correct %5.1f%%  shown-offered %5.1f%%  raw-correct %5.1f%%  median-latency %5.0f ms  missed %2d/%2d  label-changes %3d (chord changes %d)".format(+            label, frames, 100 * rate(shownCorrect), 100 * rate(shownOffered), 100 * rate(rawCorrect),+            medianLatency, missed, chordChanges, shownChanges, chordChanges,+        )+    }++    private fun namesIn(label: ChordLabel?): List<ChordName> = when (label) {+        is ChordLabel.Chord -> listOf(label.name)+        is ChordLabel.Ambiguous -> listOf(label.primary, label.secondary)+        else -> emptyList()+    }++    private fun same(a: ChordName, b: ChordName) = a.root == b.root && a.quality == b.quality++    private fun symbol(name: ChordName) = spellPitchClass(name.root) + name.quality.symbol++    private fun describe(label: ChordLabel?): String = when (label) {+        null -> "blank"+        is ChordLabel.Chord -> symbol(label.name)+        is ChordLabel.Ambiguous -> "${symbol(label.primary)}|${symbol(label.secondary)}"+        else -> label.javaClass.simpleName+    }++    private fun stream(instrument: Instrument, extractor: ChordExtractor, take: StrumSynth.Take): Metrics {+        val detector = ChordDetector(Signals.SAMPLE_RATE, extractor = extractor)+        detector.setInstrument(instrument)+        val presenter = ChordPresenter()+        val window = detector.requiredSamples+        val metrics = Metrics()+        var chordFrames = 0+        var previousShown: ChordLabel? = null+        val firstHit = HashMap<StrumSynth.Segment, Int>()++        var end = window+        while (end <= take.audio.size) {+            val frame = take.audio.copyOfRange(end - window, end)+            val tier = if (chordFrames < CONFIRM_FRAMES) ChordTier.PROVISIONAL else ChordTier.CONFIRMED+            chordFrames+++            val reading = detector.analyse(frame, tier, !instrument.reentrant)+            val alone = (reading.label as? ChordLabel.Chord)?.name+            if (alone != null && alone.quality.tier == QualityTier.B && reading.bass != alone.root) metrics.tierBAlone+++            if (presenter.update(reading) == ChordDisplay.CLEARED) {+                detector.reset()+                presenter.reset()+                chordFrames = 0+            }+            val shown = presenter.current?.label+            if (shown != previousShown) metrics.shownChanges+++            previousShown = shown++            val segment = take.segments.firstOrNull { end - 1 >= it.start && end - 1 < it.end }+            if (segment != null) {+                metrics.frames+++                val truth = segment.chord+                val shownChord = (shown as? ChordLabel.Chord)?.name+                if (shownChord != null && same(shownChord, truth)) metrics.shownCorrect+++                val rawChord = (reading.label as? ChordLabel.Chord)?.name+                if (rawChord != null && same(rawChord, truth)) metrics.rawCorrect+++                if (namesIn(shown).any { same(it, truth) }) {+                    metrics.shownOffered+++                    if (segment !in firstHit) firstHit[segment] = end+                } else {+                    val key = "${symbol(truth)} -> ${describe(shown)}"+                    metrics.confusions[key] = (metrics.confusions[key] ?: 0) + 1+                }+            }+            end += HOP+        }+        for (segment in take.segments) {+            metrics.chordChanges+++            val hit = firstHit[segment]+            if (hit == null) metrics.missed++ else metrics.latenciesMs += (hit - segment.start) / Signals.SAMPLE_RATE * 1000+        }+        return metrics+    }++    private fun evaluate(instrument: Instrument, progressions: List<List<ChordName>>, extractor: ChordExtractor): Metrics {+        val total = Metrics()+        for ((index, progression) in progressions.withIndex()) {+            for (seed in SEEDS) {+                total.add(stream(instrument, extractor, takes.getOrPut(Triple(instrument.id, index, seed)) {+                    StrumSynth.take(instrument, progression, seed = seed * 101 + index)+                }))+            }+        }+        return total+    }++    private val takes = HashMap<Triple<String, Int, Int>, StrumSynth.Take>()++    @Test+    fun chromaHmmBeatsTheSieveOnStrummedProgressions() {+        val report = StringBuilder("Synthetic strummed progressions, streamed as TunerViewModel does\n")+        val results = HashMap<Pair<String, ChordExtractor>, Metrics>()+        for ((instrument, progressions) in listOf(guitar to guitarProgressions, ukulele to ukuleleProgressions)) {+            report.appendLine("=== ${instrument.id}: ${progressions.size} progressions x ${SEEDS.size} takes")+            for (extractor in listOf(ChordExtractor.SIEVE, ChordExtractor.CHROMA_HMM)) {+                val metrics = evaluate(instrument, progressions, extractor)+                results[instrument.id to extractor] = metrics+                report.appendLine(metrics.row(extractor.name))+                val top = metrics.confusions.entries.sortedByDescending { it.value }.take(6)+                report.appendLine("      misses: " + top.joinToString { "${it.key} x${it.value}" })+            }+        }+        File("build").mkdirs()+        File("build/chord-eval-report.txt").writeText(report.toString())+        println(report)++        for ((instrument, floor) in listOf(guitar to GUITAR_FLOOR, ukulele to UKULELE_FLOOR)) {+            val hmm = results.getValue(instrument.id to ChordExtractor.CHROMA_HMM)+            assertTrue(hmm.rate(hmm.shownOffered) >= floor, "${instrument.id}: offered fell below $floor\n$report")+            assertEquals(0, hmm.tierBAlone, "${instrument.id}: a tier-B quality was named without its bass")+        }+        for (instrument in listOf(guitar, ukulele)) {+            val sieve = results.getValue(instrument.id to ChordExtractor.SIEVE)+            val hmm = results.getValue(instrument.id to ChordExtractor.CHROMA_HMM)+            assertTrue(+                hmm.rate(hmm.shownOffered) > sieve.rate(sieve.shownOffered),+                "${instrument.id}: CHROMA_HMM offered the right chord less often than the sieve\n$report",+            )+            assertTrue(+                hmm.rate(hmm.shownCorrect) > sieve.rate(sieve.shownCorrect),+                "${instrument.id}: CHROMA_HMM named the right chord less often than the sieve\n$report",+            )+        }+    }++    private companion object {+        /** Matches `TunerViewModel.CHORD_EVERY` x `NOTE_HOP`. */+        const val HOP = 8 * 512++        /** Matches `TunerViewModel.CONFIRM_FRAMES`. */+        const val CONFIRM_FRAMES = 8++        val SEEDS = listOf(1, 2)++        /** Measured 83% (guitar) and 88% (ukulele) on 2026-11-01; the sieve scored 73% and 83%. */+        const val GUITAR_FLOOR = 0.75+        const val UKULELE_FLOOR = 0.80+    }++    @Test+    fun analysisFitsInsideTheHop() {+        val detector = ChordDetector(Signals.SAMPLE_RATE)+        detector.setInstrument(guitar)+        val take = StrumSynth.take(guitar, guitarProgressions[0], seed = 5)+        val window = detector.requiredSamples+        val first = System.nanoTime()+        detector.analyse(take.audio.copyOfRange(0, window), ChordTier.CONFIRMED)+        val buildMs = (System.nanoTime() - first) / 1e6++        var frames = 0+        val start = System.nanoTime()+        var end = window + HOP+        while (end <= take.audio.size) {+            detector.analyse(take.audio.copyOfRange(end - window, end), ChordTier.CONFIRMED)+            frames+++            end += HOP+        }+        val perFrameMs = (System.nanoTime() - start) / 1e6 / frames+        println("MEASURED first frame incl. template bank %.1f ms, then %.2f ms per frame".format(buildMs, perFrameMs))+        // JVM on a laptop, so loose: a phone is slower, but the hop is 85 ms.+        assertTrue(perFrameMs < 20.0, "analysis takes $perFrameMs ms a frame")+    }+}
tuner/src/test/java/com/vayunmathur/tuner/domain/RealAudioHarnessTest.kt
diff --git a/tuner/src/test/java/com/vayunmathur/tuner/domain/RealAudioHarnessTest.kt b/tuner/src/test/java/com/vayunmathur/tuner/domain/RealAudioHarnessTest.ktindex 2eca46fbd8..3147a87a78 100644--- a/tuner/src/test/java/com/vayunmathur/tuner/domain/RealAudioHarnessTest.kt+++ b/tuner/src/test/java/com/vayunmathur/tuner/domain/RealAudioHarnessTest.kt@@ -121,6 +121,14 @@ class RealAudioHarnessTest {             report.appendLine("  tuning self-estimated  ${"%.1f".format(cents)} cents")             report.appendLine()         }+        val (chromaOnly, _) = production(+            pcm,+            ChordExtractor.CHROMA_HMM,+            withVoicings = false,+            label = "CHROMA_HMM, production path, chroma templates only (no voicings)",+        )+        report.appendLine(chromaOnly.report())+        report.appendLine()     }      private fun appendPolyphonySweep(report: StringBuilder, pcm: DoubleArray) {@@ -161,16 +169,18 @@ class RealAudioHarnessTest {         // frame bought a note or two and no name. The sieve finds 3.39, so frames that were not         // worth passing then may be worth passing now. Swept here rather than reasoned about,         // because the synthetic corpus has nothing to say about where a real decay tail sits.-        report.appendLine("=== tonality gate sweep, SIEVE, production path")-        report.appendLine("  flatness   tonal   named   CORRECT   notes/tonal")-        for (threshold in FLATNESS_SWEEP) {-            val (score, _) = production(pcm, ChordExtractor.SIEVE, threshold)-            val perTonal = if (score.tonal == 0) 0.0 else score.notes.toDouble() / score.tonal-            report.appendLine(-                "  %8.2f %7d %7d %9d %13.2f".format(-                    threshold, score.tonal, score.named, score.correct, perTonal,-                ),-            )+        report.appendLine("=== tonality gate sweep, production path")+        report.appendLine("  extractor    flatness   tonal   named   CORRECT   notes/tonal")+        for (extractor in listOf(ChordExtractor.SIEVE, ChordExtractor.CHROMA_HMM)) {+            for (threshold in FLATNESS_SWEEP) {+                val (score, _) = production(pcm, extractor, threshold)+                val perTonal = if (score.tonal == 0) 0.0 else score.notes.toDouble() / score.tonal+                report.appendLine(+                    "  %-10s %8.2f %7d %7d %9d %13.2f".format(+                        extractor, threshold, score.tonal, score.named, score.correct, perTonal,+                    ),+                )+            }         }         report.appendLine()     }@@ -186,9 +196,11 @@ class RealAudioHarnessTest {     private fun production(         pcm: DoubleArray,         extractor: ChordExtractor,-        maxFlatness: Double = Tonality.MAX_FLATNESS,+        maxFlatness: Double =+            if (extractor == ChordExtractor.CHROMA_HMM) Tonality.CHROMA_MAX_FLATNESS else Tonality.MAX_FLATNESS,         polyphony: Int = ukulele.polyphony,         relativeFloor: Double = HarmonicSieve.RELATIVE_FLOOR,+        withVoicings: Boolean = true,         label: String? = null,     ): Pair<Score, Double> {         val constantQ = ConstantQ(RealAudioHarness.RATE)@@ -201,6 +213,7 @@ class RealAudioHarnessTest {             maxFlatness,             polyphony,             relativeFloor,+            if (withVoicings) ukulele else null,         )         detector.reset()         val score = Score(label ?: "$extractor, production path (${frames.size} frames)")
tuner/src/test/java/com/vayunmathur/tuner/domain/StrumStabilityTest.kt
diff --git a/tuner/src/test/java/com/vayunmathur/tuner/domain/StrumStabilityTest.kt b/tuner/src/test/java/com/vayunmathur/tuner/domain/StrumStabilityTest.ktindex 2f4df35d10..41e8c7bc48 100644--- a/tuner/src/test/java/com/vayunmathur/tuner/domain/StrumStabilityTest.kt+++ b/tuner/src/test/java/com/vayunmathur/tuner/domain/StrumStabilityTest.kt@@ -29,7 +29,13 @@ import kotlin.test.assertTrue  */ class StrumStabilityTest {     private val constantQ = ConstantQ(Signals.SAMPLE_RATE)-    private val detector = ChordDetector(Signals.SAMPLE_RATE)++    /**+     * Pinned to the note-first gate. The shipping [ChordExtractor.CHROMA_HMM] gate sits at+     * [Tonality.CHROMA_MAX_FLATNESS] and does not drop out on this strum at all (asserted below),+     * so it cannot produce the flickering input the presenter has to be proven against.+     */+    private val detector = ChordDetector(Signals.SAMPLE_RATE, maxFlatness = Tonality.MAX_FLATNESS)     private val window = constantQ.requiredSamples      /** 8 note hops of 512 samples: what TunerViewModel.CHORD_EVERY produces, ~85 ms. */@@ -47,7 +53,10 @@ class StrumStabilityTest {      * Ukulele, so the bass is suppressed: on a re-entrant instrument the lowest sounding pitch      * is routinely not the root.      */-    private fun traces(signal: DoubleArray): Pair<List<ChordLabel?>, List<ChordLabel?>> {+    private fun traces(+        signal: DoubleArray,+        detector: ChordDetector = this.detector,+    ): Pair<List<ChordLabel?>, List<ChordLabel?>> {         val presenter = ChordPresenter()         detector.reset()         val raw = ArrayList<ChordLabel?>()@@ -87,6 +96,13 @@ class StrumStabilityTest {         assertTrue(dropouts(shown) <= 1, "display flickered ${dropouts(shown)} times: $shown")     } +    @Test+    fun theShippingDetectorHoldsTheSameStrumWithoutThePresenter() {+        val total = window + hop * 20+        val (raw, _) = traces(Signals.strum(ukeC, total, roomSigma = 0.055), ChordDetector(Signals.SAMPLE_RATE))+        assertTrue(dropouts(raw) <= 1, "the shipping gate dropped out ${dropouts(raw)} times: $raw")+    }+     @Test     fun aGatedFrameInTheMiddleOfAStrumDoesNotBlankTheTab() {         // The exact failure mode measured on the device: one frame slips over the flatness gate
tuner/src/test/java/com/vayunmathur/tuner/domain/StrumSynth.kt
diff --git a/tuner/src/test/java/com/vayunmathur/tuner/domain/StrumSynth.kt b/tuner/src/test/java/com/vayunmathur/tuner/domain/StrumSynth.ktnew file mode 100644index 0000000000..541af7bca9--- /dev/null+++ b/tuner/src/test/java/com/vayunmathur/tuner/domain/StrumSynth.kt@@ -0,0 +1,133 @@+package com.vayunmathur.tuner.domain++import com.vayunmathur.tuner.data.Instrument+import kotlin.math.PI+import kotlin.math.exp+import kotlin.math.pow+import kotlin.math.sin+import kotlin.math.sqrt+import kotlin.random.Random++/**+ * Labelled chord progressions strummed on a modelled fretted instrument.+ *+ * Built to be unlike the detector's own model wherever that is cheap to arrange, because a corpus+ * generated from the templates it is scored against measures nothing (see `HarmonicSieve`). Each+ * take draws its own partial law, inharmonicity, detuning, strum timing, per-string level and+ * decay, room noise level, and picks among every shape [VoicingGenerator] offers rather than the+ * recommended one.+ *+ * Still synthetic: no body resonance, sympathetic strings, fret buzz or microphone colouring. It+ * is a regression and comparison tool, not a prediction of real accuracy - Record-3 is that.+ */+internal object StrumSynth {+    data class Segment(val chord: ChordName, val start: Int, val end: Int)++    class Take(val audio: DoubleArray, val segments: List<Segment>) {+        /** The chord sounding at [sample], or null before the first strum. */+        fun chordAt(sample: Int): ChordName? = segments.firstOrNull { sample >= it.start && sample < it.end }?.chord+    }++    fun take(+        instrument: Instrument,+        progression: List<ChordName>,+        seed: Int,+        secondsPerChord: Double = 2.0,+    ): Take {+        val random = Random(seed)+        val rate = Signals.SAMPLE_RATE+        val chordSamples = (secondsPerChord * rate).toInt()+        val lead = (0.3 * rate).toInt()+        val total = lead + chordSamples * progression.size+        val out = DoubleArray(total)++        val rolloff = 0.8 + 1.4 * random.nextDouble()+        val partialJitter = List(PARTIALS) { 0.6 + 0.8 * random.nextDouble() }+        val stiffness = 3e-4 * random.nextDouble()+        // Biased flat to match TuningOffset, which reads more than 25 cents sharp as flat of the+        // semitone above - an ambiguity in the audio, not something either extractor can resolve.+        val globalCents = -45.0 + 65.0 * random.nextDouble()++        val segments = ArrayList<Segment>()+        val notes = ArrayList<Note>()+        val lastOnString = HashMap<Int, Note>()+        for ((index, chord) in progression.withIndex()) {+            val start = lead + index * chordSamples+            val end = start + chordSamples+            segments += Segment(chord, start, end)+            val shapes = VoicingGenerator.generate(instrument, chord)+            require(shapes.isNotEmpty()) { "no voicing for $chord on ${instrument.id}" }+            val shape = shapes[random.nextInt(shapes.size)]++            // Refretting damps whatever was ringing.+            for (note in lastOnString.values) note.dampAt = minOf(note.dampAt, start)++            val strums = if (random.nextBoolean()) listOf(start) else listOf(start, start + chordSamples / 2)+            for ((k, strumStart) in strums.withIndex()) {+                val downward = k % 2 == 0+                val order = instrument.strings.indices+                    .filter { shape.frets[it] >= 0 }+                    .sortedBy { instrument.strings[it].openMidi.let { open -> if (downward) open else -open } }+                val stagger = (0.005 + 0.020 * random.nextDouble()) * rate+                for ((position, string) in order.withIndex()) {+                    val midi = instrument.strings[string].openMidi + shape.frets[string]+                    val cents = globalCents - 4.0 + 8.0 * random.nextDouble()+                    val note = Note(+                        hz = 440.0 * 2.0.pow((midi - 69) / 12.0 + cents / 1200.0),+                        onset = strumStart + (position * stagger).toInt(),+                        level = 0.12 * (0.5 + 0.5 * random.nextDouble()),+                        decay = 0.6 + 1.9 * random.nextDouble(),+                        dampAt = total,+                    )+                    // A restrike damps the same string's previous note.+                    lastOnString[string]?.let { it.dampAt = minOf(it.dampAt, note.onset) }+                    lastOnString[string] = note+                    notes += note+                }+            }+        }+        for (note in notes) render(out, note, rolloff, partialJitter, stiffness)++        addRoom(out, snrDb = 15.0 + 20.0 * random.nextDouble(), seed = seed)+        return Take(out, segments)+    }++    private class Note(val hz: Double, val onset: Int, val level: Double, val decay: Double, var dampAt: Int)++    private fun render(out: DoubleArray, note: Note, rolloff: Double, jitter: List<Double>, stiffness: Double) {+        val rate = Signals.SAMPLE_RATE+        val stop = minOf(out.size, note.dampAt + (DAMP_SECONDS * 6 * rate).toInt())+        for (n in 1..PARTIALS) {+            val hz = n * note.hz * sqrt(1.0 + stiffness * n * n)+            if (hz >= rate / 2) break+            val amplitude = note.level * jitter[n - 1] / n.toDouble().pow(rolloff)+            // Upper partials die faster, as on a real string.+            val decay = note.decay / (1.0 + 0.3 * (n - 1))+            val step = 2.0 * PI * hz / rate+            for (i in note.onset until stop) {+                val t = (i - note.onset) / rate+                var envelope = exp(-t / decay)+                if (i > note.dampAt) envelope *= exp(-(i - note.dampAt) / rate / DAMP_SECONDS)+                out[i] += amplitude * envelope * sin(step * (i - note.onset) + n)+            }+        }+        // Pick noise.+        val random = Random(note.onset)+        val burst = (0.004 * rate).toInt()+        for (i in note.onset until minOf(out.size, note.onset + burst)) {+            out[i] += note.level * 0.5 * (2 * random.nextDouble() - 1) * exp(-(i - note.onset) / (burst / 4.0))+        }+    }++    private fun addRoom(out: DoubleArray, snrDb: Double, seed: Int) {+        var power = 0.0+        for (v in out) power += v * v+        power /= out.size+        val sigma = sqrt(power / 10.0.pow(snrDb / 10.0))+        val room = Signals.pinkNoise(out.size, sigma = sigma, seed = seed + 1)+        for (i in out.indices) out[i] += room[i]+    }++    private const val PARTIALS = 10+    private const val DAMP_SECONDS = 0.04+}