Skip to main content

alpha2_engine/extract/
descriptor.rs

1//! What an extractor declares, and what one run asks of it.
2
3use alpha2_media::SourceId;
4use alpha2_model::{DataInterpolation, DataKind, DataSetId};
5use alpha2_time::{FrameRate, MediaTime, TimeRange};
6use serde::{Deserialize, Serialize};
7use std::collections::BTreeMap;
8
9/// The longest edge of a delivered video frame when the descriptor gives none.
10pub const DEFAULT_MAX_SIZE: u32 = 960;
11/// Audio frames per delivered block when the descriptor gives none.
12pub const DEFAULT_BLOCK_FRAMES: u32 = 1024;
13/// The range of `block_frames` a descriptor may declare.
14pub const BLOCK_FRAMES_RANGE: std::ops::RangeInclusive<u32> = 64..=65_536;
15/// Most outputs one extractor declares.
16pub const MAX_EXTRACTOR_OUTPUTS: usize = 32;
17/// Most passes one request asks for.
18pub const MAX_EXTRACTOR_PASSES: usize = 64;
19/// The longest output `label`, in characters.
20pub const MAX_OUTPUT_LABEL_CHARS: usize = 80;
21/// The longest output `description`, in characters.
22pub const MAX_OUTPUT_DESCRIPTION_CHARS: usize = 400;
23
24/// What an extractor declares, with its identity, the input it reads and the outputs it emits.
25#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
26#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
27#[serde(deny_unknown_fields)]
28pub struct Descriptor {
29    /// Reverse-DNS id; `alpha2.` is reserved for first-party plugins by convention.
30    pub id: String,
31    /// The output contract's version.
32    pub version: u32,
33    /// What the extractor reads.
34    pub input: InputSpec,
35    /// JSON Schema of the request's `params`, for interfaces and validation by surface helpers.
36    #[serde(default = "empty_schema")]
37    pub params_schema: serde_json::Value,
38    /// The outputs it emits, by name.
39    pub outputs: Vec<OutputSpec>,
40}
41
42fn empty_schema() -> serde_json::Value {
43    serde_json::json!({})
44}
45
46/// What an extractor reads.
47#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
48#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
49#[serde(tag = "media", rename_all = "snake_case", deny_unknown_fields)]
50pub enum InputSpec {
51    /// Pictures.
52    Video {
53        /// The inputs it can read.
54        from: Vec<InputFrom>,
55        /// The pixel format delivered.
56        format: VideoFormat,
57        /// The longest edge a delivered frame may have, in pixels.
58        #[serde(default = "default_max_size")]
59        max_size: u32,
60    },
61    /// Sound.
62    Audio {
63        /// The inputs it can read.
64        from: Vec<InputFrom>,
65        /// The sample format delivered.
66        format: AudioFormat,
67        /// The rate it needs, if fixed.
68        #[serde(default, skip_serializing_if = "Option::is_none")]
69        sample_rate: Option<u32>,
70        /// The channel layout it needs, if fixed.
71        #[serde(default, skip_serializing_if = "Option::is_none")]
72        channels: Option<AudioChannels>,
73        /// Frames per delivered block, in [`BLOCK_FRAMES_RANGE`].
74        #[serde(default = "default_block_frames")]
75        block_frames: u32,
76    },
77}
78
79const fn default_max_size() -> u32 {
80    DEFAULT_MAX_SIZE
81}
82
83const fn default_block_frames() -> u32 {
84    DEFAULT_BLOCK_FRAMES
85}
86
87impl InputSpec {
88    /// The inputs the extractor can read.
89    #[must_use]
90    pub fn from(&self) -> &[InputFrom] {
91        match self {
92            Self::Video { from, .. } | Self::Audio { from, .. } => from,
93        }
94    }
95}
96
97/// Which clock an extractor reads on.
98#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
99#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Hash, Serialize)]
100#[serde(rename_all = "snake_case")]
101pub enum InputFrom {
102    /// A source, in source time; its outputs are anchored to that source.
103    Source,
104    /// The rendered timeline, in timeline time; its outputs are anchored to the timeline.
105    Timeline,
106}
107
108/// How delivered video frames are packed.
109#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
110#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Hash, Serialize)]
111#[serde(rename_all = "snake_case")]
112pub enum VideoFormat {
113    /// Four bytes a pixel: straight-alpha, sRGB-encoded RGBA.
114    Rgba8,
115    /// One byte a pixel: BT.709 Y' of the sRGB-encoded RGB.
116    Luma8,
117}
118
119impl VideoFormat {
120    /// Bytes a pixel.
121    #[must_use]
122    pub const fn bytes_per_pixel(self) -> usize {
123        match self {
124            Self::Rgba8 => 4,
125            Self::Luma8 => 1,
126        }
127    }
128}
129
130/// How delivered audio is stored.
131#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
132#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Hash, Serialize)]
133#[serde(rename_all = "snake_case")]
134pub enum AudioFormat {
135    /// Planar 32-bit float, channel after channel.
136    F32,
137}
138
139/// Which channels delivered audio has.
140#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
141#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Hash, Serialize)]
142#[serde(rename_all = "snake_case")]
143pub enum AudioChannels {
144    /// One channel, the mixer's equal-weight downmix.
145    Mono,
146    /// The source's (or the mix's) own channels.
147    Source,
148}
149
150/// One output an extractor emits.
151#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
152#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
153#[serde(deny_unknown_fields)]
154pub struct OutputSpec {
155    /// Its name, unique among the outputs.
156    pub name: String,
157    /// The kind of data it holds.
158    pub kind: DataKind,
159    /// Channel names, for `points` and `scalars`.
160    #[serde(default, skip_serializing_if = "Vec::is_empty")]
161    pub channels: Vec<String>,
162    /// How the values read between samples, for the sampled kinds; `hold` when left out.
163    #[serde(default, skip_serializing_if = "Option::is_none")]
164    pub interpolation: Option<DataInterpolation>,
165    /// How the output is usually used, for interfaces. The engine ignores it.
166    #[serde(default, skip_serializing_if = "Option::is_none")]
167    pub suggest: Option<Suggest>,
168    /// The output's name in an interface, plain text without control characters. The engine
169    /// ignores it.
170    #[serde(default, skip_serializing_if = "Option::is_none")]
171    #[cfg_attr(
172        feature = "schema",
173        schemars(length(min = 1, max = MAX_OUTPUT_LABEL_CHARS), regex(pattern = PLAIN_TEXT_PATTERN))
174    )]
175    pub label: Option<String>,
176    /// What the output holds, for an interface, plain text without control characters. The
177    /// engine ignores it.
178    #[serde(default, skip_serializing_if = "Option::is_none")]
179    #[cfg_attr(
180        feature = "schema",
181        schemars(length(max = MAX_OUTPUT_DESCRIPTION_CHARS), regex(pattern = PLAIN_TEXT_PATTERN))
182    )]
183    pub description: Option<String>,
184}
185
186#[cfg(feature = "schema")]
187pub(super) const PLAIN_TEXT_PATTERN: &str = r"^[^\u0000-\u001F\u007F-\u009F]*$";
188
189pub(super) fn plain_text(text: &str, min: usize, max: usize) -> bool {
190    (min..=max).contains(&text.chars().count()) && !text.chars().any(char::is_control)
191}
192
193impl OutputSpec {
194    /// Numbers per sample of this output, channels times components; zero for words and intervals.
195    #[must_use]
196    pub fn sample_width(&self) -> usize {
197        match self.kind {
198            DataKind::Points => self.channels.len() * 2,
199            DataKind::Scalars => self.channels.len(),
200            DataKind::Similarity => alpha2_model::SIMILARITY_ARITY,
201            DataKind::Words | DataKind::Intervals => 0,
202        }
203    }
204
205    /// The most samples, words or intervals one data set of this output holds, from the data
206    /// limits ([`alpha2_model::MAX_DATA_VALUES`] counts numbers, not samples).
207    #[must_use]
208    pub fn max_items(&self) -> usize {
209        match self.kind {
210            DataKind::Points | DataKind::Scalars | DataKind::Similarity => {
211                alpha2_model::MAX_DATA_VALUES / self.sample_width().max(1)
212            }
213            DataKind::Words => alpha2_model::MAX_DATA_WORDS,
214            DataKind::Intervals => alpha2_model::MAX_DATA_INTERVALS,
215        }
216    }
217}
218
219/// How an output is usually used.
220#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
221#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Hash, Serialize)]
222#[serde(rename_all = "snake_case")]
223pub enum Suggest {
224    /// Values bind to it.
225    Bind,
226    /// `remove_ranges` applies it.
227    RemoveRanges,
228    /// `split_at` applies it.
229    SplitAt,
230}
231
232/// One run of an extractor.
233#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
234#[serde(deny_unknown_fields)]
235pub struct ExtractRequest {
236    /// The descriptor's id.
237    pub extractor: String,
238    /// The descriptor's version.
239    pub version: u32,
240    /// Parameters, validated against the descriptor's schema by the surface helper.
241    #[serde(default)]
242    pub params: serde_json::Map<String, serde_json::Value>,
243    /// What is read.
244    pub input: RequestInput,
245    /// For each output recorded, the data set id it becomes; outputs left out are discarded.
246    pub outputs: BTreeMap<String, DataSetId>,
247}
248
249/// What a run reads.
250#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
251#[serde(deny_unknown_fields)]
252pub struct RequestInput {
253    /// The clock read.
254    pub from: InputFrom,
255    /// The source, for source input.
256    #[serde(default, skip_serializing_if = "Option::is_none")]
257    pub source_id: Option<SourceId>,
258    /// The interval read, on that clock.
259    pub range: TimeRange,
260    /// The passes; none means one forward pass from the range start.
261    #[serde(default, skip_serializing_if = "Vec::is_empty")]
262    pub passes: Vec<Pass>,
263    /// The longest edge of delivered frames; at most the descriptor's `max_size`, its default.
264    #[serde(default, skip_serializing_if = "Option::is_none")]
265    pub size: Option<u32>,
266    /// The frame rate of timeline frames; the project's by default.
267    #[serde(default, skip_serializing_if = "Option::is_none")]
268    pub frame_rate: Option<FrameRate>,
269    /// The source's audio stream ordinal, for source audio; the first by default.
270    #[serde(default, skip_serializing_if = "Option::is_none")]
271    pub stream: Option<u32>,
272    /// The audio rate; the descriptor's if fixed, else the project's.
273    #[serde(default, skip_serializing_if = "Option::is_none")]
274    pub sample_rate: Option<u32>,
275    /// The audio channels; the descriptor's if fixed, else mono.
276    #[serde(default, skip_serializing_if = "Option::is_none")]
277    pub channels: Option<AudioChannels>,
278}
279
280/// One pass of a run, from a start time in one direction.
281#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
282#[serde(deny_unknown_fields)]
283pub struct Pass {
284    /// Where the pass starts, inside the range.
285    pub start: MediaTime,
286    /// Which way it runs.
287    pub direction: Direction,
288}
289
290/// The direction of a pass.
291#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Hash, Serialize)]
292#[serde(rename_all = "snake_case")]
293pub enum Direction {
294    /// Toward the range end.
295    Forward,
296    /// Toward the range start.
297    Backward,
298}