1use crate::Curve;
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6use std::collections::HashMap;
7use std::path::{Path, PathBuf};
8
9#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
11#[serde(deny_unknown_fields)]
12pub struct InlineMeasurement {
13 #[serde(default, skip_serializing_if = "Vec::is_empty")]
15 pub frequencies: Vec<f64>,
16 #[serde(default, skip_serializing_if = "Vec::is_empty")]
18 pub magnitude_db: Vec<f64>,
19 #[serde(default, skip_serializing_if = "Option::is_none")]
21 pub phase_deg: Option<Vec<f64>>,
22 #[serde(default, skip_serializing_if = "Option::is_none")]
24 pub name: Option<String>,
25 #[serde(default, skip_serializing_if = "Option::is_none")]
27 pub wav_path: Option<String>,
28 #[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#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
52#[serde(untagged)]
53pub enum MeasurementRef {
54 Inline(InlineMeasurement),
56 Named {
58 path: PathBuf,
60 #[serde(skip_serializing_if = "Option::is_none")]
62 name: Option<String>,
63 },
64 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#[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#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
191pub struct MeasurementMultiple {
192 pub measurements: Vec<MeasurementRef>,
193 #[serde(default, skip_serializing_if = "Option::is_none")]
195 pub speaker_name: Option<String>,
196}
197
198#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
200#[serde(untagged)]
201pub enum MeasurementSource {
202 Single(MeasurementSingle),
204 Multiple(MeasurementMultiple),
206 #[serde(skip)]
209 InMemory(Curve),
210 #[serde(skip)]
211 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 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#[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}