Skip to main content

strata/runtime/
media_host.rs

1//! Declarative `<audio>` and `<video>` DOM media element reconciliation and playback registry.
2
3use std::collections::HashMap;
4use strata_dom::{Attribute, NodeBlueprint, Tag};
5
6/// Kind of declarative media element discovered in a Strata RSX blueprint tree.
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum MediaElementKind {
9    Audio,
10    Video,
11}
12
13/// Extracted declarative attributes of an `<audio>` or `<video>` DOM node.
14#[derive(Debug, Clone, PartialEq)]
15pub struct MediaElementSpec {
16    pub id: String,
17    pub kind: MediaElementKind,
18    pub src: Option<String>,
19    pub poster: Option<String>,
20    pub camera: Option<String>,
21    pub autoplay: bool,
22    pub looping: bool,
23    pub muted: bool,
24    pub controls: bool,
25    pub volume: f32,
26    pub playback_rate: f32,
27}
28
29/// Runtime registry reconciling declarative `<audio>` and `<video>` elements across view rebuilds.
30#[derive(Default)]
31pub struct MediaHostRegistry {
32    elements: HashMap<String, MediaElementSpec>,
33    #[cfg(feature = "audio-dsp")]
34    audio_players: HashMap<String, strata_audio::AudioPlayer>,
35    #[cfg(feature = "media")]
36    video_players: HashMap<String, strata_media::VideoPlayer>,
37}
38
39impl std::fmt::Debug for MediaHostRegistry {
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41        f.debug_struct("MediaHostRegistry")
42            .field("elements", &self.elements)
43            .finish()
44    }
45}
46
47impl MediaHostRegistry {
48    pub fn new() -> Self {
49        Self::default()
50    }
51
52    /// Scans a [`strata_dom::View`] and reconciles active `<audio>` and `<video>` instances.
53    pub fn sync_from_view(&mut self, view: &strata_dom::View) {
54        self.sync_from_blueprint(&view.root);
55    }
56
57    /// Scans a [`NodeBlueprint`] tree and reconciles active `<audio>` and `<video>` instances.
58    pub fn sync_from_blueprint(&mut self, root: &NodeBlueprint) {
59        let mut discovered = Vec::new();
60        let mut auto_idx = 0usize;
61        collect_media_elements(root, &mut discovered, &mut auto_idx);
62
63        let mut next_ids = Vec::with_capacity(discovered.len());
64        for spec in discovered {
65            let id = spec.id.clone();
66            next_ids.push(id.clone());
67
68            #[cfg(feature = "audio-dsp")]
69            if spec.kind == MediaElementKind::Audio {
70                let src_changed = self
71                    .elements
72                    .get(&id)
73                    .map(|prev| prev.src != spec.src)
74                    .unwrap_or(true);
75                let player = self.audio_players.entry(id.clone()).or_default();
76                player.set_volume(spec.volume);
77                player.set_muted(spec.muted);
78                player.set_looping(spec.looping);
79                player.set_playback_rate(spec.playback_rate);
80                if src_changed {
81                    if let Some(ref src) = spec.src {
82                        let path = std::path::Path::new(src);
83                        if path.exists() {
84                            let _ = player.load_file(path);
85                            if spec.autoplay {
86                                player.play();
87                            }
88                        }
89                    }
90                }
91            }
92
93            #[cfg(feature = "media")]
94            if spec.kind == MediaElementKind::Video {
95                let player = self.video_players.entry(id.clone()).or_default();
96                player.set_looping(spec.looping);
97                if spec.autoplay {
98                    player.play();
99                }
100            }
101
102            self.elements.insert(id, spec);
103        }
104
105        self.elements.retain(|id, _| next_ids.contains(id));
106        #[cfg(feature = "audio-dsp")]
107        self.audio_players.retain(|id, _| next_ids.contains(id));
108        #[cfg(feature = "media")]
109        self.video_players.retain(|id, _| next_ids.contains(id));
110    }
111
112    /// Returns all currently reconciled `<audio>` and `<video>` element specifications.
113    pub fn elements(&self) -> &HashMap<String, MediaElementSpec> {
114        &self.elements
115    }
116
117    /// Returns an immutable reference to a reconciled `<audio>` player by element ID.
118    #[cfg(feature = "audio-dsp")]
119    pub fn audio_player(&self, id: &str) -> Option<&strata_audio::AudioPlayer> {
120        self.audio_players.get(id)
121    }
122
123    /// Returns a mutable reference to a reconciled `<audio>` player by element ID.
124    #[cfg(feature = "audio-dsp")]
125    pub fn audio_player_mut(&mut self, id: &str) -> Option<&mut strata_audio::AudioPlayer> {
126        self.audio_players.get_mut(id)
127    }
128
129    /// Returns an immutable reference to a reconciled `<video>` player by element ID.
130    #[cfg(feature = "media")]
131    pub fn video_player(&self, id: &str) -> Option<&strata_media::VideoPlayer> {
132        self.video_players.get(id)
133    }
134
135    /// Returns a mutable reference to a reconciled `<video>` player by element ID.
136    #[cfg(feature = "media")]
137    pub fn video_player_mut(&mut self, id: &str) -> Option<&mut strata_media::VideoPlayer> {
138        self.video_players.get_mut(id)
139    }
140}
141
142fn collect_media_elements(
143    node: &NodeBlueprint,
144    out: &mut Vec<MediaElementSpec>,
145    auto_idx: &mut usize,
146) {
147    match node {
148        NodeBlueprint::Element {
149            tag,
150            attributes,
151            children,
152            ..
153        } => {
154            if matches!(tag, Tag::Audio | Tag::Video) {
155                let kind = if *tag == Tag::Audio {
156                    MediaElementKind::Audio
157                } else {
158                    MediaElementKind::Video
159                };
160                let mut id = None;
161                let mut src = None;
162                let mut poster = None;
163                let mut camera = None;
164                let mut autoplay = false;
165                let mut looping = false;
166                let mut muted = false;
167                let mut controls = false;
168                let mut volume = 1.0f32;
169                let mut playback_rate = 1.0f32;
170
171                for attr in attributes {
172                    if let Attribute::Property { key, value } = attr {
173                        match key.as_str() {
174                            "id" => id = Some(value.clone()),
175                            "src" => src = Some(value.clone()),
176                            "poster" => poster = Some(value.clone()),
177                            "camera" => camera = Some(value.clone()),
178                            "autoplay" => autoplay = parse_bool_attr(value),
179                            "loop" => looping = parse_bool_attr(value),
180                            "muted" => muted = parse_bool_attr(value),
181                            "controls" => controls = parse_bool_attr(value),
182                            "volume" => {
183                                if let Ok(v) = value.parse::<f32>() {
184                                    volume = v.clamp(0.0, 2.0);
185                                }
186                            }
187                            "playbackRate" | "playback-rate" => {
188                                if let Ok(r) = value.parse::<f32>() {
189                                    playback_rate = r.clamp(0.25, 4.0);
190                                }
191                            }
192                            _ => {}
193                        }
194                    }
195                }
196
197                let resolved_id = id.unwrap_or_else(|| {
198                    let idx = *auto_idx;
199                    *auto_idx += 1;
200                    format!(
201                        "strata-media-{}-{idx}",
202                        if kind == MediaElementKind::Audio {
203                            "audio"
204                        } else {
205                            "video"
206                        }
207                    )
208                });
209
210                out.push(MediaElementSpec {
211                    id: resolved_id,
212                    kind,
213                    src,
214                    poster,
215                    camera,
216                    autoplay,
217                    looping,
218                    muted,
219                    controls,
220                    volume,
221                    playback_rate,
222                });
223            }
224
225            for child in children {
226                collect_media_elements(child, out, auto_idx);
227            }
228        }
229        NodeBlueprint::Fragment(children) => {
230            for child in children {
231                collect_media_elements(child, out, auto_idx);
232            }
233        }
234        _ => {}
235    }
236}
237
238#[inline]
239fn parse_bool_attr(value: &str) -> bool {
240    let trimmed = value.trim();
241    trimmed.is_empty()
242        || trimmed.eq_ignore_ascii_case("true")
243        || trimmed == "1"
244        || trimmed.eq_ignore_ascii_case("yes")
245}