Files
pluriwave/lib/servicios/servicio_ecualizador.dart
T
FreeTLab 39ead7bea4
Build & Deploy PluriWave / Análisis de código (push) Successful in 27s
Build & Deploy PluriWave / Build APK + AAB release (push) Successful in 1m39s
fix(eq): stop the phone speaker from impersonating a Bluetooth device
deviceToMap handed the builtin_speaker id to EVERY output type its `when`
did not name. A car stereo on LE Audio (TYPE_BLE_HEADSET) or an automotive
bus (TYPE_BUS) therefore arrived in Dart under the phone speaker's own id,
carrying a type that maps to `desconocido` -- which slipped past the
type-only esBase guard and persisted a device entry keyed builtin_speaker.
From that moment on, every playback through the phone's own speaker matched
that entry, so the green active-output dot stayed pinned to whatever the user
had renamed it to (a car, in the reported case) whether or not anything was
connected. The dot was never wrong; the row was poisoned.

Give unnamed output types their own `other:<type>:<address>` id namespace,
and match esBase by id as well as by type so no future native regression can
re-create the collision. A guarded one-time migration purges what the
collision already persisted from all three device-keyed maps.

Fix the ranking too: builtin_speaker sat inside the priority list as a peer,
so any type absent from that list sorted BELOW the always-present speaker
and could never win. The speaker is now the explicit last resort, externally
connected outputs outrank it, and virtual or call-only sinks (earpiece,
telephony, remote submix, SCO) are ranked below it so they can never be
reported as where music is playing.

Route every AudioDeviceInfo.getAddress read through a version-guarded
helper. It is API 28 with minSdk 24, and two pre-existing unguarded calls in
this same method were latent NoSuchMethodError crashes on Android 7-8.1.
Android lint for :app goes from 8 errors to 6.

Also lets the user manage the list, which is how they recover from a bad
entry without waiting for a release: a remove action clears a device's
preset, name and matrix entries, unnamed rows show their transport and
address tail instead of a raw bt_a2dp:AA:BB:... id, and the green dot
finally carries a tooltip and a semantics label saying what it means.

Device QA pending for wired and USB outputs: no jack or adapter available to
exercise those paths. Their detection is unchanged by this commit.
2026-07-25 16:10:36 +02:00

409 lines
15 KiB
Dart

