Skip to main content

yaiko_core/
waveform_serialization.rs

1//! Bounded waveform serialization for media-editor clients.
2
3use serde::Serialize;
4
5#[derive(Debug, Clone, PartialEq, Eq)]
6pub enum WaveformSerializationError {
7    Empty,
8    TooManySamples,
9    InvalidAmplitude,
10    InvalidChapter,
11    MetadataTooLarge,
12}
13
14#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
15pub struct WaveformChapter {
16    pub at_ms: u64,
17    pub label: String,
18}
19
20#[derive(Debug, Clone, PartialEq, Serialize)]
21struct WireWaveform<'a> {
22    samples: &'a [u16],
23    duration_ms: u64,
24    chapters: &'a [WaveformChapter],
25}
26
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct SerializedWaveform {
29    pub json: String,
30    pub sample_count: usize,
31    pub duration_ms: u64,
32}
33
34pub fn serialize_waveform(
35    samples: &[f32],
36    duration_ms: u64,
37    chapters: &[WaveformChapter],
38    max_samples: usize,
39    max_bytes: usize,
40) -> Result<SerializedWaveform, WaveformSerializationError> {
41    if samples.is_empty() || duration_ms == 0 {
42        return Err(WaveformSerializationError::Empty);
43    }
44    if samples.len() > max_samples || max_samples == 0 {
45        return Err(WaveformSerializationError::TooManySamples);
46    }
47    if chapters.iter().any(|chapter| {
48        chapter.at_ms > duration_ms
49            || chapter.label.is_empty()
50            || chapter.label.len() > 128
51            || chapter.label.chars().any(|c| c.is_control())
52    }) {
53        return Err(WaveformSerializationError::InvalidChapter);
54    }
55    let quantized = samples
56        .iter()
57        .map(|sample| {
58            if !sample.is_finite() || !(-1.0..=1.0).contains(sample) {
59                return Err(WaveformSerializationError::InvalidAmplitude);
60            }
61            Ok(((sample.abs() * 65535.0).round()) as u16)
62        })
63        .collect::<Result<Vec<_>, _>>()?;
64    let wire = WireWaveform {
65        samples: &quantized,
66        duration_ms,
67        chapters,
68    };
69    let json =
70        serde_json::to_string(&wire).map_err(|_| WaveformSerializationError::MetadataTooLarge)?;
71    if json.len() > max_bytes || max_bytes == 0 {
72        return Err(WaveformSerializationError::MetadataTooLarge);
73    }
74    Ok(SerializedWaveform {
75        json,
76        sample_count: samples.len(),
77        duration_ms,
78    })
79}
80
81#[cfg(test)]
82mod tests {
83    use super::*;
84    #[test]
85    fn serializes_deterministic_quantized_waveform() {
86        let chapters = vec![WaveformChapter {
87            at_ms: 0,
88            label: "intro".into(),
89        }];
90        let a = serialize_waveform(&[-1.0, 0.5, 0.0], 1000, &chapters, 10, 1024).unwrap();
91        let b = serialize_waveform(&[-1.0, 0.5, 0.0], 1000, &chapters, 10, 1024).unwrap();
92        assert_eq!(a, b);
93        assert!(a.json.contains("65535"));
94        assert_eq!(a.sample_count, 3);
95    }
96    #[test]
97    fn rejects_invalid_samples_chapters_and_bounds() {
98        assert_eq!(
99            serialize_waveform(&[], 1000, &[], 10, 1024),
100            Err(WaveformSerializationError::Empty)
101        );
102        assert_eq!(
103            serialize_waveform(&[f32::NAN], 1000, &[], 10, 1024),
104            Err(WaveformSerializationError::InvalidAmplitude)
105        );
106        assert_eq!(
107            serialize_waveform(&[2.0], 1000, &[], 10, 1024),
108            Err(WaveformSerializationError::InvalidAmplitude)
109        );
110        assert_eq!(
111            serialize_waveform(
112                &[0.5],
113                1000,
114                &[WaveformChapter {
115                    at_ms: 1001,
116                    label: "bad".into()
117                }],
118                10,
119                1024
120            ),
121            Err(WaveformSerializationError::InvalidChapter)
122        );
123        assert_eq!(
124            serialize_waveform(&[0.5; 11], 1000, &[], 10, 1024),
125            Err(WaveformSerializationError::TooManySamples)
126        );
127    }
128}