fix(eq): entregar los decibelios que pide el usuario, sin estirarlos
Build & Deploy PluriWave / Análisis de código (push) Successful in 29s
Build & Deploy PluriWave / Build APK + AAB release (push) Successful in 2m56s

La app promete decibelios en cuatro sitios y no los entregaba en ninguno. El
slider abarca un +/-12 fijo, escribe el numero con su unidad debajo de cada
banda, y `equalizerBandValue` le dice literalmente "decibelios" a TalkBack. El
modelo documenta las bandas como dB y los presets de fabrica estan escritos en
dB. just_audio documenta `setGain` en decibelios y multiplica por 1000 para
llegar a milibelios sin normalizar nada: `minDecibels`/`maxDecibels` son la
CAPACIDAD del dispositivo, no una escala a la que normalizar.

Pese a eso, la ganancia se estiraba por `maxDecibels/12`. Un +6 dB llegaba como
+10 en un movil de rango ancho.

El estiramiento nunca fue una decision de diseño

Antes de a9202c6 el codigo era `setGain(preset.bandas[i])`, decibelios
literales. Ese commit metio la normalizacion sin docstring, sin test y sin nota
de diseño, y traia un fallo: 0 dB caia en el punto medio del rango, asi que un
preset PLANO realzaba. 3449e2c corrigio exactamente eso y nada mas -- su propio
mensaje dice que el objetivo era "0 dB es siempre 0" -- heredando el
estiramiento sin discutirlo. No hay ADR, spec ni comentario que lo justifique.

Lo que de verdad rompia: la portabilidad

Lo que se persiste y se exporta son los dB del usuario, sin escalar; el escalado
ocurre solo al escribir en el efecto nativo. Asi que el mismo backup suena
distinto en cada telefono, y la interfaz informa de una restauracion perfecta
mientras el audio no lo es. Peor con el rango asimetrico habitual de Android
([-12, +19]): los realces se multiplican por 1.58 y los cortes por 1.0, de modo
que el preset no solo sube de nivel, CAMBIA DE FORMA. Jazz [3, -1, -1.5, 2, 4]
se entregaba como [4.75, -1, -1.5, 3.17, 6.33]. Con presets por dispositivo, el
mismo preset se deformaba distinto en el altavoz y en el Bluetooth.

No es un clamp a secas

`db.clamp(minDecibels, maxDecibels)` habria reintroducido el fallo de 3449e2c:
en un dispositivo que reporte [+3, +19], el cero se convierte en +3 y el preset
plano vuelve a realzar. La ventana se fuerza a contener el cero, asi que se
conservan todas las invariantes ganadas -- 0 siempre es 0, el signo nunca se
invierte, el resultado nunca escapa del rango nativo, un dispositivo sin margen
en un lado no puede realzar por ese lado -- y solo desaparece el estiramiento.

Que se oye distinto: en un movil de +/-12 dB, identico a hoy. En uno de rango
ancho los realces bajan, hasta un 40% menos en dB en uno de +/-20. Los cortes
apenas se mueven, porque la forma habitual es [-12, +N] y el lado negativo ya
iba practicamente 1:1. A cambio, los seis presets de fabrica suenan por fin
igual en cualquier telefono.

Ningun preset guardado necesita migracion: lo almacenado siempre fueron los dB
del usuario.

