Skip to main content

alpha2_extensions/
registry.rs

1//! Provider selection by probing bytes in registration order, with no fallback after a failure.
2//!
3//! Every provider call goes through [`contained`], so a panic in third-party parsing code fails
4//! only that file. In the browser module panics abort, and `alpha2/extensions` restarts the module.
5
6use std::panic::{AssertUnwindSafe, catch_unwind};
7use std::sync::Arc;
8
9use alpha2_model::ProviderSource;
10use alpha2_time::MediaTime;
11
12use crate::api::{
13    ExtensionError, ProbeReport, SharedResolver, VisualFrame, VisualProvider, VisualSource,
14};
15
16/// The providers a host's build includes, highest priority first.
17#[derive(Default)]
18pub struct Registry {
19    providers: Vec<Box<dyn VisualProvider>>,
20}
21
22impl Registry {
23    /// Every provider this build includes, in order: SVG, animated images, Lottie, OpenEXR.
24    #[must_use]
25    pub fn with_defaults() -> Self {
26        #[allow(unused_mut)]
27        let mut registry = Self::default();
28        #[cfg(feature = "svg")]
29        registry.register(Box::new(crate::SvgProvider));
30        #[cfg(feature = "animated-image")]
31        registry.register(Box::new(crate::AnimatedImageProvider));
32        #[cfg(feature = "lottie")]
33        registry.register(Box::new(crate::LottieProvider));
34        #[cfg(feature = "exr")]
35        registry.register(Box::new(crate::ExrProvider));
36        registry
37    }
38
39    /// Adds `provider` after those already registered.
40    pub fn register(&mut self, provider: Box<dyn VisualProvider>) {
41        self.providers.push(provider);
42    }
43
44    /// The registered providers' names, in priority order.
45    #[must_use]
46    pub fn names(&self) -> Vec<&'static str> {
47        self.providers
48            .iter()
49            .map(|provider| provider.name())
50            .collect()
51    }
52
53    /// The first provider that claims `bytes` and its report, or `None`. A claiming provider's
54    /// error is returned as is; no other provider is tried.
55    #[must_use]
56    pub fn probe(
57        &self,
58        bytes: &[u8],
59    ) -> Option<Result<(&'static str, ProbeReport), ExtensionError>> {
60        self.providers.iter().find_map(|provider| {
61            let name = provider.name();
62            contained(name, || Ok(provider.probe(bytes)))
63                .unwrap_or_else(|error| Some(Err(error)))
64                .map(|report| report.map(|report| (name, report)))
65        })
66    }
67
68    /// Whether this build opens `source`.
69    #[must_use]
70    pub fn supports(&self, source: &ProviderSource) -> bool {
71        match source {
72            ProviderSource::ImageSequence { .. } => Self::reads_image_sequences(),
73            other => self.named(provider_name(other)).is_some(),
74        }
75    }
76
77    /// Whether this build reads image sequences, which have no registered provider.
78    #[must_use]
79    pub const fn reads_image_sequences() -> bool {
80        cfg!(feature = "image-sequence")
81    }
82
83    /// Locators [`Self::open`] reads for `source` (an image sequence's first frame).
84    #[must_use]
85    pub fn open_needs(&self, source: &ProviderSource) -> Vec<String> {
86        match source {
87            ProviderSource::ImageSequence { frames, .. } => {
88                frames.first().cloned().flatten().into_iter().collect()
89            }
90            _ => Vec::new(),
91        }
92    }
93
94    /// Opens a project's provider source from its bytes (`None` for an image sequence, whose
95    /// frames come from `resolver`).
96    ///
97    /// Renders go through the same panic boundary. After one render panics, every later render
98    /// fails without running provider code on the state the panic left.
99    ///
100    /// # Errors
101    /// [`ExtensionError::Unsupported`] without a provider, [`ExtensionError::Mismatch`] for
102    /// another format, or the provider's error ([`ExtensionError::Malformed`] if it panicked).
103    #[cfg_attr(not(feature = "image-sequence"), allow(clippy::needless_pass_by_value))]
104    pub fn open(
105        &self,
106        source: &ProviderSource,
107        bytes: Option<Arc<[u8]>>,
108        resolver: SharedResolver,
109    ) -> Result<Box<dyn VisualSource>, ExtensionError> {
110        let name = provider_name(source);
111        let opened = match source {
112            #[cfg(feature = "image-sequence")]
113            ProviderSource::ImageSequence {
114                frames,
115                frame_rate,
116                missing,
117                primaries,
118                ..
119            } => contained(name, || {
120                crate::open_sequence(frames, *frame_rate, *missing, *primaries, resolver)
121            })?,
122            other => {
123                let provider = self.named(name).ok_or_else(|| {
124                    ExtensionError::Unsupported(format!("this build has no {name} provider"))
125                })?;
126                let bytes = bytes.ok_or_else(|| {
127                    ExtensionError::MissingResource("the source's own bytes".into())
128                })?;
129                // Open detects a format mismatch itself, so no extra probe pass is needed.
130                contained(name, || provider.open(bytes, other, &*resolver))?
131            }
132        };
133        Ok(Box::new(Contained {
134            name,
135            source: opened,
136            failed: None,
137        }))
138    }
139
140    fn named(&self, name: &str) -> Option<&dyn VisualProvider> {
141        self.providers
142            .iter()
143            .find(|provider| provider.name() == name)
144            .map(AsRef::as_ref)
145    }
146}
147
148/// A source whose renders go through the panic boundary.
149struct Contained {
150    name: &'static str,
151    source: Box<dyn VisualSource>,
152    /// Set once a render panics, and returned by every later render.
153    failed: Option<ExtensionError>,
154}
155
156impl VisualSource for Contained {
157    fn report(&self) -> &ProbeReport {
158        self.source.report()
159    }
160
161    fn render(&mut self, time: MediaTime, fit: (u32, u32)) -> Result<VisualFrame, ExtensionError> {
162        if let Some(error) = &self.failed {
163            return Err(error.clone());
164        }
165        let source = &mut self.source;
166        catch_unwind(AssertUnwindSafe(|| source.render(time, fit))).unwrap_or_else(|payload| {
167            let error = panicked(self.name, payload.as_ref());
168            self.failed = Some(error.clone());
169            Err(error)
170        })
171    }
172
173    fn needs(&self, time: MediaTime) -> Vec<String> {
174        if self.failed.is_some() {
175            return Vec::new();
176        }
177        catch_unwind(AssertUnwindSafe(|| self.source.needs(time))).unwrap_or_default()
178    }
179
180    fn resident_bytes(&self) -> usize {
181        catch_unwind(AssertUnwindSafe(|| self.source.resident_bytes())).unwrap_or_default()
182    }
183
184    /// None after a panic, since shared state may be what the panic left.
185    fn reader(&self) -> Option<Box<dyn VisualSource>> {
186        if self.failed.is_some() {
187            return None;
188        }
189        let source = catch_unwind(AssertUnwindSafe(|| self.source.reader())).ok()??;
190        Some(Box::new(Self {
191            name: self.name,
192            source,
193            failed: None,
194        }))
195    }
196
197    fn shared_bytes(&self) -> usize {
198        catch_unwind(AssertUnwindSafe(|| self.source.shared_bytes())).unwrap_or_default()
199    }
200}
201
202/// Runs `call`, turning a panic into the file's failure.
203fn contained<T>(
204    provider: &str,
205    call: impl FnOnce() -> Result<T, ExtensionError>,
206) -> Result<T, ExtensionError> {
207    catch_unwind(AssertUnwindSafe(call))
208        .unwrap_or_else(|payload| Err(panicked(provider, payload.as_ref())))
209}
210
211fn panicked(provider: &str, payload: &(dyn std::any::Any + Send)) -> ExtensionError {
212    let message = payload
213        .downcast_ref::<&str>()
214        .copied()
215        .or_else(|| payload.downcast_ref::<String>().map(String::as_str))
216        .unwrap_or("no message");
217    ExtensionError::Malformed(format!(
218        "the {provider} provider failed on this file (it panicked: {message})"
219    ))
220}
221
222fn provider_name(source: &ProviderSource) -> &'static str {
223    match source {
224        ProviderSource::Svg => "svg",
225        ProviderSource::AnimatedImage => "animated-image",
226        ProviderSource::Lottie { .. } => "lottie",
227        ProviderSource::Exr { .. } => "exr",
228        _ => "image-sequence",
229    }
230}