Skip to main content

alpha2_engine/extract/
mod.rs

1//! The extractor contract. Code outside the engine is supplied frames or audio and returns
2//! primitives that a project records as data sets.
3//!
4//! An extractor runs ahead of time over a range, never while a frame renders. The host drives an
5//! [`ExtractSession`]. It supplies each [`Need`] from its own decoders or renderer, hands each
6//! [`Delivery`] to the extractor, and passes the extractor's [`Emit`]s back for the session to
7//! validate. [`ExtractSession::finish`] returns sorted, validated data sets. Rust extractors
8//! implement [`Extractor`] and run through [`drive`]; other surfaces wrap the same step machine.
9//!
10//! Source frames are delivered display-oriented, contain-fit to at most `size` on the long edge
11//! ([`delivered_size`]), as straight-alpha sRGB `rgba8` or BT.709 `luma8` ([`luma8_from_rgba8`]).
12//! The module uses plain data only; the render path never calls it.
13//!
14//! # A minimal extractor
15//!
16//! The mean brightness of each timeline frame, as a `scalars` data set:
17//!
18//! ```
19//! use alpha2_engine::extract::{
20//!     AudioInput, Descriptor, Emitter, ExtractRequest, ExtractSession, Extractor,
21//!     ExtractorError, Need, PassInfo, RunContext, SuppliedAudio, SuppliedFrame, Supplier,
22//!     VideoInput, delivered_size, drive,
23//! };
24//! use serde_json::json;
25//!
26//! struct Brightness(Descriptor);
27//!
28//! impl Extractor for Brightness {
29//!     fn describe(&self) -> &Descriptor {
30//!         &self.0
31//!     }
32//!     fn begin(&mut self, _context: &RunContext) -> Result<(), ExtractorError> {
33//!         Ok(())
34//!     }
35//!     fn pass(&mut self, _pass: &PassInfo) -> Result<(), ExtractorError> {
36//!         Ok(())
37//!     }
38//!     fn video(&mut self, frame: &VideoInput, out: &mut Emitter) -> Result<(), ExtractorError> {
39//!         let sum: u64 = frame.bytes.iter().map(|&value| u64::from(value)).sum();
40//!         let mean = sum as f32 / frame.bytes.len() as f32 / 255.0;
41//!         out.sample("level", frame.time, &[Some(mean)]);
42//!         Ok(())
43//!     }
44//!     fn audio(&mut self, _block: &AudioInput, _out: &mut Emitter) -> Result<(), ExtractorError> {
45//!         Ok(())
46//!     }
47//!     fn end(&mut self, _out: &mut Emitter) -> Result<(), ExtractorError> {
48//!         Ok(())
49//!     }
50//! }
51//!
52//! /// Grey frames; a host supplies decoded or rendered ones.
53//! struct Grey;
54//!
55//! impl Supplier for Grey {
56//!     fn frame(&mut self, need: &Need) -> Result<Option<SuppliedFrame>, String> {
57//!         let Need::TimelineFrame { time, size, .. } = need else {
58//!             return Err("timeline frames only".into());
59//!         };
60//!         let (width, height) = delivered_size((64, 36), *size);
61//!         let rgba = vec![128; (width * height * 4) as usize];
62//!         Ok(Some(SuppliedFrame { pts: *time, width, height, rgba }))
63//!     }
64//!     fn audio(&mut self, _need: &Need) -> Result<SuppliedAudio, String> {
65//!         Err("no audio".into())
66//!     }
67//! }
68//!
69//! let project = alpha2_model::Project::from_json(&json!({
70//!     "schema_version": 1, "id": "p", "name": "P",
71//!     "settings": { "width": 64, "height": 36, "frame_rate": { "num": 30, "den": 1 },
72//!                   "sample_rate": 48_000 },
73//!     "sources": [], "timeline": { "tracks": [] }
74//! }).to_string())?;
75//! let descriptor: Descriptor = serde_json::from_value(json!({
76//!     "id": "com.example.brightness", "version": 1,
77//!     "input": { "media": "video", "from": ["timeline"], "format": "luma8" },
78//!     "outputs": [{ "name": "level", "kind": "scalars", "channels": ["y"] }]
79//! }))?;
80//! let request: ExtractRequest = serde_json::from_value(json!({
81//!     "extractor": "com.example.brightness", "version": 1,
82//!     "input": { "from": "timeline", "range": { "start": 0, "end": 12_000 }, "size": 32 },
83//!     "outputs": { "level": "brightness" }
84//! }))?;
85//! let session = ExtractSession::new(&project, &descriptor, request)?;
86//! let sets = drive(session, &mut Brightness(descriptor), &mut Grey)?;
87//! assert_eq!(sets[0].id.as_str(), "brightness");
88//! # Ok::<(), Box<dyn std::error::Error>>(())
89//! ```
90//!
91//! # Limits
92//!
93//! - Outputs per descriptor: [`MAX_EXTRACTOR_OUTPUTS`]; passes per request:
94//!   [`MAX_EXTRACTOR_PASSES`].
95//! - A delivered frame's long edge when the descriptor names none: [`DEFAULT_MAX_SIZE`].
96//! - Frames per audio block: [`BLOCK_FRAMES_RANGE`], [`DEFAULT_BLOCK_FRAMES`] when unnamed.
97//! - Project-rate samples a timeline audio read mixes at once: [`TIMELINE_MIX_BLOCK`].
98//! - Plugin manifest size: [`MAX_MANIFEST_BYTES`]; artifacts and resources per manifest:
99//!   [`MAX_PLUGIN_ARTIFACTS`], [`MAX_PLUGIN_RESOURCES`]; file lengths:
100//!   [`MAX_PLUGIN_ARTIFACT_BYTES`], [`MAX_PLUGIN_RESOURCE_BYTES`],
101//!   [`MAX_PLUGIN_RESOURCES_TOTAL_BYTES`].
102//! - Data sets per project: [`alpha2_model::MAX_DATA_SETS`]; channels per output:
103//!   [`alpha2_model::MAX_DATA_CHANNELS`].
104//! - Values, words and intervals per data set: [`alpha2_model::MAX_DATA_VALUES`],
105//!   [`alpha2_model::MAX_DATA_WORDS`], [`alpha2_model::MAX_DATA_INTERVALS`].
106//! - Data set ids, and labels, texts, speakers and channel names:
107//!   [`alpha2_model::MAX_DATA_ID_BYTES`], [`alpha2_model::MAX_DATA_LABEL_BYTES`].
108//! - Emitted values: [`alpha2_model::MAX_DATA_COORDINATE`] for points and similarity
109//!   translation, [`alpha2_model::MAX_DATA_SCALAR`] for scalars and interval scores, and for
110//!   similarity [`alpha2_model::MAX_DATA_ROTATION_DEGREES`] and [`alpha2_model::MAX_DATA_SCALE`].
111
112mod descriptor;
113mod diagnose;
114mod drive;
115#[cfg(any(test, feature = "extract-fixtures"))]
116pub mod fixtures;
117mod manifest;
118mod pixels;
119mod session;
120#[cfg(test)]
121mod tests;
122mod timeline_audio;
123mod wire;
124
125pub use descriptor::{
126    AudioChannels, AudioFormat, BLOCK_FRAMES_RANGE, DEFAULT_BLOCK_FRAMES, DEFAULT_MAX_SIZE,
127    Descriptor, Direction, ExtractRequest, InputFrom, InputSpec, MAX_EXTRACTOR_OUTPUTS,
128    MAX_EXTRACTOR_PASSES, MAX_OUTPUT_DESCRIPTION_CHARS, MAX_OUTPUT_LABEL_CHARS, OutputSpec, Pass,
129    RequestInput, Suggest, VideoFormat,
130};
131pub use diagnose::{
132    MANIFEST_CODES, MANIFEST_REFUSED, MANIFEST_TOO_LARGE, MANIFEST_UNSUPPORTED_ABI,
133    diagnose_manifest,
134};
135pub use drive::{
136    DriveError, Emitter, Extractor, ExtractorError, FramePlace, PassInfo, Supplier, drive,
137    supply_frame,
138};
139pub use manifest::{
140    ArtifactKind, MAX_ABOUT_AUTHOR_CHARS, MAX_ABOUT_HOMEPAGE_CHARS, MAX_ABOUT_LICENSE_CHARS,
141    MAX_ABOUT_NAME_CHARS, MAX_ABOUT_SUMMARY_CHARS, MAX_MANIFEST_BYTES, MAX_PLUGIN_ARTIFACT_BYTES,
142    MAX_PLUGIN_ARTIFACTS, MAX_PLUGIN_RESOURCE_BYTES, MAX_PLUGIN_RESOURCES,
143    MAX_PLUGIN_RESOURCES_TOTAL_BYTES, MAX_PLUGIN_SLOTS, MAX_SLOT_ACCEPT, MAX_SLOT_ACCEPT_BYTES,
144    MAX_SLOT_NAME_BYTES, ManifestError, PLUGIN_MANIFEST_SCHEMA_ID, PinnedResource, PluginAbout,
145    PluginArtifact, PluginKind, PluginManifest, PluginResource, Reference, ResourceSource,
146    SlotShape, SuppliedSlot, WASM_TARGET, is_slot_name, reference,
147};
148#[cfg(feature = "schema")]
149pub use manifest::{plugin_manifest_json_schema, plugin_manifest_shape_json};
150pub use pixels::{
151    delivered_size, displayed_size, luma8_from_rgba8, mono_downmix, present_for_extraction,
152    present_for_extraction_into,
153};
154pub use session::{
155    AudioInput, Delivery, Emit, ExtractSession, FrameFrom, Need, PassProgress, RequestError,
156    RunContext, SessionError, Stage, Step, SuppliedAudio, SuppliedFrame, VideoInput,
157};
158pub use timeline_audio::{TIMELINE_MIX_BLOCK, TimelineAudioRead};
159pub use wire::{client_context_json, emit_from_json, progress_json};