# BLOQUE 3: Mapeo de Hardware MIDI & Sensores (T166-T180)

## Resumen Ejecutivo

Módulo completo de integración de hardware MIDI para control en vivo, incluyendo:
- Mapeo de controladores (Xone:K2, APC40, Pioneer DDJ)
- Callbacks asíncronos para filtros
- Sincronización MIDI Clock
- Feedback luminoso
- Modo Performance
- Detección de silencio
- Y más...

---

## T166: Mapeo de Hardware

### Controladores Soportados

#### 1. Allen & Heath Xone:K2

| Control | CC | Canal | Función Asignada |
|---------|-----|-------|------------------|
| Knob 1 (Filter High) | 1 | 0 | Filter High para Music Bus |
| Knob 2 (Filter Mid) | 2 | 0 | Filter Mid para Music Bus |
| Knob 3 (Filter Low) | 3 | 0 | Filter Low para Music Bus |
| Knob 4 | 4 | 0 | Gain Staging |
| Knob 5 | 5 | 0 | Humanize Amount |
| Knob 6 | 6 | 0 | Sidechain Amount (Bass Bus) |
| Knob 7 | 7 | 0 | Reverb Send |
| Knob 8 | 8 | 0 | Delay Send |
| Fader 1 | 11 | 0 | Drums Bus Volume |
| Fader 2 | 12 | 0 | Bass Bus Volume |
| Fader 3 | 13 | 0 | Music Bus Volume |
| Fader 4 | 14 | 0 | FX Bus Volume |
| Master Fader | 15 | 0 | Master Volume |

**Pads (Notas MIDI):**

| Pad | Nota | Canal | Función |
|-----|------|-------|---------|
| Scene 1 | 32 | 0 | Fire Scene 1 |
| Scene 2 | 33 | 0 | Fire Scene 2 |
| Scene 3 | 34 | 0 | Fire Scene 3 |
| Scene 4 | 35 | 0 | Fire Scene 4 |
| Panic | 36 | 0 | Botón de Pánico |
| Fill Trigger | 37 | 0 | Disparar Fill |
| Backup Track | 38 | 0 | Toggle Track Backup |
| Performance Mode | 39 | 0 | Toggle Performance Mode |
| Pads 1-8 | 40-47 | 1 | Drum Pads (Fills) |

#### 2. AKAI APC40 MKII

| Control | CC | Canal | Función |
|---------|-----|-------|---------|
| Master Fader | 14 | 0 | Master Volume |
| Fader 1-4 | 48-51 | 0 | Bus Volumes |
| Knob 1-4 (Device) | 16-19 | 0 | Device Macros |
| Knob 5-8 (Send) | 20-23 | 0 | Humanize/Sidechain/Reverb/Delay |

**Pads de Clip (5x8 matrix):**
- Notas 53-89 en canales 0-7
- Cada pad puede disparar clips o funciones especiales

**Botones de Scene:**
- Notas 82-85 para lanzar scenes 1-4

#### 3. Pioneer DDJ (Mapeo Estándar)

| Control | CC | Canal | Función |
|---------|-----|-------|---------|
| CH1 Fader | 2 | 0 | Drums Bus |
| CH2 Fader | 3 | 0 | Bass Bus |
| CH3 Fader | 4 | 0 | Music Bus |
| CH4 Fader | 5 | 0 | Vocals/FX Bus |
| Master | 6 | 0 | Master Volume |
| Crossfader | 8 | 0 | Crossfade entre A/B |
| EQ High/Mid/Low CH1 | 10-12 | 0 | EQ Drums Bus |
| EQ High/Mid/Low CH2 | 13-15 | 0 | EQ Bass Bus |
| Filter CH1 | 20 | 0 | Filter Drums |
| Filter CH2 | 21 | 0 | Filter Bass |

---

## T167: Ligadura Asíncrona de Filtros

```python
# Ejemplo de uso
bind_filter_to_bus_async(
    filter_cc=1,        # CC del knob de filtro
    bus_name="music_bus",  # Bus objetivo
    hardware_type="xone_k2"
)
```

**Parámetros de Smoothing:**
- Smoothing: 0.1 (10% por paso)
- Respuesta: Suave para evitar saltos bruscos

---

## T168: Monitor de Pista

```python
toggle_track_monitor(track_index=0)  # Toggle monitor track 0
```

