Skip to main content

alpha2_plugin_abi/
records.rs

1//! Emit records, which a plugin passes to `emit` one batch per call.
2//!
3//! A batch is records back to back. Each record is an 8-byte header (`u8` tag, `u8` 0, `u16`
4//! output index in the descriptor's `outputs`, `u32` body length) and its body. Integers and floats
5//! are little-endian and unaligned.
6
7use alloc::string::String;
8use alloc::vec::Vec;
9use core::fmt;
10
11/// Header tag of a [`Record::Sample`].
12pub const SAMPLE: u8 = 1;
13/// Header tag of a [`Record::Word`].
14pub const WORD: u8 = 2;
15/// Header tag of a [`Record::Interval`].
16pub const INTERVAL: u8 = 3;
17
18/// Length of a text field that is absent.
19const ABSENT: u32 = u32::MAX;
20
21/// One emitted value, by output index.
22#[derive(Clone, Debug, PartialEq)]
23pub enum Record {
24    /// A sample of a `points`, `scalars` or `similarity` output; `None` is a lost channel.
25    Sample {
26        /// Index in the descriptor's `outputs`.
27        output: u16,
28        /// Ticks on the input's clock.
29        time: i64,
30        /// One per channel component.
31        values: Vec<Option<f32>>,
32    },
33    /// A word of a `words` output.
34    Word {
35        /// Index in the descriptor's `outputs`.
36        output: u16,
37        /// Ticks on the input's clock.
38        start: i64,
39        /// Ticks on the input's clock.
40        end: i64,
41        /// The word.
42        text: String,
43        /// Who said it.
44        speaker: Option<String>,
45    },
46    /// An interval of an `intervals` output.
47    Interval {
48        /// Index in the descriptor's `outputs`.
49        output: u16,
50        /// Ticks on the input's clock.
51        start: i64,
52        /// Ticks on the input's clock.
53        end: i64,
54        /// What the interval is.
55        label: Option<String>,
56        /// How sure the extractor is.
57        score: Option<f32>,
58    },
59}
60
61impl Record {
62    /// Index in the descriptor's `outputs`.
63    #[must_use]
64    pub const fn output(&self) -> u16 {
65        match self {
66            Self::Sample { output, .. }
67            | Self::Word { output, .. }
68            | Self::Interval { output, .. } => *output,
69        }
70    }
71}
72
73/// Why a batch could not be read.
74#[derive(Clone, Debug, PartialEq, Eq)]
75pub struct RecordError {
76    /// Index of the record that could not be read.
77    pub index: usize,
78    /// What is wrong with it.
79    pub reason: &'static str,
80}
81
82impl fmt::Display for RecordError {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        write!(f, "record {}: {}", self.index, self.reason)
85    }
86}
87
88impl core::error::Error for RecordError {}
89
90/// Appends `record` to `out`.
91///
92/// # Panics
93/// When a body or a text is longer than `u32::MAX` bytes.
94pub fn encode(record: &Record, out: &mut Vec<u8>) {
95    let header = out.len();
96    let tag = match record {
97        Record::Sample { .. } => SAMPLE,
98        Record::Word { .. } => WORD,
99        Record::Interval { .. } => INTERVAL,
100    };
101    out.extend_from_slice(&[tag, 0]);
102    out.extend_from_slice(&record.output().to_le_bytes());
103    out.extend_from_slice(&[0; 4]);
104    let body = out.len();
105    match record {
106        Record::Sample { time, values, .. } => {
107            out.extend_from_slice(&time.to_le_bytes());
108            out.extend_from_slice(&length(values.len()).to_le_bytes());
109            for word in values.chunks(32) {
110                let lost = word
111                    .iter()
112                    .enumerate()
113                    .filter(|(_, value)| value.is_none())
114                    .fold(0_u32, |mask, (bit, _)| mask | 1 << bit);
115                out.extend_from_slice(&lost.to_le_bytes());
116            }
117            for value in values {
118                out.extend_from_slice(&value.unwrap_or(0.0).to_le_bytes());
119            }
120        }
121        Record::Word {
122            start,
123            end,
124            text,
125            speaker,
126            ..
127        } => {
128            out.extend_from_slice(&start.to_le_bytes());
129            out.extend_from_slice(&end.to_le_bytes());
130            out.extend_from_slice(&length(text.len()).to_le_bytes());
131            out.extend_from_slice(&optional_length(speaker.as_deref()).to_le_bytes());
132            out.extend_from_slice(text.as_bytes());
133            out.extend_from_slice(speaker.as_deref().unwrap_or_default().as_bytes());
134        }
135        Record::Interval {
136            start,
137            end,
138            label,
139            score,
140            ..
141        } => {
142            out.extend_from_slice(&start.to_le_bytes());
143            out.extend_from_slice(&end.to_le_bytes());
144            out.extend_from_slice(&u32::from(score.is_some()).to_le_bytes());
145            out.extend_from_slice(&score.unwrap_or(0.0).to_le_bytes());
146            out.extend_from_slice(&optional_length(label.as_deref()).to_le_bytes());
147            out.extend_from_slice(label.as_deref().unwrap_or_default().as_bytes());
148        }
149    }
150    let size = length(out.len() - body).to_le_bytes();
151    out[header + 4..header + 8].copy_from_slice(&size);
152}
153
154fn length(len: usize) -> u32 {
155    u32::try_from(len)
156        .ok()
157        .filter(|len| *len != ABSENT)
158        .expect("record field too long")
159}
160
161fn optional_length(text: Option<&str>) -> u32 {
162    text.map_or(ABSENT, |text| length(text.len()))
163}
164
165/// Bounds on one record, checked before anything is allocated for it.
166#[derive(Clone, Copy, Debug, PartialEq, Eq)]
167pub struct Limits {
168    /// The most values one sample may carry.
169    pub max_values: usize,
170    /// The most bytes one text may have.
171    pub max_text_bytes: usize,
172}
173
174impl Limits {
175    /// No bound beyond the batch's own length.
176    pub const NONE: Self = Self {
177        max_values: usize::MAX,
178        max_text_bytes: usize::MAX,
179    };
180}
181
182/// Reads a batch one record at a time, ending after the first error.
183///
184/// # Errors
185/// Each item is an error for a record with an unknown tag, a nonzero reserved byte, a body that
186/// ends early or has bytes left over, text that is not UTF-8, or a value count or text length
187/// past `limits`.
188pub fn records(batch: &[u8], limits: Limits) -> impl Iterator<Item = Result<Record, RecordError>> {
189    Records {
190        rest: batch,
191        index: 0,
192        limits,
193    }
194}
195
196/// Reads a whole batch.
197///
198/// # Errors
199/// The first record [`records`] refuses with [`Limits::NONE`].
200pub fn decode(batch: &[u8]) -> Result<Vec<Record>, RecordError> {
201    records(batch, Limits::NONE).collect()
202}
203
204struct Records<'a> {
205    rest: &'a [u8],
206    index: usize,
207    limits: Limits,
208}
209
210impl Iterator for Records<'_> {
211    type Item = Result<Record, RecordError>;
212
213    fn next(&mut self) -> Option<Self::Item> {
214        if self.rest.is_empty() {
215            return None;
216        }
217        let record = self.read();
218        self.index += 1;
219        if record.is_err() {
220            self.rest = &[];
221        }
222        Some(record)
223    }
224}
225
226impl Records<'_> {
227    fn read(&mut self) -> Result<Record, RecordError> {
228        let index = self.index;
229        let fail = |reason| RecordError { index, reason };
230        let mut header = Reader(self.rest);
231        let tag = header.u8().ok_or(fail("the header ends early"))?;
232        let reserved = header.u8().ok_or(fail("the header ends early"))?;
233        let output = header.u16().ok_or(fail("the header ends early"))?;
234        let size = header.u32().ok_or(fail("the header ends early"))? as usize;
235        if reserved != 0 {
236            return Err(fail("the reserved header byte is not 0"));
237        }
238        let body = header
239            .take(size)
240            .ok_or(fail("the body is shorter than its length"))?;
241        self.rest = header.0;
242        let mut body = Reader(body);
243        let limits = self.limits;
244        let record = match tag {
245            SAMPLE => body.sample(output, limits),
246            WORD => body.word(output, limits),
247            INTERVAL => body.interval(output, limits),
248            _ => Err("unknown record tag"),
249        }
250        .map_err(fail)?;
251        if !body.0.is_empty() {
252            return Err(fail("the body is longer than its fields"));
253        }
254        Ok(record)
255    }
256}
257
258struct Reader<'a>(&'a [u8]);
259
260impl<'a> Reader<'a> {
261    fn take(&mut self, count: usize) -> Option<&'a [u8]> {
262        if self.0.len() < count {
263            return None;
264        }
265        let (taken, rest) = self.0.split_at(count);
266        self.0 = rest;
267        Some(taken)
268    }
269
270    fn array<const N: usize>(&mut self) -> Option<[u8; N]> {
271        self.take(N)?.try_into().ok()
272    }
273
274    fn u8(&mut self) -> Option<u8> {
275        self.array::<1>().map(|[byte]| byte)
276    }
277
278    fn u16(&mut self) -> Option<u16> {
279        self.array().map(u16::from_le_bytes)
280    }
281
282    fn u32(&mut self) -> Option<u32> {
283        self.array().map(u32::from_le_bytes)
284    }
285
286    fn i64(&mut self) -> Option<i64> {
287        self.array().map(i64::from_le_bytes)
288    }
289
290    fn f32(&mut self) -> Option<f32> {
291        self.array().map(f32::from_le_bytes)
292    }
293
294    fn text(&mut self, len: u32, limits: Limits) -> Result<Option<String>, &'static str> {
295        if len == ABSENT {
296            return Ok(None);
297        }
298        if len as usize > limits.max_text_bytes {
299            return Err("a text is longer than the host takes");
300        }
301        let bytes = self.take(len as usize).ok_or("a text runs past the body")?;
302        core::str::from_utf8(bytes)
303            .map(|text| Some(String::from(text)))
304            .map_err(|_| "a text is not UTF-8")
305    }
306
307    fn sample(&mut self, output: u16, limits: Limits) -> Result<Record, &'static str> {
308        const SHORT: &str = "the sample's fields end early";
309        let time = self.i64().ok_or(SHORT)?;
310        let count = self.u32().ok_or(SHORT)? as usize;
311        if count > limits.max_values {
312            return Err("a sample has more values than the host takes");
313        }
314        // Every value takes at least 4 bytes, so a count the body cannot hold is refused before
315        // anything is allocated for it.
316        if count > self.0.len() / 4 {
317            return Err(SHORT);
318        }
319        let mut lost = Vec::with_capacity(count.div_ceil(32));
320        for _ in 0..count.div_ceil(32) {
321            lost.push(self.u32().ok_or(SHORT)?);
322        }
323        let mut values = Vec::with_capacity(count);
324        for index in 0..count {
325            let value = self.f32().ok_or(SHORT)?;
326            let is_lost = lost[index / 32] >> (index % 32) & 1 == 1;
327            values.push((!is_lost).then_some(value));
328        }
329        if lost
330            .last()
331            .is_some_and(|mask| !count.is_multiple_of(32) && mask >> (count % 32) != 0)
332        {
333            return Err("a lost mask marks a value past the count");
334        }
335        Ok(Record::Sample {
336            output,
337            time,
338            values,
339        })
340    }
341
342    fn word(&mut self, output: u16, limits: Limits) -> Result<Record, &'static str> {
343        const SHORT: &str = "the word's fields end early";
344        let start = self.i64().ok_or(SHORT)?;
345        let end = self.i64().ok_or(SHORT)?;
346        let text_len = self.u32().ok_or(SHORT)?;
347        let speaker_len = self.u32().ok_or(SHORT)?;
348        let text = self.text(text_len, limits)?.ok_or("a word has no text")?;
349        let speaker = self.text(speaker_len, limits)?;
350        Ok(Record::Word {
351            output,
352            start,
353            end,
354            text,
355            speaker,
356        })
357    }
358
359    fn interval(&mut self, output: u16, limits: Limits) -> Result<Record, &'static str> {
360        const SHORT: &str = "the interval's fields end early";
361        let start = self.i64().ok_or(SHORT)?;
362        let end = self.i64().ok_or(SHORT)?;
363        let flags = self.u32().ok_or(SHORT)?;
364        let score = self.f32().ok_or(SHORT)?;
365        let label_len = self.u32().ok_or(SHORT)?;
366        if flags > 1 {
367            return Err("unknown interval flags");
368        }
369        let label = self.text(label_len, limits)?;
370        Ok(Record::Interval {
371            output,
372            start,
373            end,
374            label,
375            score: (flags == 1).then_some(score),
376        })
377    }
378}