Suite completa: 1534 pasan, 2 omitidos. flutter analyze mantiene los 5 avisos
preexistentes.
This commit is contained in:
2026-09-06 00:08:09 +02:00
parent 8fc3d99fbd
commit b1bf289e0d
2 changed files with 148 additions and 63 deletions
+39 -30
View File
@@ -687,44 +687,51 @@ DecisionToggleEq decidirToggleEq({
requiereLlamadaNativa: eqDisponible,
);
/// Translates a gain on the app's fixed ±12 dB slider scale to the range the
/// device's native equalizer actually reports
/// (`AndroidEqualizerParameters.min/maxDecibels`, itself derived from
/// `Equalizer.getBandLevelRange()`).
/// Delivers a gain from the app's ±12 dB slider to the device's native
/// equalizer, clamped by what the device reports it can do
/// (`AndroidEqualizerParameters.min/maxDecibels`, itself
/// `Equalizer.getBandLevelRange()` in millibels divided by 1000).
///
/// Top-level and pure so the mapping is testable without a device.
///
/// THE DEFECT THIS REPLACES, and the likely source of the reported «suena muy
/// alto»: the previous implementation normalised across the whole range and
/// interpolated linearly,
/// THE CONTRACT: the decibels the user reads are the decibels the device is
/// asked for. The native range BOUNDS the request; it is not a scale to
/// normalise into. Both sides are already the same unit — `just_audio`
/// documents `setGain` as taking decibels and its Android bridge does
/// `setBandLevel(band, round(gain * 1000.0))`, plain dB to millibels with no
/// normalisation — so multiplying by the device's headroom was a unit error.
///
/// minDecibels + ((db + 12) / 24) * (maxDecibels - minDecibels)
/// WHY IT MATTERS, in the app's own terms. The slider is hard-coded
/// `min: -12.0, max: 12.0`, the label under each band prints
/// `'${banda.toStringAsFixed(1)}dB'`, and TalkBack reads `equalizerBandValue`
/// = "{value} decibels": one promise, made three ways. Presets are persisted
/// and exported as those same raw slider values (`PresetEcualizador.toJson`),
/// so scaling at this boundary made an exported backup mean a different SOUND
/// on a different phone while displaying identical numbers — and on the
/// common asymmetric shape [-12, +19] it multiplied boosts by 1.58 and cuts
/// by 1.0, deforming a preset's shape rather than just its depth.
///
/// which puts 0 dB at the MIDPOINT of the native range. That is only 0 when
/// the range is symmetric, and Android guarantees no such thing — the
/// Equalizer contract only promises a min/max pair. On a device reporting,
/// say, [-12, +19] dB, every band of a FLAT preset was pushed to +3.5 dB of
/// real boost: audibly louder, with the on/off button still reading "off"
/// and nothing in the UI to explain it.
///
/// The contract here instead: 0 dB is always exactly 0, and each side of the
/// scale is stretched independently against its own end of the native range,
/// so a cut can never become a boost. A range with no headroom on one side
/// (or none at all) collapses that side to 0 rather than inverting it.
/// WHAT IS DELIBERATELY KEPT from the mapping this replaces — every invariant
/// the «suena muy alto» fix earned. Note the clamp window is widened to
/// always contain 0: a naive `db.clamp(minDecibels, maxDecibels)` would, on a
/// device reporting a wholly positive range such as [+3, +19], turn a FLAT
/// preset's 0 dB into +3 dB of real boost on every band — exactly the bug
/// that was fixed. So 0 dB is always exactly 0, the sign of the user's intent
/// is never inverted, the result never escapes the native range, a device
/// with no headroom above unity can never boost, and a zero-width range
/// collapses to 0.
double mapearGananciaNativa(
double db, {
required double minDecibels,
required double maxDecibels,
}) {
final limitado = db.clamp(-12.0, 12.0);
if (limitado == 0) return 0;
if (limitado > 0) {
// Only genuine headroom above unity counts as boost.
final techo = maxDecibels > 0 ? maxDecibels : 0.0;
return (limitado / 12.0) * techo;
}
// The clamp window is the device's range widened to include 0, so that a
// device reporting no headroom on one side collapses that side to "no
// change" instead of forcing a gain the user never asked for.
final suelo = minDecibels < 0 ? minDecibels : 0.0;
return (limitado.abs() / 12.0) * suelo;
final techo = maxDecibels > 0 ? maxDecibels : 0.0;
return limitado.clamp(suelo, techo);
}
/// Advances to the NEXT factory preset after [actual] in [presets] order
@@ -2720,10 +2727,12 @@ class PluriWaveAudioHandler extends BaseAudioHandler
try {
final params = await _eq.parameters;
_eqDisponible = params.bands.isNotEmpty;
// eq-estado-unico item E: the ONE number that decides whether
// [mapearGananciaNativa] can be silently boosting a FLAT preset on
// this device. `Equalizer.getBandLevelRange()` is not required to be
// symmetric, and nothing else in the app can observe what it returned.
// eq-estado-unico item E: the ONE number that decides how much of the
// ±12 dB slider [mapearGananciaNativa] can actually honour on this
// device — anything past this range is clamped, so a report of "the
// slider stops doing anything past N" is answered from this line.
// `Equalizer.getBandLevelRange()` is not required to be symmetric, and
// nothing else in the app can observe what it returned.
// `debugPrint` (never `dart:developer`'s `log`) so it reaches logcat in
// the release build, which is the only one that ever runs in a car:
//