Modern Apps git

← Modern-Apps.git

tuner: pick the Note tab's note by harmonic-summation salience

Commit
8da16690f7dd3003272d8ab2482cdca29ec73460
Author
Vayun Mathur <[email protected]>
When
2026-11-01 18:27 UTC (1 month ago)
Parents
53030af
Reported: an A4 read as E2. Unrestricted YIN reports the period of the whole
signal, so with another string ringing it settled on a much lower note: A4 over
a low E at -12 dB read F2, over six open strings A0, over 60 Hz hum B1.

PredominantPitch implements Klapuri's harmonic-summation salience (2006) with
spectral whitening to choose the note; YIN and phase-slope then measure it
within one semitone, so precision is unchanged. Extra guards: a lower note
must have its own partials (missing-fundamental low E), a candidate must earn
its energy from its first partials (no phantom root under a strum), and a
sub-100 Hz tone with no overtone series is rejected. The aperiodicity gate
moves 0.20 -> 0.45, measured at the chosen note: noise never scores below 0.89.

- A4 + low E / six open strings / hum: A4 within 0.7 cents
- Existing accuracy tests unchanged (worst 0.06 cents)
- Record-3 sub-100 Hz misreads: 310 -> ~60 frames

Diff

tuner/AGENTS.md
diff --git a/tuner/AGENTS.md b/tuner/AGENTS.mdindex ec242948ad..b64e262aac 100644--- a/tuner/AGENTS.md+++ b/tuner/AGENTS.md@@ -13,7 +13,7 @@ _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 + 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/`.+**Key features:** Raw-mic `AudioCapture` → `domain/` DSP chain (Klapuri harmonic-summation salience picks the note, YIN + phase-slope measure it; 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:** `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. @@ -26,6 +26,7 @@ _Install: ./install tuner (dev by default)._ - com/vayunmathur/tuner/data/Instruments.kt ### domain/ — pure DSP (no Android) - com/vayunmathur/tuner/domain/PitchDetector.kt+- com/vayunmathur/tuner/domain/PredominantPitch.kt - com/vayunmathur/tuner/domain/Yin.kt - com/vayunmathur/tuner/domain/Fft.kt - com/vayunmathur/tuner/domain/ConstantQ.kt
tuner/src/main/java/com/vayunmathur/tuner/domain/PitchDetector.kt
diff --git a/tuner/src/main/java/com/vayunmathur/tuner/domain/PitchDetector.kt b/tuner/src/main/java/com/vayunmathur/tuner/domain/PitchDetector.ktindex c717f6b3a9..d760b0c7d5 100644--- a/tuner/src/main/java/com/vayunmathur/tuner/domain/PitchDetector.kt+++ b/tuner/src/main/java/com/vayunmathur/tuner/domain/PitchDetector.kt@@ -2,6 +2,7 @@ package com.vayunmathur.tuner.domain  import kotlin.math.abs import kotlin.math.exp+import kotlin.math.pow  /** Which of the two operating bands produced a reading (TUNER_SPEC A.4). */ enum class PitchBand(@@ -9,12 +10,14 @@ enum class PitchBand(     val hopSize: Int,     val subWindow: Int,     val separation: Int,+    /** Samples [PredominantPitch] reads; longer than the YIN window in the fast band, to resolve semitones. */+    val salienceWindow: Int, ) {     /** Guitar D3 and up, ukulele, piano E3+. ~32 ms latency. */-    FAST(windowSize = 2048, hopSize = 512, subWindow = 1024, separation = 1024),+    FAST(windowSize = 2048, hopSize = 512, subWindow = 1024, separation = 1024, salienceWindow = 4096),      /** Bass, guitar low E/A, piano bass. ~107 ms latency, and worth every millisecond. */-    LOW(windowSize = 8192, hopSize = 1024, subWindow = 4096, separation = 4096),+    LOW(windowSize = 8192, hopSize = 1024, subWindow = 4096, separation = 4096, salienceWindow = 8192), }  /** One accepted frame of the Note tab's pipeline. */@@ -56,8 +59,12 @@ interface PitchAnalyzer { }  /**- * Two-stage YIN then harmonic phase-slope, with the operating band selected by the detected- * octave rather than by compromising on either window length.+ * Predominant-note selection, then two-stage YIN and harmonic phase-slope, with the operating band+ * selected by the detected octave rather than by compromising on either window length.+ *+ * [PredominantPitch] decides which note is sounding; YIN only measures it, searching within+ * [NOTE_SPAN_SEMITONES] of that note. Unrestricted, YIN reports the period of the whole mixture,+ * which with another string ringing is a note far below the one plucked.  *  * Cold start is the low band, so a bass note is caught on the first frame instead of after a  * failed fast-band attempt.@@ -67,6 +74,7 @@ class YinPhaseSlopeAnalyzer(val sampleRate: Double) : PitchAnalyzer {     private val refiner = PitchBand.entries.associateWith {         PhaseSlope(sampleRate, it.subWindow, it.separation)     }+    private val predominant = PredominantPitch(sampleRate)      private var band = PitchBand.LOW     private var lowVotes = 0@@ -86,8 +94,15 @@ class YinPhaseSlopeAnalyzer(val sampleRate: Double) : PitchAnalyzer {         require(samples.size >= requiredSamples) { "need at least $requiredSamples samples" }         val active = band         val offset = samples.size - active.windowSize-        val coarse = yin.getValue(active).analyse(samples, offset, minHz, maxHz)-            ?: return reject(PitchRejection.OUT_OF_RANGE, 0.0)+        val note = predominant.estimate(samples, active.salienceWindow, minHz, maxHz)+            ?: return reject(PitchRejection.NOT_PERIODIC, 0.0)+        val span = 2.0.pow(NOTE_SPAN_SEMITONES / 12.0)+        val coarse = yin.getValue(active).analyse(+            samples,+            offset,+            maxOf(minHz, note / span),+            minOf(maxHz, note * span),+        ) ?: return reject(PitchRejection.OUT_OF_RANGE, 0.0)          if (coarse.rms < noiseFloor * NOISE_MARGIN) {             return reject(PitchRejection.TOO_QUIET, coarse.rms)@@ -156,12 +171,24 @@ class YinPhaseSlopeAnalyzer(val sampleRate: Double) : PitchAnalyzer {     }      private companion object {-        const val APERIODICITY_GATE = 0.20+        /**+         * Measured at the predominant note: noise never scores below 0.89, an A4 over six open+         * strings at -12 dB scores 0.35, and an equal-level chord - not one note - 0.79. The old+         * 0.20 was set for unrestricted YIN, which got its low numbers by settling on the+         * mixture's period instead of the plucked note.+         */+        const val APERIODICITY_GATE = 0.45         const val CROSS_CHECK_CENTS = 25.0         const val LOW_BAND_ENTRY_HZ = 150.0         const val FAST_BAND_ENTRY_HZ = 175.0         const val BAND_VOTES = 3 +        /**+         * How far from the predominant note YIN may look. The salience grid is 10 cents and the+         * displayed range is +/-50, so this only has to hold one dip of the difference function.+         */+        const val NOTE_SPAN_SEMITONES = 1.0+         /** +12 dB above the tracked floor. */         const val NOISE_MARGIN = 3.98 
tuner/src/main/java/com/vayunmathur/tuner/domain/PredominantPitch.kt
diff --git a/tuner/src/main/java/com/vayunmathur/tuner/domain/PredominantPitch.kt b/tuner/src/main/java/com/vayunmathur/tuner/domain/PredominantPitch.ktnew file mode 100644index 0000000000..cb1e8d8aa2--- /dev/null+++ b/tuner/src/main/java/com/vayunmathur/tuner/domain/PredominantPitch.kt@@ -0,0 +1,257 @@+package com.vayunmathur.tuner.domain++import kotlin.math.PI+import kotlin.math.cos+import kotlin.math.pow+import kotlin.math.sqrt++/**+ * Which note is the loudest thing sounding: Klapuri's harmonic-summation salience (Klapuri 2006,+ * "Multiple fundamental frequency estimation by summing harmonic amplitudes"), the standard+ * method for the predominant pitch of a mixture.+ *+ * YIN alone answers a different question - the period of the *whole* signal - and with anything+ * else sounding that period is far below the plucked note: an A4 over a low E ringing at -12 dB+ * read F2 (five A4 periods, where E2 also nearly repeats), and over six open strings it read A0.+ * Here every candidate f0 instead collects whitened spectral peaks at its partials, weighted by+ * `g(f, m) = (f + ALPHA) / (m * f + BETA)`. The weight is what makes the plucked note win: A4's+ * own fundamental counts 3.5 times more towards A4 than towards F2, which can only claim it as+ * its fifth partial.+ *+ * The weighting leans slightly upward, so a low string with no fundamental can look like its own+ * octave. [subharmonicOf] undoes that only when the lower note's *own* partials - those the+ * higher candidate cannot claim - carry real energy: a real E2 has 82, 247 and 412 Hz; the+ * phantom F2 under an A4 has nothing at 87, 175, 262 or 349 Hz.+ *+ * Only the note is taken from here. The displayed frequency still comes from YIN and phase-slope,+ * restricted to this note's neighbourhood, so sub-cent precision is unchanged.+ */+class PredominantPitch(private val sampleRate: Double) {+    private val transforms = HashMap<Int, Workspace>()++    /** Predominant f0 in Hz of the last [length] samples of [x], or null for an empty spectrum. */+    fun estimate(x: DoubleArray, length: Int, minHz: Double, maxHz: Double): Double? {+        val space = transforms.getOrPut(length) { Workspace(length) }+        val spectrum = space.whitened(x, x.size - length) ?: return null+        val raw = space.magnitude+        val binHz = sampleRate / space.fftSize++        val candidates = ArrayList<Double>()+        var f = minHz+        while (f <= maxHz) {+            candidates += f+            f *= GRID_STEP+        }+        var best = -1+        var bestSalience = 0.0+        val saliences = DoubleArray(candidates.size)+        for ((i, candidate) in candidates.withIndex()) {+            saliences[i] = salience(spectrum, binHz, candidate, null)+            if (saliences[i] > bestSalience && supported(raw, binHz, candidate)) {+                bestSalience = saliences[i]+                best = i+            }+        }+        if (best < 0) return null+        val peak = refine(candidates, saliences, best)+        if (isPureLowTone(raw, binHz, peak)) return null+        val f0 = subharmonicOf(spectrum, raw, binHz, peak, bestSalience, minHz)+        return if (isPureLowTone(raw, binHz, f0)) null else f0+    }++    /**+     * A low tone with no overtone series is not a string. On Record-3 the gaps between strums+     * carry a 59-66 Hz tone - mains, an appliance or handling - with ~90% of its partial energy in+     * one partial, where a phone-captured low E has 33% in its strongest. Unchecked it read as+     * B1 and C2, and an octave below that as A#0.+     */+    private fun isPureLowTone(raw: DoubleArray, binHz: Double, f0: Double): Boolean {+        if (f0 >= PURE_TONE_CEILING_HZ) return false+        var total = 0.0+        var strongest = 0.0+        for (m in 1..PURE_TONE_PARTIALS) {+            val p = partialPeak(raw, binHz, m * f0)+            total += p * p+            strongest = maxOf(strongest, p * p)+        }+        return total > 0.0 && strongest / total >= PURE_TONE_SHARE+    }++    /**+     * Whether [f0]'s first partials carry their share of its energy, read off the unwhitened+     * spectrum: whitening lifts quiet low bands, which would let room noise at a phantom root's+     * fundamental and octave count as support.+     */+    private fun supported(raw: DoubleArray, binHz: Double, f0: Double): Boolean =+        salience(raw, binHz, f0, null, LOW_ORDER_PARTIALS) >= LOW_ORDER_SHARE * salience(raw, binHz, f0, null)++    private fun subharmonicOf(+        spectrum: DoubleArray,+        raw: DoubleArray,+        binHz: Double,+        f0: Double,+        salience: Double,+        minHz: Double,+    ): Double {+        for (k in MAX_SUBHARMONIC downTo 2) {+            val lower = f0 / k+            if (lower < minHz) continue+            if (salience(spectrum, binHz, lower, k) >= OWN_PARTIAL_RATIO * salience && supported(raw, binHz, lower)) {+                return lower+            }+        }+        return f0+    }++    /** Parabolic interpolation in log-frequency across the grid. */+    private fun refine(candidates: List<Double>, saliences: DoubleArray, i: Int): Double {+        if (i == 0 || i == candidates.lastIndex) return candidates[i]+        val a = saliences[i - 1]+        val b = saliences[i]+        val c = saliences[i + 1]+        val denominator = a - 2 * b + c+        if (denominator >= 0.0) return candidates[i]+        val shift = (0.5 * (a - c) / denominator).coerceIn(-0.5, 0.5)+        return candidates[i] * GRID_STEP.pow(shift)+    }++    /**+     * `sum g(f, m) * max |Y(k)|` over each partial's bin range. With [skipMultiplesOf] set, only+     * partials whose index is not a multiple of it count - the ones a candidate that many times+     * higher could not have produced.+     */+    private fun salience(+        spectrum: DoubleArray,+        binHz: Double,+        f0: Double,+        skipMultiplesOf: Int?,+        partials: Int = MAX_PARTIALS,+    ): Double {+        var total = 0.0+        var m = 1+        while (true) {+            val centre = m * f0+            if (centre > MAX_PARTIAL_HZ || m > partials) break+            if (skipMultiplesOf == null || m % skipMultiplesOf != 0) {+                total += (f0 + ALPHA) / (m * f0 + BETA) * partialPeak(spectrum, binHz, centre)+            }+            m+++        }+        return total+    }++    private fun partialPeak(spectrum: DoubleArray, binHz: Double, centre: Double): Double {+        val half = maxOf(1.0, centre * PARTIAL_TOLERANCE / binHz)+        val from = ((centre / binHz) - half).toInt().coerceAtLeast(1)+        val to = ((centre / binHz) + half + 0.5).toInt().coerceAtMost(spectrum.size - 1)+        var peak = 0.0+        for (k in from..to) if (spectrum[k] > peak) peak = spectrum[k]+        return peak+    }++    /**+     * Hann-windowed, zero-padded to twice the frame, then Klapuri's spectral whitening: each+     * auditory band is scaled by `sigma^(NU - 1)`, which flattens the instrument's envelope so a+     * bright partial cannot outvote a whole harmonic series.+     */+    private inner class Workspace(val length: Int) {+        val fftSize = 2 * length+        private val fft = Fft(fftSize)+        private val window = DoubleArray(length) { 0.5 - 0.5 * cos(2.0 * PI * it / length) }+        private val re = DoubleArray(fftSize)+        private val im = DoubleArray(fftSize)+        val magnitude = DoubleArray(fftSize / 2)+        private val binHz = sampleRate / fftSize+        private val centres = DoubleArray(BANDS + 2) { 229.0 * (10.0.pow((it + 1) / 21.4) - 1.0) }++        fun whitened(x: DoubleArray, offset: Int): DoubleArray? {+            re.fill(0.0)+            im.fill(0.0)+            for (i in 0 until length) re[i] = x[offset + i] * window[i]+            fft.forward(re, im)+            var energy = 0.0+            for (k in magnitude.indices) {+                magnitude[k] = sqrt(re[k] * re[k] + im[k] * im[k])+                energy += magnitude[k]+            }+            if (energy <= 0.0) return null++            val gain = DoubleArray(BANDS + 2)+            for (b in 1..BANDS) {+                var sum = 0.0+                var weight = 0.0+                val from = (centres[b - 1] / binHz).toInt().coerceAtLeast(1)+                val to = (centres[b + 1] / binHz).toInt().coerceAtMost(magnitude.size - 1)+                for (k in from..to) {+                    val hz = k * binHz+                    val h = if (hz <= centres[b]) {+                        (hz - centres[b - 1]) / (centres[b] - centres[b - 1])+                    } else {+                        (centres[b + 1] - hz) / (centres[b + 1] - centres[b])+                    }+                    if (h <= 0.0) continue+                    sum += h * magnitude[k] * magnitude[k]+                    weight += h+                }+                val sigma = if (weight > 0.0) sqrt(sum / weight) else 0.0+                gain[b] = if (sigma > 0.0) sigma.pow(NU - 1.0) else 0.0+            }+            gain[0] = gain[1]+            gain[BANDS + 1] = gain[BANDS]++            val out = DoubleArray(magnitude.size)+            var band = 0+            for (k in out.indices) {+                val hz = k * binHz+                while (band < BANDS && hz > centres[band + 1]) band+++                val g = if (hz <= centres[0]) {+                    gain[0]+                } else if (band >= BANDS) {+                    gain[BANDS]+                } else {+                    val t = (hz - centres[band]) / (centres[band + 1] - centres[band])+                    gain[band] * (1 - t) + gain[band + 1] * t+                }+                out[k] = g * magnitude[k]+            }+            return out+        }+    }++    private companion object {+        /** Klapuri's weighting constants for frames of this length. */+        const val ALPHA = 52.0+        const val BETA = 320.0++        /** Whitening exponent and the number of auditory bands (Klapuri 2006). */+        const val NU = 0.33+        const val BANDS = 30++        /** 10 cents. Fine enough that a partial is never missed between grid points. */+        val GRID_STEP: Double = 2.0.pow(10.0 / 1200.0)++        /** Bin range searched around each partial, relative: covers the grid and string stiffness. */+        const val PARTIAL_TOLERANCE = 0.006++        const val MAX_PARTIALS = 20+        const val MAX_PARTIAL_HZ = 6000.0++        const val MAX_SUBHARMONIC = 3++        /** A lower note is real when its own partials carry this share of the winner's salience. */+        const val OWN_PARTIAL_RATIO = 0.5++        /**+         * A candidate must earn this share of its salience from its first [LOW_ORDER_PARTIALS]+         * partials. A real low string always does - even with no fundamental, its octave and+         * twelfth are strong - while the common root under a strummed C chord collects C4, E4, G4+         * and C5 as partials 4, 5, 6 and 8 and has nothing at C2, C3 or G3.+         */+        const val LOW_ORDER_PARTIALS = 3+        const val LOW_ORDER_SHARE = 0.25++        const val PURE_TONE_CEILING_HZ = 100.0+        const val PURE_TONE_PARTIALS = 8+        const val PURE_TONE_SHARE = 0.65+    }+}
tuner/src/test/java/com/vayunmathur/tuner/domain/PitchDetectorTest.kt
diff --git a/tuner/src/test/java/com/vayunmathur/tuner/domain/PitchDetectorTest.kt b/tuner/src/test/java/com/vayunmathur/tuner/domain/PitchDetectorTest.ktindex b3cc77a916..2188d9de78 100644--- a/tuner/src/test/java/com/vayunmathur/tuner/domain/PitchDetectorTest.kt+++ b/tuner/src/test/java/com/vayunmathur/tuner/domain/PitchDetectorTest.kt@@ -185,6 +185,73 @@ class PitchDetectorTest {         assertTrue(frame is PitchFrame.Silent, "white noise was reported as $frame")     } +    /**+     * The plucked note, not the period of everything sounding.+     *+     * Reported from real use: an A4 read as E2. Unrestricted YIN finds the mixture's period, so+     * with another string ringing it answered F2 (five A4 periods, where E2 also nearly repeats)+     * and with all six open strings it answered A0, on every frame.+     */+    @Test+    fun theLoudestNoteWinsOverOtherStringsRinging() {+        val samples = PitchBand.LOW.windowSize+        val a4 = reference.referenceHz(69)+        val openStrings = listOf(40, 45, 50, 55, 59, 64).map { reference.referenceHz(it) }+        val hum = Signals.harmonic(60.0, samples, listOf(1.0, 0.5, 0.3))+        val cases = listOf(+            "low E ringing at -12 dB" to listOf(reference.referenceHz(40) to 0.25),+            "six open strings at -12 dB" to openStrings.map { it to 0.25 },+            "six open strings at -20 dB" to openStrings.map { it to 0.1 },+        )+        for ((label, background) in cases) {+            val signal = pluck(a4, samples)+            for ((hz, level) in background) {+                val part = pluck(hz, samples)+                for (i in signal.indices) signal[i] += level * part[i]+            }+            assertA4(label, signal, a4)+        }+        val withHum = pluck(a4, samples)+        for (i in withHum.indices) withHum[i] += 0.25 * 0.45 * hum[i]+        assertA4("60 Hz hum at -12 dB", withHum, a4)+    }++    @Test+    fun aLowHumWithNoOvertonesIsNotANote() {+        // Measured on Record-3: a 59-66 Hz tone in the gaps between strums read as B1 and C2.+        val hum = Signals.harmonic(60.0, PitchBand.LOW.windowSize, listOf(0.3, 0.02, 0.01))+        val frame = settle(YinPhaseSlopeAnalyzer(Signals.SAMPLE_RATE), hum, 27.5, 4186.0)+        assertTrue(frame is PitchFrame.Silent, "a 60 Hz hum was reported as $frame")+    }++    /**+     * A strum on the Note tab is not one note. "Not periodic" is an honest answer to it; a note+     * that is not being played is not. Every chord tone is a partial of the chord's common root+     * two octaves down, so harmonic summation without a low-partial check read a ukulele C as C2.+     */+    @Test+    fun aStrummedChordNeverReadsAsANoteThatIsNotPlayed() {+        for (midis in listOf(listOf(67, 60, 64, 72), listOf(69, 60, 65, 69), listOf(48, 52, 55, 60, 64))) {+            val analyzer = YinPhaseSlopeAnalyzer(Signals.SAMPLE_RATE)+            val frame = settle(analyzer, Signals.chord(midis, PitchBand.LOW.windowSize), 27.5, 4186.0)+            if (frame !is PitchFrame.Detected) {+                println("strum $midis -> $frame")+                continue+            }+            val midi = reference.nearestMidi(frame.estimate.frequencyHz)+            println("strum $midis read as ${spell(midi)}")+            assertTrue(midi in midis, "strum $midis read as ${spell(midi)}, which is not being played")+        }+    }++    private fun assertA4(label: String, signal: DoubleArray, a4: Double) {+        val estimate = detected(signal, 27.5, 4186.0)+        val cents = centsError(estimate.frequencyHz, a4)+        println("mixture $label: ${spell(reference.nearestMidi(estimate.frequencyHz))} error=$cents cents")+        assertEquals(69, reference.nearestMidi(estimate.frequencyHz), "$label read the wrong note")+        assertTrue(abs(cents) < 2.0, "$label: the error was $cents cents")+    }+     @Test     fun theReportedFrequencyAndCentsAgreeWithEachOther() {         // The two numbers on screen come from the same estimate, so they must be consistent: