Skip to main content

autoeq_core/
measurement_contracts.rs

1//! I/O-free measurement descriptors shared by model and loader crates.
2
3use crate::Curve;
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6use std::collections::HashMap;
7use std::path::{Path, PathBuf};
8
9/// Inline measurement data (frequencies, SPL, phase)
10#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
11#[serde(deny_unknown_fields)]
12pub struct InlineMeasurement {
13    /// Frequency points in Hz
14    #[serde(default, skip_serializing_if = "Vec::is_empty")]
15    pub frequencies: Vec<f64>,
16    /// Sound Pressure Level in dB
17    #[serde(default, skip_serializing_if = "Vec::is_empty")]
18    pub magnitude_db: Vec<f64>,
19    /// Phase in degrees (optional)
20    #[serde(default, skip_serializing_if = "Option::is_none")]
21    pub phase_deg: Option<Vec<f64>>,
22    /// Optional display name
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub name: Option<String>,
25    /// Optional path to associated WAV file
26    #[serde(default, skip_serializing_if = "Option::is_none")]
27    pub wav_path: Option<String>,
28    /// Optional path to associated CSV file
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    pub csv_path: Option<String>,
31}
32
33impl InlineMeasurement {
34    pub fn resolve_paths(&mut self, base_dir: &Path) {
35        if let Some(csv_path) = &self.csv_path {
36            let path = PathBuf::from(csv_path);
37            if path.is_relative() {
38                self.csv_path = Some(base_dir.join(path).to_string_lossy().into_owned());
39            }
40        }
41        if let Some(wav_path) = &self.wav_path {
42            let path = PathBuf::from(wav_path);
43            if path.is_relative() {
44                self.wav_path = Some(base_dir.join(path).to_string_lossy().into_owned());
45            }
46        }
47    }
48}
49
50/// Reference to a measurement file
51#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
52#[serde(untagged)]
53pub enum MeasurementRef {
54    /// Inline measurement data (stored directly in JSON)
55    Inline(InlineMeasurement),
56    /// Named measurement with optional metadata
57    Named {
58        /// Path to the CSV measurement file.
59        path: PathBuf,
60        /// Optional display name for the measurement.
61        #[serde(skip_serializing_if = "Option::is_none")]
62        name: Option<String>,
63    },
64    /// Path to CSV file (freq, spl, phase columns)
65    Path(PathBuf),
66}
67
68impl MeasurementRef {
69    pub fn path(&self) -> Option<&PathBuf> {
70        match self {
71            Self::Path(path) | Self::Named { path, .. } => Some(path),
72            Self::Inline(_) => None,
73        }
74    }
75
76    pub fn name(&self) -> Option<&str> {
77        match self {
78            Self::Path(_) => None,
79            Self::Named { name, .. } => name.as_deref(),
80            Self::Inline(inline) => inline.name.as_deref(),
81        }
82    }
83
84    pub fn is_inline(&self) -> bool {
85        matches!(self, Self::Inline(_))
86    }
87
88    pub fn inline_data(&self) -> Option<&InlineMeasurement> {
89        match self {
90            Self::Inline(data) => Some(data),
91            _ => None,
92        }
93    }
94
95    pub fn resolve_paths(&mut self, base_dir: &Path) {
96        match self {
97            Self::Path(path) | Self::Named { path, .. } if path.is_relative() => {
98                *path = base_dir.join(&*path);
99            }
100            Self::Inline(inline) => inline.resolve_paths(base_dir),
101            _ => {}
102        }
103    }
104}
105
106/// Single measurement with metadata
107///
108/// Custom implementation to support both string path and object with speaker_name
109#[derive(Debug, Clone, JsonSchema)]
110pub struct MeasurementSingle {
111    pub measurement: MeasurementRef,
112    pub speaker_name: Option<String>,
113}
114
115impl Serialize for MeasurementSingle {
116    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
117    where
118        S: serde::Serializer,
119    {
120        if self.speaker_name.is_none() {
121            return self.measurement.serialize(serializer);
122        }
123        use serde::ser::SerializeMap;
124        let mut map = serializer.serialize_map(None)?;
125        match &self.measurement {
126            MeasurementRef::Path(path) => map.serialize_entry("path", path)?,
127            MeasurementRef::Named { path, name } => {
128                map.serialize_entry("path", path)?;
129                if let Some(name) = name {
130                    map.serialize_entry("name", name)?;
131                }
132            }
133            MeasurementRef::Inline(inline) => map.serialize_entry("inline", inline)?,
134        }
135        map.serialize_entry("speaker_name", &self.speaker_name)?;
136        map.end()
137    }
138}
139
140impl<'de> Deserialize<'de> for MeasurementSingle {
141    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
142    where
143        D: serde::Deserializer<'de>,
144    {
145        #[derive(Deserialize)]
146        struct Helper {
147            path: Option<PathBuf>,
148            name: Option<String>,
149            inline: Option<InlineMeasurement>,
150            speaker_name: Option<String>,
151        }
152
153        let value = serde_json::Value::deserialize(deserializer)?;
154        if let Some(path) = value.as_str() {
155            return Ok(Self {
156                measurement: MeasurementRef::Path(path.into()),
157                speaker_name: None,
158            });
159        }
160        if let Ok(helper) = serde_json::from_value::<Helper>(value.clone()) {
161            if let Some(inline) = helper.inline {
162                return Ok(Self {
163                    measurement: MeasurementRef::Inline(inline),
164                    speaker_name: helper.speaker_name,
165                });
166            }
167            if let Some(path) = helper.path {
168                let measurement = match helper.name {
169                    Some(name) => MeasurementRef::Named {
170                        path,
171                        name: Some(name),
172                    },
173                    None => MeasurementRef::Path(path),
174                };
175                return Ok(Self {
176                    measurement,
177                    speaker_name: helper.speaker_name,
178                });
179            }
180        }
181        let measurement = serde_json::from_value(value).map_err(serde::de::Error::custom)?;
182        Ok(Self {
183            measurement,
184            speaker_name: None,
185        })
186    }
187}
188
189/// Multiple measurements with metadata
190#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
191pub struct MeasurementMultiple {
192    pub measurements: Vec<MeasurementRef>,
193    /// Optional speaker name (e.g., "Genelec 8361A")
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub speaker_name: Option<String>,
196}
197
198/// Source of measurements (single file, multiple files for averaging, or in-memory curve)
199#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
200#[serde(untagged)]
201pub enum MeasurementSource {
202    /// A single measurement file with optional speaker name
203    Single(MeasurementSingle),
204    /// Multiple measurement files to be averaged with optional speaker name
205    Multiple(MeasurementMultiple),
206    /// In-memory curve data (not serializable to JSON config files).
207    /// Use this when curves are already loaded in memory.
208    #[serde(skip)]
209    InMemory(Curve),
210    #[serde(skip)]
211    /// Multiple in-memory curves (e.g., multi-mic recordings).
212    /// Not serializable — use for GPUI in-memory data.
213    InMemoryMultiple(Vec<Curve>),
214}
215
216impl MeasurementSource {
217    pub fn speaker_name(&self) -> Option<&str> {
218        match self {
219            Self::Single(single) => single.speaker_name.as_deref(),
220            Self::Multiple(multiple) => multiple.speaker_name.as_deref(),
221            Self::InMemory(_) | Self::InMemoryMultiple(_) => None,
222        }
223    }
224
225    /// Associated recording WAV path, when the source carries inline data.
226    ///
227    /// Multi-measurement sources retain the historical convention of using the
228    /// first position's recording for channel-level arrival and SSIR analysis.
229    pub fn wav_path(&self) -> Option<&str> {
230        let measurement = match self {
231            Self::Single(single) => &single.measurement,
232            Self::Multiple(multiple) => multiple.measurements.first()?,
233            Self::InMemory(_) | Self::InMemoryMultiple(_) => return None,
234        };
235        measurement.inline_data()?.wav_path.as_deref()
236    }
237
238    pub fn resolve_paths(&mut self, base_dir: &Path) {
239        match self {
240            Self::Single(single) => single.measurement.resolve_paths(base_dir),
241            Self::Multiple(multiple) => {
242                for measurement in &mut multiple.measurements {
243                    measurement.resolve_paths(base_dir);
244                }
245            }
246            Self::InMemory(_) | Self::InMemoryMultiple(_) => {}
247        }
248    }
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254
255    fn inline(wav_path: Option<&str>) -> MeasurementRef {
256        MeasurementRef::Inline(InlineMeasurement {
257            frequencies: vec![100.0],
258            magnitude_db: vec![80.0],
259            phase_deg: None,
260            name: None,
261            wav_path: wav_path.map(String::from),
262            csv_path: None,
263        })
264    }
265
266    #[test]
267    fn measurement_source_wav_path_uses_single_or_first_position() {
268        let single = MeasurementSource::Single(MeasurementSingle {
269            measurement: inline(Some("single.wav")),
270            speaker_name: None,
271        });
272        assert_eq!(single.wav_path(), Some("single.wav"));
273
274        let multiple = MeasurementSource::Multiple(MeasurementMultiple {
275            measurements: vec![inline(Some("first.wav")), inline(Some("second.wav"))],
276            speaker_name: None,
277        });
278        assert_eq!(multiple.wav_path(), Some("first.wav"));
279        assert!(
280            MeasurementSource::InMemory(Curve::default())
281                .wav_path()
282                .is_none()
283        );
284    }
285}
286
287/// I/O-free CEA2034 / Spinorama curve bundle.
288#[derive(Debug, Clone)]
289pub struct SpinoramaBundle {
290    pub on_axis: Curve,
291    pub listening_window: Curve,
292    pub early_reflections: Curve,
293    pub sound_power: Curve,
294    pub estimated_in_room: Curve,
295    pub er_di: Curve,
296    pub sp_di: Curve,
297    pub curves: HashMap<String, Curve>,
298}
299
300impl SpinoramaBundle {
301    pub fn pir(&self) -> &Curve {
302        &self.estimated_in_room
303    }
304}