diff --git a/backend/binaural/noise.py b/backend/binaural/noise.py new file mode 100644 index 0000000..01b5613 --- /dev/null +++ b/backend/binaural/noise.py @@ -0,0 +1,71 @@ +"""Loops de ruido rosa y de lluvia, periódicos por síntesis espectral. + +Se construye el espectro (magnitud objetivo + fase aleatoria con semilla +fija) y se antitransforma: la señal resultante es periódica en la longitud +del loop por construcción → sin costura, sin crossfade. Solo numpy. +""" + +from typing import Literal + +import numpy as np + +SR_DEFECTO = 44100 +DUR_LOOP_S = 20.0 +SEMILLA = 20260830 +PICO_LOOP = 0.99 + +TipoRuido = Literal["pink", "rain"] + + +def _ruido_espectral(n: int, magnitud: np.ndarray, rng: np.random.Generator) -> np.ndarray: + """Señal real con la magnitud espectral dada y fase aleatoria.""" + fases = rng.uniform(0.0, 2.0 * np.pi, len(magnitud)) + espectro = magnitud * np.exp(1j * fases) + espectro[0] = 0.0 # sin componente DC + if n % 2 == 0: + espectro[-1] = espectro[-1].real # el bin de Nyquist debe ser real + return np.fft.irfft(espectro, n) + + +def loop_pink( + sr: int = SR_DEFECTO, dur_s: float = DUR_LOOP_S, semilla: int = SEMILLA +) -> np.ndarray: + """Ruido rosa: potencia ∝ 1/f → −3 dB/octava exactos.""" + rng = np.random.default_rng(semilla) + n = round(dur_s * sr) + f = np.fft.rfftfreq(n, 1.0 / sr) + mag = np.zeros_like(f) + mag[1:] = 1.0 / np.sqrt(f[1:]) + x = _ruido_espectral(n, mag, rng) + return x * (PICO_LOOP / np.max(np.abs(x))) + + +def loop_rain( + sr: int = SR_DEFECTO, dur_s: float = DUR_LOOP_S, semilla: int = SEMILLA + 1 +) -> np.ndarray: + """Lluvia: base rosa/marrón + pasa-banda suave + modulación lenta periódica.""" + rng = np.random.default_rng(semilla) + n = round(dur_s * sr) + f = np.fft.rfftfreq(n, 1.0 / sr) + mag = np.zeros_like(f) + mag[1:] = f[1:] ** -0.8 # pendiente entre rosa (−3 dB/oct) y marrón (−6 dB/oct) + mag[1:] /= (1.0 + (300.0 / f[1:]) ** 2) * (1.0 + (f[1:] / 2500.0) ** 2) # hombros suaves + x = _ruido_espectral(n, mag, rng) + # Modulación de amplitud con armónicos de 1/dur_s: el producto sigue siendo periódico. + t = np.arange(n) / sr + mod = np.zeros(n) + for k in range(1, 11): # 0.05-0.5 Hz + amp = rng.uniform(0.3, 1.0) / k + mod += amp * np.sin(2.0 * np.pi * (k / dur_s) * t + rng.uniform(0.0, 2.0 * np.pi)) + mod /= np.max(np.abs(mod)) + x *= 1.0 + 0.35 * mod + return x * (PICO_LOOP / np.max(np.abs(x))) + + +def generar_loop(tipo: TipoRuido, sr: int = SR_DEFECTO) -> np.ndarray: + """Loop mono de 20 s sin costura para el tipo pedido.""" + if tipo == "pink": + return loop_pink(sr) + if tipo == "rain": + return loop_rain(sr) + raise ValueError(f"tipo de ruido desconocido: {tipo!r} (usa pink o rain)") diff --git a/backend/binaural/presets.py b/backend/binaural/presets.py new file mode 100644 index 0000000..c1a9d84 --- /dev/null +++ b/backend/binaural/presets.py @@ -0,0 +1,92 @@ +"""Carga y validación de presets YAML (fuente de verdad de las sesiones).""" + +from pathlib import Path +from typing import Literal, Self + +import yaml +from pydantic import BaseModel, Field, field_validator, model_validator + +BEAT_MIN_HZ = 1.0 +BEAT_MAX_HZ = 40.0 +CARRIER_MIN_HZ = 100.0 +CARRIER_MAX_HZ = 1000.0 +DURACION_MAX_MIN = 60.0 +DIR_PRESETS = Path(__file__).resolve().parents[1] / "presets" + + +class Segmento(BaseModel): + """Tramo de sesión: mantiene un batido (`beat_hz`) o rampa hacia otro (`ramp_to_hz`).""" + + beat_hz: float | None = None + ramp_to_hz: float | None = None + minutes: float = Field(gt=0) + + @property + def hz(self) -> float: + """Batido definido por el segmento (el destino, si es rampa).""" + return self.beat_hz if self.beat_hz is not None else self.ramp_to_hz # type: ignore[return-value] + + @model_validator(mode="after") + def _validar(self) -> Self: + if (self.beat_hz is None) == (self.ramp_to_hz is None): + raise ValueError("cada segmento define beat_hz o ramp_to_hz (exactamente uno)") + if not BEAT_MIN_HZ <= self.hz <= BEAT_MAX_HZ: + raise ValueError( + f"batido {self.hz:g} Hz fuera de rango ({BEAT_MIN_HZ:g}-{BEAT_MAX_HZ:g} Hz)" + ) + return self + + +class Preset(BaseModel): + """Sesión binaural completa tal como se describe en YAML.""" + + name: str + description: str + carrier_hz: float + noise: Literal["pink", "rain", "none"] = "none" + noise_db: float = Field(default=-20.0, ge=-60.0, le=0.0) + fade_s: float = Field(default=4.0, ge=1.0, le=10.0) + segments: list[Segmento] = Field(min_length=1) + + @field_validator("carrier_hz") + @classmethod + def _validar_portadora(cls, v: float) -> float: + if not CARRIER_MIN_HZ <= v <= CARRIER_MAX_HZ: + raise ValueError( + f"portadora {v:g} Hz fuera de rango ({CARRIER_MIN_HZ:g}-{CARRIER_MAX_HZ:g} Hz)" + ) + return v + + @model_validator(mode="after") + def _validar_sesion(self) -> Self: + if self.segments[0].beat_hz is None: + raise ValueError("el primer segmento debe definir beat_hz (batido inicial)") + if self.duracion_min > DURACION_MAX_MIN: + raise ValueError( + f"duración {self.duracion_min:g} min supera el máximo ({DURACION_MAX_MIN:g} min)" + ) + return self + + @property + def duracion_min(self) -> float: + """Duración total en minutos (sin pre-roll).""" + return sum(s.minutes for s in self.segments) + + @property + def rango_batido(self) -> tuple[float, float]: + """(mínimo, máximo) de batido que recorre la sesión.""" + hz = [s.hz for s in self.segments] + return min(hz), max(hz) + + +def cargar_preset(ruta: Path) -> Preset: + """Carga y valida un YAML de preset.""" + with ruta.open(encoding="utf-8") as fh: + datos = yaml.safe_load(fh) + return Preset.model_validate(datos) + + +def cargar_presets(directorio: Path = DIR_PRESETS) -> dict[str, Preset]: + """Carga todos los presets del directorio, indexados por nombre.""" + presets = [cargar_preset(p) for p in sorted(directorio.glob("*.yaml"))] + return {p.name: p for p in presets} diff --git a/backend/binaural/session.py b/backend/binaural/session.py new file mode 100644 index 0000000..6138b39 --- /dev/null +++ b/backend/binaural/session.py @@ -0,0 +1,70 @@ +"""Preset → schedule (curva de batido) y frecuencia instantánea. + +El `schedule` es la única fuente de verdad: el frontend aplica sus puntos +con rampas lineales de Web Audio y `f_inst` es exactamente la misma +interpolación en Python. Consistencia entre motores por construcción. +""" + +import numpy as np +from pydantic import BaseModel + +from .presets import DURACION_MAX_MIN, Preset + +PREROLL_S = 1.5 # silencio inicial: arranque del enlace Bluetooth AAC + + +class Punto(BaseModel): + """Vértice de la curva de batido: tiempo en s de sesión y batido en Hz.""" + + t: float + beat_hz: float + + +class Schedule(BaseModel): + """Curva completa de la sesión, compartida por web y export.""" + + carrier_hz: float + fade_s: float + noise: str + noise_db: float + duration_s: float + preroll_s: float = PREROLL_S + points: list[Punto] + + +def schedule_de_preset(preset: Preset, duracion_min: float | None = None) -> Schedule: + """Construye el schedule; `duracion_min` escala los segmentos proporcionalmente.""" + beat = preset.segments[0].hz + puntos = [Punto(t=0.0, beat_hz=beat)] + t = 0.0 + for seg in preset.segments: + fin = t + seg.minutes * 60.0 + if seg.beat_hz is not None and seg.beat_hz != beat: + puntos.append(Punto(t=t, beat_hz=seg.beat_hz)) # salto instantáneo + beat = seg.hz + puntos.append(Punto(t=fin, beat_hz=beat)) + t = fin + if duracion_min is not None: + if not 0 < duracion_min <= DURACION_MAX_MIN: + raise ValueError( + f"duración {duracion_min:g} min fuera de rango (0-{DURACION_MAX_MIN:g} min)" + ) + factor = duracion_min * 60.0 / t + for p in puntos: + p.t *= factor + t = duracion_min * 60.0 + return Schedule( + carrier_hz=preset.carrier_hz, + fade_s=preset.fade_s, + noise=preset.noise, + noise_db=preset.noise_db, + duration_s=t, + points=puntos, + ) + + +def f_inst(schedule: Schedule, t: np.ndarray | float) -> np.ndarray: + """Batido instantáneo en `t`: interpolación lineal de los puntos del schedule.""" + ts = np.asarray([p.t for p in schedule.points]) + bs = np.asarray([p.beat_hz for p in schedule.points]) + return np.interp(t, ts, bs) diff --git a/backend/binaural/synth.py b/backend/binaural/synth.py new file mode 100644 index 0000000..5e17052 --- /dev/null +++ b/backend/binaural/synth.py @@ -0,0 +1,103 @@ +"""Síntesis de la sesión: tonos con fase continua, ruido, envolvente y mezcla. + +La fase se obtiene integrando la frecuencia instantánea con la regla del +trapecio acumulada (exacta para f lineal a trozos), nunca como sin(2π·f·t). +El pico se limita a −3 dBFS con una escala determinista: nunca se recorta. +""" + +from collections.abc import Iterator + +import numpy as np + +from .session import Schedule, f_inst + +SR_DEFECTO = 44100 +AMP_TONO = 0.5 +PICO_MAX = float(10 ** (-3 / 20)) # −3 dBFS +MUESTRAS_BLOQUE = 1 << 18 # ≈ 5.9 s a 44.1 kHz + + +def total_muestras(schedule: Schedule, sr: int) -> int: + """Número exacto de samples de la sesión (pre-roll incluido).""" + return round((schedule.preroll_s + schedule.duration_s) * sr) + + +def _fase_continua( + f: np.ndarray, sr: int, fase0: float, f_prev: float +) -> tuple[np.ndarray, float, float]: + """Fase por sample integrando `f` (trapecio); encadenable entre bloques. + + `fase0` y `f_prev` son la fase y frecuencia del último sample del bloque + anterior. Devuelve (fases, fase final envuelta, f final). + """ + pares = np.empty(len(f) + 1) + pares[0] = f_prev + pares[1:] = f + dfase = np.pi * (pares[:-1] + pares[1:]) / sr + fases = fase0 + np.cumsum(dfase) + return fases, float(fases[-1] % (2.0 * np.pi)), float(f[-1]) + + +def _envolvente(t: np.ndarray, preroll_s: float, fade_s: float, total_s: float) -> np.ndarray: + """Silencio durante el pre-roll, fade-in y fade-out lineales.""" + if fade_s <= 0: + return (t >= preroll_s).astype(np.float64) + subida = np.clip((t - preroll_s) / fade_s, 0.0, 1.0) + bajada = np.clip((total_s - t) / fade_s, 0.0, 1.0) + return subida * bajada + + +def bloques_sesion( + schedule: Schedule, + sr: int = SR_DEFECTO, + loop_ruido: np.ndarray | None = None, + muestras_bloque: int = MUESTRAS_BLOQUE, +) -> Iterator[np.ndarray]: + """Genera la sesión completa en bloques estéreo float64 en [−1, 1]. + + Canal L: portadora fija. Canal R: portadora + batido del schedule. + Sin ningún procesamiento estéreo: solo la diferencia de frecuencia L/R. + """ + n_total = total_muestras(schedule, sr) + n_preroll = round(schedule.preroll_s * sr) + total_s = schedule.preroll_s + schedule.duration_s + + gan_ruido = 0.0 + if loop_ruido is not None and schedule.noise != "none": + gan_ruido = float(10 ** (schedule.noise_db / 20)) + cota = AMP_TONO + (gan_ruido * float(np.max(np.abs(loop_ruido))) if gan_ruido else 0.0) + escala = min(1.0, PICO_MAX / cota) + + # Estado inicial: fase 0 exacta en el primer sample de cada canal. + f0_l = schedule.carrier_hz + f0_r = schedule.carrier_hz + float(f_inst(schedule, 0.0)) + fase_l, fprev_l = -2.0 * np.pi * f0_l / sr, f0_l + fase_r, fprev_r = -2.0 * np.pi * f0_r / sr, f0_r + + for i0 in range(0, n_total, muestras_bloque): + i1 = min(i0 + muestras_bloque, n_total) + idx = np.arange(i0, i1) + t_abs = idx / sr + t_ses = np.clip(t_abs - schedule.preroll_s, 0.0, schedule.duration_s) + + f_l = np.full(len(idx), schedule.carrier_hz) + f_r = schedule.carrier_hz + f_inst(schedule, t_ses) + fases_l, fase_l, fprev_l = _fase_continua(f_l, sr, fase_l, fprev_l) + fases_r, fase_r, fprev_r = _fase_continua(f_r, sr, fase_r, fprev_r) + + bloque = np.empty((len(idx), 2)) + bloque[:, 0] = AMP_TONO * np.sin(fases_l) + bloque[:, 1] = AMP_TONO * np.sin(fases_r) + if gan_ruido and loop_ruido is not None: + ruido = gan_ruido * loop_ruido[(idx - n_preroll) % len(loop_ruido)] + bloque += ruido[:, None] + env = _envolvente(t_abs, schedule.preroll_s, schedule.fade_s, total_s) + bloque *= (env * escala)[:, None] + yield bloque + + +def sesion_completa( + schedule: Schedule, sr: int = SR_DEFECTO, loop_ruido: np.ndarray | None = None +) -> np.ndarray: + """Render completo en memoria (para tests y clips cortos; export usa bloques).""" + return np.concatenate(list(bloques_sesion(schedule, sr=sr, loop_ruido=loop_ruido))) diff --git a/backend/presets/descanso.yaml b/backend/presets/descanso.yaml new file mode 100644 index 0000000..fda3959 --- /dev/null +++ b/backend/presets/descanso.yaml @@ -0,0 +1,13 @@ +name: descanso +description: Salir de beta · baja gradualmente hasta alpha para descansar. +carrier_hz: 200 +noise: rain +noise_db: -18 +fade_s: 4 +segments: + - beat_hz: 16 + minutes: 2 + - ramp_to_hz: 9 + minutes: 11 + - beat_hz: 9 + minutes: 2 diff --git a/backend/presets/estudio.yaml b/backend/presets/estudio.yaml new file mode 100644 index 0000000..33f4feb --- /dev/null +++ b/backend/presets/estudio.yaml @@ -0,0 +1,13 @@ +name: estudio +description: Entra en alpha, sube gradualmente a beta baja para concentrarte. +carrier_hz: 220 +noise: rain +noise_db: -20 +fade_s: 4 +segments: + - beat_hz: 10 + minutes: 5 + - ramp_to_hz: 14 + minutes: 10 + - beat_hz: 14 + minutes: 15 diff --git a/backend/presets/foco.yaml b/backend/presets/foco.yaml new file mode 100644 index 0000000..d8d9331 --- /dev/null +++ b/backend/presets/foco.yaml @@ -0,0 +1,9 @@ +name: foco +description: Trabajo profundo · beta media fija en 18 Hz. +carrier_hz: 250 +noise: pink +noise_db: -24 +fade_s: 4 +segments: + - beat_hz: 18 + minutes: 25 diff --git a/backend/presets/foco_intenso.yaml b/backend/presets/foco_intenso.yaml new file mode 100644 index 0000000..c111cfc --- /dev/null +++ b/backend/presets/foco_intenso.yaml @@ -0,0 +1,12 @@ +name: foco_intenso +description: Alerta alta · sube de beta media a beta alta, sin ruido. +carrier_hz: 250 +noise: none +fade_s: 4 +segments: + - beat_hz: 15 + minutes: 3 + - ramp_to_hz: 22 + minutes: 14 + - beat_hz: 22 + minutes: 3 diff --git a/backend/presets/relajacion.yaml b/backend/presets/relajacion.yaml new file mode 100644 index 0000000..1b23543 --- /dev/null +++ b/backend/presets/relajacion.yaml @@ -0,0 +1,9 @@ +name: relajacion +description: Bajar revoluciones · alpha sostenido en 10 Hz. +carrier_hz: 200 +noise: pink +noise_db: -18 +fade_s: 4 +segments: + - beat_hz: 10 + minutes: 20 diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py new file mode 100644 index 0000000..1beee07 --- /dev/null +++ b/backend/tests/conftest.py @@ -0,0 +1,10 @@ +"""Fixtures compartidas.""" + +import pytest + +from binaural.presets import Preset, cargar_presets + + +@pytest.fixture(scope="session") +def presets() -> dict[str, Preset]: + return cargar_presets() diff --git a/backend/tests/test_noise.py b/backend/tests/test_noise.py new file mode 100644 index 0000000..62db6f5 --- /dev/null +++ b/backend/tests/test_noise.py @@ -0,0 +1,52 @@ +"""Ruido: pendiente rosa (criterio 4) y loops sin costura (criterio 8).""" + +import numpy as np +import pytest + +from binaural.noise import generar_loop, loop_pink + +SR = 44100 + + +def _pendiente_db_por_octava(x: np.ndarray, sr: int) -> float: + """Pendiente de la PSD (Welch simple con ventana Hann) entre 100 y 5000 Hz.""" + nseg = 65536 + ventana = np.hanning(nseg) + segs = [x[i : i + nseg] * ventana for i in range(0, len(x) - nseg + 1, nseg)] + psd = np.mean([np.abs(np.fft.rfft(s)) ** 2 for s in segs], axis=0) + frecs = np.fft.rfftfreq(nseg, 1.0 / sr) + bordes = [100 * 2**k for k in range(6)] # 100 … 3200 Hz + bordes.append(5000) + niveles, centros = [], [] + for lo, hi in zip(bordes[:-1], bordes[1:], strict=True): + banda = (frecs >= lo) & (frecs < hi) + niveles.append(10 * np.log10(np.mean(psd[banda]))) + centros.append(np.log2(np.sqrt(lo * hi))) + pendiente, _ = np.polyfit(centros, niveles, 1) + return float(pendiente) + + +def test_pendiente_ruido_rosa(): + """Criterio 4: entre −4 y −2 dB/octava en 100-5000 Hz.""" + pendiente = _pendiente_db_por_octava(loop_pink(SR), SR) + assert -4.0 < pendiente < -2.0 + + +@pytest.mark.parametrize("tipo", ["pink", "rain"]) +def test_loops_sin_costura(tipo): + """Criterio 8: el salto último→primer sample no excede los saltos internos.""" + x = generar_loop(tipo, SR) + assert len(x) == 20 * SR + assert np.isclose(np.max(np.abs(x)), 0.99) + assert abs(x[0] - x[-1]) <= np.max(np.abs(np.diff(x))) + + +@pytest.mark.parametrize("tipo", ["pink", "rain"]) +def test_loops_deterministas(tipo): + """Con semilla fija el loop es reproducible (cache estable).""" + assert np.array_equal(generar_loop(tipo, SR), generar_loop(tipo, SR)) + + +def test_tipo_desconocido(): + with pytest.raises(ValueError, match="desconocido"): + generar_loop("ocean", SR) diff --git a/backend/tests/test_presets.py b/backend/tests/test_presets.py new file mode 100644 index 0000000..0cbfd0e --- /dev/null +++ b/backend/tests/test_presets.py @@ -0,0 +1,51 @@ +"""Carga de YAML (criterio 7, parte de modelos) y errores de validación.""" + +import pytest +from pydantic import ValidationError + +from binaural.presets import Preset + +NOMBRES = {"relajacion", "estudio", "foco", "foco_intenso", "descanso"} + + +def test_cargan_los_cinco_presets(presets): + assert set(presets) == NOMBRES + + +def test_duraciones_de_la_tabla(presets): + esperado = {"relajacion": 20, "estudio": 30, "foco": 25, "foco_intenso": 20, "descanso": 15} + assert {n: p.duracion_min for n, p in presets.items()} == esperado + + +def test_rango_batido(presets): + assert presets["estudio"].rango_batido == (10, 14) + assert presets["descanso"].rango_batido == (9, 16) + + +def _base(**cambios) -> dict: + datos = { + "name": "x", + "description": "x", + "carrier_hz": 200, + "segments": [{"beat_hz": 10, "minutes": 5}], + } + datos.update(cambios) + return datos + + +@pytest.mark.parametrize( + ("cambios", "fragmento"), + [ + ({"carrier_hz": 1200}, "portadora"), + ({"carrier_hz": 50}, "portadora"), + ({"segments": [{"beat_hz": 0.5, "minutes": 5}]}, "batido"), + ({"segments": [{"beat_hz": 45, "minutes": 5}]}, "batido"), + ({"segments": [{"beat_hz": 10, "ramp_to_hz": 12, "minutes": 5}]}, "exactamente uno"), + ({"segments": [{"minutes": 5}]}, "exactamente uno"), + ({"segments": [{"ramp_to_hz": 12, "minutes": 5}]}, "primer segmento"), + ({"segments": [{"beat_hz": 10, "minutes": 70}]}, "supera el máximo"), + ], +) +def test_errores_de_validacion(cambios, fragmento): + with pytest.raises(ValidationError, match=fragmento): + Preset.model_validate(_base(**cambios)) diff --git a/backend/tests/test_session.py b/backend/tests/test_session.py new file mode 100644 index 0000000..8268210 --- /dev/null +++ b/backend/tests/test_session.py @@ -0,0 +1,40 @@ +"""Schedule: forma de los puntos, escalado proporcional y consistencia (criterio 6).""" + +import numpy as np +import pytest + +from binaural.session import f_inst, schedule_de_preset + + +def test_schedule_estudio_igual_al_brief(presets): + sch = schedule_de_preset(presets["estudio"]) + assert [(p.t, p.beat_hz) for p in sch.points] == [(0, 10), (300, 10), (900, 14), (1800, 14)] + assert sch.duration_s == 1800 + assert sch.carrier_hz == 220 + assert sch.noise == "rain" + assert sch.noise_db == -20 + assert sch.fade_s == 4 + assert sch.preroll_s == 1.5 + + +def test_escalado_proporcional(presets): + sch = schedule_de_preset(presets["estudio"], duracion_min=15) + assert [p.t for p in sch.points] == [0, 150, 450, 900] + assert [p.beat_hz for p in sch.points] == [10, 10, 14, 14] + assert sch.duration_s == 900 + + +def test_duracion_fuera_de_rango(presets): + with pytest.raises(ValueError, match="fuera de rango"): + schedule_de_preset(presets["foco"], duracion_min=61) + + +def test_consistencia_motores(presets): + """Criterio 6: interpolación lineal del schedule == f_inst, error < 1e-6 Hz.""" + for preset in presets.values(): + sch = schedule_de_preset(preset) + ts = np.array([p.t for p in sch.points]) + bs = np.array([p.beat_hz for p in sch.points]) + t = np.linspace(0.0, sch.duration_s, 20001) + referencia = np.interp(t, ts, bs) # lo que hace Web Audio con rampas lineales + assert np.max(np.abs(f_inst(sch, t) - referencia)) < 1e-6 diff --git a/backend/tests/test_synth.py b/backend/tests/test_synth.py new file mode 100644 index 0000000..6c72a1c --- /dev/null +++ b/backend/tests/test_synth.py @@ -0,0 +1,73 @@ +"""Síntesis: FFT por canal (1), sin clipping (2), rampas sin saltos (3), envolvente.""" + +import numpy as np + +from binaural.noise import generar_loop +from binaural.session import Punto, Schedule, schedule_de_preset +from binaural.synth import PICO_MAX, bloques_sesion, sesion_completa, total_muestras + +SR = 44100 + + +def _sch(pts, carrier=200.0, fade=0.0, preroll=0.0, noise="none", noise_db=-20.0) -> Schedule: + return Schedule( + carrier_hz=carrier, + fade_s=fade, + noise=noise, + noise_db=noise_db, + duration_s=pts[-1][0], + preroll_s=preroll, + points=[Punto(t=t, beat_hz=b) for t, b in pts], + ) + + +def test_fft_tono_fijo(): + """Criterio 1: pico L en carrier y R en carrier+beat, ±0.1 Hz (10 s de tono).""" + x = sesion_completa(_sch([(0, 10), (10, 10)], carrier=200), sr=SR) + assert x.shape == (441000, 2) + frecs = np.fft.rfftfreq(len(x), 1.0 / SR) + for canal, esperada in ((0, 200.0), (1, 210.0)): + pico = frecs[np.argmax(np.abs(np.fft.rfft(x[:, canal])))] + assert abs(pico - esperada) <= 0.1 + + +def test_sin_clipping_en_presets(presets): + """Criterio 2: |x| < 0.999 en todos los samples de los 5 presets.""" + for preset in presets.values(): + sch = schedule_de_preset(preset) + loop = generar_loop(preset.noise, SR) if preset.noise != "none" else None + pico = max(np.max(np.abs(b)) for b in bloques_sesion(sch, sr=SR, loop_ruido=loop)) + assert pico < 0.999 + assert pico <= PICO_MAX + 1e-9 # además respeta el techo de −3 dBFS + + +def test_rampa_sin_saltos(): + """Criterio 3: la rampa 10→20 Hz no salta más entre samples que un tono fijo.""" + rampa = sesion_completa(_sch([(0, 10), (60, 20)], carrier=400), sr=SR) + fija = sesion_completa(_sch([(0, 20), (60, 20)], carrier=400), sr=SR) + for canal in (0, 1): + salto_rampa = np.max(np.abs(np.diff(rampa[:, canal]))) + salto_fija = np.max(np.abs(np.diff(fija[:, canal]))) + assert salto_rampa <= salto_fija * 1.001 + + +def test_preroll_y_fades(): + sr = 8000 + sch = _sch([(0, 10), (30, 10)], fade=4.0, preroll=1.5) + x = sesion_completa(sch, sr=sr) + assert len(x) == total_muestras(sch, sr) == round(31.5 * sr) + n_pre = round(1.5 * sr) + assert np.all(x[:n_pre] == 0) # pre-roll en silencio absoluto + assert np.max(np.abs(x[-4:])) < 1e-3 # el fade-out muere en ~0 + assert np.max(np.abs(x)) > 0.4 # y en medio sí hay señal + + +def test_bloques_equivalen_a_render_completo(): + """La generación por bloques equivale al render directo a nivel de audio.""" + sch = _sch([(0, 10), (12, 16)], fade=2.0, preroll=1.5) + entero = sesion_completa(sch, sr=8000) + por_bloques = np.concatenate(list(bloques_sesion(sch, sr=8000, muestras_bloque=1000))) + assert entero.shape == por_bloques.shape + # El envolvimiento de fase (% 2π) cae en fronteras distintas según el + # tamaño de bloque: tolerancia 1e-7, tres órdenes bajo el LSB de 16-bit. + assert np.allclose(entero, por_bloques, atol=1e-7)