---

## T169: MIDI Clock Sync

**Configuración:**
- PPQN: 24 pulsos por negra
- Rango BPM: 60-200
- Smoothing: 0.3 (suavizado de tempo)

```python
start_midi_clock_sync()  # Inicia sync
stop_midi_clock_sync()   # Detiene sync
```

---

## T170: Gain Staging desde Fader

**Mapeo CC a LUFS:**

| CC Value | LUFS Target | Rango |
|----------|-------------|-------|
| 0-63 | -23 a -14 | Streaming |
| 64-127 | -14 a -8 | Club |

```python
update_gain_staging_from_fader(cc_value=100)  # Target: ~-10.6 LUFS
```

---

## T171: Fills desde Pads

**Mapeo de Pads a Fills:**

| Pad | Fill Type | Density | Section |
|-----|-----------|---------|---------|
| 1 | fill_1 | sparse | drop |
| 2 | fill_2 | medium | build |
| 3 | fill_3 | heavy | drop |
| 4 | fill_4 | sparse | break |

```python
trigger_fill_from_pad(pad_number=1)  # Dispara fill tipo sparse
```

---

## T172: Botón de Pánico

**Efectos Afectados:**
- music_bus: Reverb send -> 0%
- vocal_bus: Delay send -> 0%
- atmos_bus: Todos los sends -> 0%

```python
trigger_panic_button()   # Activa pánico
release_panic_button() # Restaura gradualmente
```

---

## T173: Feedback Luminoso

**Colores LED (APC40):**
- 0: Off
- 1: Green
- 2: Green Blink
- 3: Red
- 4: Red Blink
- 5: Yellow
- 6: Yellow Blink
- 7: Orange

**Patrones:**
- Export Active: Secuencial blink 2 segundos
- Scene Active: Verde fijo
- Panic: Rojo blink

---

## T174: CPU Monitoring

**Configuración:**
- Intervalo: 500ms (default)
- Display: LED ring del knob master
- Escala: 0-100% -> CC 0-127

```python
start_cpu_monitoring(interval_ms=500)
```

---

## T175: Scene Trigger con Quantización

**Modos de Quantización:**

| Modo | Beats | Uso |
|------|-------|-----|
| none | 0 | Inmediato |
| 8th | 0.5 | Rápido |
| 4th | 1.0 | Precisión |
| 2nd | 2.0 | Medio compás |
| 1bar | 4.0 | Standard |
| 2bar | 8.0 | Largo |

```python
trigger_scene_from_hardware(scene_index=0, quantization="1bar")
```

---

## T176: Performance Mode

**Layouts Disponibles:**

### Default
- Fader 1: Drums Bus
- Fader 2: Bass Bus
- Fader 3: Music Bus
- Fader 4: Master

### DJ
- Fader 1: Deck A
- Fader 2: Deck B
- Fader 3: FX Bus
- Fader 4: Master

### Live
- Fader 1: Kick
- Fader 2: Snare
- Fader 3: Synth
- Fader 4: Vocals

```python
activate_performance_mode(layout="default")
```

---

## T177: Humanize Macro

**Mapeo Intensidad:**

| CC | Intensidad | Nivel |
|----|-----------|-------|
| 0-38 | 0.0-0.3 | Subtle |
| 39-76 | 0.3-0.6 | Medium |
| 77-127 | 0.6-1.0 | Extreme |

```python
update_humanize_from_knob(cc_value=64)  # ~50% intensity
```

---

## T178: Detección de Silencio

**Parámetros:**
- Threshold: -60 dB (default)
- Duration: 3000 ms (default)
- Action: Auto-trigger backup track

```python
start_silence_detection(threshold_db=-60.0, duration_ms=3000)
```

---

## T179: Nudging Asíncrono

**Precisión:**
- 1 ms = 48 samples @ 48kHz
- 5 ms = 240 samples

```python
apply_nudge_forward(ms=5.0)   # Acelera 5ms
apply_nudge_backward(ms=3.0)  # Atrasa 3ms
```

---

## T180: Macros de Visualización

**Disponibles:**

| Macro | Descripción |
|-------|-------------|
| strobe_beat | Strobe rojo sync con beat |
| level_meter | Medidor de nivel en LEDs |
| peak_indicator | Parpadeo rojo rápido |
| recording_active | LED lento parpadeante |
| midi_clock_sync | LED verde fijo |

