Skip to main content

libobs_wrapper\scenes/
group.rs

1//! Managed OBS scene groups and native-order enumeration.
2
3use std::{
4    collections::{HashMap, HashSet},
5    ffi::c_void,
6    sync::{Arc, Mutex, RwLock, Weak},
7};
8
9use libobs::obs_scene_item;
10
11use crate::{
12    run_with_obs,
13    runtime::ObsRuntime,
14    unsafe_send::{NativeObjectId, Sendable, SmartPointerSendable},
15    utils::{ObsError, ObsString},
16};
17
18use super::{
19    scene_item::{
20        mark_scene_item_removed, scene_item_native_handle, wrap_owned_scene_item_ref,
21        ObsSceneItemHandle, SceneItemTraitSealed,
22    },
23    ObsSceneRef, SceneItemTrait, SceneItemsBySource,
24};
25
26pub(super) type SceneGroups = Arc<RwLock<Vec<Arc<ObsSceneGroupRef>>>>;
27
28/// Replacement mapping returned when native libobs ungrouping replaces a child scene item.
29#[derive(Debug, Clone)]
30pub struct ObsUngroupedItem {
31    previous_object_id: NativeObjectId,
32    item: Arc<dyn SceneItemTrait>,
33}
34
35impl ObsUngroupedItem {
36    pub fn previous_object_id(&self) -> NativeObjectId {
37        self.previous_object_id
38    }
39
40    pub fn item(&self) -> &Arc<dyn SceneItemTrait> {
41        &self.item
42    }
43
44    pub fn into_item(self) -> Arc<dyn SceneItemTrait> {
45        self.item
46    }
47}
48
49/// A managed libobs group scene-item.
50///
51/// Groups behave like ordinary scene items for transforms/order, while their child items live in
52/// libobs's dedicated group scene. Reparenting uses libobs's native group operations rather than
53/// reconstructing transforms in Rust.
54#[derive(Debug, Clone)]
55pub struct ObsSceneGroupRef {
56    name: ObsString,
57    scene_item_ptr: SmartPointerSendable<*mut obs_scene_item>,
58    removed: Arc<Mutex<bool>>,
59    operation_lock: Arc<Mutex<()>>,
60    runtime: ObsRuntime,
61    _scene_ptr: SmartPointerSendable<*mut libobs::obs_scene_t>,
62    items_by_source: SceneItemsBySource,
63    groups: Weak<RwLock<Vec<Arc<ObsSceneGroupRef>>>>,
64}
65
66impl ObsSceneGroupRef {
67    pub fn name(&self) -> &ObsString {
68        &self.name
69    }
70
71    /// Moves an already-managed scene item into this group. libobs preserves its apparent
72    /// canvas transform while changing parentage.
73    pub fn add_item<T: SceneItemTrait + ?Sized>(&self, item: &T) -> Result<(), ObsError> {
74        let _operation = self
75            .operation_lock
76            .lock()
77            .map_err(|error| ObsError::LockError(error.to_string()))?;
78        self.runtime.ensure_same_runtime(&item.runtime())?;
79        if self.is_removed() || item.is_removed() {
80            return Err(ObsError::InvalidOperation(
81                "cannot group a removed scene item".into(),
82            ));
83        }
84        let group = self.scene_item_ptr.clone();
85        let item = scene_item_native_handle(item);
86        run_with_obs!(self.runtime, (group, item), move || unsafe {
87            // Safety: both managed item references remain alive for the actor call. Validate the
88            // native parent relationship before asking libobs to reparent the item.
89            if libobs::obs_sceneitem_is_group(item.get_ptr()) {
90                return Err(ObsError::InvalidOperation(
91                    "nested OBS scene groups are not supported by this managed group API".into(),
92                ));
93            }
94            let parent = libobs::obs_sceneitem_get_scene(group.get_ptr());
95            let item_parent = libobs::obs_sceneitem_get_scene(item.get_ptr());
96            if parent.is_null() || item_parent != parent {
97                return Err(ObsError::InvalidOperation(
98                    "scene item must be a top-level item in the same scene as the group".into(),
99                ));
100            }
101            libobs::obs_sceneitem_group_add_item(group.get_ptr(), item.get_ptr());
102            Ok(())
103        })?
104    }
105
106    /// Removes a child from this group and reparents it to the containing scene.
107    pub fn remove_item<T: SceneItemTrait + ?Sized>(&self, item: &T) -> Result<(), ObsError> {
108        let _operation = self
109            .operation_lock
110            .lock()
111            .map_err(|error| ObsError::LockError(error.to_string()))?;
112        self.runtime.ensure_same_runtime(&item.runtime())?;
113        if self.is_removed() || item.is_removed() {
114            return Err(ObsError::InvalidOperation(
115                "cannot ungroup a removed scene item".into(),
116            ));
117        }
118        let group = self.scene_item_ptr.clone();
119        let item = scene_item_native_handle(item);
120        run_with_obs!(self.runtime, (group, item), move || unsafe {
121            // Safety: both handles remain alive. Validate membership because the underlying libobs
122            // function trusts the caller and otherwise reparents an item from any scene/group.
123            let group_scene = libobs::obs_sceneitem_group_get_scene(group.get_ptr());
124            let item_parent = libobs::obs_sceneitem_get_scene(item.get_ptr());
125            if group_scene.is_null() || item_parent != group_scene {
126                return Err(ObsError::InvalidOperation(
127                    "scene item is not a child of this group".into(),
128                ));
129            }
130            libobs::obs_sceneitem_group_remove_item(group.get_ptr(), item.get_ptr());
131            Ok(())
132        })?
133    }
134
135    /// Returns group children in libobs's actual bottom-to-top native order.
136    pub fn items_in_order(&self) -> Result<Vec<Arc<dyn SceneItemTrait>>, ObsError> {
137        let _operation = self
138            .operation_lock
139            .lock()
140            .map_err(|error| ObsError::LockError(error.to_string()))?;
141        self.items_in_order_unlocked()
142    }
143
144    fn items_in_order_unlocked(&self) -> Result<Vec<Arc<dyn SceneItemTrait>>, ObsError> {
145        if self.is_removed() {
146            return Ok(Vec::new());
147        }
148        let group = self.scene_item_ptr.clone();
149        let addresses = run_with_obs!(self.runtime, (group), move || unsafe {
150            let mut result = Vec::<usize>::new();
151            // Safety: enumeration is synchronous and `result` remains live for all callbacks.
152            libobs::obs_sceneitem_group_enum_items(
153                group.get_ptr(),
154                Some(collect_item_address),
155                (&mut result as *mut Vec<usize>).cast::<c_void>(),
156            );
157            result
158        })?;
159        map_native_order(
160            addresses,
161            &self.items_by_source,
162            self.groups.upgrade().as_ref(),
163        )
164    }
165
166    /// Dissolves this group and returns replacement handles for every child.
167    ///
168    /// libobs implements ungrouping by creating new parent-scene items and copying each child into
169    /// them. Consequently, existing child handles cannot remain the identity of the visible item.
170    /// This method marks those old handles removed, rebinds the scene registry, and returns a
171    /// mapping from each previous object ID to its replacement managed handle.
172    pub fn ungroup(&self) -> Result<Vec<ObsUngroupedItem>, ObsError> {
173        let _operation = self
174            .operation_lock
175            .lock()
176            .map_err(|error| ObsError::LockError(error.to_string()))?;
177        if self.is_removed() {
178            return Ok(Vec::new());
179        }
180
181        let old_children = self.items_in_order_unlocked()?;
182        let old_ids = old_children
183            .iter()
184            .map(|item| item.object_id())
185            .collect::<Vec<_>>();
186
187        // Acquire every fallible managed-state lock before mutating native state. Once libobs
188        // dissolves the group there is no rollback operation that restores the old item identities.
189        let mut registry = self
190            .items_by_source
191            .write()
192            .map_err(|error| ObsError::LockError(error.to_string()))?;
193        for old_id in &old_ids {
194            let occurrences = registry
195                .values()
196                .flat_map(|(_, items)| items.iter())
197                .filter(|item| item.object_id() == *old_id)
198                .count();
199            if occurrences != 1 {
200                return Err(ObsError::InvalidOperation(format!(
201                    "group child {old_id:?} has {occurrences} managed registry entries"
202                )));
203            }
204        }
205
206        let groups = self.groups.upgrade();
207        let mut groups_guard = match groups.as_ref() {
208            Some(groups) => Some(
209                groups
210                    .write()
211                    .map_err(|error| ObsError::LockError(error.to_string()))?,
212            ),
213            None => None,
214        };
215        if let Some(groups) = groups_guard.as_ref() {
216            if !groups
217                .iter()
218                .any(|group| group.object_id() == self.object_id())
219            {
220                return Err(ObsError::InvalidOperation(
221                    "managed group is missing from its parent scene registry".into(),
222                ));
223            }
224        }
225
226        let before = native_scene_item_addresses(&self.runtime, self._scene_ptr.clone())?
227            .into_iter()
228            .collect::<HashSet<_>>();
229        let group = self.scene_item_ptr.clone();
230        let scene = self._scene_ptr.clone();
231        let new_native = run_with_obs!(self.runtime, (group, scene, before), move || unsafe {
232            // Safety: group and parent scene are held by managed leases. libobs creates replacement
233            // parent items synchronously before returning. Take one explicit reference for each new
234            // item before it leaves the actor call.
235            libobs::obs_sceneitem_group_ungroup2(group.get_ptr(), true);
236
237            let mut after = Vec::<*mut libobs::obs_sceneitem_t>::new();
238            libobs::obs_scene_enum_items(
239                scene.get_ptr(),
240                Some(collect_item_pointer),
241                (&mut after as *mut Vec<*mut libobs::obs_sceneitem_t>).cast::<c_void>(),
242            );
243            let mut replacements = Vec::new();
244            for item in after {
245                if before.contains(&(item as usize)) {
246                    continue;
247                }
248                libobs::obs_sceneitem_addref(item);
249                replacements.push(Sendable(item));
250            }
251            replacements
252        })?;
253
254        let replacement_count = new_native.len();
255        let mut replacements = Vec::with_capacity(old_children.len().min(replacement_count));
256        let mut new_native = new_native.into_iter();
257
258        for old in &old_children {
259            let previous_object_id = old.object_id();
260            let Some(raw) = new_native.next() else {
261                // Native ungroup already removed the old child. Make the managed graph reflect that
262                // even if libobs unexpectedly failed to create a replacement.
263                mark_scene_item_removed(old.as_ref());
264                for (_, items) in registry.values_mut() {
265                    items.retain(|item| item.object_id() != previous_object_id);
266                }
267                continue;
268            };
269
270            let replacement = Arc::new(ObsSceneItemHandle::from_owned_native_ref(
271                raw,
272                self._scene_ptr.clone(),
273                self.runtime.clone(),
274            ));
275            let replacement_dyn: Arc<dyn SceneItemTrait> = replacement;
276            for (_, items) in registry.values_mut() {
277                for slot in items.iter_mut() {
278                    if slot.object_id() == previous_object_id {
279                        *slot = replacement_dyn.clone();
280                    }
281                }
282            }
283            mark_scene_item_removed(old.as_ref());
284            replacements.push(ObsUngroupedItem {
285                previous_object_id,
286                item: replacement_dyn,
287            });
288        }
289        registry.retain(|_, (_, items)| !items.is_empty());
290
291        // More replacements than original children would indicate a broken libobs invariant. Do not
292        // leak the explicit references we took above; the parent scene still owns the native items.
293        let extras = new_native.collect::<Vec<_>>();
294        if !extras.is_empty() {
295            run_with_obs!(self.runtime, (extras), move || unsafe {
296                // Safety: each pointer carries exactly one explicit reference acquired above.
297                for item in extras {
298                    libobs::obs_sceneitem_release(item.0);
299                }
300            })?;
301        }
302
303        {
304            let mut removed = self
305                .removed
306                .lock()
307                .unwrap_or_else(|poisoned| poisoned.into_inner());
308            *removed = true;
309        }
310        if let Some(groups) = groups_guard.as_mut() {
311            groups.retain(|group| group.object_id() != self.object_id());
312        }
313
314        if replacement_count != old_children.len() {
315            return Err(ObsError::Unexpected(format!(
316                "OBS ungroup replaced {} children with {replacement_count} native items",
317                old_children.len()
318            )));
319        }
320
321        Ok(replacements)
322    }
323}
324
325impl SceneItemTraitSealed for ObsSceneGroupRef {
326    fn __native_handle(&self) -> &SmartPointerSendable<*mut obs_scene_item> {
327        &self.scene_item_ptr
328    }
329
330    fn __removed_flag(&self) -> &Arc<Mutex<bool>> {
331        &self.removed
332    }
333}
334
335impl SceneItemTrait for ObsSceneGroupRef {
336    fn runtime(&self) -> ObsRuntime {
337        self.runtime.clone()
338    }
339
340    fn remove_from_scene(&self) -> Result<(), ObsError> {
341        let _operation = self
342            .operation_lock
343            .lock()
344            .map_err(|error| ObsError::LockError(error.to_string()))?;
345        if self.is_removed() {
346            return Ok(());
347        }
348        let children = self.items_in_order_unlocked()?;
349        let removed_ids = children
350            .iter()
351            .map(|child| child.object_id())
352            .collect::<HashSet<_>>();
353
354        // Pre-acquire all fallible registry locks before native removal. Removing a group also
355        // removes its group-scene children, so the managed registry must be updated atomically with
356        // that irreversible native transition.
357        let mut registry = self
358            .items_by_source
359            .write()
360            .map_err(|error| ObsError::LockError(error.to_string()))?;
361        for child_id in &removed_ids {
362            if !registry
363                .values()
364                .flat_map(|(_, items)| items.iter())
365                .any(|item| item.object_id() == *child_id)
366            {
367                return Err(ObsError::InvalidOperation(format!(
368                    "group child {child_id:?} is missing from its parent scene registry"
369                )));
370            }
371        }
372        let groups = self.groups.upgrade();
373        let mut groups_guard = match groups.as_ref() {
374            Some(groups) => Some(
375                groups
376                    .write()
377                    .map_err(|error| ObsError::LockError(error.to_string()))?,
378            ),
379            None => None,
380        };
381
382        let group = self.scene_item_ptr.clone();
383        run_with_obs!(self.runtime, (group), move || unsafe {
384            // Safety: the managed group owns an explicit native reference. Removing the parent
385            // scene's ownership destroys its private group scene and detaches every child.
386            libobs::obs_sceneitem_remove(group.get_ptr());
387        })?;
388
389        {
390            let mut removed = self
391                .removed
392                .lock()
393                .unwrap_or_else(|poisoned| poisoned.into_inner());
394            *removed = true;
395        }
396        for child in &children {
397            mark_scene_item_removed(child.as_ref());
398        }
399        registry.retain(|_, (_, items)| {
400            items.retain(|item| !removed_ids.contains(&item.object_id()));
401            !items.is_empty()
402        });
403        if let Some(groups) = groups_guard.as_mut() {
404            groups.retain(|group| group.object_id() != self.object_id());
405        }
406        Ok(())
407    }
408}
409
410impl ObsSceneRef {
411    /// Creates an empty managed group at the top of this scene.
412    pub fn create_group(
413        &mut self,
414        name: impl Into<ObsString>,
415    ) -> Result<ObsSceneGroupRef, ObsError> {
416        let name = name.into();
417        let scene = self.as_ptr();
418        let raw = run_with_obs!(self.runtime, (scene, name), move || unsafe {
419            // Safety: scene/name remain valid for the actor call. A successful group belongs to the
420            // scene; take one additional reference for the managed Rust handle.
421            let item = libobs::obs_scene_add_group(scene.get_ptr(), name.as_ptr().0);
422            if item.is_null() {
423                return Err(ObsError::NullPointer(Some(
424                    "OBS scene group creation".into(),
425                )));
426            }
427            libobs::obs_sceneitem_addref(item);
428            Ok(Sendable(item))
429        })??;
430        let (scene_item_ptr, removed) = wrap_owned_scene_item_ref(raw, self.runtime.clone());
431        let group = ObsSceneGroupRef {
432            name: name.clone(),
433            scene_item_ptr,
434            removed,
435            operation_lock: Arc::new(Mutex::new(())),
436            runtime: self.runtime.clone(),
437            _scene_ptr: self.as_ptr(),
438            items_by_source: self.attached_scene_items.clone(),
439            groups: Arc::downgrade(&self.attached_groups),
440        };
441        self.attached_groups
442            .write()
443            .map_err(|error| ObsError::LockError(error.to_string()))?
444            .push(Arc::new(group.clone()));
445        Ok(group)
446    }
447
448    /// Returns all currently managed groups owned by this scene.
449    pub fn groups(&self) -> Result<Vec<ObsSceneGroupRef>, ObsError> {
450        Ok(self
451            .attached_groups
452            .read()
453            .map_err(|error| ObsError::LockError(error.to_string()))?
454            .iter()
455            .filter(|group| !group.is_removed())
456            .map(|group| (**group).clone())
457            .collect())
458    }
459
460    /// Returns top-level scene items in libobs's actual bottom-to-top native order. Items inside a
461    /// group are enumerated by [`ObsSceneGroupRef::items_in_order`] instead.
462    pub fn items_in_order(&self) -> Result<Vec<Arc<dyn SceneItemTrait>>, ObsError> {
463        let addresses = native_scene_item_addresses(&self.runtime, self.as_ptr())?;
464        map_native_order(
465            addresses,
466            &self.attached_scene_items,
467            Some(&self.attached_groups),
468        )
469    }
470
471    pub(super) fn clear_groups(&mut self) -> Result<(), ObsError> {
472        let groups = self
473            .attached_groups
474            .read()
475            .map_err(|error| ObsError::LockError(error.to_string()))?
476            .clone();
477        for group in groups {
478            group.remove_from_scene()?;
479        }
480        self.attached_groups
481            .write()
482            .map_err(|error| ObsError::LockError(error.to_string()))?
483            .clear();
484        Ok(())
485    }
486}
487
488fn native_scene_item_addresses(
489    runtime: &ObsRuntime,
490    scene: SmartPointerSendable<*mut libobs::obs_scene_t>,
491) -> Result<Vec<usize>, ObsError> {
492    run_with_obs!(runtime, (scene), move || unsafe {
493        let mut result = Vec::<usize>::new();
494        // Safety: enumeration is synchronous and the vector outlives every callback.
495        libobs::obs_scene_enum_items(
496            scene.get_ptr(),
497            Some(collect_item_address),
498            (&mut result as *mut Vec<usize>).cast::<c_void>(),
499        );
500        result
501    })
502}
503
504/// # Safety
505/// `param` must point to an exclusively borrowed live `Vec<usize>` for the synchronous enumeration.
506/// `item` must be the callback-borrowed scene item supplied by libobs for that invocation.
507/// Collected addresses are identity keys only; callers must never dereference them.
508unsafe extern "C" fn collect_item_address(
509    _scene: *mut libobs::obs_scene_t,
510    item: *mut libobs::obs_sceneitem_t,
511    param: *mut c_void,
512) -> bool {
513    // Safety: callers pass a live Vec<usize> for the complete synchronous enumeration.
514    if let Some(result) = unsafe { param.cast::<Vec<usize>>().as_mut() } {
515        result.push(item as usize);
516        true
517    } else {
518        false
519    }
520}
521
522/// # Safety
523/// `param` must exclusively borrow a live Vec of scene-item pointers. The enumerated
524/// scene must retain its items unchanged until the caller has acquired owned references.
525/// The pointers must stay on the actor and must not be used after scene mutation.
526unsafe extern "C" fn collect_item_pointer(
527    _scene: *mut libobs::obs_scene_t,
528    item: *mut libobs::obs_sceneitem_t,
529    param: *mut c_void,
530) -> bool {
531    // SAFETY: The synchronous enumeration in ungroup passes its exclusively borrowed
532    // Vec with this exact element type; the actor retains the scene throughout.
533    let result = unsafe { &mut *param.cast::<Vec<*mut libobs::obs_sceneitem_t>>() };
534    result.push(item);
535    true
536}
537
538fn map_native_order(
539    addresses: Vec<usize>,
540    items_by_source: &SceneItemsBySource,
541    groups: Option<&SceneGroups>,
542) -> Result<Vec<Arc<dyn SceneItemTrait>>, ObsError> {
543    let mut managed = HashMap::<usize, Arc<dyn SceneItemTrait>>::new();
544    for (_, items) in items_by_source
545        .read()
546        .map_err(|error| ObsError::LockError(error.to_string()))?
547        .values()
548    {
549        for item in items {
550            if item.is_removed() {
551                continue;
552            }
553            let handle = scene_item_native_handle(item.as_ref());
554            // SAFETY: the address is used only as an ephemeral identity key while the managed
555            // handle remains alive; it is never dereferenced outside the actor.
556            managed.insert(unsafe { handle.raw_ptr_unchecked() } as usize, item.clone());
557        }
558    }
559    if let Some(groups) = groups {
560        for group in groups
561            .read()
562            .map_err(|error| ObsError::LockError(error.to_string()))?
563            .iter()
564        {
565            if group.is_removed() {
566                continue;
567            }
568            let handle = scene_item_native_handle(group.as_ref());
569            // SAFETY: the address is only an ephemeral lookup key; the managed group handle keeps
570            // the native item alive for the complete mapping operation and the pointer is not dereferenced.
571            managed.insert(
572                unsafe { handle.raw_ptr_unchecked() } as usize,
573                group.clone() as Arc<dyn SceneItemTrait>,
574            );
575        }
576    }
577
578    let mut ordered = Vec::with_capacity(addresses.len());
579    for address in addresses {
580        let Some(item) = managed.get(&address) else {
581            return Err(ObsError::InvalidOperation(format!(
582                "scene contains unmanaged native item at 0x{address:x}"
583            )));
584        };
585        ordered.push(item.clone());
586    }
587    Ok(ordered)
588}