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, rows packed), empty for RGBA8.
107    #[wasm_bindgen(getter, js_name = halfPixels)]
108    #[must_use]
109    pub fn half_pixels(&self) -> js_sys::Uint16Array {
110        js_sys::Uint16Array::from(self.pixels.linear_f16().unwrap_or_default())
111    }
112
113    /// Diagnostics, as a JSON array.
114    #[wasm_bindgen(getter)]
115    #[must_use]
116    pub fn diagnostics(&self) -> String {
117        serde_json::to_string(&self.diagnostics).unwrap_or_default()
118    }
119
120    /// Which of the source's frames this is.
121    #[wasm_bindgen(getter)]
122    #[must_use]
123    pub fn index(&self) -> usize {
124        self.index
125    }
126
127    /// The first source tick it shows at; 0 for the first frame.
128    #[wasm_bindgen(getter, js_name = startTicks)]
129    #[must_use]
130    pub fn start_ticks(&self) -> i64 {
131        self.start.max(0)
132    }
133
134    /// The first source tick it no longer shows at, or `undefined` for the last frame.
135    #[wasm_bindgen(getter, js_name = endTicks)]
136    #[must_use]
137    pub fn end_ticks(&self) -> Option<i64> {
138        self.end
139    }
140}
141
142impl Default for ExtensionRegistry {
143    fn default() -> Self {
144        Self::new()
145    }
146}
147
148#[wasm_bindgen]
149impl ExtensionRegistry {
150    /// Every provider this module was built with.
151    #[wasm_bindgen(constructor)]
152    #[must_use]
153    pub fn new() -> Self {
154        Self {
155            registry: Registry::with_defaults(),
156            resources: Resources::default(),
157            sources: HashMap::new(),
158            next: 1,
159        }
160    }
161
162    /// The providers' names, in priority order, as a JSON array.
163    #[must_use]
164    pub fn providers(&self) -> String {
165        serde_json::to_string(&self.registry.names()).unwrap_or_default()
166    }
167
168    /// Whether this module opens a project's provider source (JSON).
169    #[must_use]
170    pub fn supports(&self, provider: &str) -> bool {
171        serde_json::from_str::<ProviderSource>(provider)
172            .is_ok_and(|source| self.registry.supports(&source))
173    }
174
175    /// The first claiming provider's result as JSON `{ provider, report }`, or `undefined`.
176    ///
177    /// # Errors
178    /// If a claiming provider cannot read the bytes.
179    pub fn probe(&self, bytes: &[u8]) -> Result<Option<String>, JsValue> {
180        match self.registry.probe(bytes) {
181            None => Ok(None),
182            Some(Err(error)) => Err(js_error(error)),
183            Some(Ok((provider, report))) => serde_json::to_string(&serde_json::json!({
184                "provider": provider,
185                "report": report,
186            }))
187            .map(Some)
188            .map_err(js_error),
189        }
190    }
191
192    /// Registers bytes under a locator. Sources read them only during open or render, so a page
193    /// may register them just for that call (see [`Self::needs`]).
194    #[wasm_bindgen(js_name = registerResource)]
195    pub fn register_resource(&mut self, locator: String, bytes: Vec<u8>) {
196        self.resources.lock().files.insert(locator, bytes.into());
197    }
198
199    /// Forgets the bytes registered under a locator.
200    #[wasm_bindgen(js_name = releaseResource)]
201    pub fn release_resource(&mut self, locator: &str) {
202        self.resources.lock().files.remove(locator);
203    }
204
205    /// Total bytes registered under locators.
206    #[wasm_bindgen(js_name = resourceBytes)]
207    #[must_use]
208    pub fn resource_bytes(&self) -> usize {
209        self.resources
210            .lock()
211            .files
212            .values()
213            .map(|file| file.len())
214            .sum()
215    }
216
217    /// Registers a font for SVG text. Sources read fonts when they open.
218    #[wasm_bindgen(js_name = registerFont)]
219    pub fn register_font(&mut self, bytes: Vec<u8>) {
220        self.resources.lock().fonts.push(bytes.into());
221    }
222
223    /// Forgets every registered font; open sources keep theirs.
224    #[wasm_bindgen(js_name = clearFonts)]
225    pub fn clear_fonts(&mut self) {
226        self.resources.lock().fonts.clear();
227    }
228
229    /// Locators opening a provider source (JSON) reads, as a JSON array.
230    ///
231    /// # Errors
232    /// When the provider source is not valid JSON.
233    #[wasm_bindgen(js_name = openNeeds)]
234    pub fn open_needs(&self, provider: &str) -> Result<String, JsValue> {
235        let provider: ProviderSource = serde_json::from_str(provider).map_err(js_error)?;
236        serde_json::to_string(&self.registry.open_needs(&provider)).map_err(js_error)
237    }
238
239    /// Locators rendering at a source tick reads that the source does not hold, as a JSON array.
240    ///
241    /// # Errors
242    /// When the handle is not open.
243    pub fn needs(&self, handle: u32, time_ticks: i64) -> Result<String, JsValue> {
244        let source = self
245            .sources
246            .get(&handle)
247            .ok_or_else(|| js_error("the source is not open"))?;
248        serde_json::to_string(&source.needs(MediaTime::from_ticks(time_ticks))).map_err(js_error)
249    }
250
251    /// Opens a provider source (JSON) with its bytes (none for an image sequence or LaTeX) and
252    /// returns a handle.
253    ///
254    /// # Errors
255    /// If the source cannot be opened.
256    pub fn open(&mut self, provider: &str, bytes: Option<Vec<u8>>) -> Result<u32, JsValue> {
257        let provider: ProviderSource = serde_json::from_str(provider).map_err(js_error)?;
258        let source = self
259            .registry
260            .open(
261                &provider,
262                bytes.map(Arc::from),
263                Arc::new(self.resources.clone()) as SharedResolver,
264            )
265            .map_err(js_error)?;
266        let handle = self.next;
267        self.next = self.next.wrapping_add(1).max(1);
268        self.sources.insert(handle, source);
269        Ok(handle)
270    }
271
272    /// What an opened source is, as JSON.
273    ///
274    /// # Errors
275    /// When the handle is not open.
276    pub fn report(&self, handle: u32) -> Result<String, JsValue> {
277        let source = self
278            .sources
279            .get(&handle)
280            .ok_or_else(|| js_error("the source is not open"))?;
281        serde_json::to_string(source.report()).map_err(js_error)
282    }
283
284    /// The frame at a source tick. Vector sources rasterize to fit `fit_width` by `fit_height`
285    /// (0 by 0 for their own size).
286    ///
287    /// # Errors
288    /// When the handle is not open or the frame cannot be produced.
289    pub fn render(
290        &mut self,
291        handle: u32,
292        time_ticks: i64,
293        fit_width: u32,
294        fit_height: u32,
295    ) -> Result<RenderedFrame, JsValue> {
296        let source = self
297            .sources
298            .get_mut(&handle)
299            .ok_or_else(|| js_error("the source is not open"))?;
300        let frame = source
301            .render(MediaTime::from_ticks(time_ticks), (fit_width, fit_height))
302            .map_err(js_error)?;
303        Ok(RenderedFrame {
304            width: frame.width,
305            height: frame.height,
306            index: frame.index,
307            start: frame.start.ticks(),
308            end: frame.end.map(MediaTime::ticks),
309            pixels: frame.pixels,
310            diagnostics: frame.diagnostics,
311        })
312    }
313
314    /// Bytes an open source holds between renders (cached frames, images, and file bytes).
315    ///
316    /// # Errors
317    /// When the handle is not open.
318    #[wasm_bindgen(js_name = residentBytes)]
319    pub fn resident_bytes(&self, handle: u32) -> Result<usize, JsValue> {
320        self.sources
321            .get(&handle)
322            .map(|source| source.resident_bytes())
323            .ok_or_else(|| js_error("the source is not open"))
324    }
325
326    /// A handle to another independently positioned reader that shares the source's decoded
327    /// data. It stays valid after the original is closed. `undefined` when any time is equally
328    /// cheap to draw, so the page should share the source.
329    ///
330    /// # Errors
331    /// When the handle is not open.
332    pub fn reader(&mut self, handle: u32) -> Result<Option<u32>, JsValue> {
333        let source = self
334            .sources
335            .get(&handle)
336            .ok_or_else(|| js_error("the source is not open"))?;
337        let Some(reader) = source.reader() else {
338            return Ok(None);
339        };
340        let handle = self.next;
341        self.next = self.next.wrapping_add(1).max(1);
342        self.sources.insert(handle, reader);
343        Ok(Some(handle))
344    }
345
346    /// The part of [`Self::resident_bytes`] shared with [`Self::reader`] readers, counted once.
347    ///
348    /// # Errors
349    /// When the handle is not open.
350    #[wasm_bindgen(js_name = sharedBytes)]
351    pub fn shared_bytes(&self, handle: u32) -> Result<usize, JsValue> {
352        self.sources
353            .get(&handle)
354            .map(|source| source.shared_bytes())
355            .ok_or_else(|| js_error("the source is not open"))
356    }
357
358    /// Closes a source.
359    pub fn release(&mut self, handle: u32) {
360        self.sources.remove(&handle);
361    }
362}