From f63f2ca764d1d469ac359f4e05fe307e2fca6c06 Mon Sep 17 00:00:00 2001 From: zarzet <42882290+zarzet@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:00:06 +0700 Subject: [PATCH] feat(equalizer): parametric filters with a plain text filter list The equalizer was a graphic one: 5 to 31 bands at fixed frequencies. Tuning an earphone to a measurement needs filters with their own frequency, gain and width (issue 952). The Equalizer page gets a Graphic / Parametric choice. Parametric holds up to 20 filters (peak, low shelf, high shelf), each with a frequency from 20 Hz to 20 kHz, a gain of up to 24 dB either way and a Q from 0.1 to 20. A filter is edited in a sheet with sliders, and each value can be typed exactly. The bands, Bass and Treble keep their values while the filters play, and come back with Graphic. The curve, the automatic headroom and presets follow the mode. Import also takes the plain text filter list that measurement and tuning tools exchange ("Preamp: -6.2 dB", "Filter 1: ON PK Fc 105 Hz Gain -2.1 dB Q 0.70"), and Share filter list writes one. A list that names a preamp carries its own headroom, so automatic headroom is turned off with it. Filters of a kind the equalizer has none of are counted and reported. Every platform plays the same cookbook sections: - Desktop: libavfilter's equalizer, lowshelf and highshelf, checked against the formulas by impulse response. The shelves are probed like the other optional filters and reported when the library lacks them. - iOS: the plugin's own DSP takes a filters list in place of the bands. - Android: the platform equalizer is a bank of fixed bands and cannot hold such a filter, so the filters run in the app's own DSP on the PCM entering the media3 sink (16, 24 and 32-bit integer and float; 16-bit output is dithered). It sits in front of the sink, since the sink skips its processor chain for the float PCM of high resolution songs. The input gain moves there with the filters, ahead of the platform effect that keeps balance, compressor and limiter. The platform MediaPlayer engine cannot do this: with it the equalizer is bypassed while Parametric is on, and the page says the new playback engine is needed and offers to turn it on. A system-wide equalizer, also asked for in the issue, is not part of this: the app does not attach effects to other apps' audio. Known: on Android a change is heard about a second late, once the audio already in the track's buffer has played. --- .../kotlin/com/zarz/mornye/Media3Player.kt | 52 +- .../com/zarz/mornye/ParametricEqualizer.kt | 347 ++++++++++++ .../zarz/mornye/ParametricEqualizerTest.kt | 203 +++++++ lib/l10n/arb/app_en.arb | 47 +- lib/l10n/arb/app_id.arb | 47 +- lib/models/equalizer_filter_text.dart | 122 ++++ lib/models/equalizer_settings.dart | 192 ++++++- lib/providers/equalizer_provider.dart | 33 ++ lib/screens/equalizer_curve.dart | 39 +- lib/screens/equalizer_filters.dart | 536 ++++++++++++++++++ lib/screens/equalizer_screen.dart | 130 +++-- lib/screens/equalizer_widgets.dart | 11 +- lib/services/media_kit_audio_filters.dart | 45 +- lib/services/media_kit_playback_deck.dart | 12 + lib/services/music_playback_deck.dart | 10 +- lib/widgets/audio_info_sheet.dart | 4 +- test/equalizer_parametric_test.dart | 377 ++++++++++++ test/equalizer_test.dart | 14 +- test/media_kit_audio_filters_test.dart | 53 ++ test/media_kit_playback_deck_test.dart | 3 +- .../audioplayers_darwin/MORNYE_PATCHES.md | 5 +- .../audioplayers_darwin/EqualizerDSP.swift | 41 +- .../tests/EqualizerDSPTests.swift | 17 +- 23 files changed, 2245 insertions(+), 95 deletions(-) create mode 100644 android/app/src/main/kotlin/com/zarz/mornye/ParametricEqualizer.kt create mode 100644 android/app/src/test/kotlin/com/zarz/mornye/ParametricEqualizerTest.kt create mode 100644 lib/models/equalizer_filter_text.dart create mode 100644 lib/screens/equalizer_filters.dart create mode 100644 test/equalizer_parametric_test.dart diff --git a/android/app/src/main/kotlin/com/zarz/mornye/Media3Player.kt b/android/app/src/main/kotlin/com/zarz/mornye/Media3Player.kt index 366dfd8f9..6f91e1f11 100644 --- a/android/app/src/main/kotlin/com/zarz/mornye/Media3Player.kt +++ b/android/app/src/main/kotlin/com/zarz/mornye/Media3Player.kt @@ -53,15 +53,20 @@ import io.flutter.plugin.common.MethodChannel * * Buffer size: see [MAX_BUFFERED_SPEED]. */ -internal fun media3AudioRenderers(context: Context, skipSilence: () -> Boolean) = - RenderersFactory { handler, _, audioListener, _, _ -> - val sink = DefaultAudioSink.Builder(context) - .setEnableFloatOutput(true) - .setEnableAudioOutputPlaybackParameters(true) - .setAudioTrackBufferSizeProvider(cappedSpeedBufferSize) - .build() - arrayOf(Media3AudioRenderer(context, handler, audioListener, sink, skipSilence)) - } +internal fun media3AudioRenderers( + context: Context, + parametric: ParametricEqualizerDsp, + skipSilence: () -> Boolean, +) = RenderersFactory { handler, _, audioListener, _, _ -> + val sink = DefaultAudioSink.Builder(context) + .setEnableFloatOutput(true) + .setEnableAudioOutputPlaybackParameters(true) + .setAudioTrackBufferSizeProvider(cappedSpeedBufferSize) + .build() + arrayOf( + Media3AudioRenderer(context, handler, audioListener, ParametricEqualizerSink(sink, parametric), skipSilence), + ) +} /** * media3 asks every decoder for float PCM once the sink takes float, the @@ -208,6 +213,9 @@ internal class Media3Player( private var lastDurationMs: Long? = null private var nextItem = 0L private var equalizer: PlaybackEqualizer? = null + + /** The parametric filters, which the platform equalizer cannot hold. */ + private val parametric = ParametricEqualizerDsp() private var released = false /** Read by the renderer on media3's playback thread. */ @@ -217,7 +225,7 @@ internal class Media3Player( private var spatialAudio = true init { - exo = ExoPlayer.Builder(appContext, media3AudioRenderers(appContext) { skipSilence }) + exo = ExoPlayer.Builder(appContext, media3AudioRenderers(appContext, parametric) { skipSilence }) .setLooper(looper) // The app owns focus (audio_session) and becoming-noisy handling. .setAudioAttributes(media3AudioAttributes(spatialAudio), false) @@ -500,17 +508,23 @@ internal class Media3Player( } private fun setEqualizer(configuration: Map) { - if (Build.VERSION.SDK_INT < 28) { - check(configuration["enabled"] != true) { "Equalizer requires Android 9 or later" } - return - } - if (configuration["enabled"] == true && equalizer == null) { - equalizer = PlaybackEqualizer(sessionId) - } try { - equalizer?.configure(configuration) + if (Build.VERSION.SDK_INT < 28) { + check(configuration["enabled"] != true) { "Equalizer requires Android 9 or later" } + parametric.disable() + return + } + parametric.configure(configuration) + // Its filters take the input gain with them, ahead of the + // platform effect: a boost must not clip integer PCM first. + val platform = if (parametric.active) configuration + ("inputGain" to 0.0) else configuration + if (configuration["enabled"] == true && equalizer == null) { + equalizer = PlaybackEqualizer(sessionId) + } + equalizer?.configure(platform) } catch (error: Exception) { - equalizer?.close() + parametric.disable() + if (Build.VERSION.SDK_INT >= 28) equalizer?.close() equalizer = null throw error } diff --git a/android/app/src/main/kotlin/com/zarz/mornye/ParametricEqualizer.kt b/android/app/src/main/kotlin/com/zarz/mornye/ParametricEqualizer.kt new file mode 100644 index 000000000..c8e14e0f7 --- /dev/null +++ b/android/app/src/main/kotlin/com/zarz/mornye/ParametricEqualizer.kt @@ -0,0 +1,347 @@ +package com.zarz.mornye + +import android.util.Log +import androidx.annotation.OptIn +import androidx.media3.common.C +import androidx.media3.common.MimeTypes +import androidx.media3.common.util.UnstableApi +import androidx.media3.exoplayer.audio.AudioSink +import androidx.media3.exoplayer.audio.ForwardingAudioSink +import java.nio.ByteBuffer +import kotlin.math.PI +import kotlin.math.abs +import kotlin.math.cos +import kotlin.math.max +import kotlin.math.min +import kotlin.math.pow +import kotlin.math.roundToLong +import kotlin.math.sin +import kotlin.math.sqrt + +/** One filter of the `setEqualizer` configuration's `filters`. */ +internal data class ParametricFilter( + val type: String, + val frequency: Double, + val gain: Double, + val q: Double, +) { + /** + * `b0, b1, b2, a1, a2` of the cookbook section + * (https://www.w3.org/TR/audio-eq-cookbook/), the same on every platform. + */ + fun coefficients(rate: Double): DoubleArray { + val w = 2 * PI * min(frequency, rate * 0.45) / rate + val a = 10.0.pow(gain / 40) + val cosine = cos(w) + val alpha = sin(w) / (2 * q) + val slope = 2 * sqrt(a) * alpha + val b: DoubleArray + val a0: Double + val a1: Double + val a2: Double + when (type) { + LOW_SHELF -> { + b = doubleArrayOf( + a * ((a + 1) - (a - 1) * cosine + slope), + 2 * a * ((a - 1) - (a + 1) * cosine), + a * ((a + 1) - (a - 1) * cosine - slope), + ) + a0 = (a + 1) + (a - 1) * cosine + slope + a1 = -2 * ((a - 1) + (a + 1) * cosine) + a2 = (a + 1) + (a - 1) * cosine - slope + } + HIGH_SHELF -> { + b = doubleArrayOf( + a * ((a + 1) + (a - 1) * cosine + slope), + -2 * a * ((a - 1) + (a + 1) * cosine), + a * ((a + 1) + (a - 1) * cosine - slope), + ) + a0 = (a + 1) - (a - 1) * cosine + slope + a1 = 2 * ((a - 1) - (a + 1) * cosine) + a2 = (a + 1) - (a - 1) * cosine - slope + } + else -> { + b = doubleArrayOf(1 + alpha * a, -2 * cosine, 1 - alpha * a) + a0 = 1 + alpha / a + a1 = -2 * cosine + a2 = 1 - alpha / a + } + } + return doubleArrayOf(b[0] / a0, b[1] / a0, b[2] / a0, a1 / a0, a2 / a0) + } + + companion object { + const val PEAK = "peak" + const val LOW_SHELF = "lowshelf" + const val HIGH_SHELF = "highshelf" + const val MAX_FILTERS = 20 + + /** + * The filters of a configuration, or null when it is off or plays + * the graphic bands. + */ + fun parse(data: Map): List? { + if (data["enabled"] != true) return null + val raw = data["filters"] as? List<*> ?: return null + require(raw.size <= MAX_FILTERS) { "Too many equalizer filters" } + return raw.map { entry -> + val filter = entry as? Map<*, *> ?: error("Invalid equalizer filter") + fun number(key: String): Double = + (filter[key] as? Number)?.toDouble()?.takeIf { it.isFinite() } + ?: error("Invalid equalizer filter") + val type = filter["type"] as? String + require(type == PEAK || type == LOW_SHELF || type == HIGH_SHELF) { "Unknown equalizer filter" } + ParametricFilter( + type = type!!, + frequency = number("frequency").also { require(it in 10.0..24000.0) }, + gain = number("gain").also { require(abs(it) <= 24) }, + q = number("q").also { require(it in 0.05..40.0) }, + ) + } + } + } +} + +/** + * The parametric equalizer's own DSP on decoded PCM: input gain, then the + * filters. The platform equalizer is a bank of fixed bands and cannot hold + * a filter with its own frequency and width. + * + * [configure] is called from the platform thread, everything else from the + * playback thread. + */ +internal class ParametricEqualizerDsp { + private class Plan(val inputGain: Double, val filters: List) + + @Volatile + private var plan: Plan? = null + + /** The plan the sections were built for; playback thread only. */ + private var built: Plan? = null + private var rate = 0.0 + private var channels = 0 + + // Per section and channel: coefficients, their targets and the state. + private var sections = 0 + private var coefficients = DoubleArray(0) + private var targets = DoubleArray(0) + private var state = DoubleArray(0) + private var ramp = 0 + private var gain = 1.0 + private var targetGain = 1.0 + private var noise = 0x2545F491 + + val active: Boolean get() = plan != null + + /** Takes the `setEqualizer` configuration; null filters turn it off. */ + fun configure(data: Map) { + val filters = ParametricFilter.parse(data) + plan = filters?.let { + val inputGain = ((data["inputGain"] as? Number)?.toDouble() ?: 0.0) + .takeIf { it.isFinite() }?.coerceIn(-48.0, 12.0) ?: 0.0 + Plan(10.0.pow(inputGain / 20), it) + } + } + + fun disable() { + plan = null + } + + fun prepare(sampleRate: Int, channelCount: Int) { + rate = sampleRate.toDouble() + channels = channelCount + built = null + } + + /** Forgets the filters' memory, as after a seek. */ + fun reset() { + state.fill(0.0) + } + + private fun build(next: Plan) { + val smooth = built != null && next.filters.size == sections + if (!smooth) { + sections = next.filters.size + coefficients = DoubleArray(sections * 5) + state = DoubleArray(sections * channels * 2) + } + targets = DoubleArray(sections * 5) + next.filters.forEachIndexed { index, filter -> + filter.coefficients(rate).copyInto(targets, index * 5) + } + targetGain = next.inputGain + if (smooth) { + // A change slides over 5 ms, so a slider does not click. + ramp = max(1, (rate * 0.005).toInt()) + } else { + targets.copyInto(coefficients) + gain = targetGain + ramp = 0 + } + built = next + } + + /** + * Writes the processed frames of [input] to [output], which has room + * for them. Returns false, with nothing read, when the equalizer is off + * or cannot read [encoding]. + */ + fun process(input: ByteBuffer, output: ByteBuffer, encoding: Int): Boolean { + val current = plan ?: return false + val width = when (encoding) { + C.ENCODING_PCM_16BIT -> 2 + C.ENCODING_PCM_24BIT -> 3 + C.ENCODING_PCM_32BIT, C.ENCODING_PCM_FLOAT -> 4 + else -> return false + } + if (channels <= 0 || rate <= 0) return false + if (current !== built) build(current) + val frames = input.remaining() / (width * channels) + var position = input.position() + for (frame in 0 until frames) { + if (ramp > 0) { + val step = 1.0 / ramp + for (index in coefficients.indices) { + coefficients[index] += (targets[index] - coefficients[index]) * step + } + gain += (targetGain - gain) * step + ramp-- + } + for (channel in 0 until channels) { + var value = when (encoding) { + C.ENCODING_PCM_16BIT -> input.getShort(position) / 32768.0 + C.ENCODING_PCM_24BIT -> ( + (input.get(position).toInt() and 0xFF) or + ((input.get(position + 1).toInt() and 0xFF) shl 8) or + (input.get(position + 2).toInt() shl 16) + ) / 8388608.0 + C.ENCODING_PCM_32BIT -> input.getInt(position) / 2147483648.0 + else -> input.getFloat(position).toDouble() + } + if (!value.isFinite()) value = 0.0 + value *= gain + for (section in 0 until sections) { + val c = section * 5 + val z = (section * channels + channel) * 2 + val out = coefficients[c] * value + state[z] + state[z] = coefficients[c + 1] * value - coefficients[c + 3] * out + state[z + 1] + state[z + 1] = coefficients[c + 2] * value - coefficients[c + 4] * out + value = out + } + if (!value.isFinite()) { + // A filter that ran away starts over in silence. + state.fill(0.0) + value = 0.0 + } + when (encoding) { + C.ENCODING_PCM_16BIT -> { + // Triangular dither of one step hides the rounding. + val dithered = value * 32768.0 + random() - random() + output.putShort(dithered.roundToLong().coerceIn(-32768, 32767).toShort()) + } + C.ENCODING_PCM_24BIT -> { + val sample = (value * 8388608.0).roundToLong().coerceIn(-8388608, 8388607).toInt() + output.put(sample.toByte()) + output.put((sample shr 8).toByte()) + output.put((sample shr 16).toByte()) + } + C.ENCODING_PCM_32BIT -> output.putInt( + (value * 2147483648.0).roundToLong().coerceIn(-2147483648L, 2147483647L).toInt(), + ) + else -> output.putFloat(value.toFloat()) + } + position += width + } + } + input.position(position) + return true + } + + /** Uniform in 0 until 1; an xorshift is enough for dither. */ + private fun random(): Double { + noise = noise xor (noise shl 13) + noise = noise xor (noise ushr 17) + noise = noise xor (noise shl 5) + return (noise ushr 8) / 16777216.0 + } +} + +/** + * Runs [dsp] over the PCM on its way into [sink]. It sits in front of the + * sink, not in its processor chain, which `DefaultAudioSink` skips for the + * float PCM of high resolution songs. + * + * Its changes are heard once the audio already in the track's buffer has + * played (about a second), unlike the platform equalizer behind it. + */ +@OptIn(UnstableApi::class) +internal class ParametricEqualizerSink( + sink: AudioSink, + private val dsp: ParametricEqualizerDsp, +) : ForwardingAudioSink(sink) { + private var encoding = C.ENCODING_INVALID + + /** The decoder's buffer a processed copy is still being written for. */ + private var pending: ByteBuffer? = null + private var processed: ByteBuffer = ByteBuffer.allocateDirect(0) + + /** Whether the last buffer went through the filters; logged on change. */ + private var playing: Boolean? = null + + override fun configure(config: AudioSink.AudioSinkConfig) { + super.configure(config) + val format = config.format + encoding = if (format.sampleMimeType == MimeTypes.AUDIO_RAW) format.pcmEncoding else C.ENCODING_INVALID + dsp.prepare(format.sampleRate, format.channelCount) + playing = null + } + + override fun handleBuffer(buffer: ByteBuffer, presentationTimeUs: Long, encodedAccessUnitCount: Int): Boolean { + if (buffer !== pending) { + pending = null + if (!dsp.active || !buffer.hasRemaining()) { + return super.handleBuffer(buffer, presentationTimeUs, encodedAccessUnitCount) + } + // The decoder's buffer is not ours to write to. + if (processed.capacity() < buffer.remaining()) { + processed = ByteBuffer.allocateDirect(buffer.remaining()) + } + processed.clear() + processed.order(buffer.order()) + val start = buffer.position() + val played = dsp.process(buffer, processed, encoding) && !buffer.hasRemaining() + if (played != playing) { + playing = played + Log.i(TAG, "Parametric equalizer ${if (played) "plays" else "cannot play"} PCM encoding $encoding") + } + if (!played) { + // Off since the check, an encoding it cannot read, or a + // buffer that does not end on a frame: play it as it is. + buffer.position(start) + return super.handleBuffer(buffer, presentationTimeUs, encodedAccessUnitCount) + } + processed.flip() + pending = buffer + } + // The sink asks for the same buffer until it has taken all of it. + val done = super.handleBuffer(processed, presentationTimeUs, encodedAccessUnitCount) + if (done) pending = null + return done + } + + override fun flush() { + pending = null + dsp.reset() + super.flush() + } + + override fun reset() { + pending = null + dsp.reset() + super.reset() + } + + private companion object { + const val TAG = "ParametricEqualizer" + } +} diff --git a/android/app/src/test/kotlin/com/zarz/mornye/ParametricEqualizerTest.kt b/android/app/src/test/kotlin/com/zarz/mornye/ParametricEqualizerTest.kt new file mode 100644 index 000000000..56f44c8f6 --- /dev/null +++ b/android/app/src/test/kotlin/com/zarz/mornye/ParametricEqualizerTest.kt @@ -0,0 +1,203 @@ +package com.zarz.mornye + +import androidx.media3.common.C +import java.nio.ByteBuffer +import java.nio.ByteOrder +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 org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +class ParametricEqualizerTest { + private fun configuration( + filters: List>?, + inputGain: Double = 0.0, + ): Map = mapOf("enabled" to true, "inputGain" to inputGain, "filters" to filters) + + private fun filter(type: String, frequency: Double, gain: Double, q: Double) = + mapOf("type" to type, "frequency" to frequency, "gain" to gain, "q" to q) + + private fun floats(samples: FloatArray): ByteBuffer = + ByteBuffer.allocateDirect(samples.size * 4).order(ByteOrder.nativeOrder()).apply { + samples.forEach { putFloat(it) } + flip() + } + + /** Gain in dB of [dsp] for a mono sine at [hz], measured once it settled. */ + private fun gainAt(dsp: ParametricEqualizerDsp, hz: Double, rate: Int = 48000): Double { + dsp.prepare(rate, 1) + val input = FloatArray(rate) { (0.25 * sin(2 * PI * hz * it / rate)).toFloat() } + val output = ByteBuffer.allocateDirect(input.size * 4).order(ByteOrder.nativeOrder()) + assertTrue(dsp.process(floats(input), output, C.ENCODING_PCM_FLOAT)) + output.flip() + var sum = 0.0 + for (index in rate / 2 until rate) { + val value = output.getFloat(index * 4).toDouble() + sum += value * value + } + return 20 * log10(sqrt(sum / (rate / 2)) / (0.25 / sqrt(2.0))) + } + + @Test + fun graphicAndDisabledConfigurationsHaveNoFilters() { + assertNull(ParametricFilter.parse(mapOf("enabled" to false, "filters" to emptyList()))) + assertNull(ParametricFilter.parse(mapOf("enabled" to true, "filters" to null))) + assertNull(ParametricFilter.parse(mapOf("enabled" to true))) + assertEquals(0, ParametricFilter.parse(configuration(emptyList()))!!.size) + } + + @Test + fun rejectsFiltersOutOfRange() { + for (bad in listOf( + filter("notch", 1000.0, 3.0, 1.0), + filter("peak", 0.0, 3.0, 1.0), + filter("peak", 1000.0, 30.0, 1.0), + filter("peak", 1000.0, 3.0, 0.0), + filter("peak", Double.NaN, 3.0, 1.0), + )) { + assertThrows(RuntimeException::class.java) { ParametricFilter.parse(configuration(listOf(bad))) } + } + assertThrows(RuntimeException::class.java) { + ParametricFilter.parse(configuration(List(21) { filter("peak", 1000.0, 1.0, 1.0) })) + } + } + + @Test + fun peakCoefficientsAreTheCookbookSection() { + val rate = 48000.0 + val w = 2 * PI * 1000 / rate + val a = Math.pow(10.0, 6.0 / 40) + val alpha = sin(w) / (2 * 1.4) + val a0 = 1 + alpha / a + val got = ParametricFilter("peak", 1000.0, 6.0, 1.4).coefficients(rate) + val want = doubleArrayOf( + (1 + alpha * a) / a0, -2 * cos(w) / a0, (1 - alpha * a) / a0, -2 * cos(w) / a0, (1 - alpha / a) / a0, + ) + for (index in want.indices) assertEquals(want[index], got[index], 1e-12) + } + + @Test + fun filtersReachTheirGainWhereTheyShould() { + val dsp = ParametricEqualizerDsp() + dsp.configure(configuration(listOf(filter("peak", 1000.0, 6.0, 1.4)))) + assertEquals(6.0, gainAt(dsp, 1000.0), 0.02) + assertEquals(0.0, gainAt(dsp, 60.0), 0.05) + assertEquals(0.0, gainAt(dsp, 15000.0), 0.05) + + dsp.configure(configuration(listOf(filter("lowshelf", 200.0, -5.0, 0.707)))) + assertEquals(-5.0, gainAt(dsp, 30.0), 0.05) + assertEquals(-2.5, gainAt(dsp, 200.0), 0.05) + assertEquals(0.0, gainAt(dsp, 5000.0), 0.02) + + dsp.configure(configuration(listOf(filter("highshelf", 4000.0, 4.0, 0.707)))) + assertEquals(0.0, gainAt(dsp, 100.0), 0.02) + assertEquals(2.0, gainAt(dsp, 4000.0), 0.05) + assertEquals(4.0, gainAt(dsp, 18000.0), 0.1) + } + + @Test + fun inputGainAndSeveralFiltersAddUp() { + val dsp = ParametricEqualizerDsp() + dsp.configure( + configuration( + listOf(filter("peak", 1000.0, 6.0, 1.0), filter("peak", 1000.0, -2.0, 1.0)), + inputGain = -3.0, + ), + ) + // Two peaks of one width do not sum to a third exactly off centre, + // but at the centre their gains add. + assertEquals(6.0 - 2.0 - 3.0, gainAt(dsp, 1000.0), 0.02) + } + + @Test + fun offOrUnknownEncodingLeavesTheBufferUnread() { + val dsp = ParametricEqualizerDsp() + dsp.prepare(48000, 2) + val input = floats(FloatArray(8) { 0.5f }) + val output = ByteBuffer.allocateDirect(32).order(ByteOrder.nativeOrder()) + assertFalse(dsp.active) + assertFalse(dsp.process(input, output, C.ENCODING_PCM_FLOAT)) + assertEquals(0, input.position()) + dsp.configure(configuration(listOf(filter("peak", 1000.0, 6.0, 1.0)))) + assertTrue(dsp.active) + assertFalse(dsp.process(input, output, C.ENCODING_PCM_16BIT_BIG_ENDIAN)) + assertEquals(0, input.position()) + dsp.configure(mapOf("enabled" to false)) + assertFalse(dsp.active) + } + + @Test + fun integerPcmKeepsItsWidthAndLevel() { + for ((encoding, width) in listOf( + C.ENCODING_PCM_16BIT to 2, + C.ENCODING_PCM_24BIT to 3, + C.ENCODING_PCM_32BIT to 4, + )) { + val dsp = ParametricEqualizerDsp() + // No filter: the input gain alone, so each sample is checkable. + dsp.configure(configuration(emptyList(), inputGain = -6.0206)) + dsp.prepare(44100, 2) + val frames = 64 + val input = ByteBuffer.allocateDirect(frames * 2 * width).order(ByteOrder.LITTLE_ENDIAN) + val full = 1L shl (width * 8 - 1) + repeat(frames) { frame -> + for (channel in 0 until 2) { + val sample = (if (channel == 0) full / 2 else -full / 4) + frame + for (byte in 0 until width) input.put((sample shr (8 * byte)).toByte()) + } + } + input.flip() + val output = ByteBuffer.allocateDirect(input.remaining()).order(ByteOrder.LITTLE_ENDIAN) + assertTrue(dsp.process(input, output, encoding)) + assertFalse(input.hasRemaining()) + output.flip() + assertEquals(frames * 2 * width, output.remaining()) + repeat(frames) { frame -> + for (channel in 0 until 2) { + var sample = 0L + for (byte in 0 until width) { + val value = output.get().toLong() + sample = sample or ((if (byte == width - 1) value else value and 0xFF) shl (8 * byte)) + } + val want = ((if (channel == 0) full / 2 else -full / 4) + frame) / 2.0 + // Half the level, within the dither of 16-bit output and + // the rounding of the gain written in dB. + val slack = (if (width == 2) 1.6 else 1.0) + abs(want) * 1e-6 + assertTrue("$encoding $frame $channel", abs(sample - want) <= slack) + } + } + } + } + + @Test + fun changingAFilterSlidesWithoutAJump() { + val dsp = ParametricEqualizerDsp() + dsp.configure(configuration(listOf(filter("peak", 1000.0, 0.5, 1.0)))) + dsp.prepare(48000, 1) + val constant = FloatArray(4800) { 0.25f } + val first = ByteBuffer.allocateDirect(constant.size * 4).order(ByteOrder.nativeOrder()) + assertTrue(dsp.process(floats(constant), first, C.ENCODING_PCM_FLOAT)) + dsp.configure(configuration(listOf(filter("peak", 1000.0, 12.0, 1.0)), inputGain = -12.0)) + val second = ByteBuffer.allocateDirect(constant.size * 4).order(ByteOrder.nativeOrder()) + assertTrue(dsp.process(floats(constant), second, C.ENCODING_PCM_FLOAT)) + second.flip() + var previous = first.getFloat((constant.size - 1) * 4) + var largest = 0f + for (index in constant.indices) { + val value = second.getFloat(index * 4) + largest = maxOf(largest, abs(value - previous)) + previous = value + } + // The input gain falls by 12 dB over 5 ms (240 frames), not at once. + assertTrue("step $largest", largest < 0.01f) + assertEquals(0.25f * 0.2512f, previous, 0.002f) + } +} diff --git a/lib/l10n/arb/app_en.arb b/lib/l10n/arb/app_en.arb index db4779a32..2cd7f06a3 100644 --- a/lib/l10n/arb/app_en.arb +++ b/lib/l10n/arb/app_en.arb @@ -10222,7 +10222,7 @@ "appearanceCustomFontInvalid": "Could not load this font. Choose a valid TTF or OTF file up to 10 MB.", "appearanceCustomFontReset": "Use theme font", "equalizerTitle": "Equalizer", - "equalizerDescription": "5–31 bands, tone controls, preamp and dynamics", + "equalizerDescription": "5–31 bands or parametric filters, preamp and dynamics", "equalizerEnable": "Enable equalizer", "equalizerBands": "Bands", "equalizerTone": "Tone & stereo", @@ -10246,7 +10246,7 @@ "equalizerPresetName": "Preset name", "equalizerImport": "Import preset", "equalizerExport": "Share preset", - "equalizerImportInvalid": "Choose a valid Mornye equalizer preset (JSON, up to 64 KB).", + "equalizerImportInvalid": "Choose a Mornye equalizer preset (JSON) or a filter list (text), up to 64 KB.", "equalizerSaved": "Preset saved", "equalizerResetTitle": "Reset equalizer?", "equalizerResetDescription": "Restore a flat curve, default tone and dynamics settings. Saved presets are kept.", @@ -10257,6 +10257,49 @@ "equalizerDeletePreset": "Delete preset", "equalizerCustom": "Custom", "equalizerManagePresets": "Manage presets", + "equalizerModeGraphic": "Graphic", + "equalizerModeParametric": "Parametric", + "equalizerFilters": "Filters", + "equalizerFilterCount": "{count, plural, =1{1 filter} other{{count} filters}}", + "@equalizerFilterCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "equalizerFilterNumber": "Filter {number}", + "@equalizerFilterNumber": { + "placeholders": { + "number": { + "type": "int" + } + } + }, + "equalizerAddFilter": "Add filter", + "equalizerRemoveFilter": "Remove filter", + "equalizerFiltersEmpty": "No filters yet. Add one, or import a filter list.", + "equalizerFilterPeak": "Peak", + "equalizerFilterLowShelf": "Low shelf", + "equalizerFilterHighShelf": "High shelf", + "equalizerFilterFrequency": "Frequency", + "equalizerFilterGain": "Gain", + "equalizerFilterQ": "Q", + "@equalizerFilterQ": { + "description": "The quality factor (width) of a parametric equalizer filter; keep the letter Q" + }, + "equalizerFilterTypeValue": "Type the value", + "equalizerNeedsEngine": "Parametric filters play through the new playback engine. Turn it on to hear them. Applies from the next song.", + "equalizerNeedsEngineAction": "Turn on", + "equalizerExportFilters": "Share filter list", + "equalizerImportSkipped": "{count, plural, =1{Imported. 1 filter of an unsupported kind was left out.} other{Imported. {count} filters of an unsupported kind were left out.}}", + "@equalizerImportSkipped": { + "placeholders": { + "count": { + "type": "int" + } + } + }, "lyricsShareTitle": "Share lyrics", "@lyricsShareTitle": { "description": "Screen that turns selected lyric lines into an image for stories" diff --git a/lib/l10n/arb/app_id.arb b/lib/l10n/arb/app_id.arb index 3d54de53c..9f7eaef0b 100644 --- a/lib/l10n/arb/app_id.arb +++ b/lib/l10n/arb/app_id.arb @@ -8700,7 +8700,7 @@ "appearanceCustomFontInvalid": "Font tidak dapat dimuat. Pilih file TTF atau OTF yang valid, maksimal 10 MB.", "appearanceCustomFontReset": "Gunakan font tema", "equalizerTitle": "Equalizer", - "equalizerDescription": "5–31 band, kontrol nada, preamp, dan dinamika", + "equalizerDescription": "5–31 band atau filter parametrik, preamp, dan dinamika", "equalizerEnable": "Aktifkan equalizer", "equalizerBands": "Band", "equalizerTone": "Nada & stereo", @@ -8724,7 +8724,7 @@ "equalizerPresetName": "Nama preset", "equalizerImport": "Impor preset", "equalizerExport": "Bagikan preset", - "equalizerImportInvalid": "Pilih preset equalizer Mornye yang valid (JSON, maksimal 64 KB).", + "equalizerImportInvalid": "Pilih preset equalizer Mornye (JSON) atau daftar filter (teks), maksimal 64 KB.", "equalizerSaved": "Preset disimpan", "equalizerResetTitle": "Reset equalizer?", "equalizerResetDescription": "Kembalikan kurva datar serta pengaturan nada dan dinamika bawaan. Preset tersimpan tetap disimpan.", @@ -8735,6 +8735,49 @@ "equalizerDeletePreset": "Hapus preset", "equalizerCustom": "Kustom", "equalizerManagePresets": "Kelola preset", + "equalizerModeGraphic": "Grafis", + "equalizerModeParametric": "Parametrik", + "equalizerFilters": "Filter", + "equalizerFilterCount": "{count, plural, other{{count} filter}}", + "@equalizerFilterCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "equalizerFilterNumber": "Filter {number}", + "@equalizerFilterNumber": { + "placeholders": { + "number": { + "type": "int" + } + } + }, + "equalizerAddFilter": "Tambah filter", + "equalizerRemoveFilter": "Hapus filter", + "equalizerFiltersEmpty": "Belum ada filter. Tambahkan satu, atau impor daftar filter.", + "equalizerFilterPeak": "Peak", + "equalizerFilterLowShelf": "Low shelf", + "equalizerFilterHighShelf": "High shelf", + "equalizerFilterFrequency": "Frekuensi", + "equalizerFilterGain": "Gain", + "equalizerFilterQ": "Q", + "@equalizerFilterQ": { + "description": "The quality factor (width) of a parametric equalizer filter; keep the letter Q" + }, + "equalizerFilterTypeValue": "Ketik nilainya", + "equalizerNeedsEngine": "Filter parametrik diputar lewat mesin pemutar baru. Aktifkan untuk mendengarnya. Berlaku mulai lagu berikutnya.", + "equalizerNeedsEngineAction": "Aktifkan", + "equalizerExportFilters": "Bagikan daftar filter", + "equalizerImportSkipped": "{count, plural, other{Diimpor. {count} filter dari jenis yang tidak didukung dilewati.}}", + "@equalizerImportSkipped": { + "placeholders": { + "count": { + "type": "int" + } + } + }, "lyricsShareTitle": "Bagikan lirik", "@lyricsShareTitle": { "description": "Screen that turns selected lyric lines into an image for stories" diff --git a/lib/models/equalizer_filter_text.dart b/lib/models/equalizer_filter_text.dart new file mode 100644 index 000000000..06eabc4ea --- /dev/null +++ b/lib/models/equalizer_filter_text.dart @@ -0,0 +1,122 @@ +import 'package:mornye/models/equalizer_settings.dart'; + +/// The plain text list of parametric filters that measurement and tuning +/// tools exchange, one filter a line: +/// +/// ``` +/// Preamp: -6.2 dB +/// Filter 1: ON PK Fc 105 Hz Gain -2.1 dB Q 0.70 +/// Filter 2: ON LSC Fc 80 Hz Gain 4 dB Q 0.71 +/// ``` +class EqualizerFilterText { + const EqualizerFilterText({ + required this.filters, + this.preamp, + this.skipped = 0, + }); + + final List filters; + + /// The file's own gain before the filters, when it names one. + final double? preamp; + + /// Filters of a kind the equalizer has none of (pass, notch, all-pass). + final int skipped; + + static final _preamp = RegExp( + r'^\s*Preamp\s*:\s*([-+]?[0-9.,]+)\s*dB', + caseSensitive: false, + ); + static final _filter = RegExp( + r'^\s*Filter\s*\d*\s*:\s*(ON|OFF)\s+([A-Za-z]+)\b(.*)$', + caseSensitive: false, + ); + static final _frequency = RegExp( + r'\bFc\s+([0-9.,]+)\s*Hz', + caseSensitive: false, + ); + static final _gain = RegExp( + r'\bGain\s+([-+]?[0-9.,]+)\s*dB', + caseSensitive: false, + ); + static final _q = RegExp(r'\bQ\s+([0-9.,]+)', caseSensitive: false); + + static double? _number(RegExpMatch? match) => match == null + ? null + : double.tryParse(match.group(1)!.replaceAll(',', '.')); + + /// Throws a [FormatException] when [source] holds no usable filter. + factory EqualizerFilterText.parse(String source) { + double? preamp; + var skipped = 0; + final filters = []; + for (final line in source.split(RegExp(r'\r?\n'))) { + preamp ??= _number(_preamp.firstMatch(line)); + final match = _filter.firstMatch(line); + if (match == null) continue; + final type = switch (match.group(2)!.toUpperCase()) { + 'PK' || 'PEQ' || 'MODAL' => EqualizerFilterType.peak, + 'LS' || 'LSC' || 'LSQ' => EqualizerFilterType.lowShelf, + 'HS' || 'HSC' || 'HSQ' => EqualizerFilterType.highShelf, + _ => null, + }; + final rest = match.group(3)!; + final frequency = _number(_frequency.firstMatch(rest)); + final gain = _number(_gain.firstMatch(rest)); + if (type == null || frequency == null || gain == null) { + // An empty slot ("None") is not a filter that was left out. + if (match.group(2)!.toUpperCase() != 'NONE') skipped++; + continue; + } + if (!frequency.isFinite || !gain.isFinite) continue; + final q = _number(_q.firstMatch(rest)); + if (filters.length >= EqualizerSettings.maxFilters) { + skipped++; + continue; + } + filters.add( + EqualizerFilter( + type: type, + frequency: frequency.clamp( + EqualizerFilter.minFrequency, + EqualizerFilter.maxFrequency, + ), + gain: gain.clamp(-EqualizerFilter.maxGain, EqualizerFilter.maxGain), + q: (q != null && q.isFinite && q > 0 ? q : EqualizerFilter.shelfQ) + .clamp(EqualizerFilter.minQ, EqualizerFilter.maxQ), + enabled: match.group(1)!.toUpperCase() == 'ON', + ), + ); + } + if (filters.isEmpty) throw const FormatException('No filters found'); + return EqualizerFilterText( + filters: filters, + preamp: preamp != null && preamp.isFinite ? preamp : null, + skipped: skipped, + ); + } + + /// The filters of [settings] with the gain they play at, so the text + /// sounds the same in a tool without automatic headroom. + static String format(EqualizerSettings settings) { + String number(double value, int digits) { + final text = value.toStringAsFixed(digits); + return double.parse(text) == 0 ? 0.toStringAsFixed(digits) : text; + } + + final lines = ['Preamp: ${number(settings.inputGain, 1)} dB']; + for (final (index, filter) in settings.filters.indexed) { + final type = switch (filter.type) { + EqualizerFilterType.peak => 'PK', + EqualizerFilterType.lowShelf => 'LSC', + EqualizerFilterType.highShelf => 'HSC', + }; + lines.add( + 'Filter ${index + 1}: ${filter.enabled ? 'ON' : 'OFF'} $type ' + 'Fc ${number(filter.frequency, filter.frequency % 1 == 0 ? 0 : 1)} Hz ' + 'Gain ${number(filter.gain, 1)} dB Q ${number(filter.q, 2)}', + ); + } + return '${lines.join('\n')}\n'; + } +} diff --git a/lib/models/equalizer_settings.dart b/lib/models/equalizer_settings.dart index 14a3965c4..6dd73990f 100644 --- a/lib/models/equalizer_settings.dart +++ b/lib/models/equalizer_settings.dart @@ -1,9 +1,126 @@ import 'dart:math' as math; -/// Portable graphic EQ settings. Gains are independent of the system volume. +enum EqualizerFilterType { + peak('peak'), + lowShelf('lowshelf'), + highShelf('highshelf'); + + const EqualizerFilterType(this.nativeName); + + /// The name in saved settings and in the native configuration. + final String nativeName; +} + +/// One filter of the parametric equalizer: a second order section from the +/// Audio EQ Cookbook (https://www.w3.org/TR/audio-eq-cookbook/). +class EqualizerFilter { + const EqualizerFilter({ + this.type = EqualizerFilterType.peak, + this.frequency = 1000, + this.gain = 0, + this.q = 1, + this.enabled = true, + }); + + static const minFrequency = 20.0, maxFrequency = 20000.0; + static const maxGain = 24.0; + static const minQ = 0.1, maxQ = 20.0; + + /// The Q of a shelf that names none: the steepest without overshoot. + static const shelfQ = 0.707; + + final EqualizerFilterType type; + final double frequency, gain, q; + final bool enabled; + + /// Gain in dB at [hz], from the analog prototype. The digital filter + /// differs only close to half the sample rate. + double responseAt(double hz) { + if (!enabled || gain == 0) return 0; + final a = math.pow(10, gain / 40).toDouble(); + final w = hz / frequency, w2 = w * w; + switch (type) { + case EqualizerFilterType.peak: + final pass = (1 - w2) * (1 - w2); + return 10 * + math.log( + (pass + math.pow(a * w / q, 2)) / + (pass + math.pow(w / (a * q), 2)), + ) / + math.ln10; + case EqualizerFilterType.lowShelf: + case EqualizerFilterType.highShelf: + final damping = a * w2 / (q * q); + final low = math.pow(a - w2, 2) + damping; + final high = math.pow(1 - a * w2, 2) + damping; + final ratio = type == EqualizerFilterType.lowShelf + ? low / high + : high / low; + return 10 * math.log(a * a * ratio) / math.ln10; + } + } + + EqualizerFilter copyWith({ + EqualizerFilterType? type, + double? frequency, + double? gain, + double? q, + bool? enabled, + }) => EqualizerFilter( + type: type ?? this.type, + frequency: frequency ?? this.frequency, + gain: gain ?? this.gain, + q: q ?? this.q, + enabled: enabled ?? this.enabled, + ); + + Map toJson() => { + 'type': type.nativeName, + 'frequency': frequency, + 'gain': gain, + 'q': q, + 'enabled': enabled, + }; + + /// Null for an entry that is not a filter. Values are brought into range. + static EqualizerFilter? fromJson(Object? json) { + if (json is! Map) return null; + final frequency = json['frequency'], gain = json['gain'], q = json['q']; + if (frequency is! num || gain is! num || q is! num) return null; + if (!frequency.isFinite || !gain.isFinite || !q.isFinite) return null; + return EqualizerFilter( + type: EqualizerFilterType.values.firstWhere( + (type) => type.nativeName == json['type'], + orElse: () => EqualizerFilterType.peak, + ), + frequency: frequency.toDouble().clamp(minFrequency, maxFrequency), + gain: gain.toDouble().clamp(-maxGain, maxGain), + q: q.toDouble().clamp(minQ, maxQ), + enabled: json['enabled'] != false, + ); + } + + @override + bool operator ==(Object other) => + other is EqualizerFilter && + other.type == type && + other.frequency == frequency && + other.gain == gain && + other.q == q && + other.enabled == enabled; + + @override + int get hashCode => Object.hash(type, frequency, gain, q, enabled); +} + +/// Portable EQ settings: a graphic equalizer of fixed bands, or the +/// [filters] of a parametric one while [parametric] is set. Gains are +/// independent of the system volume. class EqualizerSettings { const EqualizerSettings({ this.enabled = false, + this.parametric = false, + this.filters = const [], this.gains = const [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], this.preamp = 0, this.bass = 0, @@ -19,7 +136,16 @@ class EqualizerSettings { }); static const bandCounts = [5, 10, 15, 31]; + + /// The most parametric filters kept. + static const maxFilters = 20; + final bool enabled, autoHeadroom, limiter, compressor; + + /// Whether [filters] shape the sound in place of [gains], [bass] and + /// [treble], which are kept for the way back. + final bool parametric; + final List filters; final List gains; final double preamp, bass, treble, balance; final double threshold, ratio, attack, release; @@ -90,12 +216,37 @@ class EqualizerSettings { .clamp(-24.0, 24.0), ]; - double get headroom => - autoHeadroom ? effectiveGains.fold(0.0, math.max).clamp(0.0, 24.0) : 0; + /// Gain in dB at [hz] of the curve that plays: the filters together, or + /// the bands with the tone controls. + double responseAt(double hz) => parametric + ? filters.fold(0.0, (sum, filter) => sum + filter.responseAt(hz)) + : gainAt(hz, includeTone: true); + + /// The highest point of the parametric curve, looked for on a grid of 24 + /// points an octave and at every filter's own frequency. + double get _filterPeak { + var peak = 0.0; + for (var step = 0; step <= 240; step++) { + peak = math.max(peak, responseAt(20 * math.pow(2, step / 24).toDouble())); + } + for (final filter in filters) { + peak = math.max(peak, responseAt(filter.frequency)); + } + return peak; + } + + double get headroom => !autoHeadroom + ? 0 + : (parametric ? _filterPeak : effectiveGains.fold(0.0, math.max)).clamp( + 0.0, + 24.0, + ); double get inputGain => (preamp - headroom).clamp(-48.0, 12.0); EqualizerSettings copyWith({ bool? enabled, + bool? parametric, + List? filters, List? gains, double? preamp, double? bass, @@ -110,6 +261,10 @@ class EqualizerSettings { double? release, }) => EqualizerSettings( enabled: enabled ?? this.enabled, + parametric: parametric ?? this.parametric, + filters: filters == null + ? this.filters + : List.unmodifiable(filters.take(maxFilters)), gains: gains == null ? this.gains : List.unmodifiable(gains), preamp: preamp ?? this.preamp, bass: bass ?? this.bass, @@ -133,6 +288,9 @@ class EqualizerSettings { /// A preset carries a sound; headroom, limiting, compression and balance /// stay as the listener set them. EqualizerSettings withToneOf(EqualizerSettings preset) => copyWith( + parametric: preset.parametric, + // A graphic preset leaves the listener's filters for the way back. + filters: preset.parametric ? preset.filters : null, gains: preset.gains, preamp: preset.preamp, bass: preset.bass, @@ -157,6 +315,8 @@ class EqualizerSettings { Map toJson() => { 'enabled': enabled, + 'parametric': parametric, + 'filters': [for (final filter in filters) filter.toJson()], 'gains': gains, 'preamp': preamp, 'bass': bass, @@ -171,11 +331,25 @@ class EqualizerSettings { 'release': release, }; + /// The configuration a native equalizer takes. With `filters` set it plays + /// those in place of the bands, which are then sent flat. Map toNative() => { ...toJson(), - 'frequencies': frequencies, - 'gains': effectiveGains, + 'frequencies': parametric ? _centers[10] : frequencies, + 'gains': parametric ? List.filled(10, 0.0) : effectiveGains, 'inputGain': inputGain, + 'filters': parametric + ? [ + for (final filter in filters) + if (filter.enabled && filter.gain != 0) + { + 'type': filter.type.nativeName, + 'frequency': filter.frequency, + 'gain': filter.gain, + 'q': filter.q, + }, + ] + : null, }; factory EqualizerSettings.fromJson(Map json) { @@ -191,8 +365,16 @@ class EqualizerSettings { raw.any((v) => v is! num || !v.isFinite)) { throw const FormatException('Invalid equalizer bands'); } + final filters = json['filters']; return EqualizerSettings( enabled: json['enabled'] == true, + parametric: json['parametric'] == true, + filters: List.unmodifiable( + (filters is List ? filters : const []) + .map(EqualizerFilter.fromJson) + .nonNulls + .take(maxFilters), + ), gains: List.unmodifiable( raw.map((v) => (v as num).toDouble().clamp(-15.0, 15.0)), ), diff --git a/lib/providers/equalizer_provider.dart b/lib/providers/equalizer_provider.dart index b14022383..855a3079a 100644 --- a/lib/providers/equalizer_provider.dart +++ b/lib/providers/equalizer_provider.dart @@ -3,6 +3,7 @@ import 'dart:convert'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:shared_preferences/shared_preferences.dart'; +import 'package:mornye/models/equalizer_filter_text.dart'; import 'package:mornye/models/equalizer_settings.dart'; import 'package:mornye/services/playback_equalizer.dart'; @@ -138,6 +139,38 @@ class EqualizerController extends Notifier { ...EqualizerPreset(name, state.settings).toJson(), }); + /// The filters playing now as a plain text filter list. + String exportFilters() => EqualizerFilterText.format(state.settings); + + /// Takes a preset file of the app or a plain text filter list. Returns how + /// many filters of the list were of a kind the equalizer has none of. + int importFile(String source) { + if (source.trimLeft().startsWith('{')) { + importPreset(source); + return 0; + } + return importFilters(source); + } + + /// Plays the filters of a plain text filter list. A list that names its + /// own preamp carries its headroom, so none is added on top. + int importFilters(String source) { + if (source.length > 65536) { + throw const FormatException('Preset file is too large.'); + } + final text = EqualizerFilterText.parse(source); + final preamp = text.preamp; + update( + state.settings.copyWith( + parametric: true, + filters: text.filters, + preamp: preamp?.clamp(-24.0, 12.0), + autoHeadroom: preamp == null ? null : false, + ), + ); + return text.skipped; + } + void importPreset(String source) { if (source.length > 65536) { throw const FormatException('Preset file is too large.'); diff --git a/lib/screens/equalizer_curve.dart b/lib/screens/equalizer_curve.dart index 319cdce8c..aa94dc3fb 100644 --- a/lib/screens/equalizer_curve.dart +++ b/lib/screens/equalizer_curve.dart @@ -174,14 +174,29 @@ class _EqualizerCurve extends CustomPainter { plot.center.dy - gain.clamp(-_range, _range) / _range * plot.height / 2; final curve = settings.copyWith(gains: settings.effectiveGains); - final points = [Offset(plot.left, y(curve.gains.first))]; - for (var i = 0; i < curve.gains.length; i++) { - final point = Offset(x(settings.frequencies[i]), y(curve.gains[i])); - if (point.dx > points.last.dx + 0.5 && point.dx < plot.right - 0.5) { - points.add(point); + final points = []; + if (settings.parametric) { + // The filters' own response, which has no bands to pass through. + const steps = 120; + for (var i = 0; i <= steps; i++) { + final hz = _minHz * math.pow(_maxHz / _minHz, i / steps); + points.add( + Offset( + plot.left + plot.width * i / steps, + y(settings.responseAt(hz.toDouble())), + ), + ); } + } else { + points.add(Offset(plot.left, y(curve.gains.first))); + for (var i = 0; i < curve.gains.length; i++) { + final point = Offset(x(settings.frequencies[i]), y(curve.gains[i])); + if (point.dx > points.last.dx + 0.5 && point.dx < plot.right - 0.5) { + points.add(point); + } + } + points.add(Offset(plot.right, y(curve.gains.last))); } - points.add(Offset(plot.right, y(curve.gains.last))); final line = _monotoneSpline(points); final area = Path.from(line) ..lineTo(plot.right, plot.center.dy) @@ -213,6 +228,18 @@ class _EqualizerCurve extends CustomPainter { ..strokeCap = StrokeCap.round, ); final dot = Paint()..color = color; + if (settings.parametric) { + // One dot a filter, on the curve at the filter's frequency. + for (final filter in settings.filters) { + if (!filter.enabled) continue; + canvas.drawCircle( + Offset(x(filter.frequency), y(settings.responseAt(filter.frequency))), + 4, + dot, + ); + } + return; + } final effective = curve.gains; for (var i = 0; i < effective.length; i++) { final hz = settings.frequencies[i]; diff --git a/lib/screens/equalizer_filters.dart b/lib/screens/equalizer_filters.dart new file mode 100644 index 000000000..ec13546dd --- /dev/null +++ b/lib/screens/equalizer_filters.dart @@ -0,0 +1,536 @@ +part of 'equalizer_screen.dart'; + +String _filterTypeLabel(AppLocalizations l10n, EqualizerFilterType type) => + switch (type) { + EqualizerFilterType.peak => l10n.equalizerFilterPeak, + EqualizerFilterType.lowShelf => l10n.equalizerFilterLowShelf, + EqualizerFilterType.highShelf => l10n.equalizerFilterHighShelf, + }; + +String _filterHz(double hz) => '${hz.toStringAsFixed(hz % 1 == 0 ? 0 : 1)} Hz'; + +/// A single-select row in the page's two styles, like the band count. +class _Segments extends StatelessWidget { + const _Segments({ + required this.labels, + required this.selected, + required this.onChanged, + required this.semanticLabel, + }); + + final List labels; + final int selected; + final ValueChanged onChanged; + final String semanticLabel; + + @override + Widget build(BuildContext context) => context.isMornye + ? Semantics( + label: semanticLabel, + child: MornyeSegmentedControl( + labels: labels, + selectedIndex: selected, + onChanged: onChanged, + samplesBackdrop: false, + ), + ) + : SettingsSegmentedChoice( + options: [ + for (final (index, label) in labels.indexed) + SettingsSegmentOption(value: index, label: label), + ], + selected: selected, + onChanged: onChanged, + semanticLabel: semanticLabel, + ); +} + +/// Graphic bands or parametric filters. Each keeps its values while the +/// other plays. +class _ModePicker extends ConsumerWidget { + const _ModePicker(); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final parametric = ref.watch( + equalizerProvider.select((state) => state.settings.parametric), + ); + final l10n = context.l10n; + final tokens = context.tokens; + return Padding( + padding: EdgeInsets.fromLTRB(tokens.gapLg, tokens.gapLg, tokens.gapLg, 0), + child: _Segments( + labels: [l10n.equalizerModeGraphic, l10n.equalizerModeParametric], + selected: parametric ? 1 : 0, + semanticLabel: l10n.equalizerTitle, + onChanged: (index) => ref + .read(equalizerProvider.notifier) + .update( + ref + .read(equalizerProvider) + .settings + .copyWith(parametric: index == 1), + ), + ), + ); + } +} + +/// Android plays the filters through its media3 engine alone. +class _EngineNotice extends ConsumerWidget { + const _EngineNotice(); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final needed = ref.watch( + equalizerProvider.select((state) => state.settings.parametric), + ); + final engine = ref.watch( + settingsProvider.select((settings) => settings.media3Engine), + ); + if (!needed || engine || defaultTargetPlatform != TargetPlatform.android) { + return const SizedBox.shrink(); + } + final l10n = context.l10n; + return SettingsInfoCard( + message: l10n.equalizerNeedsEngine, + icon: Icons.info_outline, + action: ExpressiveButton( + tonal: true, + onPressed: () => + ref.read(settingsProvider.notifier).setMedia3Engine(true), + child: Text(l10n.equalizerNeedsEngineAction), + ), + ); + } +} + +class _FilterList extends ConsumerWidget { + const _FilterList(); + + void _add(BuildContext context, WidgetRef ref) { + final settings = ref.read(equalizerProvider).settings; + if (settings.filters.length >= EqualizerSettings.maxFilters) return; + ref + .read(equalizerProvider.notifier) + .update( + settings.copyWith( + filters: [...settings.filters, const EqualizerFilter()], + ), + ); + _edit(context, settings.filters.length); + } + + void _edit(BuildContext context, int index) => showAppBottomSheet( + context: context, + useRootNavigator: true, + title: context.l10n.equalizerFilterNumber(index + 1), + maxHeightFactor: 0.85, + builder: (_) => _FilterSheet(index: index), + ); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final filters = ref.watch( + equalizerProvider.select((state) => state.settings.filters), + ); + final l10n = context.l10n; + final theme = Theme.of(context); + final colors = theme.colorScheme; + final tokens = context.tokens; + final mornye = context.isMornye; + final full = filters.length >= EqualizerSettings.maxFilters; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + SizedBox(height: tokens.gapSm), + if (filters.isEmpty) + Padding( + padding: EdgeInsets.symmetric( + horizontal: tokens.rowPaddingH, + vertical: tokens.gapMd, + ), + child: Text( + l10n.equalizerFiltersEmpty, + style: theme.textTheme.bodyMedium?.copyWith( + color: colors.onSurfaceVariant, + ), + ), + ), + for (final (index, filter) in filters.indexed) + SettingsItem( + title: _filterHz(filter.frequency), + subtitle: + '${_filterTypeLabel(l10n, filter.type)} · ' + '${_signed(filter.gain)} dB · ' + '${l10n.equalizerFilterQ} ${filter.q.toStringAsFixed(2)}', + trailing: AppSwitch( + value: filter.enabled, + semanticLabel: + '${l10n.equalizerFilterNumber(index + 1)}, ' + '${_filterHz(filter.frequency)}', + onChanged: (enabled) => ref + .read(equalizerProvider.notifier) + .update( + ref + .read(equalizerProvider) + .settings + .copyWith( + filters: [ + for (final (i, other) in filters.indexed) + i == index + ? other.copyWith(enabled: enabled) + : other, + ], + ), + ), + ), + onTap: () => _edit(context, index), + ), + if (mornye) + _ActionRow( + label: l10n.equalizerAddFilter, + onTap: full ? null : () => _add(context, ref), + last: true, + ) + else + Padding( + padding: EdgeInsets.fromLTRB( + tokens.rowPaddingH, + tokens.gapSm, + tokens.rowPaddingH, + tokens.gapLg, + ), + child: Align( + alignment: AlignmentDirectional.centerStart, + child: ExpressiveButton( + tonal: true, + onPressed: full ? null : () => _add(context, ref), + icon: const AppIcon(Icons.add), + child: Text(l10n.equalizerAddFilter), + ), + ), + ), + ], + ); + } +} + +/// One filter's type, frequency, gain and Q. Edits play at once. +class _FilterSheet extends ConsumerWidget { + const _FilterSheet({required this.index}); + + final int index; + + static const _hzSpan = + EqualizerFilter.maxFrequency / EqualizerFilter.minFrequency; + static const _qSpan = EqualizerFilter.maxQ / EqualizerFilter.minQ; + + /// A slider cannot land on every hertz of ten octaves: whole steps that + /// grow with the frequency. Typed values are kept as typed. + static double _roundHz(double hz) { + final step = hz < 100 + ? 1.0 + : hz < 1000 + ? 5.0 + : hz < 10000 + ? 50.0 + : 100.0; + return _snap(hz, step); + } + + static double _roundQ(double q) => _snap( + q, + q < 1 + ? 0.01 + : q < 5 + ? 0.05 + : 0.1, + ); + + void _change(WidgetRef ref, EqualizerFilter next) { + final settings = ref.read(equalizerProvider).settings; + if (index >= settings.filters.length) return; + ref + .read(equalizerProvider.notifier) + .update( + settings.copyWith( + filters: [ + for (final (i, filter) in settings.filters.indexed) + i == index ? next : filter, + ], + ), + ); + } + + void _remove(BuildContext context, WidgetRef ref) { + final settings = ref.read(equalizerProvider).settings; + Navigator.pop(context); + if (index >= settings.filters.length) return; + ref + .read(equalizerProvider.notifier) + .update( + settings.copyWith(filters: [...settings.filters]..removeAt(index)), + ); + } + + @override + Widget build(BuildContext context, WidgetRef ref) { + final filter = ref.watch( + equalizerProvider.select( + (state) => index < state.settings.filters.length + ? state.settings.filters[index] + : null, + ), + ); + if (filter == null) return const SizedBox.shrink(); + final l10n = context.l10n; + final tokens = context.tokens; + const types = EqualizerFilterType.values; + return SingleChildScrollView( + child: Padding( + padding: EdgeInsets.fromLTRB( + tokens.rowPaddingH, + tokens.gapSm, + tokens.rowPaddingH, + tokens.gapLg, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _Segments( + labels: [for (final type in types) _filterTypeLabel(l10n, type)], + selected: types.indexOf(filter.type), + semanticLabel: l10n.equalizerFilterNumber(index + 1), + onChanged: (value) => + _change(ref, filter.copyWith(type: types[value])), + ), + SizedBox(height: tokens.gapLg), + _FilterSlider( + title: l10n.equalizerFilterFrequency, + label: _filterHz(filter.frequency), + // The slider moves in octaves, as the ear hears pitch. + position: + math.log(filter.frequency / EqualizerFilter.minFrequency) / + math.log(_hzSpan), + min: 0, + max: 1, + typed: filter.frequency, + typedMin: EqualizerFilter.minFrequency, + typedMax: EqualizerFilter.maxFrequency, + unit: 'Hz', + onSlide: (position) => _change( + ref, + filter.copyWith( + frequency: + _roundHz( + EqualizerFilter.minFrequency * + math.pow(_hzSpan, position), + ).clamp( + EqualizerFilter.minFrequency, + EqualizerFilter.maxFrequency, + ), + ), + ), + onTyped: (value) => + _change(ref, filter.copyWith(frequency: value)), + ), + _FilterSlider( + title: l10n.equalizerFilterGain, + label: '${_signed(filter.gain)} dB', + position: filter.gain, + min: -EqualizerFilter.maxGain, + max: EqualizerFilter.maxGain, + centered: true, + typed: filter.gain, + typedMin: -EqualizerFilter.maxGain, + typedMax: EqualizerFilter.maxGain, + unit: 'dB', + onSlide: (value) => + _change(ref, filter.copyWith(gain: _snap(value, 0.1))), + onTyped: (value) => _change(ref, filter.copyWith(gain: value)), + ), + _FilterSlider( + title: l10n.equalizerFilterQ, + label: filter.q.toStringAsFixed(2), + position: + math.log(filter.q / EqualizerFilter.minQ) / math.log(_qSpan), + min: 0, + max: 1, + typed: filter.q, + typedMin: EqualizerFilter.minQ, + typedMax: EqualizerFilter.maxQ, + unit: '', + onSlide: (position) => _change( + ref, + filter.copyWith( + q: _roundQ( + EqualizerFilter.minQ * math.pow(_qSpan, position), + ).clamp(EqualizerFilter.minQ, EqualizerFilter.maxQ), + ), + ), + onTyped: (value) => _change(ref, filter.copyWith(q: value)), + ), + SizedBox(height: tokens.gapSm), + Align( + alignment: AlignmentDirectional.centerStart, + child: ExpressiveButton( + text: true, + onPressed: () => _remove(context, ref), + icon: AppIcon( + Icons.delete_outline, + color: Theme.of(context).colorScheme.error, + ), + child: Text( + l10n.equalizerRemoveFilter, + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + ), + ), + ], + ), + ), + ); + } +} + +/// A slider with its value, and a button to type the value exactly. +class _FilterSlider extends StatelessWidget { + const _FilterSlider({ + required this.title, + required this.label, + required this.position, + required this.min, + required this.max, + required this.typed, + required this.typedMin, + required this.typedMax, + required this.unit, + required this.onSlide, + required this.onTyped, + this.centered = false, + }); + + final String title, label, unit; + + /// The slider's own scale, which for frequency and Q is logarithmic. + final double position, min, max; + + /// The value in its unit, and the range a typed value is brought into. + final double typed, typedMin, typedMax; + final ValueChanged onSlide, onTyped; + final bool centered; + + Future _type(BuildContext context) async { + final value = await showAppDialog( + context: context, + builder: (context) => _NumberDialog( + title: title, + unit: unit, + value: typed, + min: typedMin, + max: typedMax, + ), + ); + if (value != null) onTyped(value); + } + + @override + Widget build(BuildContext context) { + final value = position.clamp(min, max); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SliderValueHeader( + title: title, + value: label, + trailing: IconButton( + tooltip: '${context.l10n.equalizerFilterTypeValue}: $title', + icon: const AppIcon(Icons.edit_outlined), + onPressed: () => _type(context), + ), + ), + if (context.isMornye) + MornyeLevelSlider( + value: value, + min: min, + max: max, + origin: centered ? (min + max) / 2 : null, + semanticLabel: title, + semanticFormatterCallback: (_) => label, + onChanged: onSlide, + ) + else + AppSlider( + value: value, + min: min, + max: max, + centered: centered, + semanticLabel: title, + semanticFormatterCallback: (_) => label, + onChanged: onSlide, + ), + ], + ); + } +} + +class _NumberDialog extends StatefulWidget { + const _NumberDialog({ + required this.title, + required this.unit, + required this.value, + required this.min, + required this.max, + }); + + final String title, unit; + final double value, min, max; + + @override + State<_NumberDialog> createState() => _NumberDialogState(); +} + +class _NumberDialogState extends State<_NumberDialog> { + late final _controller = TextEditingController( + text: widget.value.toStringAsFixed(2).replaceFirst(RegExp(r'\.?0+$'), ''), + ); + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + void _submit() { + // A decimal comma is what many keyboards offer. + final value = double.tryParse(_controller.text.trim().replaceAll(',', '.')); + if (value == null || !value.isFinite) return; + Navigator.pop(context, value.clamp(widget.min, widget.max)); + } + + @override + Widget build(BuildContext context) => AppAlertDialog( + title: Text(widget.title), + content: AppTextField( + controller: _controller, + label: widget.unit.isEmpty + ? widget.title + : '${widget.title} (${widget.unit})', + keyboardType: const TextInputType.numberWithOptions( + decimal: true, + signed: true, + ), + autofocus: true, + onSubmitted: (_) => _submit(), + ), + actions: [ + AppDialogAction( + onPressed: () => Navigator.pop(context), + child: Text(context.l10n.dialogCancel), + ), + AppDialogAction(onPressed: _submit, child: Text(context.l10n.dialogSave)), + ], + ); +} diff --git a/lib/screens/equalizer_screen.dart b/lib/screens/equalizer_screen.dart index 62d35ef53..a98857d82 100644 --- a/lib/screens/equalizer_screen.dart +++ b/lib/screens/equalizer_screen.dart @@ -1,8 +1,8 @@ import 'dart:convert'; import 'dart:math' as math; -import 'dart:typed_data'; import 'package:file_picker/file_picker.dart'; +import 'package:flutter/foundation.dart'; import 'package:material_ui/material_ui.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:material_3_expressive/material_3_expressive.dart'; @@ -10,6 +10,7 @@ import 'package:share_plus/share_plus.dart'; import 'package:mornye/l10n/l10n.dart'; import 'package:mornye/models/equalizer_settings.dart'; import 'package:mornye/providers/equalizer_provider.dart'; +import 'package:mornye/providers/settings_provider.dart'; import 'package:mornye/services/playback_equalizer.dart'; import 'package:mornye/theme/app_motion.dart'; import 'package:mornye/theme/app_tokens.dart'; @@ -36,6 +37,7 @@ import 'package:mornye/widgets/slider_value_header.dart'; part 'equalizer_widgets.dart'; part 'equalizer_curve.dart'; +part 'equalizer_filters.dart'; class EqualizerScreen extends ConsumerStatefulWidget { const EqualizerScreen({super.key}); @@ -44,7 +46,7 @@ class EqualizerScreen extends ConsumerStatefulWidget { ConsumerState createState() => _EqualizerScreenState(); } -enum _PresetAction { manage, import, export } +enum _PresetAction { manage, import, export, exportFilters } final _selectedEqualizerPresetProvider = Provider( (ref) => _matchingPreset(ref.watch(equalizerProvider)), @@ -76,14 +78,18 @@ class _EqualizerScreenState extends ConsumerState { try { final file = await FilePicker.pickFile( type: FileType.custom, - allowedExtensions: ['json'], + allowedExtensions: ['json', 'txt'], ); if (file == null) return; if ((await file.length() ?? 65537) > 65536) throw const FormatException(); final source = utf8.decode(await file.readAsBytes()); if (!mounted) return; - ref.read(equalizerProvider.notifier).importPreset(source); - _message(context.l10n.equalizerSaved); + final skipped = ref.read(equalizerProvider.notifier).importFile(source); + _message( + skipped == 0 + ? context.l10n.equalizerSaved + : context.l10n.equalizerImportSkipped(skipped), + ); } catch (_) { if (mounted) _message(context.l10n.equalizerImportInvalid); } finally { @@ -91,10 +97,13 @@ class _EqualizerScreenState extends ConsumerState { } } - Future _export() async { - final source = ref - .read(equalizerProvider.notifier) - .exportPreset('Custom EQ'); + /// Shares the app's own preset file, or with [filters] the plain text + /// list of the parametric filters that other tools read. + Future _export({bool filters = false}) async { + final notifier = ref.read(equalizerProvider.notifier); + final source = filters + ? notifier.exportFilters() + : notifier.exportPreset('Custom EQ'); final box = context.findRenderObject() as RenderBox?; try { await SharePlus.instance.share( @@ -102,10 +111,12 @@ class _EqualizerScreenState extends ConsumerState { files: [ XFile.fromData( Uint8List.fromList(utf8.encode(source)), - mimeType: 'application/json', + mimeType: filters ? 'text/plain' : 'application/json', ), ], - fileNameOverrides: ['mornye-equalizer.json'], + fileNameOverrides: [ + filters ? 'mornye-filters.txt' : 'mornye-equalizer.json', + ], sharePositionOrigin: box == null ? null : box.localToGlobal(Offset.zero) & box.size, @@ -205,10 +216,15 @@ class _EqualizerScreenState extends ConsumerState { ), ); if (mounted && accepted == true) { - final enabled = ref.read(equalizerProvider).settings.enabled; + final current = ref.read(equalizerProvider).settings; ref .read(equalizerProvider.notifier) - .update(EqualizerSettings(enabled: enabled)); + .update( + EqualizerSettings( + enabled: current.enabled, + parametric: current.parametric, + ), + ); } } @@ -224,6 +240,7 @@ class _EqualizerScreenState extends ConsumerState { equalizerProvider.select( (state) => ( enabled: state.settings.enabled, + parametric: state.settings.parametric, autoHeadroom: state.settings.autoHeadroom, limiter: state.settings.limiter, compressor: state.settings.compressor, @@ -302,8 +319,14 @@ class _EqualizerScreenState extends ConsumerState { _ActionRow( label: l10n.equalizerExport, onTap: _export, - last: true, + last: !settings.parametric, ), + if (settings.parametric) + _ActionRow( + label: l10n.equalizerExportFilters, + onTap: () => _export(filters: true), + last: true, + ), ], ), ), @@ -331,12 +354,35 @@ class _EqualizerScreenState extends ConsumerState { _PresetAction.manage => _presets(), _PresetAction.import => _import(), _PresetAction.export => _export(), + _PresetAction.exportFilters => _export(filters: true), }, ), ), ], - section(SettingsSectionHeader(title: l10n.equalizerBands)), - section(SettingsGroup(children: [const _BandEditor()])), + section( + SettingsSectionHeader( + title: settings.parametric + ? l10n.equalizerFilters + : l10n.equalizerBands, + ), + ), + section( + SettingsGroup( + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const _ModePicker(), + if (settings.parametric) + const _FilterList() + else + const _BandEditor(), + ], + ), + ], + ), + ), + section(const _EngineNotice()), section(SettingsSectionHeader(title: l10n.equalizerTone)), section( SettingsGroup( @@ -351,26 +397,30 @@ class _EqualizerScreenState extends ConsumerState { step: 0.5, unit: 'dB', ), - _SliderTile( - icon: Icons.speaker_outlined, - title: l10n.equalizerBass, - control: _ToneControl.bass, - min: -12, - max: 12, - step: 0.5, - unit: 'dB', - centered: true, - ), - _SliderTile( - icon: Icons.music_note_outlined, - title: l10n.equalizerTreble, - control: _ToneControl.treble, - min: -12, - max: 12, - step: 0.5, - unit: 'dB', - centered: true, - ), + // Bass and treble belong to the bands; a shelf filter is + // the parametric way to the same. + if (!settings.parametric) ...[ + _SliderTile( + icon: Icons.speaker_outlined, + title: l10n.equalizerBass, + control: _ToneControl.bass, + min: -12, + max: 12, + step: 0.5, + unit: 'dB', + centered: true, + ), + _SliderTile( + icon: Icons.music_note_outlined, + title: l10n.equalizerTreble, + control: _ToneControl.treble, + min: -12, + max: 12, + step: 0.5, + unit: 'dB', + centered: true, + ), + ], _SliderTile( icon: Icons.surround_sound_outlined, title: l10n.equalizerBalance, @@ -500,6 +550,14 @@ EqualizerPreset? _matchingPreset(EqualizerState state) { final current = state.settings; for (final preset in [...EqualizerPreset.builtIn, ...state.presets]) { final tone = preset.settings; + if (current.parametric != tone.parametric) continue; + if (current.parametric) { + if (same(current.preamp, tone.preamp) && + listEquals(current.filters, tone.filters)) { + return preset; + } + continue; + } if (same(current.preamp, tone.preamp) && same(current.bass, tone.bass) && same(current.treble, tone.treble) && diff --git a/lib/screens/equalizer_widgets.dart b/lib/screens/equalizer_widgets.dart index 80c116144..8bfbd5ca7 100644 --- a/lib/screens/equalizer_widgets.dart +++ b/lib/screens/equalizer_widgets.dart @@ -181,7 +181,7 @@ class _EqualizerOverview extends ConsumerWidget { const SizedBox(width: 8), Flexible( child: Text( - '${settings.gains.length} ${l10n.equalizerBands.toLowerCase()} · ${l10n.equalizerPreamp} ${_signed(settings.inputGain)} dB', + '${settings.parametric ? l10n.equalizerFilterCount(settings.filters.length) : '${settings.gains.length} ${l10n.equalizerBands.toLowerCase()}'} · ${l10n.equalizerPreamp} ${_signed(settings.inputGain)} dB', maxLines: 1, overflow: TextOverflow.ellipsis, style: theme.textTheme.bodyMedium?.copyWith( @@ -281,6 +281,9 @@ class _PresetBar extends ConsumerWidget { ); final presets = [...EqualizerPreset.builtIn, ...custom]; final selected = ref.watch(_selectedEqualizerPresetProvider); + final parametric = ref.watch( + equalizerProvider.select((state) => state.settings.parametric), + ); final l10n = context.l10n; final tokens = context.tokens; return LayoutBuilder( @@ -366,6 +369,12 @@ class _PresetBar extends ConsumerWidget { label: l10n.equalizerExport, leading: const AppIcon(Icons.ios_share), ), + if (parametric) + AppMenuItem( + value: _PresetAction.exportFilters, + label: l10n.equalizerExportFilters, + leading: const AppIcon(Icons.description_outlined), + ), ], ), ], diff --git a/lib/services/media_kit_audio_filters.dart b/lib/services/media_kit_audio_filters.dart index 0dbd7fa81..710542500 100644 --- a/lib/services/media_kit_audio_filters.dart +++ b/lib/services/media_kit_audio_filters.dart @@ -64,6 +64,8 @@ class MpvAudioFilterChain { 'stereotools', 'acompressor', 'alimiter', + 'lowshelf', + 'highshelf', }; /// Sample rate assumed before the decoder reports one. Bands above 45% of @@ -108,17 +110,32 @@ class MpvAudioFilterChain { 'volume': '${_number(settings.inputGain)}dB', }, ), - for (var i = 0; i < gains.length; i++) - MpvAudioFilter( - 'band$i', - 'equalizer', - options: { - 'f': _number(math.min(frequencies[i], rate * 0.45)), - 't': 'q', - 'w': _number(q), - 'g': _number(gains[i]), - }, - ), + if (settings.parametric) ...[ + // The same cookbook sections as the other platforms' own DSP. + for (final (i, filter) in settings.filters.indexed) + if (filter.enabled && filter.gain != 0 && has(_filterName(filter))) + MpvAudioFilter( + 'filter$i', + _filterName(filter), + options: { + 'f': _number(math.min(filter.frequency, rate * 0.45)), + 't': 'q', + 'w': _number(filter.q), + 'g': _number(filter.gain), + }, + ), + ] else + for (var i = 0; i < gains.length; i++) + MpvAudioFilter( + 'band$i', + 'equalizer', + options: { + 'f': _number(math.min(frequencies[i], rate * 0.45)), + 't': 'q', + 'w': _number(q), + 'g': _number(gains[i]), + }, + ), // Applied only when set: the filter converts its input to stereo. if (settings.balance != 0 && has('stereotools')) MpvAudioFilter( @@ -161,6 +178,12 @@ class MpvAudioFilterChain { ); } + static String _filterName(EqualizerFilter filter) => switch (filter.type) { + EqualizerFilterType.peak => 'equalizer', + EqualizerFilterType.lowShelf => 'lowshelf', + EqualizerFilterType.highShelf => 'highshelf', + }; + MpvAudioFilterChain withTempo(MpvTempo tempo) => MpvAudioFilterChain( [...filters, ...tempo.filters], volumeGainDb: volumeGainDb, diff --git a/lib/services/media_kit_playback_deck.dart b/lib/services/media_kit_playback_deck.dart index 15bd01447..e5a4f2713 100644 --- a/lib/services/media_kit_playback_deck.dart +++ b/lib/services/media_kit_playback_deck.dart @@ -1015,6 +1015,18 @@ class MediaKitPlaybackDeck implements PlaybackDeck, QueuedPlaybackDeck { 'balance', if (settings.compressor && _missingFilters.contains('acompressor')) 'compressor', + for (final (type, name) in const [ + (EqualizerFilterType.lowShelf, 'lowshelf'), + (EqualizerFilterType.highShelf, 'highshelf'), + ]) + if (settings.parametric && + _missingFilters.contains(name) && + settings.filters.any( + (filter) => filter.enabled && filter.type == type, + )) + type == EqualizerFilterType.lowShelf + ? 'low shelf filter' + : 'high shelf filter', ]; if (missing.isEmpty) return null; return 'The ${missing.join(' and ')} is not available in this system ' diff --git a/lib/services/music_playback_deck.dart b/lib/services/music_playback_deck.dart index 8911f1324..18fc85904 100644 --- a/lib/services/music_playback_deck.dart +++ b/lib/services/music_playback_deck.dart @@ -342,7 +342,15 @@ class AudioplayersPlaybackDeck implements PlaybackDeck { .invokeMethod('setEqualizer', { 'playerId': _ordinary.playerId, 'configuration': settings - .copyWith(enabled: settings.enabled && !_direct) + .copyWith( + enabled: + settings.enabled && + !_direct && + // Android's own equalizer is a bank of fixed bands: + // the filters need the media3 deck's DSP. + !(settings.parametric && + defaultTargetPlatform == TargetPlatform.android), + ) .toNative(), }) .timeout(const Duration(seconds: 3)); diff --git a/lib/widgets/audio_info_sheet.dart b/lib/widgets/audio_info_sheet.dart index 2f16e62d3..3afbef925 100644 --- a/lib/widgets/audio_info_sheet.dart +++ b/lib/widgets/audio_info_sheet.dart @@ -627,7 +627,9 @@ class _AudioFacts { ? l10n.audioInfoBypassed : [ l10n.audioInfoOn, - l10n.audioInfoBands(equalizer.gains.length), + equalizer.parametric + ? l10n.equalizerFilterCount(equalizer.filters.length) + : l10n.audioInfoBands(equalizer.gains.length), if (equalizer.inputGain != 0) '${l10n.equalizerPreamp} ${_db(equalizer.inputGain)}', if (equalizer.compressor) l10n.equalizerCompressor, diff --git a/test/equalizer_parametric_test.dart b/test/equalizer_parametric_test.dart new file mode 100644 index 000000000..1dbd44fca --- /dev/null +++ b/test/equalizer_parametric_test.dart @@ -0,0 +1,377 @@ +import 'dart:math' as math; + +import 'package:flutter/foundation.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:mornye/l10n/l10n.dart'; +import 'package:mornye/models/equalizer_filter_text.dart'; +import 'package:mornye/models/equalizer_settings.dart'; +import 'package:mornye/providers/equalizer_provider.dart'; +import 'package:mornye/providers/settings_provider.dart'; +import 'package:mornye/screens/equalizer_screen.dart'; +import 'package:mornye/services/playback_equalizer.dart'; +import 'package:mornye/theme/app_theme.dart'; +import 'package:mornye/theme/mornye_theme.dart'; +import 'package:mornye/widgets/app_switch.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +const _peak = EqualizerFilter(frequency: 1000, gain: 6, q: 1.4); +const _low = EqualizerFilter( + type: EqualizerFilterType.lowShelf, + frequency: 200, + gain: -5, + q: 0.707, +); +const _high = EqualizerFilter( + type: EqualizerFilterType.highShelf, + frequency: 4000, + gain: 4, + q: 0.707, +); + +void main() { + setUp(() { + SharedPreferences.setMockInitialValues({}); + playbackEqualizer.value = const EqualizerSettings(); + playbackEqualizerError.value = null; + }); + + test('a filter has its gain where its kind puts it', () { + expect(_peak.responseAt(1000), closeTo(6, 1e-9)); + expect(_peak.responseAt(40), closeTo(0, 0.05)); + expect(_peak.responseAt(18000), closeTo(0, 0.05)); + // The gain is halved (in dB) at the edges of the bandwidth 1 / Q. + final edge = 1000 * (0.5 / 1.4 + math.sqrt(1 + 0.25 / (1.4 * 1.4))); + expect(_peak.responseAt(edge), closeTo(3, 0.01)); + + expect(_low.responseAt(20), closeTo(-5, 0.05)); + expect(_low.responseAt(200), closeTo(-2.5, 1e-9)); + expect(_low.responseAt(8000), closeTo(0, 0.01)); + expect(_high.responseAt(50), closeTo(0, 0.01)); + expect(_high.responseAt(4000), closeTo(2, 1e-9)); + expect(_high.responseAt(20000), closeTo(4, 0.2)); + + expect(_peak.copyWith(enabled: false).responseAt(1000), 0); + expect(_peak.copyWith(gain: 0).responseAt(1000), 0); + }); + + test('parametric settings play the filters, not the bands', () { + final settings = const EqualizerSettings(enabled: true).copyWith( + parametric: true, + filters: [_peak, _low, _high.copyWith(enabled: false)], + gains: [9, 0, 0, 0, 0, 0, 0, 0, 0, 0], + bass: 6, + ); + // The bands and the tone controls wait for the way back. + expect(settings.responseAt(1000), closeTo(6, 0.05)); + expect(settings.responseAt(31.25), closeTo(-5, 0.1)); + expect(settings.headroom, closeTo(6, 0.05)); + expect(settings.inputGain, closeTo(-6, 0.05)); + + final native = settings.toNative(); + expect(native['gains'], List.filled(10, 0.0)); + expect((native['frequencies'] as List).length, 10); + expect(native['inputGain'], closeTo(-6, 0.05)); + expect(native['filters'], [ + {'type': 'peak', 'frequency': 1000.0, 'gain': 6.0, 'q': 1.4}, + {'type': 'lowshelf', 'frequency': 200.0, 'gain': -5.0, 'q': 0.707}, + ]); + + final graphic = settings.copyWith(parametric: false); + expect(graphic.toNative()['filters'], isNull); + expect(graphic.responseAt(31.25), greaterThan(9)); + expect(graphic.filters, hasLength(3)); + }); + + test('headroom finds a narrow peak between the grid points', () { + final settings = const EqualizerSettings(enabled: true).copyWith( + parametric: true, + filters: [const EqualizerFilter(frequency: 1013, gain: 9, q: 20)], + ); + expect(settings.headroom, closeTo(9, 1e-9)); + }); + + test('settings survive saving, and bad filters are left out', () { + final settings = const EqualizerSettings().copyWith( + parametric: true, + filters: [_peak, _low], + ); + final restored = EqualizerSettings.fromJson(settings.toJson()); + expect(restored.parametric, isTrue); + expect(restored.filters, [_peak, _low]); + + final old = EqualizerSettings.fromJson({'gains': List.filled(10, 0)}); + expect(old.parametric, isFalse); + expect(old.filters, isEmpty); + + final messy = EqualizerSettings.fromJson({ + 'gains': List.filled(10, 0), + 'parametric': true, + 'filters': [ + {'type': 'peak', 'frequency': 5, 'gain': 99, 'q': 0}, + {'type': 'notch', 'frequency': 500, 'gain': 1, 'q': 1}, + 'nothing', + {'frequency': 'x', 'gain': 1, 'q': 1}, + for (var i = 0; i < 30; i++) + {'type': 'peak', 'frequency': 100.0 + i, 'gain': 1, 'q': 1}, + ], + }); + expect(messy.filters, hasLength(EqualizerSettings.maxFilters)); + expect(messy.filters.first.frequency, 20); + expect(messy.filters.first.gain, 24); + expect(messy.filters.first.q, 0.1); + // An unknown kind plays as a peak rather than being lost. + expect(messy.filters[1].type, EqualizerFilterType.peak); + }); + + test('a preset carries its filters; a graphic one keeps them', () { + final current = const EqualizerSettings( + enabled: true, + limiter: false, + ).copyWith(parametric: true, filters: [_peak]); + final graphic = current.withToneOf(EqualizerPreset.builtIn[1].settings); + expect(graphic.parametric, isFalse); + expect(graphic.filters, [_peak]); + expect(graphic.limiter, isFalse); + + final parametric = graphic.withToneOf( + const EqualizerSettings().copyWith(parametric: true, filters: [_low]), + ); + expect(parametric.parametric, isTrue); + expect(parametric.filters, [_low]); + }); + + group('filter list text', () { + test('reads the usual lines', () { + final text = EqualizerFilterText.parse( + 'Preamp: -6.2 dB\r\n' + 'Filter 1: ON PK Fc 105 Hz Gain -2.1 dB Q 0.70\r\n' + 'Filter 2: ON LSC Fc 80 Hz Gain 4 dB Q 0.71\n' + 'Filter 3: OFF HSC Fc 10000 Hz Gain -3,5 dB Q 0,5\n' + 'Filter 4: ON LS Fc 60 Hz Gain 2 dB\n' + 'Filter 5: ON LP Fc 18000 Hz\n' + 'Filter 6: ON None\n' + 'Filter 7: ON NO Fc 1000 Hz Gain 1 dB Q 1\n' + '# a comment\n', + ); + expect(text.preamp, -6.2); + expect(text.skipped, 2); + expect(text.filters, const [ + EqualizerFilter(frequency: 105, gain: -2.1, q: 0.7), + EqualizerFilter( + type: EqualizerFilterType.lowShelf, + frequency: 80, + gain: 4, + q: 0.71, + ), + EqualizerFilter( + type: EqualizerFilterType.highShelf, + frequency: 10000, + gain: -3.5, + q: 0.5, + enabled: false, + ), + EqualizerFilter( + type: EqualizerFilterType.lowShelf, + frequency: 60, + gain: 2, + q: EqualizerFilter.shelfQ, + ), + ]); + }); + + test('rejects text without a filter and keeps at most twenty', () { + expect( + () => EqualizerFilterText.parse('Preamp: -3 dB\nhello'), + throwsFormatException, + ); + final many = EqualizerFilterText.parse( + [ + for (var i = 1; i <= 25; i++) + 'Filter $i: ON PK Fc ${100 * i} Hz Gain 1 dB Q 1', + ].join('\n'), + ); + expect(many.filters, hasLength(20)); + expect(many.skipped, 5); + expect(many.preamp, isNull); + }); + + test('writes what it reads, with the gain that plays', () { + final settings = const EqualizerSettings(enabled: true).copyWith( + parametric: true, + filters: [_peak, _low, _high.copyWith(enabled: false)], + ); + final text = EqualizerFilterText.format(settings); + expect( + text, + 'Preamp: -6.0 dB\n' + 'Filter 1: ON PK Fc 1000 Hz Gain 6.0 dB Q 1.40\n' + 'Filter 2: ON LSC Fc 200 Hz Gain -5.0 dB Q 0.71\n' + 'Filter 3: OFF HSC Fc 4000 Hz Gain 4.0 dB Q 0.71\n', + ); + final read = EqualizerFilterText.parse(text); + expect(read.preamp, -6); + expect(read.filters.map((filter) => filter.type), [ + EqualizerFilterType.peak, + EqualizerFilterType.lowShelf, + EqualizerFilterType.highShelf, + ]); + expect(read.filters.last.enabled, isFalse); + }); + }); + + test( + 'importing a filter list plays it with the list\'s own preamp', + () async { + final container = ProviderContainer(); + addTearDown(container.dispose); + final notifier = container.read(equalizerProvider.notifier); + await notifier.ensureLoaded(); + notifier.update(const EqualizerSettings(enabled: true, preamp: 2)); + + expect( + notifier.importFile( + 'Preamp: -4 dB\n' + 'Filter 1: ON PK Fc 3000 Hz Gain 4 dB Q 2\n' + 'Filter 2: ON BP Fc 500 Hz Q 1\n', + ), + 1, + ); + var settings = container.read(equalizerProvider).settings; + expect(settings.parametric, isTrue); + expect(settings.enabled, isTrue); + expect(settings.filters, [ + const EqualizerFilter(frequency: 3000, gain: 4, q: 2), + ]); + // The list's preamp is its headroom: none is taken twice. + expect(settings.preamp, -4); + expect(settings.autoHeadroom, isFalse); + expect(settings.inputGain, -4); + expect(playbackEqualizer.value.filters, settings.filters); + expect( + notifier.exportFilters(), + startsWith('Preamp: -4.0 dB\nFilter 1: ON PK'), + ); + + // Without a preamp line the listener's own choices stay. + notifier.update(settings.copyWith(autoHeadroom: true, preamp: 1)); + expect(notifier.importFile('Filter 1: ON PK Fc 60 Hz Gain 3 dB Q 1'), 0); + settings = container.read(equalizerProvider).settings; + expect(settings.preamp, 1); + expect(settings.autoHeadroom, isTrue); + + expect(() => notifier.importFile('not a list'), throwsFormatException); + // The app's own preset file still goes the old way. + notifier.importFile(notifier.exportPreset('Mine')); + expect(container.read(equalizerProvider).presets.single.name, 'Mine'); + expect( + container.read(equalizerProvider).presets.single.settings.filters, + settings.filters, + ); + }, + ); + + for (final mornye in [false, true]) { + testWidgets('the page edits filters (Mornye=$mornye)', (tester) async { + tester.view.physicalSize = const Size(420, 2600); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final container = ProviderContainer(); + addTearDown(container.dispose); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + theme: mornye + ? MornyeTheme.build(Brightness.light) + : AppTheme.light(), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: const EqualizerScreen(), + ), + ), + ); + await tester.pumpAndSettle(); + EqualizerSettings settings() => + container.read(equalizerProvider).settings; + + expect(find.text('Bands'), findsOneWidget); + expect(find.text('Bass'), findsOneWidget); + // A Material segment lays its label out twice. + await tester.tap(find.text('Parametric').first); + await tester.pumpAndSettle(); + expect(settings().parametric, isTrue); + expect(find.text('Filters'), findsOneWidget); + expect(find.text('Bass'), findsNothing); + expect(find.text('Treble'), findsNothing); + expect(find.text('Balance'), findsOneWidget); + expect( + find.text('No filters yet. Add one, or import a filter list.'), + findsOneWidget, + ); + + // Tests run as Android: the filters need the new engine there. + expect(defaultTargetPlatform, TargetPlatform.android); + expect(find.textContaining('new playback engine'), findsOneWidget); + await tester.tap(find.text('Turn on')); + await tester.pumpAndSettle(); + expect(container.read(settingsProvider).media3Engine, isTrue); + expect(find.textContaining('new playback engine'), findsNothing); + + await tester.tap(find.text('Add filter')); + await tester.pumpAndSettle(); + expect(settings().filters, [const EqualizerFilter()]); + expect(find.text('Filter 1'), findsOneWidget); + await tester.tap(find.text('Low shelf').first); + await tester.pumpAndSettle(); + expect(settings().filters.single.type, EqualizerFilterType.lowShelf); + + // An exact value is typed; the slider only gets near it. + await tester.tap(find.byTooltip('Type the value: Frequency')); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(EditableText), '105,5'); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + expect(settings().filters.single.frequency, 105.5); + await tester.tap(find.byTooltip('Type the value: Gain')); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(EditableText), '-99'); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + expect(settings().filters.single.gain, -24); + expect(find.text('105.5 Hz'), findsWidgets); + + await tester.tapAt(const Offset(10, 10)); + await tester.pumpAndSettle(); + expect( + find.textContaining('Low shelf · −24.0 dB · Q 1.00'), + findsOneWidget, + ); + await tester.tap( + find.descendant( + of: find.byType(EqualizerScreen), + matching: find.byWidgetPredicate( + (widget) => + widget is AppSwitch && + (widget.semanticLabel ?? '').startsWith('Filter 1'), + ), + ), + ); + await tester.pumpAndSettle(); + expect(settings().filters.single.enabled, isFalse); + + await tester.tap(find.text('105.5 Hz')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Remove filter')); + await tester.pumpAndSettle(); + expect(settings().filters, isEmpty); + + await tester.tap(find.text('Graphic').first); + await tester.pumpAndSettle(); + expect(settings().parametric, isFalse); + expect(find.text('Bass'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + } +} diff --git a/test/equalizer_test.dart b/test/equalizer_test.dart index 4d99442b4..5c322123f 100644 --- a/test/equalizer_test.dart +++ b/test/equalizer_test.dart @@ -103,9 +103,10 @@ void main() { ); await tester.pumpAndSettle(); final page = tester.widget(find.byType(Scaffold)); - final picker = find.byType( - mornye ? MornyeSegmentedControl : M3EButtonGroup, - ); + // The band count, under the Graphic or Parametric choice. + final picker = find + .byType(mornye ? MornyeSegmentedControl : M3EButtonGroup) + .last; final bandPicker = tester.widget(picker); Widget bass() => mornye ? tester @@ -417,8 +418,11 @@ void main() { ), ); await tester.pumpAndSettle(); - final picker = find.byType( - mornye ? MornyeSegmentedControl : M3EButtonGroup, + // The band count, not the Graphic or Parametric choice above it. + final picker = find.byWidgetPredicate( + (widget) => mornye + ? widget is MornyeSegmentedControl && widget.labels.length == 4 + : widget is M3EButtonGroup && widget.actions.length == 4, ); await tester.scrollUntilVisible( picker, diff --git a/test/media_kit_audio_filters_test.dart b/test/media_kit_audio_filters_test.dart index bbc500d08..86fc510ba 100644 --- a/test/media_kit_audio_filters_test.dart +++ b/test/media_kit_audio_filters_test.dart @@ -88,6 +88,59 @@ void main() { }); }); + test('parametric filters replace the bands with their own sections', () { + final settings = const EqualizerSettings(enabled: true).copyWith( + parametric: true, + gains: [6, 0, 0, 0, 0, 0, 0, 0, 0, 0], + bass: 4, + filters: const [ + EqualizerFilter(frequency: 105, gain: -2.1, q: 0.7), + EqualizerFilter( + type: EqualizerFilterType.lowShelf, + frequency: 80, + gain: 4, + q: 0.71, + ), + EqualizerFilter( + type: EqualizerFilterType.highShelf, + frequency: 30000, + gain: -3, + q: 0.5, + ), + EqualizerFilter(frequency: 500, gain: 0), + EqualizerFilter(frequency: 900, gain: 5, enabled: false), + ], + ); + final chain = MpvAudioFilterChain.fromEqualizer( + settings, + sampleRate: 48000, + ); + final sections = chain.filters + .where((f) => f.id.startsWith('filter')) + .map((f) => f.spec) + .toList(); + expect(sections, [ + 'equalizer@filter0=f=105:t=q:w=0.7:g=-2.1', + 'lowshelf@filter1=f=80:t=q:w=0.71:g=4', + // Kept below 45% of the sample rate, like a band. + 'highshelf@filter2=f=21600:t=q:w=0.5:g=-3', + ]); + expect(chain.filters.any((f) => f.id.startsWith('band')), isFalse); + // The headroom is the filters' own peak, not the waiting bands': the + // shelf's 4 dB less what the cut beside it takes off. + expect(chain.filters.first.options['volume'], '-3.8297dB'); + + final bare = MpvAudioFilterChain.fromEqualizer( + settings, + sampleRate: 48000, + unavailable: const {'lowshelf', 'highshelf'}, + ); + expect( + bare.filters.where((f) => f.id.startsWith('filter')).map((f) => f.name), + ['equalizer'], + ); + }); + test('filters missing from libmpv are left out', () { final settings = const EqualizerSettings( enabled: true, diff --git a/test/media_kit_playback_deck_test.dart b/test/media_kit_playback_deck_test.dart index 9749139ee..90bfd3735 100644 --- a/test/media_kit_playback_deck_test.dart +++ b/test/media_kit_playback_deck_test.dart @@ -403,7 +403,8 @@ void main() { final probes = engine.filterWrites .where((call) => call[2].startsWith('@mornye_probe')) .length; - expect(probes, 4); + // Volume, balance, compressor, limiter and the two shelves. + expect(probes, 6); final other = FakeMpvEngine()..missingFilters = engine.missingFilters; final second = MediaKitPlaybackDeck(playerId: 'mpv-other', engine: other); await _settle(); diff --git a/third_party/audioplayers_darwin/MORNYE_PATCHES.md b/third_party/audioplayers_darwin/MORNYE_PATCHES.md index 24c36731e..23a1be10e 100644 --- a/third_party/audioplayers_darwin/MORNYE_PATCHES.md +++ b/third_party/audioplayers_darwin/MORNYE_PATCHES.md @@ -36,7 +36,10 @@ other userInfo values are omitted so playback errors cannot expose NAS credentia - EqualizerDSP.swift (new) processes decoded PCM with cascaded RBJ peaking biquads, plus input gain, balance, a compressor and a limiter. It accepts 5, 10, 15 or 31 bands with gains from -24 to 24 dB, the same limits as the - Android fork. + Android fork. With a `filters` list in the configuration (the parametric + equalizer: up to 20 entries of `type` `peak`, `lowshelf` or `highshelf` + with `frequency`, `gain` and `q`) it plays those cookbook sections in + place of the bands; an entry it cannot read turns the equalizer off. ### External playback diff --git a/third_party/audioplayers_darwin/darwin/audioplayers_darwin/Sources/audioplayers_darwin/EqualizerDSP.swift b/third_party/audioplayers_darwin/darwin/audioplayers_darwin/Sources/audioplayers_darwin/EqualizerDSP.swift index c76adb10c..308b34540 100644 --- a/third_party/audioplayers_darwin/darwin/audioplayers_darwin/Sources/audioplayers_darwin/EqualizerDSP.swift +++ b/third_party/audioplayers_darwin/darwin/audioplayers_darwin/Sources/audioplayers_darwin/EqualizerDSP.swift @@ -25,6 +25,21 @@ final class EqualizerDSP { a2: (1 - alpha / a) / divisor) } + /// A shelf of the cookbook; `high` turns it around the frequency. + static func shelf(high: Bool, frequency: Double, gain: Double, q: Double, rate: Double) -> Biquad { + let w = 2 * Double.pi * min(frequency, rate * 0.45) / rate + let a = pow(10, gain / 40) + let cosine = high ? -cos(w) : cos(w) + let slope = 2 * sqrt(a) * sin(w) / (2 * q) + let divisor = (a + 1) + (a - 1) * cosine + slope + let sign = high ? -1.0 : 1.0 + return Biquad(b0: a * ((a + 1) - (a - 1) * cosine + slope) / divisor, + b1: sign * 2 * a * ((a - 1) - (a + 1) * cosine) / divisor, + b2: a * ((a + 1) - (a - 1) * cosine - slope) / divisor, + a1: sign * -2 * ((a - 1) + (a + 1) * cosine) / divisor, + a2: ((a + 1) + (a - 1) * cosine - slope) / divisor) + } + mutating func process(_ input: Double) -> Double { if ramp > 0 { let step = 1 / Double(ramp) @@ -93,11 +108,31 @@ final class EqualizerDSP { } let step = pow(frequencies.last! / frequencies.first!, 1 / Double(gains.count - 1)) let q = sqrt(step) / (step - 1) + var sections = zip(frequencies, gains).map { + Biquad.peak(frequency: $0.0, gain: $0.1, q: q, rate: rate) + } + // Parametric: the listener's own filters play in place of the bands. + if let parametric = configuration["filters"] as? [[String: Any]] { + guard parametric.count <= 20 else { enabled = false; return } + sections = [] + for filter in parametric { + guard let type = filter["type"] as? String, + let frequency = (filter["frequency"] as? NSNumber)?.doubleValue, + let gain = (filter["gain"] as? NSNumber)?.doubleValue, + let width = (filter["q"] as? NSNumber)?.doubleValue, + ["peak", "lowshelf", "highshelf"].contains(type), + frequency.isFinite, frequency >= 10, frequency <= 24000, + gain.isFinite, abs(gain) <= 24, width.isFinite, width >= 0.05, width <= 40 + else { enabled = false; return } + sections.append(type == "peak" + ? Biquad.peak(frequency: frequency, gain: gain, q: width, rate: rate) + : Biquad.shelf(high: type == "highshelf", frequency: frequency, gain: gain, q: width, rate: rate)) + } + } for channel in filters.indices { let old = filters[channel] - filters[channel] = zip(frequencies, gains).enumerated().map { index, band in - let next = Biquad.peak(frequency: band.0, gain: band.1, q: q, rate: rate) - guard old.count == gains.count else { return next } + filters[channel] = sections.enumerated().map { index, next in + guard old.count == sections.count else { return next } var filter = old[index] filter.retarget(next, frames: Int(rate * 0.005)) return filter diff --git a/third_party/audioplayers_darwin/tests/EqualizerDSPTests.swift b/third_party/audioplayers_darwin/tests/EqualizerDSPTests.swift index 8f72cbdaa..e945f6bf4 100644 --- a/third_party/audioplayers_darwin/tests/EqualizerDSPTests.swift +++ b/third_party/audioplayers_darwin/tests/EqualizerDSPTests.swift @@ -64,6 +64,21 @@ import Foundation assert(frame.allSatisfy { $0.isFinite && abs($0) <= pow(10, -0.5 / 20) + 1e-9 }) } } - print("PASS: flat, gain, preamp, compressor, limiter, pan, mono, bypass and 31-band multi-rate stability") + // Parametric filters play in place of the bands, which are sent flat. + func level(_ filters: [[String: Any]], at frequency: Double) -> Double { + 20 * log10(rms(engine(["filters": filters]), amplitude: 0.1, frequency: frequency) / flat) + } + let peak: [String: Any] = ["type": "peak", "frequency": 1000.0, "gain": 6.0, "q": 1.4] + assert(abs(level([peak], at: 1000) - 6) < 0.02 && abs(level([peak], at: 60)) < 0.05) + let low: [String: Any] = ["type": "lowshelf", "frequency": 200.0, "gain": -5.0, "q": 0.707] + assert(abs(level([low], at: 30) + 5) < 0.05 && abs(level([low], at: 200) + 2.5) < 0.05) + assert(abs(level([low], at: 5000)) < 0.02) + let high: [String: Any] = ["type": "highshelf", "frequency": 4000.0, "gain": 4.0, "q": 0.707] + assert(abs(level([high], at: 100)) < 0.02 && abs(level([high], at: 4000) - 2) < 0.05) + assert(abs(level([high], at: 18000) - 4) < 0.1) + assert(abs(level([], at: 1000)) < 1e-6, "No filters must play flat, not the bands") + let invalid = engine(["filters": [["type": "notch", "frequency": 1000.0, "gain": 3.0, "q": 1.0]]]) + assert(!invalid.enabled, "An unknown filter must turn the equalizer off") + print("PASS: flat, gain, preamp, compressor, limiter, pan, mono, bypass, 31-band multi-rate stability and parametric filters") } }