Skip to main content

alpha2_extensions_web/
lib.rs

1//! The extension providers as a separate wasm module, loaded only by pages that need them.
2
3use std::collections::HashMap;
4use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
5
6use alpha2_extensions::{
7    Diagnostic, ExtensionError, FramePixels, Registry, ResourceResolver, SharedResolver,
8    VisualSource,
9};
10use alpha2_model::ProviderSource;
11use alpha2_time::MediaTime;
12use wasm_bindgen::prelude::*;
13
14fn js_error(error: impl std::fmt::Display) -> JsValue {
15    JsValue::from_str(&error.to_string())
16}
17
18/// Resources registered by the page: files by locator, and fonts.
19#[derive(Default)]
20struct Files {
21    files: HashMap<String, Arc<[u8]>>,
22    fonts: Vec<Arc<[u8]>>,
23}
24
25/// The page's resources, shared with sources that read them while rendering.
26#[derive(Clone, Default)]
27struct Resources(Arc<Mutex<Files>>);
28
29impl Resources {
30    fn lock(&self) -> MutexGuard<'_, Files> {
31        self.0.lock().unwrap_or_else(PoisonError::into_inner)
32    }
33}
34
35impl ResourceResolver for Resources {
36    fn bytes(&self, locator: &str) -> Result<Arc<[u8]>, ExtensionError> {
37        self.lock()
38            .files
39            .get(locator)
40            .cloned()
41            .ok_or_else(|| ExtensionError::MissingResource(locator.to_owned()))
42    }
43
44    fn fonts(&self) -> Vec<Arc<[u8]>> {
45        self.lock().fonts.clone()
46    }
47}
48
49/// The providers this module was built with, and the sources a page opened.
50///
51/// Failures are thrown as plain string messages, not `Error` objects.
52#[wasm_bindgen]
53pub struct ExtensionRegistry {
54    registry: Registry,
55    resources: Resources,
56    sources: HashMap<u32, Box<dyn VisualSource>>,
57    next: u32,
58}
59
60/// One frame a source rendered.
61#[wasm_bindgen]
62pub struct RenderedFrame {
63    width: u32,
64    height: u32,
65    pixels: FramePixels,
66    index: usize,
67    start: i64,
68    end: Option<i64>,
69    diagnostics: Vec<Diagnostic>,
70}
71
72#[wasm_bindgen]
73impl RenderedFrame {
74    /// Width in pixels.
75    #[wasm_bindgen(getter)]
76    #[must_use]
77    pub fn width(&self) -> u32 {
78        self.width
79    }
80
81    /// Height in pixels.
82    #[wasm_bindgen(getter)]
83    #[must_use]
84    pub fn height(&self) -> u32 {
85        self.height
86    }
87
88    /// `rgba8` for [`Self::pixels`], `linear_f16` for [`Self::half_pixels`].
89    #[wasm_bindgen(getter)]
90    #[must_use]
91    pub fn precision(&self) -> String {
92        match self.pixels {
93            FramePixels::LinearF16(_) => "linear_f16",
94            _ => "rgba8",
95        }
96        .to_owned()
97    }
98
99    /// Premultiplied, sRGB-encoded, packed RGBA8 rows; empty for another precision.
100    #[wasm_bindgen(getter)]
101    #[must_use]
102    pub fn pixels(&self) -> js_sys::Uint8Array {
103        js_sys::Uint8Array::from(self.pixels.rgba8().unwrap_or_default())
104    }
105
106    /// Premultiplied linear-light RGBA half-float bits, BT.709 primaries, rows packed; empty for
107    /// another precision.
108    #[wasm_bindgen(getter, js_name = halfPixels)]
109    #[must_use]
110    pub fn half_pixels(&self) -> js_sys::Uint16Array {
111        js_sys::Uint16Array::from(self.pixels.linear_f16().unwrap_or_default())
112    }
113
114    /// Diagnostics, as a JSON array.
115    #[wasm_bindgen(getter)]
116    #[must_use]
117    pub fn diagnostics(&self) -> String {
118        serde_json::to_string(&self.diagnostics).unwrap_or_default()
119    }
120
121    /// Which of the source's frames this is.
122    #[wasm_bindgen(getter)]
123    #[must_use]
124    pub fn index(&self) -> usize {
125        self.index
126    }
127
128    /// The first source tick it shows at; 0 for the first frame.
129    #[wasm_bindgen(getter, js_name = startTicks)]
130    #[must_use]
131    pub fn start_ticks(&self) -> i64 {
132        self.start.max(0)
133    }
134
135    /// The first source tick it no longer shows at, or `undefined` for the last frame.
136    #[wasm_bindgen(getter, js_name = endTicks)]
137    #[must_use]
138    pub fn end_ticks(&self) -> Option<i64> {
139        self.end
140    }
141}
142
143impl Default for ExtensionRegistry {
144    fn default() -> Self {
145        Self::new()
146    }
147}
148
149#[wasm_bindgen]
150impl ExtensionRegistry {
151    /// Every provider this module was built with.
152    #[wasm_bindgen(constructor)]
153    #[must_use]
154    pub fn new() -> Self {
155        Self {
156            registry: Registry::with_defaults(),
157            resources: Resources::default(),
158            sources: HashMap::new(),
159            next: 1,
160        }
161    }
162
163    /// The providers' names, in priority order, as a JSON array.
164    #[must_use]
165    pub fn providers(&self) -> String {
166        serde_json::to_string(&self.registry.names()).unwrap_or_default()
167    }
168
169    /// Whether this module opens a project's provider source (JSON).
170    #[must_use]
171    pub fn supports(&self, provider: &str) -> bool {
172        serde_json::from_str::<ProviderSource>(provider)
173            .is_ok_and(|source| self.registry.supports(&source))
174    }
175
176    /// The first claiming provider's result as JSON `{ provider, report }`, or `undefined`.
177    ///
178    /// # Errors
179    /// If a claiming provider cannot read the bytes.
180    pub fn probe(&self, bytes: &[u8]) -> Result<Option<String>, JsValue> {
181        match self.registry.probe(bytes) {
182            None => Ok(None),
183            Some(Err(error)) => Err(js_error(error)),
184            Some(Ok((provider, report))) => serde_json::to_string(&serde_json::json!({
185                "provider": provider,
186                "report": report,
187            }))
188            .map(Some)
189            .map_err(js_error),
190        }
191    }
192
193    /// Registers bytes under a locator. Sources read them only during open or render, so a page
194    /// may register them just for that call (see [`Self::needs`]).
195    #[wasm_bindgen(js_name = registerResource)]
196    pub fn register_resource(&mut self, locator: String, bytes: Vec<u8>) {
197        self.resources.lock().files.insert(locator, bytes.into());
198    }
199
200    /// Forgets the bytes registered under a locator.
201    #[wasm_bindgen(js_name = releaseResource)]
202    pub fn release_resource(&mut self, locator: &str) {
203        self.resources.lock().files.remove(locator);
204    }
205
206    /// Total bytes registered under locators.
207    #[wasm_bindgen(js_name = resourceBytes)]
208    #[must_use]
209    pub fn resource_bytes(&self) -> usize {
210        self.resources
211            .lock()
212            .files
213            .values()
214            .map(|file| file.len())
215            .sum()
216    }
217
218    /// Registers a font for SVG text. Sources read fonts when they open.
219    #[wasm_bindgen(js_name = registerFont)]
220    pub fn register_font(&mut self, bytes: Vec<u8>) {
221        self.resources.lock().fonts.push(bytes.into());
222    }
223
224    /// Forgets every registered font; open sources keep theirs.
225    #[wasm_bindgen(js_name = clearFonts)]
226    pub fn clear_fonts(&mut self) {
227        self.resources.lock().fonts.clear();
228    }
229
230    /// Locators opening a provider source (JSON) reads, as a JSON array.
231    ///
232    /// # Errors
233    /// When the provider source is not valid JSON.
234    #[wasm_bindgen(js_name = openNeeds)]
235    pub fn open_needs(&self, provider: &str) -> Result<String, JsValue> {
236        let provider: ProviderSource = serde_json::from_str(provider).map_err(js_error)?;
237        serde_json::to_string(&self.registry.open_needs(&provider)).map_err(js_error)
238    }
239
240    /// Locators rendering at a source tick reads that the source does not hold, as a JSON array.
241    ///
242    /// # Errors
243    /// When the handle is not open.
244    pub fn needs(&self, handle: u32, time_ticks: i64) -> Result<String, JsValue> {
245        let source = self
246            .sources
247            .get(&handle)
248            .ok_or_else(|| js_error("the source is not open"))?;
249        serde_json::to_string(&source.needs(MediaTime::from_ticks(time_ticks))).map_err(js_error)
250    }
251
252    /// Opens a provider source (JSON) with its bytes (none for an image sequence) and returns a
253    /// handle.
254    ///
255    /// # Errors
256    /// If the source cannot be opened.
257    pub fn open(&mut self, provider: &str, bytes: Option<Vec<u8>>) -> Result<u32, JsValue> {
258        let provider: ProviderSource = serde_json::from_str(provider).map_err(js_error)?;
259        let source = self
260            .registry
261            .open(
262                &provider,
263                bytes.map(Arc::from),
264                Arc::new(self.resources.clone()) as SharedResolver,
265            )
266            .map_err(js_error)?;
267        let handle = self.next;
268        self.next = self.next.wrapping_add(1).max(1);
269        self.sources.insert(handle, source);
270        Ok(handle)
271    }
272
273    /// What an opened source is, as JSON.
274    ///
275    /// # Errors
276    /// When the handle is not open.
277    pub fn report(&self, handle: u32) -> Result<String, JsValue> {
278        let source = self
279            .sources
280            .get(&handle)
281            .ok_or_else(|| js_error("the source is not open"))?;
282        serde_json::to_string(source.report()).map_err(js_error)
283    }
284
285    /// The frame at a source tick. Vector sources rasterize to fit `fit_width` by `fit_height`
286    /// (0 by 0 for their own size).
287    ///
288    /// # Errors
289    /// When the handle is not open or the frame cannot be produced.
290    pub fn render(
291        &mut self,
292        handle: u32,
293        time_ticks: i64,
294        fit_width: u32,
295        fit_height: u32,
296    ) -> Result<RenderedFrame, JsValue> {
297        let source = self
298            .sources
299            .get_mut(&handle)
300            .ok_or_else(|| js_error("the source is not open"))?;
301        let frame = source
302            .render(MediaTime::from_ticks(time_ticks), (fit_width, fit_height))
303            .map_err(js_error)?;
304        Ok(RenderedFrame {
305            width: frame.width,
306            height: frame.height,
307            index: frame.index,
308            start: frame.start.ticks(),
309            end: frame.end.map(MediaTime::ticks),
310            pixels: frame.pixels,
311            diagnostics: frame.diagnostics,
312        })
313    }
314
315    /// Bytes an open source holds between renders (cached frames, images, and file bytes).
316    ///
317    /// # Errors
318    /// When the handle is not open.
319    #[wasm_bindgen(js_name = residentBytes)]
320    pub fn resident_bytes(&self, handle: u32) -> Result<usize, JsValue> {
321        self.sources
322            .get(&handle)
323            .map(|source| source.resident_bytes())
324            .ok_or_else(|| js_error("the source is not open"))
325    }
326
327    /// A handle to another independently positioned reader that shares the source's decoded
328    /// data. It stays valid after the original is closed. `undefined` when any time is equally
329    /// cheap to draw, so the page should share the source.
330    ///
331    /// # Errors
332    /// When the handle is not open.
333    pub fn reader(&mut self, handle: u32) -> Result<Option<u32>, JsValue> {
334        let source = self
335            .sources
336            .get(&handle)
337            .ok_or_else(|| js_error("the source is not open"))?;
338        let Some(reader) = source.reader() else {
339            return Ok(None);
340        };
341        let handle = self.next;
342        self.next = self.next.wrapping_add(1).max(1);
343        self.sources.insert(handle, reader);
344        Ok(Some(handle))
345    }
346
347    /// The part of [`Self::resident_bytes`] shared with [`Self::reader`] readers, counted once.
348    ///
349    /// # Errors
350    /// When the handle is not open.
351    #[wasm_bindgen(js_name = sharedBytes)]
352    pub fn shared_bytes(&self, handle: u32) -> Result<usize, JsValue> {
353        self.sources
354            .get(&handle)
355            .map(|source| source.shared_bytes())
356            .ok_or_else(|| js_error("the source is not open"))
357    }
358
359    /// Closes a source.
360    pub fn release(&mut self, handle: u32) {
361        self.sources.remove(&handle);
362    }
363}