1use crate::{ClipId, DataSetId, MediaFingerprint, NodeId};
9use alpha2_media::SourceId;
10use alpha2_time::MediaTime;
11use serde::{Deserialize, Serialize};
12use std::fmt;
13
14pub const MAX_DATA_SETS: usize = 256;
20pub const MAX_DATA_CHANNELS: usize = 64;
22pub const MAX_DATA_VALUES: usize = 4_000_000;
24pub const MAX_DATA_WORDS: usize = 200_000;
26pub const MAX_DATA_INTERVALS: usize = 200_000;
28pub const MAX_DATA_LABEL_BYTES: usize = 256;
30pub const MAX_DATA_ID_BYTES: usize = 64;
32pub const MAX_DATA_COORDINATE: f32 = 16.0;
34pub const MAX_DATA_SCALAR: f32 = 1e9;
36pub const MAX_DATA_ROTATION_DEGREES: f32 = 36_000.0;
38pub const MAX_DATA_SCALE: f32 = 1_000.0;
40pub const MAX_FOLLOW_DEPTH: usize = 8;
42
43#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize)]
45#[serde(tag = "type", rename_all = "snake_case")]
46pub enum DataAnchor {
47 Source {
50 source_id: SourceId,
52 },
53 Timeline,
55}
56
57impl DataAnchor {
58 #[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 {
76 source_id: SourceId,
78 },
79 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#[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 #[default]
110 Hold,
111 Linear,
113}
114
115#[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 Points,
122 Scalars,
124 Similarity,
126 Words,
128 Intervals,
130}
131
132impl DataKind {
133 #[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 #[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
163pub const SIMILARITY_ARITY: usize = 4;
165
166#[derive(Clone, Debug, Default, PartialEq)]
172pub struct DataSamples {
173 pub interpolation: DataInterpolation,
175 pub channels: Vec<String>,
177 pub times: Vec<MediaTime>,
179 pub values: Vec<Option<f32>>,
181}
182
183impl DataSamples {
184 #[must_use]
186 pub fn channel(&self, channel: &str) -> Option<usize> {
187 self.channels.iter().position(|name| name == channel)
188 }
189}
190
191#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
193#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
194#[serde(deny_unknown_fields)]
195pub struct DataWord {
196 pub start: MediaTime,
198 pub end: MediaTime,
200 pub text: String,
202 #[serde(default, skip_serializing_if = "Option::is_none")]
204 pub speaker: Option<String>,
205}
206
207#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
209#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
210#[serde(deny_unknown_fields)]
211pub struct DataInterval {
212 pub start: MediaTime,
214 pub end: MediaTime,
216 #[serde(default, skip_serializing_if = "Option::is_none")]
218 pub label: Option<String>,
219 #[serde(default, skip_serializing_if = "Option::is_none")]
221 pub score: Option<f32>,
222}
223
224#[derive(Clone, Debug, PartialEq)]
226pub enum DataValues {
227 Points(DataSamples),
229 Scalars(DataSamples),
231 Similarity(DataSamples),
233 Words(Vec<DataWord>),
235 Intervals(Vec<DataInterval>),
237}
238
239impl DataValues {
240 #[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 #[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#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
266#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
267#[serde(deny_unknown_fields)]
268pub struct MadeBy {
269 pub extractor: String,
271 pub version: u32,
273 #[serde(default)]
275 pub params: serde_json::Map<String, serde_json::Value>,
276 #[serde(default, skip_serializing_if = "Option::is_none")]
278 pub plugin: Option<MadeByPlugin>,
279}
280
281#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
283#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
284#[serde(deny_unknown_fields)]
285pub struct MadeByPlugin {
286 pub version: String,
288 pub artifact_sha256: String,
290 pub manifest_sha256: String,
292 #[serde(default, skip_serializing_if = "Vec::is_empty")]
294 pub supplied: Vec<SuppliedFile>,
295}
296
297pub const MAX_SUPPLIED_FILES: usize = 1024;
299pub const MAX_SUPPLIED_NAME_BYTES: usize = 512;
301
302#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
304#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
305#[serde(deny_unknown_fields)]
306pub struct SuppliedFile {
307 pub name: String,
310 pub sha256: String,
312 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#[derive(Clone, Debug, PartialEq)]
336pub struct DataSet {
337 pub id: DataSetId,
339 pub anchor: DataAnchor,
341 pub values: DataValues,
343 pub made_by: Option<MadeBy>,
345 pub made_from: Option<MediaFingerprint>,
348}
349
350impl DataSet {
351 #[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 #[must_use]
365 pub const fn kind(&self) -> DataKind {
366 self.values.kind()
367 }
368}
369
370#[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 Points {
380 id: DataSetId,
382 anchor: DataAnchor,
384 interpolation: DataInterpolation,
386 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_DATA_CHANNELS)))]
388 channels: Vec<String>,
389 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_DATA_VALUES)))]
391 times: Vec<MediaTime>,
392 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_DATA_VALUES)))]
394 values: Vec<Option<f32>>,
395 #[serde(default)]
397 made_by: Option<MadeBy>,
398 #[serde(default)]
400 made_from: Option<MediaFingerprint>,
401 },
402 Scalars {
404 id: DataSetId,
406 anchor: DataAnchor,
408 interpolation: DataInterpolation,
410 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_DATA_CHANNELS)))]
412 channels: Vec<String>,
413 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_DATA_VALUES)))]
415 times: Vec<MediaTime>,
416 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_DATA_VALUES)))]
418 values: Vec<Option<f32>>,
419 #[serde(default)]
421 made_by: Option<MadeBy>,
422 #[serde(default)]
424 made_from: Option<MediaFingerprint>,
425 },
426 Similarity {
429 id: DataSetId,
431 anchor: DataAnchor,
433 interpolation: DataInterpolation,
435 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_DATA_VALUES)))]
437 times: Vec<MediaTime>,
438 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_DATA_VALUES)))]
440 values: Vec<Option<f32>>,
441 #[serde(default)]
443 made_by: Option<MadeBy>,
444 #[serde(default)]
446 made_from: Option<MediaFingerprint>,
447 },
448 Words {
450 id: DataSetId,
452 anchor: DataAnchor,
454 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_DATA_WORDS)))]
456 words: Vec<DataWord>,
457 #[serde(default)]
459 made_by: Option<MadeBy>,
460 #[serde(default)]
462 made_from: Option<MediaFingerprint>,
463 },
464 Intervals {
466 id: DataSetId,
468 anchor: DataAnchor,
470 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_DATA_INTERVALS)))]
472 intervals: Vec<DataInterval>,
473 #[serde(default)]
475 made_by: Option<MadeBy>,
476 #[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#[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#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
662#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
663#[serde(deny_unknown_fields)]
664pub struct DataBinding {
665 pub data: DataSetId,
667 pub channel: String,
669 #[serde(default, skip_serializing_if = "Option::is_none")]
672 pub via: Option<DataVia>,
673 #[serde(default, skip_serializing_if = "Option::is_none")]
675 pub space: Option<DataSpace>,
676 #[serde(default, skip_serializing_if = "Option::is_none")]
678 pub offset: Option<[f32; 2]>,
679 #[serde(default, skip_serializing_if = "Option::is_none")]
681 pub remap: Option<DataRemap>,
682}
683
684#[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 Clip(ClipId),
691 Node(NodeId),
694}
695
696#[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 Picture,
703 Canvas,
706}
707
708#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
710#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
711#[serde(deny_unknown_fields)]
712pub struct DataRemap {
713 pub input: [f32; 2],
715 pub output: [f32; 2],
717}
718
719impl DataRemap {
720 #[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 #[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#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
749#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
750#[serde(deny_unknown_fields)]
751pub struct CorrectionRef {
752 pub data: DataSetId,
754}
755
756#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
758#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
759#[serde(deny_unknown_fields)]
760pub struct CaptionsFromWords {
761 pub data: DataSetId,
763 #[serde(default, skip_serializing_if = "Option::is_none")]
766 pub track: Option<crate::TrackId>,
767 pub max_chars: u32,
769}
770
771#[derive(Clone, Debug, Eq, PartialEq)]
773#[non_exhaustive]
774pub enum DataProblem {
775 IdTooLong,
777 UnknownSource(SourceId),
779 SourceWithoutMedia(SourceId),
781 ChannelCount,
783 ChannelName,
785 TooManyValues,
787 ValueCount,
789 TimesNotAscending,
791 NegativeTime,
793 InvalidValue {
796 index: usize,
798 },
799 TooManyItems,
801 InvalidItem {
804 index: usize,
806 },
807 InvalidMadeBy,
809 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#[derive(Clone, Debug, Eq, PartialEq)]
856#[non_exhaustive]
857pub enum BindingProblem {
858 UnknownData,
860 WrongKind(DataKind),
862 TypeRefusesData,
864 ClockRefusesAnchor,
867 UnknownChannel,
869 ViaRequired,
871 ViaForbidden,
873 ViaWrongReader,
875 UnknownViaClip,
877 InvalidViaNode,
879 ViaShowsOtherSource,
881 SpaceRequired,
883 FieldNotApplicable(&'static str),
885 InvalidRemap,
887 Cycle,
889 TooDeep,
891 NotOwnSource,
893 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#[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#[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#[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 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 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 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}