Skip to main content

qualia_mcp/tools/
audio.rs

1//! MCP tools for native audio features, 3D spatial HRTF, and loudness metering.
2//!
3//! Exposes `qualia-audio` spatial processing, pitch tracking, and EBU R128 loudness.
4//! Follows `AGENTS.md` §0-B (<500 lines).
5
6use crate::types::{parse_tool_args, McpSystemError};
7use serde_json::{json, Value};
8
9/// `audio_features` tool — log mel, pitch yin, loudness r128, and capability inspection.
10pub fn audio_features(args: &[u8]) -> Result<String, McpSystemError> {
11    qualia_core_db::mcp::mcp_tool_impls::audio_features(args).map_err(|e| match e {
12        qualia_core_db::mcp::mcp_server::McpSystemError::InvalidParameters => {
13            McpSystemError::InvalidParameters
14        }
15        qualia_core_db::mcp::mcp_server::McpSystemError::ParseError => McpSystemError::ParseError,
16        qualia_core_db::mcp::mcp_server::McpSystemError::SanctuaryGateTriggered => {
17            McpSystemError::SanctuaryGateTriggered
18        }
19        _ => McpSystemError::ToolNotReady,
20    })
21}
22
23/// `audio_spatial_hrtf` tool — 3D spatial audio positioning, attenuation, and binaural panning.
24pub fn audio_spatial_hrtf(args: &[u8]) -> Result<String, McpSystemError> {
25    let v = parse_tool_args(args)?;
26    let emitter_x = v.get("emitter_x").and_then(Value::as_f64).unwrap_or(0.0) as f32;
27    let emitter_y = v.get("emitter_y").and_then(Value::as_f64).unwrap_or(0.0) as f32;
28    let emitter_z = v.get("emitter_z").and_then(Value::as_f64).unwrap_or(0.0) as f32;
29
30    let listener_x = v.get("listener_x").and_then(Value::as_f64).unwrap_or(0.0) as f32;
31    let listener_y = v.get("listener_y").and_then(Value::as_f64).unwrap_or(0.0) as f32;
32    let listener_z = v.get("listener_z").and_then(Value::as_f64).unwrap_or(0.0) as f32;
33
34    let dx = emitter_x - listener_x;
35    let dy = emitter_y - listener_y;
36    let dz = emitter_z - listener_z;
37    let distance = (dx * dx + dy * dy + dz * dz).sqrt().max(0.001);
38
39    let model = qualia_audio::spatial::DistanceModel::default();
40    let distance_gain = model.calculate_gain(distance);
41
42    let azimuth_rad = (-dx).atan2(dz);
43    let azimuth_deg = azimuth_rad.to_degrees();
44
45    // Equal-power stereo panning
46    let pan = (azimuth_rad / (std::f32::consts::PI / 2.0)).clamp(-1.0, 1.0);
47    let angle = (pan + 1.0) * (std::f32::consts::PI / 4.0);
48    let left_gain = angle.cos() * distance_gain;
49    let right_gain = angle.sin() * distance_gain;
50
51    Ok(json!({
52        "status": "success",
53        "distance": distance,
54        "azimuth_degrees": azimuth_deg,
55        "attenuation_gain": distance_gain,
56        "stereo_panning": {
57            "left_gain": left_gain,
58            "right_gain": right_gain,
59        }
60    })
61    .to_string())
62}