1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
//! [MediaStream][1] related objects.
//!
//! [1]: https://www.w3.org/TR/mediacapture-streams/#mediastream

use std::{
    collections::HashMap,
    rc::{Rc, Weak},
};

use medea_client_api_proto::MediaType;
use wasm_bindgen::{prelude::*, JsValue};
use web_sys::MediaStream as SysMediaStream;

use crate::utils::WasmErr;

use super::{MediaTrack, TrackId};

/// Actual data of a [`MediaStream`].
///
/// Shared between JS side ([`MediaStreamHandle`]) and Rust side
/// ([`MediaStream`]).
struct InnerStream {
    /// Actual underlying [MediaStream][1] object.
    ///
    /// [1]: https://www.w3.org/TR/mediacapture-streams/#mediastream
    stream: SysMediaStream,

    /// List of audio tracks.
    audio_tracks: HashMap<u64, Rc<MediaTrack>>,

    /// List of video tracks.
    video_tracks: HashMap<u64, Rc<MediaTrack>>,
}

impl InnerStream {
    /// Instantiates new [`InnerStream`].
    fn new() -> Self {
        Self {
            stream: SysMediaStream::new().unwrap(),
            audio_tracks: HashMap::new(),
            video_tracks: HashMap::new(),
        }
    }

    /// Adds provided [`MediaTrack`] to a stream.
    fn add_track(&mut self, track: Rc<MediaTrack>) {
        self.stream.add_track(track.track());
        let caps = track.caps();
        match caps {
            MediaType::Audio(_) => {
                self.audio_tracks.insert(track.id(), track);
            }
            MediaType::Video(_) => {
                self.video_tracks.insert(track.id(), track);
            }
        }
    }
}

/// Representation of [MediaStream][1] object.
///
/// It's used on Rust side and represents a handle to [`InnerStream`] data.
///
/// For using [`MediaStream`] on JS side, consider the [`MediaStreamHandle`].
///
/// [1]: https://www.w3.org/TR/mediacapture-streams/#mediastream
#[allow(clippy::module_name_repetitions)]
pub struct MediaStream(Rc<InnerStream>);

impl MediaStream {
    /// Creates new [`MediaStream`] from a given collection of [`MediaTrack`]s.
    pub fn from_tracks<I>(tracks: I) -> Self
    where
        I: IntoIterator<Item = Rc<MediaTrack>>,
    {
        let mut stream = InnerStream::new();
        for track in tracks {
            stream.add_track(track);
        }
        Self(Rc::new(stream))
    }

    /// Checks if [`MediaStream`] contains a [`MediaTrack`] with specified ID.
    pub fn has_track(&self, id: TrackId) -> bool {
        self.0.video_tracks.contains_key(&id)
            || self.0.audio_tracks.contains_key(&id)
    }

    /// Returns a [`MediaTrack`] of [`MediaStream`] by its ID, if any.
    pub fn get_track_by_id(&self, track_id: TrackId) -> Option<Rc<MediaTrack>> {
        match self.0.video_tracks.get(&track_id) {
            Some(track) => Some(Rc::clone(track)),
            None => match self.0.audio_tracks.get(&track_id) {
                Some(track) => Some(Rc::clone(track)),
                None => None,
            },
        }
    }

    /// Instantiates new [`MediaStreamHandle`] for use on JS side.
    pub fn new_handle(&self) -> MediaStreamHandle {
        MediaStreamHandle(Rc::downgrade(&self.0))
    }
}

/// JS side handle to [`MediaStream`].
///
/// Actually, represents a [`Weak`]-based handle to `InnerStream`.
///
/// For using [`MediaStreamHandle`] on Rust side, consider the [`MediaStream`].
#[wasm_bindgen]
pub struct MediaStreamHandle(Weak<InnerStream>);

#[wasm_bindgen]
impl MediaStreamHandle {
    /// Returns the underlying [`MediaStream`][`SysMediaStream`] object.
    pub fn get_media_stream(&self) -> Result<SysMediaStream, JsValue> {
        match self.0.upgrade() {
            Some(inner) => Ok(inner.stream.clone()),
            None => Err(WasmErr::from("Detached state").into()),
        }
    }
}