import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../modelos/preset_ecualizador.dart';
import 'persistencia_tolerante.dart';
import 'servicio_dispositivo_audio.dart' show idAltavozInterno;
class ConfiguracionEcualizador {
const ConfiguracionEcualizador({
required this.principal,
required this.porEmisora,
this.activo = true,
this.eqMultiDeviceEnabled = false,
this.presetsDispositivo = const {},
this.presetsMatriz = const {},
this.nombresDispositivos = const {},
});
final PresetEcualizador principal;
final Map<String, PresetEcualizador> porEmisora;
final bool activo;
/// Feature toggle: when false all multi-device logic is bypassed.
final bool eqMultiDeviceEnabled;
/// Per-device presets: deviceId → PresetEcualizador.
final Map<String, PresetEcualizador> presetsDispositivo;
/// Matrix presets: "stationUuid:deviceId" → PresetEcualizador.
final Map<String, PresetEcualizador> presetsMatriz;
/// Custom display names for devices: deviceId → custom name.
final Map<String, String> nombresDispositivos;
}
class ServicioEcualizador {
ServicioEcualizador({SharedPreferences? prefs}) : _prefs = prefs;
static const _keyPresetPrincipal = 'eq_preset_principal_v1';
static const _keyPresetsPorEmisora = 'eq_presets_por_emisora_v1';
static const _keyActivo = 'eq_activo_v1';
static const _keyMultiDeviceEnabled = 'eq_multi_device_enabled_v1';
static const _keyPresetsPorDispositivo = 'eq_preset_por_dispositivo_v1';
static const _keyPresetsMatriz = 'eq_presets_matriz_v1';
static const _keyNombresDispositivos = 'eq_nombres_dispositivos_v1';
/// bt-device-identity ADR-5: guard flag for the one-time placeholder purge.
static const _keyPlaceholderPurgaHecha = 'eq_placeholder_purge_done_v1';
/// bt-device-identity ADR-3: the exact OS placeholder MAC, in the
/// `bt_a2dp:`-prefixed id shape used across all device-keyed SP maps.
static const _placeholderMacLiteral = 'bt_a2dp:02:00:00:00:00:00';
/// Guard flag for the one-time `builtin_speaker` collision purge.
static const _keyColisionBasePurgaHecha = 'eq_builtin_speaker_purge_done_v1';
final SharedPreferences? _prefs;
/// Injected startup instance (S3-R4); getInstance() is only a fallback.
Future<SharedPreferences> _resolverPrefs() async =>
_prefs ?? SharedPreferences.getInstance();
Future<ConfiguracionEcualizador> cargar() async {
await migrarClavesPlaceholder();
await migrarColisionAltavozInterno();
final prefs = await _resolverPrefs();
final principal = _leerPresetPrincipal(prefs);
final porEmisora = _leerPresetsPorEmisora(prefs);
final presetsDispositivo = _leerMapa(prefs, _keyPresetsPorDispositivo);
final presetsMatriz = _leerMapa(prefs, _keyPresetsMatriz);
final nombresDispositivos = _leerMapaStrings(prefs, _keyNombresDispositivos);
return ConfiguracionEcualizador(
principal: principal,
porEmisora: porEmisora,
activo: prefs.getBool(_keyActivo) ?? true,
eqMultiDeviceEnabled: prefs.getBool(_keyMultiDeviceEnabled) ?? false,
presetsDispositivo: presetsDispositivo,
presetsMatriz: presetsMatriz,
nombresDispositivos: nombresDispositivos,
);
}
/// One-time guarded migration (bt-device-identity ADR-5): purges entries
/// keyed by the exact OS placeholder MAC ([_placeholderMacLiteral]) from
/// all three device-keyed SP maps. Idempotent — short-circuits via
/// [_keyPlaceholderPurgaHecha] after the first successful run. Every other
/// entry (including near-miss keys) is preserved byte-for-byte.
Future<void> migrarClavesPlaceholder() async {
final prefs = await _resolverPrefs();
if (prefs.getBool(_keyPlaceholderPurgaHecha) ?? false) return;
await _purgarDeviceId(prefs, _placeholderMacLiteral);
await prefs.setBool(_keyPlaceholderPurgaHecha, true);
}
/// One-time guarded migration: purges entries keyed by [idAltavozInterno].
///
/// `MainActivity.deviceToMap` used to hand the phone-speaker id to ANY output
/// type it could not name (LE Audio, car bus, dock). Dart then created a
/// device entry under that id, and from then on every playback through the
/// phone's own speaker matched it — permanently flagging whatever the user
/// had renamed it to as the active device. The native id is fixed; this
/// clears what the collision already persisted. Idempotent via
/// [_keyColisionBasePurgaHecha]; every other entry survives byte-for-byte.
Future<void> migrarColisionAltavozInterno() async {
final prefs = await _resolverPrefs();
if (prefs.getBool(_keyColisionBasePurgaHecha) ?? false) return;
await _purgarDeviceId(prefs, idAltavozInterno);
await prefs.setBool(_keyColisionBasePurgaHecha, true);
}
/// Removes every trace of [deviceId] from the three device-keyed SP maps.
///
/// Shared by the guarded migrations and by [eliminarDispositivo]; each map is
/// only rewritten when the key was actually present.
Future<void> _purgarDeviceId(SharedPreferences prefs, String deviceId) async {
final presetsPorDispositivo = _leerMapa(prefs, _keyPresetsPorDispositivo);
if (presetsPorDispositivo.remove(deviceId) != null) {
await _guardarMapa(
prefs,
_keyPresetsPorDispositivo,
presetsPorDispositivo,
);
}
// Matrix keys are "stationUuid:deviceId"; split on the FIRST colon only
// (station UUIDs are RFC4122 and contain no colons — multi-device-eq
// ADR-3), since deviceId itself may contain colons (e.g. a MAC-based id).
final presetsMatriz = _leerMapa(prefs, _keyPresetsMatriz);
final clavesMatrizAPurgar = presetsMatriz.keys.where((clave) {
final separador = clave.indexOf(':');
if (separador == -1) return false;
return clave.substring(separador + 1) == deviceId;
}).toList();
if (clavesMatrizAPurgar.isNotEmpty) {
for (final clave in clavesMatrizAPurgar) {
presetsMatriz.remove(clave);
}
await _guardarMapa(prefs, _keyPresetsMatriz, presetsMatriz);
}
final nombresDispositivos = _leerMapaStrings(
prefs,
_keyNombresDispositivos,
);
if (nombresDispositivos.remove(deviceId) != null) {
await _guardarMapaStrings(
prefs,
_keyNombresDispositivos,
nombresDispositivos,
);
}
}
/// Forgets a device completely: its preset, its custom name and every matrix
/// entry that targets it. Used by the "remove device" action so the user can
/// clear stale or duplicate entries from the known-devices list.
Future<void> eliminarDispositivo(String deviceId) async {
final prefs = await _resolverPrefs();
await _purgarDeviceId(prefs, deviceId);
}
Future<void> guardarPrincipal(PresetEcualizador preset) async {
final prefs = await _resolverPrefs();
await prefs.setString(_keyPresetPrincipal, jsonEncode(preset.toJson()));
}
Future<void> guardarPorEmisora(String uuid, PresetEcualizador preset) async {
final prefs = await _resolverPrefs();
final mapa = _leerPresetsPorEmisora(prefs);
mapa[uuid] = preset;
await _guardarPresetsPorEmisora(prefs, mapa);
}
Future<void> guardarActivo(bool activo) async {
final prefs = await _resolverPrefs();
await prefs.setBool(_keyActivo, activo);
}
Future<void> eliminarPorEmisora(String uuid) async {
final prefs = await _resolverPrefs();
final mapa = _leerPresetsPorEmisora(prefs);
mapa.remove(uuid);
await _guardarPresetsPorEmisora(prefs, mapa);
}
Future<void> guardarConfiguracion(ConfiguracionEcualizador config) async {
final prefs = await _resolverPrefs();
await prefs.setString(
_keyPresetPrincipal,
jsonEncode(config.principal.toJson()),
);
await _guardarPresetsPorEmisora(prefs, config.porEmisora);
await prefs.setBool(_keyActivo, config.activo);
await prefs.setBool(_keyMultiDeviceEnabled, config.eqMultiDeviceEnabled);
await _guardarMapa(
prefs,
_keyPresetsPorDispositivo,
config.presetsDispositivo,
);
await _guardarMapa(prefs, _keyPresetsMatriz, config.presetsMatriz);
await _guardarMapaStrings(
prefs,
_keyNombresDispositivos,
config.nombresDispositivos,
);
}
/// Persists the multi-device feature toggle.
Future<void> guardarToggleMultiDispositivo(bool habilitado) async {
final prefs = await _resolverPrefs();
await prefs.setBool(_keyMultiDeviceEnabled, habilitado);
}
/// Saves a per-device preset.
Future<void> guardarPresetDispositivo(
String deviceId,
PresetEcualizador preset,
) async {
final prefs = await _resolverPrefs();
final mapa = _leerMapa(prefs, _keyPresetsPorDispositivo);
mapa[deviceId] = preset;
await _guardarMapa(prefs, _keyPresetsPorDispositivo, mapa);
}
/// Saves a matrix (stationUuid:deviceId) preset entry.
Future<void> guardarPresetMatriz(
String clave,
PresetEcualizador preset,
) async {
final prefs = await _resolverPrefs();
final mapa = _leerMapa(prefs, _keyPresetsMatriz);
mapa[clave] = preset;
await _guardarMapa(prefs, _keyPresetsMatriz, mapa);
}
/// Removes a per-device preset entry.
Future<void> eliminarPresetDispositivo(String deviceId) async {
final prefs = await _resolverPrefs();
final mapa = _leerMapa(prefs, _keyPresetsPorDispositivo);
mapa.remove(deviceId);
await _guardarMapa(prefs, _keyPresetsPorDispositivo, mapa);
}
/// Removes a matrix preset entry.
Future<void> eliminarPresetMatriz(String clave) async {
final prefs = await _resolverPrefs();
final mapa = _leerMapa(prefs, _keyPresetsMatriz);
mapa.remove(clave);
await _guardarMapa(prefs, _keyPresetsMatriz, mapa);
}
/// Returns the persisted device custom names map.
Future<Map<String, String>> cargarNombresDispositivos() async {
final prefs = await _resolverPrefs();
return _leerMapaStrings(prefs, _keyNombresDispositivos);
}
/// Persists the device custom names map.
Future<void> guardarNombresDispositivos(Map<String, String> nombres) async {
final prefs = await _resolverPrefs();
await _guardarMapaStrings(prefs, _keyNombresDispositivos, nombres);
}
/// Reads a `Map<String, PresetEcualizador>` from a SharedPreferences JSON
/// key with per-entry tolerance (persistence-resilience D6): a value that
/// fails to parse is skipped and logged, its sibling entries survive and
/// every surviving key (including the matrix's colon-delimited
/// `stationUuid:deviceId` keys) is preserved byte-for-byte. A top-level
/// decode failure still degrades the whole map to empty (now logged too);
/// no flag/quarantine here — EQ presets are explicit-only writes and
/// trivially re-creatable (D6, intentional asymmetry vs. Alarms/Stations).
Map<String, PresetEcualizador> _leerMapa(
SharedPreferences prefs,
String key,
) {
final raw = prefs.getString(key);
if (raw == null || raw.isEmpty) return {};
try {
final data = Map<String, dynamic>.from(jsonDecode(raw) as Map);
final resultado = parseMapaTolerante<PresetEcualizador>(
data,
(valor) => PresetEcualizador.desdeJson(
Map<String, dynamic>.from(valor as Map),
),
subsistema: 'ecualizador',
coleccion: key,
);
return resultado.validas;
} catch (e) {
registrarSaltoPersistencia(
subsistema: 'ecualizador',
detalle: key,
razon: e.toString(),
);
return {};
}
}
Future<void> _guardarMapa(
SharedPreferences prefs,
String key,
Map<String, PresetEcualizador> mapa,
) async {
final serializado = mapa.map((k, v) => MapEntry(k, v.toJson()));
await prefs.setString(key, jsonEncode(serializado));
}
/// Reads a `Map<String, String>` from a SharedPreferences JSON key with
/// per-entry tolerance (persistence-resilience D6): a value that is not a
/// String is skipped and logged, sibling entries and keys survive
/// untouched. A top-level decode failure still degrades the whole map to
/// empty (now logged too); no flag/quarantine here (D6).
Map<String, String> _leerMapaStrings(SharedPreferences prefs, String key) {
final raw = prefs.getString(key);
if (raw == null || raw.isEmpty) return {};
try {
final data = Map<String, dynamic>.from(jsonDecode(raw) as Map);
final resultado = parseMapaTolerante<String>(
data,
(valor) => valor as String,
subsistema: 'ecualizador',
coleccion: key,
);
return resultado.validas;
} catch (e) {
registrarSaltoPersistencia(
subsistema: 'ecualizador',
detalle: key,
razon: e.toString(),
);
return {};
}
}
Future<void> _guardarMapaStrings(
SharedPreferences prefs,
String key,
Map<String, String> mapa,
) async {
await prefs.setString(key, jsonEncode(mapa));
}
/// Reads the single principal-preset key. Single-value (not a collection)
/// so there is nothing to skip per-entry; a decode failure still falls
/// back to [PresetEcualizador.flat] (unchanged behavior) but is now
/// logged too (persistence-resilience D6, diagnostics).
PresetEcualizador _leerPresetPrincipal(SharedPreferences prefs) {
final raw = prefs.getString(_keyPresetPrincipal);
if (raw == null || raw.isEmpty) {
return PresetEcualizador.flat;
}
try {
return PresetEcualizador.desdeJson(
Map<String, dynamic>.from(jsonDecode(raw) as Map),
);
} catch (e) {
registrarSaltoPersistencia(
subsistema: 'ecualizador',
detalle: _keyPresetPrincipal,
razon: e.toString(),
);
return PresetEcualizador.flat;
}
}
/// Reads the per-station preset map with per-entry tolerance
/// (persistence-resilience D6) via the same shared helper as [_leerMapa];
/// a station whose preset value fails to parse is skipped and logged, its
/// siblings survive under their original uuid keys.
Map<String, PresetEcualizador> _leerPresetsPorEmisora(
SharedPreferences prefs,
) {
final raw = prefs.getString(_keyPresetsPorEmisora);
if (raw == null || raw.isEmpty) {
return {};
}
try {
final data = Map<String, dynamic>.from(jsonDecode(raw) as Map);
final resultado = parseMapaTolerante<PresetEcualizador>(
data,
(valor) => PresetEcualizador.desdeJson(
Map<String, dynamic>.from(valor as Map),
),
subsistema: 'ecualizador',
coleccion: _keyPresetsPorEmisora,
);
return resultado.validas;
} catch (e) {
registrarSaltoPersistencia(
subsistema: 'ecualizador',
detalle: _keyPresetsPorEmisora,
razon: e.toString(),
);
return {};
}
}
Future<void> _guardarPresetsPorEmisora(
SharedPreferences prefs,
Map<String, PresetEcualizador> mapa,
) async {
final serializado = mapa.map(
(uuid, preset) => MapEntry(uuid, preset.toJson()),
);
await prefs.setString(_keyPresetsPorEmisora, jsonEncode(serializado));
}
}