tuner: detekt clean (138 tests)
- Commit
da1b4b238770710f859d04798f1d0e439ede274d- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-14 23:21 UTC (21 days ago)
- Parents
f83a134
Fix all detekt findings in tuner by fixing code, not config (detekt.yml untouched, no baselines added): - UndocumentedPublicClass: KDoc for the flagged types. - Complexity: extracted shapeFit/adjustedScore from logLikelihoods, bandGains from whitened, settledReading from namedReading, gateRejection from analyse (also fixes ReturnCount), scoreSegment from the eval test's stream loop. Behaviour unchanged. - MaxLineLength: wrapped the over-length lines. Verified: ./gradlew :tuner:detekt :tuner:testDevUnitTest :tuner:lint --max-workers=32 all pass (138 unit tests).
Diff
tuner/src/main/java/com/vayunmathur/tuner/MainActivity.kt
diff --git a/tuner/src/main/java/com/vayunmathur/tuner/MainActivity.kt b/tuner/src/main/java/com/vayunmathur/tuner/MainActivity.ktindex f3b977b264..ff0ab33fc7 100644--- a/tuner/src/main/java/com/vayunmathur/tuner/MainActivity.kt+++ b/tuner/src/main/java/com/vayunmathur/tuner/MainActivity.kt@@ -10,6 +10,7 @@ import com.vayunmathur.library.ui.MaActivity import com.vayunmathur.library.ui.PermissionRequirement import com.vayunmathur.tuner.platform.TunerViewModel +/** Main Activity: a ma activity implementation for main activity. */ class MainActivity : MaActivity() { private val viewModel: TunerViewModel by viewModels()
tuner/src/main/java/com/vayunmathur/tuner/Route.kt
diff --git a/tuner/src/main/java/com/vayunmathur/tuner/Route.kt b/tuner/src/main/java/com/vayunmathur/tuner/Route.ktindex 515eb8d3d6..b256fa9c78 100644--- a/tuner/src/main/java/com/vayunmathur/tuner/Route.kt+++ b/tuner/src/main/java/com/vayunmathur/tuner/Route.kt@@ -3,8 +3,10 @@ package com.vayunmathur.tuner import com.vayunmathur.library.util.NavKey import kotlinx.serialization.Serializable +/** Contract for route. */ @Serializable sealed interface Route : NavKey {+ /** Singleton holding tuner state and operations. */ @Serializable data object Tuner : Route }
tuner/src/main/java/com/vayunmathur/tuner/data/Instruments.kt
diff --git a/tuner/src/main/java/com/vayunmathur/tuner/data/Instruments.kt b/tuner/src/main/java/com/vayunmathur/tuner/data/Instruments.ktindex bf9fef7025..a2226de7ca 100644--- a/tuner/src/main/java/com/vayunmathur/tuner/data/Instruments.kt+++ b/tuner/src/main/java/com/vayunmathur/tuner/data/Instruments.kt@@ -158,6 +158,7 @@ data class InstrumentCatalog(@SerialName("instruments") val instruments: List<In /** Looks an instrument up, falling back to the first entry so the UI always has one. */ fun byId(id: String): Instrument = instruments.firstOrNull { it.id == id } ?: instruments.first() + /** Shared constants and helpers for InstrumentCatalog. */ companion object { private val json = Json { ignoreUnknownKeys = true }
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 ddb10e0ccb..eab39a38c0 100644--- a/tuner/src/main/java/com/vayunmathur/tuner/domain/ChordDetector.kt+++ b/tuner/src/main/java/com/vayunmathur/tuner/domain/ChordDetector.kt@@ -204,8 +204,12 @@ class ChordDetector( 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)+ 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)@@ -253,19 +257,28 @@ class ChordDetector( 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)+ 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)- }+ return settledReading(posterior[best], named, alternates, reading)+ }++ /** An uncontested winner: named above the confident threshold, tentative between them. */+ private fun settledReading(+ confidence: Double,+ named: ChordName,+ alternates: List<ChordCandidate>,+ reading: (ChordLabel, List<ChordCandidate>, Double, ChordPresentation) -> ChordReading,+ ): ChordReading = 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>? {@@ -294,7 +307,8 @@ class ChordDetector( 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+ val stronger = frame.semitones[n] > frame.semitones[best - LOWEST_NOTE_MIDI]+ if (pitchClassOf(midi) == pitchClass && stronger) best = midi } return best }
tuner/src/main/java/com/vayunmathur/tuner/domain/ChordPresenter.kt
diff --git a/tuner/src/main/java/com/vayunmathur/tuner/domain/ChordPresenter.kt b/tuner/src/main/java/com/vayunmathur/tuner/domain/ChordPresenter.ktindex f42d28392e..9a14bec591 100644--- a/tuner/src/main/java/com/vayunmathur/tuner/domain/ChordPresenter.kt+++ b/tuner/src/main/java/com/vayunmathur/tuner/domain/ChordPresenter.kt@@ -75,6 +75,7 @@ class ChordPresenter { return ++pendingCount >= HYSTERESIS_FRAMES } + /** Shared constants and helpers for ChordPresenter. */ companion object { /** A new name must win this many consecutive frames before it replaces the shown one. */ const val HYSTERESIS_FRAMES: Int = 2
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.ktindex 2251246bc6..72f2fd1cf5 100644--- a/tuner/src/main/java/com/vayunmathur/tuner/domain/ChordTemplates.kt+++ b/tuner/src/main/java/com/vayunmathur/tuner/domain/ChordTemplates.kt@@ -35,11 +35,12 @@ internal class ChordTemplates(partials: List<Double>, instrument: Instrument?) { } 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 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])) } @@ -53,37 +54,52 @@ internal class ChordTemplates(partials: List<Double>, instrument: Instrument?) { 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+ score = CHROMA_WEIGHT * score + (1 - CHROMA_WEIGHT) * shapeFit(frame, s, frameNorm, firstNote) }+ score = adjustedScore(score, states[s], frame, trebleMax, bassPitchClass) out[s] = SHARPNESS * score } out[noChord] = SHARPNESS * NO_CHORD_SCORE } + /** Best cosine fit of the frame against this state's rendered voicing shapes. */+ private fun shapeFit(frame: ChromaFrame, s: Int, frameNorm: Double, firstNote: Int): Double {+ if (frameNorm <= 0.0) return 0.0+ var best = 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+ }+ return best+ }++ /** Per-state score adjustments: strict-interval veto, complexity cost, bass bonus. */+ private fun adjustedScore(+ score: Double,+ state: ChordState,+ frame: ChromaFrame,+ trebleMax: Double,+ bassPitchClass: Int?,+ ): Double = when (state) {+ 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+ var adjusted = score+ if (strict != null &&+ frame.treble[pitchClassOf(state.name.root + strict)] <= ChordNaming.STRICT_TONE * trebleMax+ ) {+ adjusted = 0.0+ }+ adjusted -= COMPLEXITY_COST * state.name.quality.complexity+ if (bassPitchClass == state.name.root) adjusted += BASS_BONUS+ adjusted+ }+ is ChordState.Note -> if (bassPitchClass == state.pitchClass) score + BASS_BONUS else score+ ChordState.NoChord -> score+ }+ private fun pitchClassesOf(state: ChordState): Set<Int> = when (state) { is ChordState.Named -> state.name.pitchClasses is ChordState.Note -> setOf(state.pitchClass)@@ -101,7 +117,9 @@ internal class ChordTemplates(partials: List<Double>, instrument: Instrument?) { 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)) }+ is ChordState.Note -> instrument.soundingRange+ .filter { pitchClassOf(it) == state.pitchClass }+ .map { render(listOf(it)) } ChordState.NoChord -> emptyList() } }
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 849c83287b..37f9a792c8 100644--- a/tuner/src/main/java/com/vayunmathur/tuner/domain/HarmonicSieve.kt+++ b/tuner/src/main/java/com/vayunmathur/tuner/domain/HarmonicSieve.kt@@ -220,6 +220,7 @@ class HarmonicSieve( } } + /** Shared constants and helpers for HarmonicSieve. */ companion object { /** 341 ms at 48 kHz: 2.93 Hz a bin, against 15.5 Hz between semitones at C4. */ const val FFT_SIZE: Int = 16384
tuner/src/main/java/com/vayunmathur/tuner/domain/Nnls.kt
diff --git a/tuner/src/main/java/com/vayunmathur/tuner/domain/Nnls.kt b/tuner/src/main/java/com/vayunmathur/tuner/domain/Nnls.ktindex d761e2a49a..274607bf4d 100644--- a/tuner/src/main/java/com/vayunmathur/tuner/domain/Nnls.kt+++ b/tuner/src/main/java/com/vayunmathur/tuner/domain/Nnls.kt@@ -279,6 +279,7 @@ class NoteSalience( return column } + /** Shared constants and helpers for NoteSalience. */ companion object { /** Every note the CQT covers: C2..B6. */ val FULL_RANGE: IntRange = LOWEST_NOTE_MIDI until (LOWEST_NOTE_MIDI + NOTE_COUNT)
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 d760b0c7d5..2bcb86e5b3 100644--- a/tuner/src/main/java/com/vayunmathur/tuner/domain/PitchDetector.kt+++ b/tuner/src/main/java/com/vayunmathur/tuner/domain/PitchDetector.kt@@ -104,12 +104,7 @@ class YinPhaseSlopeAnalyzer(val sampleRate: Double) : PitchAnalyzer { 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)- }- if (coarse.aperiodicity > APERIODICITY_GATE) {- return reject(PitchRejection.NOT_PERIODIC, coarse.rms)- }+ gateRejection(coarse)?.let { return it } updateBand(coarse.frequencyHz) @@ -137,6 +132,13 @@ class YinPhaseSlopeAnalyzer(val sampleRate: Double) : PitchAnalyzer { ) } ++ /** Level and periodicity gates on the coarse estimate; null lets the frame through. */+ private fun gateRejection(coarse: YinResult): PitchFrame? = when {+ coarse.rms < noiseFloor * NOISE_MARGIN -> reject(PitchRejection.TOO_QUIET, coarse.rms)+ coarse.aperiodicity > APERIODICITY_GATE -> reject(PitchRejection.NOT_PERIODIC, coarse.rms)+ else -> null+ } private fun reject(reason: PitchRejection, rms: Double): PitchFrame { // Asymmetric on purpose. Averaging rejected frames symmetrically latches the gate shut: a // strum or an attack transient is loud *and* aperiodic, so it is rejected at full signal
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.ktindex cb1e8d8aa2..42579cedaa 100644--- a/tuner/src/main/java/com/vayunmathur/tuner/domain/PredominantPitch.kt+++ b/tuner/src/main/java/com/vayunmathur/tuner/domain/PredominantPitch.kt@@ -176,6 +176,28 @@ class PredominantPitch(private val sampleRate: Double) { } if (energy <= 0.0) return null + val gain = bandGains()++ 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+ }++ /** Per-band whitening gains from the triangular auditory filterbank. */+ private fun bandGains(): DoubleArray { val gain = DoubleArray(BANDS + 2) for (b in 1..BANDS) { var sum = 0.0@@ -198,23 +220,7 @@ class PredominantPitch(private val sampleRate: Double) { } 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+ return gain } }
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 6350aeb3bb..c8b845e143 100644--- a/tuner/src/main/java/com/vayunmathur/tuner/domain/Tonality.kt+++ b/tuner/src/main/java/com/vayunmathur/tuner/domain/Tonality.kt@@ -61,6 +61,7 @@ data class Tonality( val isTonal: Boolean get() = flatness <= MAX_FLATNESS && peakSalience >= MIN_PEAK_SALIENCE + /** Shared constants and helpers for Tonality. */ companion object { /** * Measured (TonalityTest): chords 0.004..0.142, noise 0.709..1.000 - a factor of five
tuner/src/main/java/com/vayunmathur/tuner/domain/TuningOffset.kt
diff --git a/tuner/src/main/java/com/vayunmathur/tuner/domain/TuningOffset.kt b/tuner/src/main/java/com/vayunmathur/tuner/domain/TuningOffset.ktindex 10183906ee..ffe8b0cb26 100644--- a/tuner/src/main/java/com/vayunmathur/tuner/domain/TuningOffset.kt+++ b/tuner/src/main/java/com/vayunmathur/tuner/domain/TuningOffset.kt@@ -85,6 +85,7 @@ class TuningOffset { } } + /** Shared constants and helpers for TuningOffset. */ companion object { /** A local maximum this far below the frame's strongest is a sidelobe, not a partial. */ const val PEAK_FRACTION: Double = 0.25
tuner/src/main/java/com/vayunmathur/tuner/platform/AudioCapture.kt
diff --git a/tuner/src/main/java/com/vayunmathur/tuner/platform/AudioCapture.kt b/tuner/src/main/java/com/vayunmathur/tuner/platform/AudioCapture.ktindex 72b59b353c..388cfa7473 100644--- a/tuner/src/main/java/com/vayunmathur/tuner/platform/AudioCapture.kt+++ b/tuner/src/main/java/com/vayunmathur/tuner/platform/AudioCapture.kt@@ -179,6 +179,7 @@ class AudioCapture(private val context: Context) { }.onFailure { Log.status(TAG, "could not detach voice processing", it) } } + /** Shared constants and helpers for AudioCapture. */ companion object { /** Native rate on effectively every modern device. Never resample. */ const val SAMPLE_RATE = 48_000
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.ktindex 44e2955170..f6092f9b11 100644--- a/tuner/src/test/java/com/vayunmathur/tuner/domain/ChordProgressionEvalTest.kt+++ b/tuner/src/test/java/com/vayunmathur/tuner/domain/ChordProgressionEvalTest.kt@@ -90,6 +90,30 @@ class ChordProgressionEvalTest { else -> label.javaClass.simpleName } ++ /** Scores one frame against the segment that contains it. */+ private fun scoreSegment(+ metrics: Metrics,+ firstHit: HashMap<StrumSynth.Segment, Int>,+ segment: StrumSynth.Segment,+ shown: ChordLabel?,+ reading: ChordReading,+ end: Int,+ ) {+ 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+ }+ } private fun stream(instrument: Instrument, extractor: ChordExtractor, take: StrumSynth.Take): Metrics { val detector = ChordDetector(Signals.SAMPLE_RATE, extractor = extractor) detector.setInstrument(instrument)@@ -119,19 +143,7 @@ class ChordProgressionEvalTest { 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- }+ scoreSegment(metrics, firstHit, segment, shown, reading, end) } end += HOP }