Skip to main content

alpha2_model/
data.rs

1//! Data sets, the values an extractor derived from media, recorded in the project and anchored to
2//! a source's clock or the timeline's.
3//!
4//! The engine consumes data in two ways. Values and caption tracks bind to a data set and
5//! follow it at render time through the same time map the picture uses; edit operations apply
6//! interval data to the document once. No extractor runs while a frame renders.
7
8use crate::{ClipId, DataSetId, MediaFingerprint, NodeId};
9use alpha2_media::SourceId;
10use alpha2_time::MediaTime;
11use serde::{Deserialize, Serialize};
12use std::fmt;
13
14/// Most data sets in one project.
15///
16/// The per-set limits below bound one set; together they admit far more than a document holds.
17/// The byte cap ([`crate::MAX_PROJECT_JSON_BYTES`]) binds first: about 6 million values of full
18/// precision fill it, and every writer refuses a project past it.
19pub const MAX_DATA_SETS: usize = 256;
20/// Most channels of one `points` or `scalars` data set.
21pub const MAX_DATA_CHANNELS: usize = 64;
22/// Most values (numbers or lost markers) of one sampled data set.
23pub const MAX_DATA_VALUES: usize = 4_000_000;
24/// Most words of one `words` data set.
25pub const MAX_DATA_WORDS: usize = 200_000;
26/// Most intervals of one `intervals` data set.
27pub const MAX_DATA_INTERVALS: usize = 200_000;
28/// Most bytes of an interval label, a word's text or speaker, or a channel name.
29pub const MAX_DATA_LABEL_BYTES: usize = 256;
30/// Most bytes of a data set's id.
31pub const MAX_DATA_ID_BYTES: usize = 64;
32/// Largest magnitude of a normalized coordinate (points, similarity translation).
33pub const MAX_DATA_COORDINATE: f32 = 16.0;
34/// Largest magnitude of a scalar or an interval score.
35pub const MAX_DATA_SCALAR: f32 = 1e9;
36/// Largest magnitude of a similarity rotation, in degrees.
37pub const MAX_DATA_ROTATION_DEGREES: f32 = 36_000.0;
38/// Largest similarity scale; the smallest is just above zero.
39pub const MAX_DATA_SCALE: f32 = 1_000.0;
40/// Longest chain of canvas-space follows from one clip, counted in links.
41pub const MAX_FOLLOW_DEPTH: usize = 8;
42
43/// The clock a data set's times are on.
44#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize)]
45#[serde(tag = "type", rename_all = "snake_case")]
46pub enum DataAnchor {
47    /// Source time, the presentation times the source's pictures and sound carry once decoded.
48    /// Points are normalized to the displayed source picture.
49    Source {
50        /// The source.
51        source_id: SourceId,
52    },
53    /// Timeline time. Points are normalized to the canvas.
54    Timeline,
55}
56
57impl DataAnchor {
58    /// The anchored source, if any.
59    #[must_use]
60    pub const fn source(&self) -> Option<&SourceId> {
61        match self {
62            Self::Source { source_id } => Some(source_id),
63            Self::Timeline => None,
64        }
65    }
66}
67
68#[derive(Deserialize)]
69#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
70#[cfg_attr(feature = "schema", schemars(rename = "DataAnchor"))]
71#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
72enum DataAnchorWire {
73    /// Source time, the presentation times the source's pictures and sound carry once decoded.
74    /// Points are normalized to the displayed source picture.
75    Source {
76        /// The source.
77        source_id: SourceId,
78    },
79    /// Timeline time. Points are normalized to the canvas.
80    Timeline {},
81}
82
83impl<'de> Deserialize<'de> for DataAnchor {
84    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
85        Ok(match DataAnchorWire::deserialize(deserializer)? {
86            DataAnchorWire::Source { source_id } => Self::Source { source_id },
87            DataAnchorWire::Timeline {} => Self::Timeline,
88        })
89    }
90}
91
92#[cfg(feature = "schema")]
93impl schemars::JsonSchema for DataAnchor {
94    fn schema_name() -> std::borrow::Cow<'static, str> {
95        DataAnchorWire::schema_name()
96    }
97
98    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
99        DataAnchorWire::json_schema(generator)
100    }
101}
102
103/// How a sampled data set reads between its samples.
104#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Hash, Serialize)]
105#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
106#[serde(rename_all = "snake_case")]
107pub enum DataInterpolation {
108    /// The sample at or before the time, as the picture shown at that time is chosen.
109    #[default]
110    Hold,
111    /// A straight line between the samples around the time.
112    Linear,
113}
114
115/// What a data set holds; each kind has a consumer in the engine.
116#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Hash, Serialize)]
117#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
118#[serde(rename_all = "snake_case")]
119pub enum DataKind {
120    /// Named channels of normalized `(x, y)` points.
121    Points,
122    /// Named channels of numbers.
123    Scalars,
124    /// One translation, rotation and uniform scale per sample.
125    Similarity,
126    /// Timed words with text.
127    Words,
128    /// Timed ranges, a zero-length one being an instant.
129    Intervals,
130}
131
132impl DataKind {
133    /// Numbers per channel and sample of a sampled kind; `None` for words and intervals.
134    #[must_use]
135    pub const fn arity(self) -> Option<usize> {
136        match self {
137            Self::Points => Some(2),
138            Self::Scalars => Some(1),
139            Self::Similarity => Some(SIMILARITY_ARITY),
140            Self::Words | Self::Intervals => None,
141        }
142    }
143
144    /// The kind's wire name.
145    #[must_use]
146    pub const fn name(self) -> &'static str {
147        match self {
148            Self::Points => "points",
149            Self::Scalars => "scalars",
150            Self::Similarity => "similarity",
151            Self::Words => "words",
152            Self::Intervals => "intervals",
153        }
154    }
155}
156
157impl fmt::Display for DataKind {
158    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
159        formatter.write_str(self.name())
160    }
161}
162
163/// Numbers per similarity sample: `tx`, `ty`, rotation in degrees, scale.
164pub const SIMILARITY_ARITY: usize = 4;
165
166/// Samples on one time grid, stored by column.
167///
168/// `values` holds `times.len() * channels * arity` numbers: sample after sample, channel after
169/// channel within a sample, components within a channel. `None` marks a channel lost at that
170/// sample, and covers all of its components.
171#[derive(Clone, Debug, Default, PartialEq)]
172pub struct DataSamples {
173    /// How the values read between samples.
174    pub interpolation: DataInterpolation,
175    /// Channel names, unique; empty for `similarity`.
176    pub channels: Vec<String>,
177    /// Sample times in ticks on the anchor's clock, strictly ascending.
178    pub times: Vec<MediaTime>,
179    /// The values, as described on the type.
180    pub values: Vec<Option<f32>>,
181}
182
183impl DataSamples {
184    /// The position of `channel`, if the set has it.
185    #[must_use]
186    pub fn channel(&self, channel: &str) -> Option<usize> {
187        self.channels.iter().position(|name| name == channel)
188    }
189}
190
191/// One timed word.
192#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
193#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
194#[serde(deny_unknown_fields)]
195pub struct DataWord {
196    /// When the word starts, in ticks on the anchor's clock.
197    pub start: MediaTime,
198    /// When it ends; after `start`.
199    pub end: MediaTime,
200    /// The word, non-empty, at most [`MAX_DATA_LABEL_BYTES`] bytes.
201    pub text: String,
202    /// Who says it, at most [`MAX_DATA_LABEL_BYTES`] bytes.
203    #[serde(default, skip_serializing_if = "Option::is_none")]
204    pub speaker: Option<String>,
205}
206
207/// One timed range; `start == end` is an instant.
208#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
209#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
210#[serde(deny_unknown_fields)]
211pub struct DataInterval {
212    /// When it starts, in ticks on the anchor's clock.
213    pub start: MediaTime,
214    /// When it ends; not before `start`.
215    pub end: MediaTime,
216    /// A free label, at most [`MAX_DATA_LABEL_BYTES`] bytes. Edit operations ignore it.
217    #[serde(default, skip_serializing_if = "Option::is_none")]
218    pub label: Option<String>,
219    /// A free, finite score of at most [`MAX_DATA_SCALAR`] in magnitude; edit operations ignore it.
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub score: Option<f32>,
222}
223
224/// The values of a data set, by kind.
225#[derive(Clone, Debug, PartialEq)]
226pub enum DataValues {
227    /// Channels of `(x, y)` points.
228    Points(DataSamples),
229    /// Channels of numbers.
230    Scalars(DataSamples),
231    /// `tx`, `ty`, rotation in degrees and scale per sample, with no channels.
232    Similarity(DataSamples),
233    /// Words sorted by `(start, end)`; they may overlap.
234    Words(Vec<DataWord>),
235    /// Intervals sorted by `(start, end)`; they may overlap.
236    Intervals(Vec<DataInterval>),
237}
238
239impl DataValues {
240    /// The kind of these values.
241    #[must_use]
242    pub const fn kind(&self) -> DataKind {
243        match self {
244            Self::Points(_) => DataKind::Points,
245            Self::Scalars(_) => DataKind::Scalars,
246            Self::Similarity(_) => DataKind::Similarity,
247            Self::Words(_) => DataKind::Words,
248            Self::Intervals(_) => DataKind::Intervals,
249        }
250    }
251
252    /// The samples of a sampled kind.
253    #[must_use]
254    pub const fn samples(&self) -> Option<&DataSamples> {
255        match self {
256            Self::Points(samples) | Self::Scalars(samples) | Self::Similarity(samples) => {
257                Some(samples)
258            }
259            Self::Words(_) | Self::Intervals(_) => None,
260        }
261    }
262}
263
264/// Which extractor made a data set. Recorded for hosts; the engine never reads it.
265#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
266#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
267#[serde(deny_unknown_fields)]
268pub struct MadeBy {
269    /// The extractor's reverse-DNS id.
270    pub extractor: String,
271    /// The extractor's output-contract version.
272    pub version: u32,
273    /// The parameters it ran with.
274    #[serde(default)]
275    pub params: serde_json::Map<String, serde_json::Value>,
276    /// The plugin that ran, when the extractor was one.
277    #[serde(default, skip_serializing_if = "Option::is_none")]
278    pub plugin: Option<MadeByPlugin>,
279}
280
281/// The plugin build that made a data set.
282#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
283#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
284#[serde(deny_unknown_fields)]
285pub struct MadeByPlugin {
286    /// The package's semantic version.
287    pub version: String,
288    /// SHA-256 of the artifact that ran, as 64 lowercase hexadecimal digits.
289    pub artifact_sha256: String,
290    /// SHA-256 of the manifest's bytes, 64 lowercase hex digits; it covers the pinned resources.
291    pub manifest_sha256: String,
292    /// The slot files the run read, sorted by name; at most [`MAX_SUPPLIED_FILES`].
293    #[serde(default, skip_serializing_if = "Vec::is_empty")]
294    pub supplied: Vec<SuppliedFile>,
295}
296
297/// The most supplied files one plugin run reads, and one directory slot holds.
298pub const MAX_SUPPLIED_FILES: usize = 1024;
299/// The longest resource name of a supplied file, in bytes.
300pub const MAX_SUPPLIED_NAME_BYTES: usize = 512;
301
302/// A file of a resource slot that a plugin run read, by name and content, never by path.
303#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
304#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
305#[serde(deny_unknown_fields)]
306pub struct SuppliedFile {
307    /// The resource name the plugin read it by, `<slot>` or `<slot>/<relative path>`; at most
308    /// [`MAX_SUPPLIED_NAME_BYTES`] bytes.
309    pub name: String,
310    /// SHA-256 of its bytes, as 64 lowercase hexadecimal digits.
311    pub sha256: String,
312    /// Its length in bytes.
313    pub bytes: u64,
314}
315
316impl MadeByPlugin {
317    fn is_valid(&self) -> bool {
318        !self.version.is_empty()
319            && valid_sha256(&self.artifact_sha256)
320            && valid_sha256(&self.manifest_sha256)
321            && self.supplied.len() <= MAX_SUPPLIED_FILES
322            && self.supplied.iter().all(|file| {
323                !file.name.is_empty()
324                    && file.name.len() <= MAX_SUPPLIED_NAME_BYTES
325                    && valid_sha256(&file.sha256)
326            })
327            && self
328                .supplied
329                .windows(2)
330                .all(|pair| pair[0].name < pair[1].name)
331    }
332}
333
334/// Values derived from media, anchored to a source or to the timeline.
335#[derive(Clone, Debug, PartialEq)]
336pub struct DataSet {
337    /// Stable identity; at most [`MAX_DATA_ID_BYTES`] bytes.
338    pub id: DataSetId,
339    /// The clock the times are on.
340    pub anchor: DataAnchor,
341    /// The values.
342    pub values: DataValues,
343    /// Which extractor made it.
344    pub made_by: Option<MadeBy>,
345    /// The original source's fingerprint when the data was made; absent for timeline anchors.
346    /// Hosts compare it with the source's current one to report stale data.
347    pub made_from: Option<MediaFingerprint>,
348}
349
350impl DataSet {
351    /// Its latest time: the last sample, or the latest word or interval end.
352    #[must_use]
353    pub fn last_time(&self) -> Option<MediaTime> {
354        match &self.values {
355            DataValues::Points(samples)
356            | DataValues::Scalars(samples)
357            | DataValues::Similarity(samples) => samples.times.last().copied(),
358            DataValues::Words(words) => words.iter().map(|word| word.end).max(),
359            DataValues::Intervals(intervals) => intervals.iter().map(|interval| interval.end).max(),
360        }
361    }
362
363    /// The kind of the values.
364    #[must_use]
365    pub const fn kind(&self) -> DataKind {
366        self.values.kind()
367    }
368}
369
370// The schema of a `DataSet`: one flat object per kind with only that kind's fields.
371/// Values derived from media, anchored to a source's clock or the timeline's.
372#[cfg(feature = "schema")]
373#[allow(dead_code)]
374#[derive(schemars::JsonSchema)]
375#[schemars(rename = "DataSet")]
376#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
377enum DataSetSchema {
378    /// Named channels of normalized `(x, y)` points, each pair `null` when lost.
379    Points {
380        /// Stable identity, 1 to 64 bytes.
381        id: DataSetId,
382        /// The clock the times are on.
383        anchor: DataAnchor,
384        /// How the values read between samples.
385        interpolation: DataInterpolation,
386        /// Channel names, unique, 1 to 256 bytes each.
387        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_DATA_CHANNELS)))]
388        channels: Vec<String>,
389        /// Sample times in ticks on the anchor's clock, strictly ascending.
390        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_DATA_VALUES)))]
391        times: Vec<MediaTime>,
392        /// `times.len() * channels.len() * 2` numbers, sample after sample, channel after channel.
393        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_DATA_VALUES)))]
394        values: Vec<Option<f32>>,
395        /// Which extractor made it.
396        #[serde(default)]
397        made_by: Option<MadeBy>,
398        /// The original source's fingerprint when it was made.
399        #[serde(default)]
400        made_from: Option<MediaFingerprint>,
401    },
402    /// Named channels of numbers, each `null` when lost.
403    Scalars {
404        /// Stable identity, 1 to 64 bytes.
405        id: DataSetId,
406        /// The clock the times are on.
407        anchor: DataAnchor,
408        /// How the values read between samples.
409        interpolation: DataInterpolation,
410        /// Channel names, unique, 1 to 256 bytes each.
411        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_DATA_CHANNELS)))]
412        channels: Vec<String>,
413        /// Sample times in ticks on the anchor's clock, strictly ascending.
414        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_DATA_VALUES)))]
415        times: Vec<MediaTime>,
416        /// `times.len() * channels.len()` numbers, sample after sample, channel after channel.
417        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_DATA_VALUES)))]
418        values: Vec<Option<f32>>,
419        /// Which extractor made it.
420        #[serde(default)]
421        made_by: Option<MadeBy>,
422        /// The original source's fingerprint when it was made.
423        #[serde(default)]
424        made_from: Option<MediaFingerprint>,
425    },
426    /// Translation (normalized), rotation (degrees) and uniform scale about the picture's
427    /// center, per sample; four `null`s when lost.
428    Similarity {
429        /// Stable identity, 1 to 64 bytes.
430        id: DataSetId,
431        /// The clock the times are on.
432        anchor: DataAnchor,
433        /// How the values read between samples.
434        interpolation: DataInterpolation,
435        /// Sample times in ticks on the anchor's clock, strictly ascending.
436        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_DATA_VALUES)))]
437        times: Vec<MediaTime>,
438        /// `times.len() * 4` numbers: `tx`, `ty`, rotation, scale per sample.
439        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_DATA_VALUES)))]
440        values: Vec<Option<f32>>,
441        /// Which extractor made it.
442        #[serde(default)]
443        made_by: Option<MadeBy>,
444        /// The original source's fingerprint when it was made.
445        #[serde(default)]
446        made_from: Option<MediaFingerprint>,
447    },
448    /// Timed words.
449    Words {
450        /// Stable identity, 1 to 64 bytes.
451        id: DataSetId,
452        /// The clock the times are on.
453        anchor: DataAnchor,
454        /// Words sorted by `(start, end)`.
455        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_DATA_WORDS)))]
456        words: Vec<DataWord>,
457        /// Which extractor made it.
458        #[serde(default)]
459        made_by: Option<MadeBy>,
460        /// The original source's fingerprint when it was made.
461        #[serde(default)]
462        made_from: Option<MediaFingerprint>,
463    },
464    /// Timed ranges.
465    Intervals {
466        /// Stable identity, 1 to 64 bytes.
467        id: DataSetId,
468        /// The clock the times are on.
469        anchor: DataAnchor,
470        /// Intervals sorted by `(start, end)`.
471        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_DATA_INTERVALS)))]
472        intervals: Vec<DataInterval>,
473        /// Which extractor made it.
474        #[serde(default)]
475        made_by: Option<MadeBy>,
476        /// The original source's fingerprint when it was made.
477        #[serde(default)]
478        made_from: Option<MediaFingerprint>,
479    },
480}
481
482#[cfg(feature = "schema")]
483impl schemars::JsonSchema for DataSet {
484    fn schema_name() -> std::borrow::Cow<'static, str> {
485        DataSetSchema::schema_name()
486    }
487
488    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
489        DataSetSchema::json_schema(generator)
490    }
491}
492
493/// Every field any kind has, read without buffering, then checked against the kind.
494#[derive(Deserialize)]
495#[serde(deny_unknown_fields)]
496struct DataSetFlat {
497    id: DataSetId,
498    anchor: DataAnchor,
499    kind: DataKind,
500    #[serde(default)]
501    interpolation: Option<DataInterpolation>,
502    #[serde(default)]
503    #[serde(deserialize_with = "crate::bounded::option_seq::<_, _, { crate::MAX_DATA_CHANNELS }>")]
504    channels: Option<Vec<String>>,
505    #[serde(default)]
506    #[serde(deserialize_with = "crate::bounded::option_seq::<_, _, { crate::MAX_DATA_VALUES }>")]
507    times: Option<Vec<MediaTime>>,
508    #[serde(default)]
509    #[serde(deserialize_with = "crate::bounded::option_seq::<_, _, { crate::MAX_DATA_VALUES }>")]
510    values: Option<Vec<Option<f32>>>,
511    #[serde(default)]
512    #[serde(deserialize_with = "crate::bounded::option_seq::<_, _, { crate::MAX_DATA_WORDS }>")]
513    words: Option<Vec<DataWord>>,
514    #[serde(default)]
515    #[serde(
516        deserialize_with = "crate::bounded::option_seq::<_, _, { crate::MAX_DATA_INTERVALS }>"
517    )]
518    intervals: Option<Vec<DataInterval>>,
519    #[serde(default)]
520    made_by: Option<MadeBy>,
521    #[serde(default)]
522    made_from: Option<MediaFingerprint>,
523}
524
525impl TryFrom<DataSetFlat> for DataSet {
526    type Error = String;
527
528    fn try_from(flat: DataSetFlat) -> Result<Self, Self::Error> {
529        let kind = flat.kind;
530        let stray = |field: &str| format!("a {kind} data set has no field `{field}`");
531        let missing = |field: &str| format!("a {kind} data set needs `{field}`");
532        let values = match kind {
533            DataKind::Points | DataKind::Scalars | DataKind::Similarity => {
534                if flat.words.is_some() {
535                    return Err(stray("words"));
536                }
537                if flat.intervals.is_some() {
538                    return Err(stray("intervals"));
539                }
540                let channels = if kind == DataKind::Similarity {
541                    if flat.channels.is_some() {
542                        return Err(stray("channels"));
543                    }
544                    Vec::new()
545                } else {
546                    flat.channels.ok_or_else(|| missing("channels"))?
547                };
548                let samples = DataSamples {
549                    interpolation: flat.interpolation.ok_or_else(|| missing("interpolation"))?,
550                    channels,
551                    times: flat.times.ok_or_else(|| missing("times"))?,
552                    values: flat.values.ok_or_else(|| missing("values"))?,
553                };
554                match kind {
555                    DataKind::Points => DataValues::Points(samples),
556                    DataKind::Scalars => DataValues::Scalars(samples),
557                    _ => DataValues::Similarity(samples),
558                }
559            }
560            DataKind::Words | DataKind::Intervals => {
561                for (field, present) in [
562                    ("interpolation", flat.interpolation.is_some()),
563                    ("channels", flat.channels.is_some()),
564                    ("times", flat.times.is_some()),
565                    ("values", flat.values.is_some()),
566                ] {
567                    if present {
568                        return Err(stray(field));
569                    }
570                }
571                if kind == DataKind::Words {
572                    if flat.intervals.is_some() {
573                        return Err(stray("intervals"));
574                    }
575                    DataValues::Words(flat.words.ok_or_else(|| missing("words"))?)
576                } else {
577                    if flat.words.is_some() {
578                        return Err(stray("words"));
579                    }
580                    DataValues::Intervals(flat.intervals.ok_or_else(|| missing("intervals"))?)
581                }
582            }
583        };
584        Ok(Self {
585            id: flat.id,
586            anchor: flat.anchor,
587            values,
588            made_by: flat.made_by,
589            made_from: flat.made_from,
590        })
591    }
592}
593
594impl<'de> Deserialize<'de> for DataSet {
595    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
596        let flat = DataSetFlat::deserialize(deserializer)?;
597        Self::try_from(flat).map_err(serde::de::Error::custom)
598    }
599}
600
601#[derive(Serialize)]
602struct DataSetRef<'a> {
603    id: &'a DataSetId,
604    anchor: &'a DataAnchor,
605    kind: DataKind,
606    #[serde(skip_serializing_if = "Option::is_none")]
607    interpolation: Option<DataInterpolation>,
608    #[serde(skip_serializing_if = "Option::is_none")]
609    channels: Option<&'a [String]>,
610    #[serde(skip_serializing_if = "Option::is_none")]
611    times: Option<&'a [MediaTime]>,
612    #[serde(skip_serializing_if = "Option::is_none")]
613    values: Option<&'a [Option<f32>]>,
614    #[serde(skip_serializing_if = "Option::is_none")]
615    words: Option<&'a [DataWord]>,
616    #[serde(skip_serializing_if = "Option::is_none")]
617    intervals: Option<&'a [DataInterval]>,
618    #[serde(skip_serializing_if = "Option::is_none")]
619    made_by: Option<&'a MadeBy>,
620    #[serde(skip_serializing_if = "Option::is_none")]
621    made_from: Option<&'a MediaFingerprint>,
622}
623
624impl Serialize for DataSet {
625    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
626        let mut wire = DataSetRef {
627            id: &self.id,
628            anchor: &self.anchor,
629            kind: self.kind(),
630            interpolation: None,
631            channels: None,
632            times: None,
633            values: None,
634            words: None,
635            intervals: None,
636            made_by: self.made_by.as_ref(),
637            made_from: self.made_from.as_ref(),
638        };
639        match &self.values {
640            DataValues::Points(samples)
641            | DataValues::Scalars(samples)
642            | DataValues::Similarity(samples) => {
643                wire.interpolation = Some(samples.interpolation);
644                if self.kind() != DataKind::Similarity {
645                    wire.channels = Some(&samples.channels);
646                }
647                wire.times = Some(&samples.times);
648                wire.values = Some(&samples.values);
649            }
650            DataValues::Words(words) => wire.words = Some(words),
651            DataValues::Intervals(intervals) => wire.intervals = Some(intervals),
652        }
653        wire.serialize(serializer)
654    }
655}
656
657/// A value that follows a channel of a data set at render time: the `data` value mode.
658///
659/// A source-anchored set is read through a reader (`via`) whose time map gives source time, so
660/// the value follows the picture through any speed, reverse, loop or freeze.
661#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
662#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
663#[serde(deny_unknown_fields)]
664pub struct DataBinding {
665    /// The data set, a `points` or `scalars` one.
666    pub data: DataSetId,
667    /// The channel followed.
668    pub channel: String,
669    /// The reader whose time map gives source time: required for a source-anchored set,
670    /// forbidden for a timeline-anchored one.
671    #[serde(default, skip_serializing_if = "Option::is_none")]
672    pub via: Option<DataVia>,
673    /// Where a point is read (points with `via` only, where it is required).
674    #[serde(default, skip_serializing_if = "Option::is_none")]
675    pub space: Option<DataSpace>,
676    /// `[x, y]` added after the space mapping, in that space's normalized units (points only).
677    #[serde(default, skip_serializing_if = "Option::is_none")]
678    pub offset: Option<[f32; 2]>,
679    /// A linear map of the value (scalars only).
680    #[serde(default, skip_serializing_if = "Option::is_none")]
681    pub remap: Option<DataRemap>,
682}
683
684/// The reader whose clock maps time onto a source-anchored data set.
685#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Hash, Serialize)]
686#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
687#[serde(rename_all = "snake_case", deny_unknown_fields)]
688pub enum DataVia {
689    /// A timeline clip showing the anchor's source; its picture time map gives source time.
690    Clip(ClipId),
691    /// A `media` node of the same composition reading the anchor's source; its start plus the
692    /// composition time gives source time.
693    Node(NodeId),
694}
695
696/// Where a bound point is read.
697#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Hash, Serialize)]
698#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
699#[serde(rename_all = "snake_case")]
700pub enum DataSpace {
701    /// The normalized source picture, unchanged: effect params and the clip's own masks.
702    Picture,
703    /// Normalized canvas coordinates through the `via` clip's presentation and evaluated
704    /// visual: another clip's position.
705    Canvas,
706}
707
708/// A linear map from `input` to `output`, clamped to `output`.
709#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
710#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
711#[serde(deny_unknown_fields)]
712pub struct DataRemap {
713    /// The input values mapped to `output[0]` and `output[1]`; distinct and finite.
714    pub input: [f32; 2],
715    /// The output range; finite.
716    pub output: [f32; 2],
717}
718
719impl DataRemap {
720    /// Maps `value`, clamped to the output range.
721    #[must_use]
722    pub fn apply(&self, value: f32) -> f32 {
723        let [in0, in1] = self.input.map(f64::from);
724        let [out0, out1] = self.output.map(f64::from);
725        let mapped = out0 + (f64::from(value) - in0) * (out1 - out0) / (in1 - in0);
726        let (low, high) = if out0 <= out1 {
727            (out0, out1)
728        } else {
729            (out1, out0)
730        };
731        #[allow(clippy::cast_possible_truncation)]
732        let clamped = mapped.clamp(low, high) as f32;
733        clamped
734    }
735
736    // Equal inputs give no slope; any two distinct values do.
737    #[allow(clippy::float_cmp)]
738    fn is_valid(&self) -> bool {
739        self.input
740            .iter()
741            .chain(&self.output)
742            .all(|value| value.is_finite())
743            && self.input[0] != self.input[1]
744    }
745}
746
747/// A `similarity` data set applied to a clip's own picture before its transform.
748#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
749#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
750#[serde(deny_unknown_fields)]
751pub struct CorrectionRef {
752    /// The data set, a `similarity` one anchored to the clip's source.
753    pub data: DataSetId,
754}
755
756/// Caption cues built from a `words` data set.
757#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
758#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
759#[serde(deny_unknown_fields)]
760pub struct CaptionsFromWords {
761    /// The data set, a `words` one.
762    pub data: DataSetId,
763    /// For a source-anchored set, the track whose clips showing the source give the words their
764    /// timeline times; forbidden for a timeline-anchored set.
765    #[serde(default, skip_serializing_if = "Option::is_none")]
766    pub track: Option<crate::TrackId>,
767    /// Most characters of one cue, at least 1.
768    pub max_chars: u32,
769}
770
771/// What is wrong with a data set.
772#[derive(Clone, Debug, Eq, PartialEq)]
773#[non_exhaustive]
774pub enum DataProblem {
775    /// The id is longer than [`MAX_DATA_ID_BYTES`].
776    IdTooLong,
777    /// The anchor names no source of the project.
778    UnknownSource(SourceId),
779    /// The anchor names a source that has no media clock (a generated or composition source).
780    SourceWithoutMedia(SourceId),
781    /// More than [`MAX_DATA_CHANNELS`] channels, or none.
782    ChannelCount,
783    /// A channel name is empty, too long or repeated.
784    ChannelName,
785    /// More than [`MAX_DATA_VALUES`] values.
786    TooManyValues,
787    /// `values` does not hold exactly `times * channels * arity` entries.
788    ValueCount,
789    /// Times are not strictly ascending.
790    TimesNotAscending,
791    /// A time is negative.
792    NegativeTime,
793    /// A value is not finite, outside its kind's bounds, or a lost marker covers only part of a
794    /// channel or sample.
795    InvalidValue {
796        /// The value's position in `values`.
797        index: usize,
798    },
799    /// More than [`MAX_DATA_WORDS`] words or [`MAX_DATA_INTERVALS`] intervals.
800    TooManyItems,
801    /// A word or interval is out of order, has its end before its start (or at it, for a
802    /// word), empty word text, a score out of bounds, or a text too long.
803    InvalidItem {
804        /// The item's position.
805        index: usize,
806    },
807    /// `made_by` has an empty extractor id or a malformed plugin hash.
808    InvalidMadeBy,
809    /// `made_from` has a malformed part (by field name), or is present on a timeline anchor.
810    InvalidMadeFrom(&'static str),
811}
812
813impl fmt::Display for DataProblem {
814    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
815        match self {
816            Self::IdTooLong => write!(formatter, "has an id over {MAX_DATA_ID_BYTES} bytes"),
817            Self::UnknownSource(source) => {
818                write!(formatter, "is anchored to unknown source {source}")
819            }
820            Self::SourceWithoutMedia(source) => {
821                write!(
822                    formatter,
823                    "is anchored to source {source}, which has no media"
824                )
825            }
826            Self::ChannelCount => {
827                write!(formatter, "needs 1 to {MAX_DATA_CHANNELS} channels")
828            }
829            Self::ChannelName => {
830                formatter.write_str("has an empty, overlong or repeated channel name")
831            }
832            Self::TooManyValues => write!(formatter, "has more than {MAX_DATA_VALUES} values"),
833            Self::ValueCount => {
834                formatter.write_str("does not have times * channels * arity values")
835            }
836            Self::TimesNotAscending => {
837                formatter.write_str("has times that are not strictly ascending")
838            }
839            Self::NegativeTime => formatter.write_str("has a negative time"),
840            Self::InvalidValue { index } => {
841                write!(formatter, "has an invalid value at values[{index}]")
842            }
843            Self::TooManyItems => write!(
844                formatter,
845                "has more than {MAX_DATA_WORDS} words or {MAX_DATA_INTERVALS} intervals"
846            ),
847            Self::InvalidItem { index } => write!(formatter, "has an invalid item at [{index}]"),
848            Self::InvalidMadeBy => formatter.write_str("has an invalid made_by"),
849            Self::InvalidMadeFrom(part) => write!(formatter, "has an invalid made_from.{part}"),
850        }
851    }
852}
853
854/// What is wrong with a [`DataBinding`], a [`CorrectionRef`] or a [`CaptionsFromWords`].
855#[derive(Clone, Debug, Eq, PartialEq)]
856#[non_exhaustive]
857pub enum BindingProblem {
858    /// It names no data set of the project.
859    UnknownData,
860    /// The data set's kind does not fit the place's type.
861    WrongKind(DataKind),
862    /// The value's type takes no data (an effect parameter that is not a Float or Vec2).
863    TypeRefusesData,
864    /// The place's clock refuses this anchor, as a composition-time place refuses a timeline anchor
865    /// and a picture-time place refuses any.
866    ClockRefusesAnchor,
867    /// The channel is not one of the data set's.
868    UnknownChannel,
869    /// A source-anchored set needs `via`.
870    ViaRequired,
871    /// A timeline-anchored set takes no `via`.
872    ViaForbidden,
873    /// `via` names a clip at a composition-time place, or a node at a timeline-time place.
874    ViaWrongReader,
875    /// `via` names no timeline clip.
876    UnknownViaClip,
877    /// `via` names no node of the composition, or one that is not a `media` node.
878    InvalidViaNode,
879    /// The reader does not show the data set's source.
880    ViaShowsOtherSource,
881    /// A point read through `via` needs `space`.
882    SpaceRequired,
883    /// `space`, `offset` or `remap` where it does not apply, or `canvas` through a node.
884    FieldNotApplicable(&'static str),
885    /// `remap` has a non-finite value or equal inputs; `offset` a non-finite component.
886    InvalidRemap,
887    /// Following clips in canvas space forms a cycle.
888    Cycle,
889    /// The clip follows clips in canvas space through more than [`MAX_FOLLOW_DEPTH`] links.
890    TooDeep,
891    /// A correction's data set is not anchored to the clip's own source.
892    NotOwnSource,
893    /// A caption track's `track` is missing for a source anchor, given for a timeline anchor,
894    /// or names no visual or audio track; or `max_chars` is zero.
895    InvalidCaptionTrack,
896}
897
898impl fmt::Display for BindingProblem {
899    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
900        match self {
901            Self::UnknownData => formatter.write_str("names an unknown data set"),
902            Self::WrongKind(kind) => write!(formatter, "cannot follow {kind} data"),
903            Self::TypeRefusesData => formatter.write_str("is a value whose type takes no data"),
904            Self::ClockRefusesAnchor => {
905                formatter.write_str("is keyed on a clock that refuses this anchor")
906            }
907            Self::UnknownChannel => formatter.write_str("names an unknown channel"),
908            Self::ViaRequired => formatter.write_str("needs `via` for a source-anchored data set"),
909            Self::ViaForbidden => {
910                formatter.write_str("takes no `via` for a timeline-anchored data set")
911            }
912            Self::ViaWrongReader => {
913                formatter.write_str("names a reader of the wrong kind for its clock")
914            }
915            Self::UnknownViaClip => formatter.write_str("reads through an unknown clip"),
916            Self::InvalidViaNode => formatter
917                .write_str("reads through a node that is not a media node of its composition"),
918            Self::ViaShowsOtherSource => {
919                formatter.write_str("reads through a reader of another source")
920            }
921            Self::SpaceRequired => {
922                formatter.write_str("needs `space` for a point read through `via`")
923            }
924            Self::FieldNotApplicable(field) => {
925                write!(formatter, "has `{field}` where it does not apply")
926            }
927            Self::InvalidRemap => formatter
928                .write_str("has a non-finite offset or remap, or a remap with equal inputs"),
929            Self::Cycle => formatter.write_str("follows clips in canvas space in a cycle"),
930            Self::TooDeep => write!(
931                formatter,
932                "follows clips in canvas space more than {MAX_FOLLOW_DEPTH} deep"
933            ),
934            Self::NotOwnSource => {
935                formatter.write_str("corrects with data anchored to another source")
936            }
937            Self::InvalidCaptionTrack => {
938                formatter.write_str("has an invalid words track or max_chars")
939            }
940        }
941    }
942}
943
944pub(crate) fn valid_label(text: &str) -> bool {
945    text.len() <= MAX_DATA_LABEL_BYTES
946}
947
948fn valid_sha256(hash: &str) -> bool {
949    hash.len() == 64
950        && hash
951            .bytes()
952            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
953}
954
955/// Whether `value` is inside its kind's bounds; `component` is the position within a sample's
956/// numbers for a similarity set.
957#[must_use]
958pub fn value_in_bounds(kind: DataKind, component: usize, value: f32) -> bool {
959    value.is_finite()
960        && match kind {
961            DataKind::Points => value.abs() <= MAX_DATA_COORDINATE,
962            DataKind::Similarity => match component {
963                0 | 1 => value.abs() <= MAX_DATA_COORDINATE,
964                2 => value.abs() <= MAX_DATA_ROTATION_DEGREES,
965                _ => value > 0.0 && value <= MAX_DATA_SCALE,
966            },
967            DataKind::Scalars | DataKind::Words | DataKind::Intervals => {
968                value.abs() <= MAX_DATA_SCALAR
969            }
970        }
971}
972
973/// Checks a word's own fields (order against its neighbours is checked by the caller).
974#[must_use]
975pub fn valid_word(word: &DataWord) -> bool {
976    word.start.ticks() >= 0
977        && word.start < word.end
978        && !word.text.is_empty()
979        && valid_label(&word.text)
980        && word.speaker.as_deref().is_none_or(valid_label)
981}
982
983/// Checks an interval's own fields (order against its neighbours is checked by the caller).
984#[must_use]
985pub fn valid_interval(interval: &DataInterval) -> bool {
986    interval.start.ticks() >= 0
987        && interval.start <= interval.end
988        && interval.label.as_deref().is_none_or(valid_label)
989        && interval
990            .score
991            .is_none_or(|score| value_in_bounds(DataKind::Scalars, 0, score))
992}
993
994impl DataSet {
995    /// Checks the set on its own against the model's rules (everything but its anchor's
996    /// existence). A time past its source's recorded duration is not an invalid set but stale
997    /// data, which [`crate::Project::lint`] reports, since a host may replace the duration.
998    ///
999    /// # Errors
1000    /// The first [`DataProblem`] found.
1001    pub fn validate(&self) -> Result<(), DataProblem> {
1002        if self.id.as_str().len() > MAX_DATA_ID_BYTES {
1003            return Err(DataProblem::IdTooLong);
1004        }
1005        if let Some(made_by) = &self.made_by {
1006            let plugin_ok = made_by.plugin.as_ref().is_none_or(MadeByPlugin::is_valid);
1007            if made_by.extractor.is_empty() || !plugin_ok {
1008                return Err(DataProblem::InvalidMadeBy);
1009            }
1010        }
1011        if let Some(made_from) = &self.made_from {
1012            if self.anchor == DataAnchor::Timeline {
1013                return Err(DataProblem::InvalidMadeFrom("anchor"));
1014            }
1015            if let Some(part) = made_from.malformed_part() {
1016                return Err(DataProblem::InvalidMadeFrom(part));
1017            }
1018        }
1019        let time_ok = |time: MediaTime| -> Result<(), DataProblem> {
1020            if time.ticks() < 0 {
1021                return Err(DataProblem::NegativeTime);
1022            }
1023            Ok(())
1024        };
1025        let kind = self.kind();
1026        match &self.values {
1027            DataValues::Points(samples)
1028            | DataValues::Scalars(samples)
1029            | DataValues::Similarity(samples) => {
1030                check_samples(kind, samples, &time_ok)?;
1031            }
1032            DataValues::Words(words) => {
1033                if words.len() > MAX_DATA_WORDS {
1034                    return Err(DataProblem::TooManyItems);
1035                }
1036                for (index, word) in words.iter().enumerate() {
1037                    let ordered = index == 0 || {
1038                        let before = &words[index - 1];
1039                        (before.start, before.end) <= (word.start, word.end)
1040                    };
1041                    if !valid_word(word) || !ordered {
1042                        return Err(DataProblem::InvalidItem { index });
1043                    }
1044                    time_ok(word.start)?;
1045                    time_ok(word.end)?;
1046                }
1047            }
1048            DataValues::Intervals(intervals) => {
1049                if intervals.len() > MAX_DATA_INTERVALS {
1050                    return Err(DataProblem::TooManyItems);
1051                }
1052                for (index, interval) in intervals.iter().enumerate() {
1053                    let ordered = index == 0 || {
1054                        let before = &intervals[index - 1];
1055                        (before.start, before.end) <= (interval.start, interval.end)
1056                    };
1057                    if !valid_interval(interval) || !ordered {
1058                        return Err(DataProblem::InvalidItem { index });
1059                    }
1060                    time_ok(interval.start)?;
1061                    time_ok(interval.end)?;
1062                }
1063            }
1064        }
1065        Ok(())
1066    }
1067}
1068
1069fn check_samples(
1070    kind: DataKind,
1071    samples: &DataSamples,
1072    time_ok: &dyn Fn(MediaTime) -> Result<(), DataProblem>,
1073) -> Result<(), DataProblem> {
1074    let arity = kind.arity().unwrap_or(1);
1075    let channels = if kind == DataKind::Similarity {
1076        1
1077    } else {
1078        if samples.channels.is_empty() || samples.channels.len() > MAX_DATA_CHANNELS {
1079            return Err(DataProblem::ChannelCount);
1080        }
1081        for (index, name) in samples.channels.iter().enumerate() {
1082            if name.is_empty() || !valid_label(name) || samples.channels[..index].contains(name) {
1083                return Err(DataProblem::ChannelName);
1084            }
1085        }
1086        samples.channels.len()
1087    };
1088    if samples.values.len() > MAX_DATA_VALUES {
1089        return Err(DataProblem::TooManyValues);
1090    }
1091    let expected = samples
1092        .times
1093        .len()
1094        .checked_mul(channels * arity)
1095        .ok_or(DataProblem::ValueCount)?;
1096    if samples.values.len() != expected {
1097        return Err(DataProblem::ValueCount);
1098    }
1099    for (index, time) in samples.times.iter().enumerate() {
1100        if index > 0 && samples.times[index - 1] >= *time {
1101            return Err(DataProblem::TimesNotAscending);
1102        }
1103        time_ok(*time)?;
1104    }
1105    // A lost marker covers a whole channel of a sample: all of its components or none.
1106    for (group, values) in samples.values.chunks_exact(arity).enumerate() {
1107        let lost = values[0].is_none();
1108        for (component, value) in values.iter().enumerate() {
1109            let index = group * arity + component;
1110            let ok = match value {
1111                None => lost,
1112                Some(value) => !lost && value_in_bounds(kind, component, *value),
1113            };
1114            if !ok {
1115                return Err(DataProblem::InvalidValue { index });
1116            }
1117        }
1118    }
1119    Ok(())
1120}
1121
1122impl DataBinding {
1123    /// Checks the fields that need no project: finite offset and a usable remap.
1124    pub(crate) fn fields_valid(&self) -> bool {
1125        self.offset
1126            .is_none_or(|offset| offset.iter().all(|value| value.is_finite()))
1127            && self.remap.is_none_or(|remap| remap.is_valid())
1128    }
1129}