servo_media_streams/
registry.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::collections::HashMap;
6use std::sync::{Arc, LazyLock, Mutex};
7
8use malloc_size_of_derive::MallocSizeOf;
9use uuid::Uuid;
10
11use super::MediaStream;
12
13type RegisteredMediaStream = Arc<Mutex<dyn MediaStream>>;
14
15static MEDIA_STREAMS_REGISTRY: LazyLock<Mutex<HashMap<MediaStreamId, RegisteredMediaStream>>> =
16    LazyLock::new(|| Mutex::new(HashMap::new()));
17
18#[derive(Clone, Copy, Default, Hash, Eq, PartialEq, MallocSizeOf)]
19pub struct MediaStreamId(Uuid);
20impl MediaStreamId {
21    pub fn new() -> MediaStreamId {
22        Default::default()
23    }
24
25    pub fn id(self) -> Uuid {
26        self.0
27    }
28}
29
30pub fn register_stream(stream: Arc<Mutex<dyn MediaStream>>) -> MediaStreamId {
31    let id = MediaStreamId::new();
32    stream.lock().unwrap().set_id(id);
33    MEDIA_STREAMS_REGISTRY.lock().unwrap().insert(id, stream);
34    id
35}
36
37pub fn unregister_stream(stream: &MediaStreamId) {
38    MEDIA_STREAMS_REGISTRY.lock().unwrap().remove(stream);
39}
40
41pub fn get_stream(stream: &MediaStreamId) -> Option<Arc<Mutex<dyn MediaStream>>> {
42    MEDIA_STREAMS_REGISTRY.lock().unwrap().get(stream).cloned()
43}