Skip to main content

alpha2_engine/extract/
descriptor.rs

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