musicbrainz: add a polyphase resampler and PCM buffers for Opus encoding
- Commit
0f3300c46ccacb95000fcc949b903f00a4898d5b- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-20 17:25 UTC (3 months ago)
- Parents
a247f09
Diff
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/PcmBuffers.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/PcmBuffers.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/PcmBuffers.ktnew file mode 100644index 0000000000..482b5fb0e7--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/PcmBuffers.kt@@ -0,0 +1,125 @@+package com.vayunmathur.musicbrainz.data.download++import java.nio.ByteBuffer+import java.nio.ByteOrder++/**+ * Converts between the PCM a MediaCodec decoder hands out and the float frames the+ * resampler works in, and holds the bytes waiting for the encoder.+ *+ * Kept apart from [PolyphaseResampler] so the resampler stays codec-agnostic: it only ever+ * sees interleaved floats at a known rate, and everything to do with sample formats,+ * channel counts and buffer boundaries lives here.+ */+internal object PcmBuffers {++ /** Full-scale for signed 16-bit, used both ways so a round trip is symmetric. */+ private const val S16_SCALE = 32768f+ private const val S16_MAX = 32767+ private const val S16_MIN = -32768++ /**+ * Reads [buffer] as signed 16-bit little-endian PCM into [out] as floats in -1..1,+ * returning how many samples were written.+ */+ fun readS16(buffer: ByteBuffer, out: FloatArray): Int {+ val shorts = buffer.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer()+ val count = shorts.remaining()+ for (i in 0 until count) out[i] = shorts.get() / S16_SCALE+ return count+ }++ /** Reads [buffer] as 32-bit float PCM into [out], returning how many samples were written. */+ fun readFloat(buffer: ByteBuffer, out: FloatArray): Int {+ val floats = buffer.order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer()+ val count = floats.remaining()+ for (i in 0 until count) out[i] = floats.get()+ return count+ }++ /**+ * Writes the first [samples] of [input] as signed 16-bit little-endian PCM.+ *+ * Clamped rather than wrapped: a resampler's ringing can overshoot a full-scale source+ * by a fraction of a decibel, and letting that wrap would turn a loud passage into a+ * burst of noise instead of a hint of clipping.+ */+ fun writeS16(input: FloatArray, samples: Int, out: ByteArray): Int {+ var index = 0+ for (i in 0 until samples) {+ val value = Math.round(input[i] * S16_SCALE).coerceIn(S16_MIN, S16_MAX)+ out[index++] = value.toByte()+ out[index++] = (value shr 8).toByte()+ }+ return index+ }++ /**+ * Reduces [channels]-channel interleaved audio in place to the front pair.+ *+ * The Opus encoder takes at most two channels. Multichannel music is not something+ * either source serves - Tidal's Dolby streams are rejected earlier as protected - so+ * this keeps the front left/right pair rather than guessing at a downmix matrix for a+ * channel order it has no way to confirm.+ */+ fun foldToStereo(interleaved: FloatArray, frames: Int, channels: Int): Int {+ require(channels > 2) { "only wider than stereo needs folding" }+ for (frame in 0 until frames) {+ interleaved[frame * 2] = interleaved[frame * channels]+ interleaved[frame * 2 + 1] = interleaved[frame * channels + 1]+ }+ return frames * 2+ }+}++/**+ * A byte FIFO for the PCM waiting to be encoded.+ *+ * The resampler emits whatever the ratio produces, while the encoder wants whole frames in+ * whatever size its input buffer happens to be, so the two do not line up. This holds the+ * remainder between them and hands out only whole frames, which matters because half a+ * frame queued would swap the channels of everything after it.+ */+internal class PcmQueue(initialCapacity: Int = 64 * 1024) {++ private var buffer = ByteArray(initialCapacity)+ private var head = 0+ private var tail = 0++ val size: Int get() = tail - head++ fun write(source: ByteArray, length: Int) {+ if (length <= 0) return+ if (tail + length > buffer.size) compact(length)+ System.arraycopy(source, 0, buffer, tail, length)+ tail += length+ }++ /**+ * Moves up to [limit] bytes into [destination], truncated to a whole number of+ * [frameBytes]-sized frames. Returns how many bytes were moved.+ */+ fun drainTo(destination: ByteBuffer, limit: Int, frameBytes: Int): Int {+ val take = minOf(size, limit, destination.remaining()) / frameBytes * frameBytes+ if (take <= 0) return 0+ destination.put(buffer, head, take)+ head += take+ if (head == tail) {+ head = 0+ tail = 0+ }+ return take+ }++ private fun compact(incoming: Int) {+ val remaining = size+ if (head > 0) {+ System.arraycopy(buffer, head, buffer, 0, remaining)+ head = 0+ tail = remaining+ }+ if (remaining + incoming > buffer.size) {+ buffer = buffer.copyOf(maxOf(remaining + incoming, buffer.size * 2))+ }+ }+}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/PolyphaseResampler.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/PolyphaseResampler.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/PolyphaseResampler.ktnew file mode 100644index 0000000000..87e7b9f341--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/PolyphaseResampler.kt@@ -0,0 +1,306 @@+package com.vayunmathur.musicbrainz.data.download++import kotlin.math.PI+import kotlin.math.ceil+import kotlin.math.min+import kotlin.math.sin+import kotlin.math.sqrt++/**+ * Resamples interleaved float PCM between two rates by a rational ratio.+ *+ * Every download is encoded to Opus, and Opus only accepts 8/12/16/24/48 kHz - it cannot+ * encode 44.1 kHz at all - so a CD-rate or hi-res source has to be resampled to 48 kHz+ * before it reaches the encoder. That makes this the one piece of DSP in the app, and the+ * platform ships no resampler to borrow.+ *+ * The design is the textbook one: conceptually insert `L - 1` zeros between input frames,+ * low-pass, then keep every `M`th sample. Nothing is materialised at the `L * inputRate`+ * intermediate rate; the prototype filter is decomposed into `L` phases so each output+ * frame costs one dot product of [tapsPerPhase] taps per channel. `L` and `M` come from+ * reducing the two rates by their gcd, so 44.1 kHz gives 160/147, 96 kHz gives 1/2 and+ * 192 kHz gives 1/4 with no ratio table.+ *+ * ### Filter+ *+ * One Kaiser-windowed sinc, cut off just under half the *lower* of the two rates: that+ * single expression buys anti-imaging when upsampling and anti-aliasing when downsampling,+ * because in both cases the band that has to survive is bounded by the lower rate.+ *+ * The length is chosen to hit a fixed transition width rather than being a fixed tap count:+ * a fixed count would leave a decimate-by-4 filter four times too short and audibly dull+ * the top octave. The passband reaches [PASSBAND_FRACTION] of the lower rate and the+ * stopband starts at its Nyquist, so a 44.1 kHz source is flat to 19.3 kHz and 80 dB down+ * by 22.05 kHz. Stopping short of 20 kHz is deliberate: the transition band has to fit+ * between the passband edge and the Nyquist it protects, and every extra kilohertz of+ * flatness up there costs taps in proportion. Nothing audible is lost, and the 48 kHz Opus+ * encode that follows discards everything above roughly 20 kHz anyway.+ *+ * ### Streaming+ *+ * [process] emits only the output frames whose whole tap window has arrived and keeps the+ * rest of the window as history, so the chunk sizes a caller happens to use cannot change+ * a single output sample; [flush] drains the tail at the end of the track. The window is+ * centred on the output instant, which cancels the filter's group delay, so the output is+ * time-aligned with the input to within a fraction of a sample.+ */+internal class PolyphaseResampler(+ private val inputRate: Int,+ private val outputRate: Int,+ private val channels: Int,+) {+ /** `L`: how many output samples the intermediate rate carries per input sample. */+ val interpolation: Int++ /** `M`: how many intermediate samples are dropped per output sample. */+ val decimation: Int++ /** Taps per phase, i.e. how many input frames each output frame is a weighted sum of. */+ val tapsPerPhase: Int++ private val passthrough = inputRate == outputRate++ /** `[phase][tap]`, each phase normalised to sum to 1 so a DC input passes at unity. */+ private val coefficients: Array<FloatArray>++ /**+ * The input frames still needed as tap history, interleaved, oldest first.+ * `history[0]` is the frame at absolute index [historyStart].+ */+ private var history = FloatArray(0)+ private var historyFrames = 0+ private var historyStart = 0L++ /** Absolute count of input frames handed to [process] so far. */+ private var framesIn = 0L++ /** Absolute index of the newest input frame the next output frame reads. */+ private var window = 0L++ /** `(outputIndex * M) mod L`, advanced by `M` and wrapped by `L`. */+ private var phase = 0++ init {+ require(inputRate > 0 && outputRate > 0) { "rates must be positive" }+ require(channels in 1..MAX_CHANNELS) { "channels must be 1..$MAX_CHANNELS" }+ val divisor = gcd(inputRate, outputRate)+ interpolation = outputRate / divisor+ decimation = inputRate / divisor+ if (passthrough) {+ tapsPerPhase = 0+ coefficients = emptyArray()+ } else {+ tapsPerPhase = tapsPerPhaseFor(interpolation, decimation)+ val cutoffFraction = (PASSBAND_FRACTION + STOPBAND_FRACTION) / 2.0+ coefficients = buildCoefficients(+ interpolation,+ tapsPerPhase,+ cutoff = cutoffFraction * min(inputRate, outputRate) /+ (interpolation.toDouble() * inputRate),+ )+ }+ window = (tapsPerPhase / 2).toLong()+ }++ /**+ * Resamples [frames] interleaved frames from the front of [input].+ *+ * Returns exactly the output frames whose tap window is complete, which is why calling+ * this once with a whole track and calling it repeatedly with arbitrary chunks give+ * byte-identical results.+ */+ fun process(input: FloatArray, frames: Int): FloatArray {+ if (frames <= 0) return EMPTY+ if (passthrough) return input.copyOf(frames * channels)+ appendHistory(input, frames)+ framesIn += frames+ // The newest frame the next output needs must already have arrived.+ return emit(available = framesIn, limit = framesIn)+ }++ /**+ * Drains the outputs still owed for the input already supplied, reading past the end of+ * the stream as silence. Called once, at the end of the track.+ */+ fun flush(): FloatArray {+ if (passthrough) return EMPTY+ return emit(available = Long.MAX_VALUE, limit = framesIn)+ }++ /**+ * Produces output frames while the window's newest frame is below [available] and the+ * output still corresponds to an input frame that exists ([limit]).+ */+ private fun emit(available: Long, limit: Long): FloatArray {+ val taps = tapsPerPhase+ var count = 0+ // The output index reading window `w` corresponds to input frame `w - taps/2`, and+ // exists while that is below `limit`. Counting first keeps the result a single+ // exact allocation, and costs only integer arithmetic.+ run {+ var w = window+ var p = phase+ while (w - taps / 2 < limit && w < available) {+ count+++ val advanced = p + decimation+ w += advanced / interpolation+ p = advanced % interpolation+ }+ }+ if (count == 0) return EMPTY++ val out = FloatArray(count * channels)+ val stereo = channels == 2+ var outIndex = 0+ repeat(count) {+ val phaseTaps = coefficients[phase]+ // Taps whose frame falls outside the stream contribute nothing, so clamp the+ // range instead of bounds-checking every one. Inside the range the history is+ // interleaved with a stride of `channels`, so one coefficient load feeds both+ // channel accumulators.+ val newest = (window - historyStart).toInt()+ val from = maxOf(0, newest - historyFrames + 1)+ val to = minOf(taps - 1, newest)+ var left = 0f+ var right = 0f+ var sample = (newest - from) * channels+ for (k in from..to) {+ val coefficient = phaseTaps[k]+ left += coefficient * history[sample]+ if (stereo) right += coefficient * history[sample + 1]+ sample -= channels+ }+ out[outIndex++] = left+ if (stereo) out[outIndex++] = right++ val advanced = phase + decimation+ window += advanced / interpolation+ phase = advanced % interpolation+ }+ dropHistoryBefore(window - taps + 1)+ return out+ }++ private fun appendHistory(input: FloatArray, frames: Int) {+ val needed = (historyFrames + frames) * channels+ if (history.size < needed) {+ history = history.copyOf(maxOf(needed, history.size * 2, INITIAL_HISTORY_FRAMES * channels))+ }+ System.arraycopy(input, 0, history, historyFrames * channels, frames * channels)+ historyFrames += frames+ }++ private fun dropHistoryBefore(frame: Long) {+ val drop = (frame - historyStart).coerceAtMost(historyFrames.toLong()).toInt()+ if (drop <= 0) return+ val remaining = historyFrames - drop+ System.arraycopy(history, drop * channels, history, 0, remaining * channels)+ historyFrames = remaining+ historyStart += drop+ }++ private companion object {+ val EMPTY = FloatArray(0)++ /** The Opus encoder takes at most stereo, so nothing wider ever reaches this. */+ const val MAX_CHANNELS = 2++ const val INITIAL_HISTORY_FRAMES = 4096++ /**+ * The passband edge and the stopband edge, as fractions of the lower of the two+ * rates. The stopband starts at that rate's Nyquist, which is the frequency above+ * which imaging or aliasing folds into the output band.+ */+ const val PASSBAND_FRACTION = 0.4375+ const val STOPBAND_FRACTION = 0.5++ /** Stopband attenuation the length and the Kaiser window are designed for. */+ const val STOPBAND_DB = 80.0++ fun gcd(a: Int, b: Int): Int {+ var x = a+ var y = b+ while (y != 0) {+ val t = x % y+ x = y+ y = t+ }+ return x+ }++ /**+ * Kaiser's length estimate, `N = (A - 8) / (2.285 * transition in rad/sample)`,+ * expressed per phase.+ *+ * The transition width in Hz works out independent of `L`, so this reduces to a+ * constant for any upsample and scales with `M / L` for a downsample - which is+ * exactly the wanted behaviour, since decimating by four needs four times the taps+ * to hold the same transition. The cap is what stops a 192 kHz source, the only+ * ratio that reaches it, from costing four times a CD-rate one for a difference+ * that is entirely above 18 kHz.+ */+ fun tapsPerPhaseFor(interpolation: Int, decimation: Int): Int {+ val transition = STOPBAND_FRACTION - PASSBAND_FRACTION+ val perPhase = (STOPBAND_DB - 8.0) *+ maxOf(1.0, decimation.toDouble() / interpolation) /+ (2.285 * 2.0 * PI * transition)+ // Even, so the window centres cleanly on the output instant.+ val taps = 2 * ceil(perPhase / 2.0).toInt()+ return taps.coerceIn(MIN_TAPS_PER_PHASE, MAX_TAPS_PER_PHASE)+ }++ const val MIN_TAPS_PER_PHASE = 16+ const val MAX_TAPS_PER_PHASE = 192++ /**+ * Splits one prototype low-pass into `L` phases.+ *+ * Phase `p` holds `h[p], h[p + L], h[p + 2L], ...`, which is the subset of taps that+ * lands on a real input frame rather than on one of the inserted zeros. Each phase+ * is normalised to sum to 1 so DC passes at exactly unity, which also makes the+ * `20 * log10(L)` gain blunder impossible.+ */+ fun buildCoefficients(interpolation: Int, tapsPerPhase: Int, cutoff: Double): Array<FloatArray> {+ val length = tapsPerPhase * interpolation+ val centre = (length - 1) / 2.0+ val beta = kaiserBeta(STOPBAND_DB)+ val i0Beta = besselI0(beta)+ val prototype = DoubleArray(length) { n ->+ val x = n - centre+ val window = besselI0(beta * sqrt(1.0 - (2.0 * n / (length - 1) - 1.0).let { it * it })) / i0Beta+ 2.0 * cutoff * sinc(2.0 * cutoff * x) * window+ }+ return Array(interpolation) { phase ->+ val taps = DoubleArray(tapsPerPhase) { k -> prototype[phase + k * interpolation] }+ val sum = taps.sum()+ FloatArray(tapsPerPhase) { k -> (taps[k] / sum).toFloat() }+ }+ }++ /** Kaiser's β for a given stopband attenuation, for the 21..50 dB and >50 dB cases. */+ fun kaiserBeta(attenuationDb: Double): Double = when {+ attenuationDb > 50 -> 0.1102 * (attenuationDb - 8.7)+ attenuationDb >= 21 -> 0.5842 * Math.pow(attenuationDb - 21, 0.4) ++ 0.07886 * (attenuationDb - 21)+ else -> 0.0+ }++ fun sinc(x: Double): Double = if (x == 0.0) 1.0 else sin(PI * x) / (PI * x)++ /** Modified Bessel function of the first kind, order zero, by its power series. */+ fun besselI0(x: Double): Double {+ var sum = 1.0+ var term = 1.0+ val half = x / 2.0+ var k = 1+ while (k < 40) {+ term *= half * half / (k * k)+ sum += term+ if (term < sum * 1e-16) break+ k+++ }+ return sum+ }+ }+}
musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/PcmBuffersTest.kt
diff --git a/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/PcmBuffersTest.kt b/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/PcmBuffersTest.ktnew file mode 100644index 0000000000..2b1aa3ac9c--- /dev/null+++ b/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/PcmBuffersTest.kt@@ -0,0 +1,124 @@+package com.vayunmathur.musicbrainz.data.download++import java.nio.ByteBuffer+import java.nio.ByteOrder+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Tests for the PCM plumbing between the decoder, the resampler and the encoder.+ *+ * The failures these catch are the silent kind: a clip that wraps turns a loud passage into+ * a burst of noise instead of a hint of distortion, and half a frame left in the queue swaps+ * the channels of everything after it.+ */+class PcmBuffersTest {++ private fun s16(vararg values: Int): ByteBuffer {+ val buffer = ByteBuffer.allocate(values.size * 2).order(ByteOrder.LITTLE_ENDIAN)+ values.forEach { buffer.putShort(it.toShort()) }+ buffer.flip()+ return buffer+ }++ @Test+ fun `reads signed 16-bit pcm as normalised floats`() {+ val out = FloatArray(4)+ assertEquals(4, PcmBuffers.readS16(s16(0, 16384, -16384, -32768), out))+ assertEquals(0f, out[0])+ assertEquals(0.5f, out[1])+ assertEquals(-0.5f, out[2])+ assertEquals(-1f, out[3])+ }++ @Test+ fun `reads 32-bit float pcm unchanged`() {+ val buffer = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN)+ buffer.putFloat(0.25f)+ buffer.putFloat(-0.75f)+ buffer.flip()+ val out = FloatArray(2)+ assertEquals(2, PcmBuffers.readFloat(buffer, out))+ assertEquals(0.25f, out[0])+ assertEquals(-0.75f, out[1])+ }++ @Test+ fun `round trips a level through float and back`() {+ val out = ByteArray(4)+ PcmBuffers.writeS16(floatArrayOf(0.5f, -0.5f), 2, out)+ val back = FloatArray(2)+ PcmBuffers.readS16(ByteBuffer.wrap(out), back)+ assertEquals(0.5f, back[0])+ assertEquals(-0.5f, back[1])+ }++ @Test+ fun `clamps an overshoot instead of wrapping it`() {+ val out = ByteArray(8)+ PcmBuffers.writeS16(floatArrayOf(1.2f, -1.2f, 1f, -1f), 4, out)+ val shorts = ByteBuffer.wrap(out).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer()+ assertEquals(32767, shorts.get().toInt(), "a positive overshoot must not wrap negative")+ assertEquals(-32768, shorts.get().toInt())+ assertEquals(32767, shorts.get().toInt())+ assertEquals(-32768, shorts.get().toInt())+ }++ @Test+ fun `folds a wider layout onto its front pair`() {+ // Two frames of 5.1, channels numbered so a mix-up is obvious.+ val input = floatArrayOf(+ 0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f,+ 0.7f, 0.8f, 0.9f, 1.0f, 0.0f, 0.0f,+ )+ assertEquals(4, PcmBuffers.foldToStereo(input, frames = 2, channels = 6))+ assertEquals(listOf(0.1f, 0.2f, 0.7f, 0.8f), input.take(4))+ }++ // ------------------------------------------------------------------+ // PcmQueue+ // ------------------------------------------------------------------++ @Test+ fun `hands out only whole frames and keeps the remainder`() {+ val queue = PcmQueue(initialCapacity = 16)+ // Nine bytes of stereo 16-bit audio: two whole frames and one stray byte.+ queue.write(ByteArray(9) { it.toByte() }, 9)++ val first = ByteBuffer.allocate(16)+ assertEquals(8, queue.drainTo(first, limit = 16, frameBytes = 4))+ assertEquals(1, queue.size, "the odd byte must stay queued, not be handed over")++ // Once the rest of that frame arrives it comes out with the right alignment.+ queue.write(ByteArray(3) { (9 + it).toByte() }, 3)+ val second = ByteBuffer.allocate(16)+ assertEquals(4, queue.drainTo(second, limit = 16, frameBytes = 4))+ assertEquals(0, queue.size)+ assertEquals(listOf<Byte>(8, 9, 10, 11), second.array().take(4))+ }++ @Test+ fun `respects the destination and the limit`() {+ val queue = PcmQueue(initialCapacity = 8)+ queue.write(ByteArray(64), 64)+ assertEquals(4, queue.drainTo(ByteBuffer.allocate(5), limit = 64, frameBytes = 4))+ assertEquals(8, queue.drainTo(ByteBuffer.allocate(64), limit = 10, frameBytes = 4))+ assertEquals(52, queue.size)+ }++ @Test+ fun `grows and compacts across many partial drains`() {+ val queue = PcmQueue(initialCapacity = 8)+ var written = 0+ var drained = 0+ repeat(200) {+ queue.write(ByteArray(37) { 1 }, 37)+ written += 37+ val destination = ByteBuffer.allocate(20)+ drained += queue.drainTo(destination, limit = 20, frameBytes = 4)+ }+ assertEquals(written - drained, queue.size)+ assertTrue(drained > 0, "a queue that never drains would grow without bound")+ }+}
musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/PolyphaseResamplerTest.kt
diff --git a/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/PolyphaseResamplerTest.kt b/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/PolyphaseResamplerTest.ktnew file mode 100644index 0000000000..6eaa860624--- /dev/null+++ b/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/PolyphaseResamplerTest.kt@@ -0,0 +1,264 @@+package com.vayunmathur.musicbrainz.data.download++import kotlin.math.PI+import kotlin.math.abs+import kotlin.math.cos+import kotlin.math.log10+import kotlin.math.sin+import kotlin.math.sqrt+import kotlin.random.Random+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Tests for the one piece of DSP in the app.+ *+ * A resampler fails quietly: a wrong ratio is a pitch shift, a seam between chunks is a+ * click, a normalisation slip is a level change, and a filter that is too short lets+ * aliases fold into the audible band. None of that shows up in a build, and none of it can+ * be tested on a device from here, so it is all pinned down with synthetic signals: a DC+ * level for gain, tones for the frequency response, out-of-band tones for aliasing, and the+ * same input fed in different chunk sizes for the seams.+ */+class PolyphaseResamplerTest {++ private val outputRate = 48_000++ private fun resampler(inputRate: Int, channels: Int = 1) =+ PolyphaseResampler(inputRate, outputRate, channels)++ /** Runs a whole signal through in one call plus a flush, as the transcoder does. */+ private fun runAll(+ resampler: PolyphaseResampler,+ input: FloatArray,+ channels: Int = 1,+ ): FloatArray = resampler.process(input, input.size / channels) + resampler.flush()++ private fun sine(frequency: Double, rate: Int, frames: Int, amplitude: Double = 1.0) =+ FloatArray(frames) { (amplitude * sin(2.0 * PI * frequency * it / rate)).toFloat() }++ /**+ * Energy at [frequency] as a fraction of full scale, by the Goertzel algorithm.+ *+ * Cheaper and sharper than an FFT for the handful of bins these tests care about, and+ * it needs no power-of-two length.+ */+ private fun amplitudeAt(signal: FloatArray, frequency: Double, rate: Int, from: Int, to: Int): Double {+ val omega = 2.0 * PI * frequency / rate+ val coefficient = 2.0 * cos(omega)+ var s1 = 0.0+ var s2 = 0.0+ for (i in from until to) {+ val s = signal[i] + coefficient * s1 - s2+ s2 = s1+ s1 = s+ }+ val real = s1 - s2 * cos(omega)+ val imaginary = s2 * sin(omega)+ return 2.0 * sqrt(real * real + imaginary * imaginary) / (to - from)+ }++ private fun dbfs(amplitude: Double): Double =+ if (amplitude <= 0.0) -200.0 else 20.0 * log10(amplitude)++ private fun rms(signal: FloatArray, from: Int, to: Int): Double {+ var sum = 0.0+ for (i in from until to) sum += signal[i].toDouble() * signal[i]+ return sqrt(sum / (to - from))+ }++ // ------------------------------------------------------------------+ // Ratio+ // ------------------------------------------------------------------++ @Test+ fun `reduces every source rate to its lowest terms`() {+ val expected = mapOf(+ 44_100 to (160 to 147),+ 88_200 to (80 to 147),+ 176_400 to (40 to 147),+ 96_000 to (1 to 2),+ 192_000 to (1 to 4),+ 32_000 to (3 to 2),+ )+ for ((rate, ratio) in expected) {+ val resampler = resampler(rate)+ assertEquals(+ ratio,+ resampler.interpolation to resampler.decimation,+ "$rate Hz should resample by L/M = ${ratio.first}/${ratio.second}",+ )+ }+ }++ @Test+ fun `copies the input untouched when the rates already match`() {+ val input = FloatArray(1000) { Random(7).nextFloat() * 2f - 1f }+ val output = runAll(resampler(outputRate), input)+ assertEquals(input.size, output.size)+ assertTrue(input.contentEquals(output), "48 kHz should be a straight copy")+ }++ // ------------------------------------------------------------------+ // Gain and length+ // ------------------------------------------------------------------++ @Test+ fun `passes a DC level through at unity`() {+ val output = runAll(resampler(44_100), FloatArray(20_000) { 0.5f })+ // Skip the filter's ramp at either end, where the window straddles the silence+ // outside the signal.+ val settled = output.copyOfRange(2_000, output.size - 2_000)+ for (sample in settled) {+ assertTrue(+ abs(sample - 0.5f) < 1e-3f,+ "DC should come through at 0.5, not $sample - a phase is mis-normalised",+ )+ }+ }++ @Test+ fun `produces the frame count the ratio implies`() {+ for (rate in listOf(44_100, 88_200, 96_000, 176_400, 192_000, 32_000)) {+ val resampler = resampler(rate)+ val frames = 50_000+ val output = runAll(resampler, FloatArray(frames))+ val expected = frames.toLong() * resampler.interpolation / resampler.decimation+ assertTrue(+ abs(output.size - expected) <= 1,+ "$rate Hz: expected about $expected frames, got ${output.size}",+ )+ }+ }++ // ------------------------------------------------------------------+ // Frequency response+ // ------------------------------------------------------------------++ @Test+ fun `keeps a mid-band tone at its original level and adds nothing else`() {+ val input = sine(1_000.0, 44_100, 44_100, amplitude = 0.5)+ val output = runAll(resampler(44_100), input)+ val from = 2_000+ val to = output.size - 2_000++ val tone = amplitudeAt(output, 1_000.0, outputRate, from, to)+ assertTrue(+ abs(dbfs(tone) - dbfs(0.5)) < 0.1,+ "1 kHz should survive within 0.1 dB, got ${dbfs(tone)} dBFS",+ )++ // Everything that is not the tone: imaging that folded back in, plus arithmetic+ // noise. The images of a 1 kHz tone land around 4.9 kHz after decimation, so this+ // is a real measurement of the stopband and not just rounding.+ val total = rms(output, from, to)+ val residual = sqrt((total * total - tone * tone / 2.0).coerceAtLeast(0.0))+ assertTrue(+ dbfs(residual) < -70.0,+ "residual after removing the tone should be under -70 dBFS, got ${dbfs(residual)}",+ )+ }++ @Test+ fun `passes the top of the audible band and stops the rest`() {+ val frames = 44_100+ val passband = amplitudeAt(+ runAll(resampler(44_100), sine(18_000.0, 44_100, frames)),+ 18_000.0,+ outputRate,+ 2_000,+ frames * 160 / 147 - 2_000,+ )+ assertTrue(+ dbfs(passband) > -1.0,+ "18 kHz should pass near unity, got ${dbfs(passband)} dBFS",+ )++ val stopband = amplitudeAt(+ runAll(resampler(44_100), sine(22_040.0, 44_100, frames)),+ 22_040.0,+ outputRate,+ 2_000,+ frames * 160 / 147 - 2_000,+ )+ assertTrue(+ dbfs(stopband) < -40.0,+ "22 kHz should be well down, got ${dbfs(stopband)} dBFS",+ )+ }++ @Test+ fun `does not let a downsample fold ultrasonics into the audible band`() {+ // 30 kHz at 96 kHz and 40 kHz at 192 kHz are both above the 24 kHz output Nyquist,+ // so without an anti-alias filter they would reappear at 18 kHz and 8 kHz - the+ // second of those squarely audible.+ val cases = listOf(+ Triple(96_000, 30_000.0, 18_000.0),+ Triple(192_000, 40_000.0, 8_000.0),+ )+ for ((rate, tone, alias) in cases) {+ val output = runAll(resampler(rate), sine(tone, rate, rate))+ val from = 2_000+ val to = output.size - 2_000+ val leaked = amplitudeAt(output, alias, outputRate, from, to)+ assertTrue(+ dbfs(leaked) < -70.0,+ "$rate Hz: ${tone.toInt()} Hz should not alias to ${alias.toInt()} Hz, " ++ "got ${dbfs(leaked)} dBFS",+ )+ }+ }++ // ------------------------------------------------------------------+ // Streaming+ // ------------------------------------------------------------------++ @Test+ fun `gives the same output whatever chunk sizes it is fed in`() {+ val input = FloatArray(100_000) { sin(it * 0.017).toFloat() * 0.8f }+ val whole = runAll(resampler(44_100), input)++ val random = Random(1234)+ val sizes = listOf(1, 7, 960, 4096)+ val chunked = resampler(44_100)+ val pieces = ArrayList<FloatArray>()+ var offset = 0+ while (offset < input.size) {+ val size = minOf(sizes[random.nextInt(sizes.size)], input.size - offset)+ pieces.add(chunked.process(input.copyOfRange(offset, offset + size), size))+ offset += size+ }+ pieces.add(chunked.flush())+ val joined = FloatArray(pieces.sumOf { it.size })+ var at = 0+ for (piece in pieces) {+ piece.copyInto(joined, at)+ at += piece.size+ }++ assertEquals(whole.size, joined.size, "chunking changed the output length")+ for (i in whole.indices) {+ assertTrue(+ abs(whole[i] - joined[i]) < 1e-6f,+ "chunk boundary at frame $i changed the output - that is an audible click",+ )+ }+ }++ @Test+ fun `keeps the channels apart`() {+ val frames = 20_000+ val input = FloatArray(frames * 2)+ val tone = sine(1_000.0, 44_100, frames)+ for (i in 0 until frames) input[i * 2] = tone[i]++ val output = runAll(resampler(44_100, channels = 2), input, channels = 2)+ var right = 0.0+ for (i in 1 until output.size step 2) right += output[i].toDouble() * output[i]+ assertTrue(+ dbfs(sqrt(right / (output.size / 2))) < -100.0,+ "a silent right channel must stay silent",+ )+ }+}