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