```python
trigger_visualization_macro("strobe_beat")
```

---

## API MCP Disponible

### Herramientas Exports

```python
# T166
ableton_mcp_ai_get_hardware_mapping(hardware_type: str)

# T167
ableton_mcp_ai_bind_filter_to_bus(filter_cc: int, bus_name: str, hardware_type: str)

# T168
ableton_mcp_ai_toggle_track_monitor(track_index: int)

# T169
ableton_mcp_ai_start_midi_clock_sync()
ableton_mcp_ai_stop_midi_clock_sync()

# T170
ableton_mcp_ai_update_gain_staging(cc_value: int)

# T171
ableton_mcp_ai_trigger_fill_from_pad(pad_number: int)

# T172
ableton_mcp_ai_trigger_panic()
ableton_mcp_ai_release_panic()

# T173
ableton_mcp_ai_indicate_export()

# T174
ableton_mcp_ai_start_cpu_monitoring(interval_ms: int)
ableton_mcp_ai_stop_cpu_monitoring()

# T175
ableton_mcp_ai_trigger_scene_hardware(scene_index: int, quantization: str)
ableton_mcp_ai_set_scene_quantization(mode: str)

# T176
ableton_mcp_ai_activate_performance_mode(layout: str)
ableton_mcp_ai_deactivate_performance_mode()

# T177
ableton_mcp_ai_update_humanize_macro(cc_value: int)

# T178
ableton_mcp_ai_start_silence_detection(threshold_db: float, duration_ms: int)
ableton_mcp_ai_stop_silence_detection()

# T179
ableton_mcp_ai_apply_nudge_forward(ms: float)
ableton_mcp_ai_apply_nudge_backward(ms: float)

# T180
ableton_mcp_ai_trigger_visualization_macro(macro_name: str)

# Status completo
ableton_mcp_ai_get_hardware_status()
```

---

## Archivos del Bloque 3

| Archivo | Descripción |
|---------|-------------|
| `hardware_integration.py` | Módulo principal (1100+ líneas) |
| `tests/test_hardware_integration.py` | Test suite completo |
| `docs/HARDWARE_MAPEO.md` | Esta documentación |

---

## Estado de Implementación

| Tarea | Estado | Cobertura |
|-------|--------|-----------|
| T166 | ✅ Completado | 3 controladores mapeados |
| T167 | ✅ Completado | Async filter bindings |
| T168 | ✅ Completado | Track monitor toggle |
| T169 | ✅ Completado | MIDI Clock sync |
| T170 | ✅ Completado | Gain staging fader |
| T171 | ✅ Completado | Drum pad fills |
| T172 | ✅ Completado | Panic button |
| T173 | ✅ Completado | LED feedback |
| T174 | ✅ Completado | CPU monitoring |
| T175 | ✅ Completado | Scene quantization |
| T176 | ✅ Completado | Performance mode |
| T177 | ✅ Completado | Humanize macro |
| T178 | ✅ Completado | Silence detection |
| T179 | ✅ Completado | Async nudging |
| T180 | ✅ Completado | Visualization macros |

**Total: 15/15 tareas completadas**

---

## Uso Ejemplo

```python
# 1. Inicializar hardware
ableton_mcp_ai_get_hardware_mapping("xone_k2")

# 2. Activar performance mode
ableton_mcp_ai_activate_performance_mode("default")

# 3. Configurar sync MIDI
ableton_mcp_ai_start_midi_clock_sync()

# 4. Monitorear CPU
ableton_mcp_ai_start_cpu_monitoring(500)

# 5. Listo para live performance!
```

---

## Notas Técnicas

### Dependencias
- `mido`: Opcional, para I/O MIDI real
- Sin dependencias obligatorias para funcionamiento simulado

### Thread Safety
- Todos los controladores usan locks (threading/asyncio)
- Callbacks asíncronos para operaciones en tiempo real
- No bloquea el hilo principal

### Integración Live
- Los callbacks están preparados para conectar con Ableton Live API
- Señales MIDI se pueden mapear a funciones de Live vía Remote Script

---

**Documentación generada: 2026-04-08**
**Versión: 1.0.0**
**Módulo: AbletonMCP-AI Hardware Integration**
