Use channel instead of callbacks & removed participant events
This commit is contained in:
@@ -1,123 +0,0 @@
|
|||||||
use crate::room::id::TrackSid;
|
|
||||||
use crate::room::participant::remote_participant::RemoteParticipant;
|
|
||||||
use crate::room::publication::RemoteTrackPublication;
|
|
||||||
use crate::room::room_session::{ConnectionState, RoomSession};
|
|
||||||
use crate::room::track::remote_track::RemoteTrackHandle;
|
|
||||||
use futures::future::Future;
|
|
||||||
use futures_util::future::BoxFuture;
|
|
||||||
use parking_lot::Mutex;
|
|
||||||
use std::fmt::Debug;
|
|
||||||
use std::sync::Arc;
|
|
||||||
use thiserror::Error;
|
|
||||||
|
|
||||||
type EventHandler<T> = Box<dyn FnMut(T) -> BoxFuture<'static, ()> + Send + Sync>;
|
|
||||||
|
|
||||||
macro_rules! event_setter {
|
|
||||||
($fnc:ident, $event:ty) => {
|
|
||||||
pub fn $fnc<F, Fut>(&self, mut callback: F)
|
|
||||||
where
|
|
||||||
F: FnMut($event) -> Fut + Send + Sync + 'static,
|
|
||||||
Fut: Future<Output = ()> + Send + 'static,
|
|
||||||
{
|
|
||||||
*self.$fnc.lock() = Some(Box::new(move |event| Box::pin(callback(event))));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Error, Debug, Clone)]
|
|
||||||
pub enum TrackError {
|
|
||||||
#[error("could not find published track with sid: {0}")]
|
|
||||||
TrackNotFound(String),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct ParticipantConnectedEvent {
|
|
||||||
pub room_session: RoomSession,
|
|
||||||
pub participant: Arc<RemoteParticipant>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct ParticipantDisconnectedEvent {
|
|
||||||
pub room_session: RoomSession,
|
|
||||||
pub participant: Arc<RemoteParticipant>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct TrackSubscribedEvent {
|
|
||||||
pub room_session: RoomSession,
|
|
||||||
pub track: RemoteTrackHandle,
|
|
||||||
pub publication: RemoteTrackPublication,
|
|
||||||
pub participant: Arc<RemoteParticipant>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct TrackPublishedEvent {
|
|
||||||
pub room_session: RoomSession,
|
|
||||||
pub publication: RemoteTrackPublication,
|
|
||||||
pub participant: Arc<RemoteParticipant>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct TrackSubscriptionFailedEvent {
|
|
||||||
pub room_session: RoomSession,
|
|
||||||
pub error: TrackError,
|
|
||||||
pub sid: TrackSid,
|
|
||||||
pub participant: Arc<RemoteParticipant>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct ConnectionStateChangedEvent {
|
|
||||||
pub room_session: RoomSession,
|
|
||||||
pub state: ConnectionState,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) type OnParticipantConnectedHandler = EventHandler<ParticipantConnectedEvent>;
|
|
||||||
pub(crate) type OnParticipantDisconnectedHandler = EventHandler<ParticipantDisconnectedEvent>;
|
|
||||||
pub(crate) type OnTrackSubscribedHandler = EventHandler<TrackSubscribedEvent>;
|
|
||||||
pub(crate) type OnTrackPublishedHandler = EventHandler<TrackPublishedEvent>;
|
|
||||||
pub(crate) type OnTrackSubscriptionFailedHandler = EventHandler<TrackSubscriptionFailedEvent>;
|
|
||||||
pub(crate) type OnConnectionStateChangedHandler = EventHandler<ConnectionStateChangedEvent>;
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
pub struct RoomEvents {
|
|
||||||
pub(crate) on_participant_connected: Mutex<Option<OnParticipantConnectedHandler>>,
|
|
||||||
pub(crate) on_participant_disconnected: Mutex<Option<OnParticipantDisconnectedHandler>>,
|
|
||||||
pub(crate) on_track_subscribed: Mutex<Option<OnTrackSubscribedHandler>>,
|
|
||||||
pub(crate) on_track_published: Mutex<Option<OnTrackPublishedHandler>>,
|
|
||||||
pub(crate) on_track_subscription_failed: Mutex<Option<OnTrackSubscriptionFailedHandler>>,
|
|
||||||
pub(crate) on_connection_state_changed: Mutex<Option<OnConnectionStateChangedHandler>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Debug for RoomEvents {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
write!(f, "RoomEvents")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RoomEvents {
|
|
||||||
event_setter!(on_participant_connected, ParticipantConnectedEvent);
|
|
||||||
event_setter!(on_participant_disconnected, ParticipantDisconnectedEvent);
|
|
||||||
event_setter!(on_track_subscribed, TrackSubscribedEvent);
|
|
||||||
event_setter!(on_track_published, TrackPublishedEvent);
|
|
||||||
event_setter!(on_track_subscription_failed, TrackSubscriptionFailedEvent);
|
|
||||||
event_setter!(on_connection_state_changed, ConnectionStateChangedEvent);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
pub struct ParticipantEvents {
|
|
||||||
pub(crate) on_track_published: Mutex<Option<OnTrackPublishedHandler>>,
|
|
||||||
pub(crate) on_track_subscribed: Mutex<Option<OnTrackSubscribedHandler>>,
|
|
||||||
pub(crate) on_track_subscription_failed: Mutex<Option<OnTrackSubscriptionFailedHandler>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Debug for ParticipantEvents {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
write!(f, "ParticipantEvents")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ParticipantEvents {
|
|
||||||
event_setter!(on_track_published, TrackPublishedEvent);
|
|
||||||
event_setter!(on_track_subscribed, TrackSubscribedEvent);
|
|
||||||
event_setter!(on_track_subscription_failed, TrackSubscriptionFailedEvent);
|
|
||||||
}
|
|
||||||
@@ -7,5 +7,4 @@ pub mod proto {
|
|||||||
mod rtc_engine;
|
mod rtc_engine;
|
||||||
mod signal_client;
|
mod signal_client;
|
||||||
|
|
||||||
pub mod events;
|
|
||||||
pub mod room;
|
pub mod room;
|
||||||
|
|||||||
@@ -1,25 +1,13 @@
|
|||||||
use parking_lot::{Mutex, RwLock};
|
use self::room_session::{ConnectionState, RoomSession, SessionHandle};
|
||||||
use std::collections::HashMap;
|
use crate::room::id::TrackSid;
|
||||||
use std::sync::atomic::{AtomicU8, Ordering};
|
use crate::room::participant::remote_participant::RemoteParticipant;
|
||||||
|
use crate::room::publication::RemoteTrackPublication;
|
||||||
|
use crate::room::track::remote_track::RemoteTrackHandle;
|
||||||
|
use crate::rtc_engine::EngineError;
|
||||||
|
use std::fmt::Debug;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use self::id::{ParticipantIdentity, ParticipantSid};
|
|
||||||
use self::participant::local_participant::LocalParticipant;
|
|
||||||
use self::participant::remote_participant::RemoteParticipant;
|
|
||||||
use self::participant::ParticipantInternalTrait;
|
|
||||||
use self::participant::ParticipantTrait;
|
|
||||||
use self::room_session::{RoomInternal, RoomSession};
|
|
||||||
use crate::events::{
|
|
||||||
ParticipantConnectedEvent, ParticipantDisconnectedEvent, RoomEvents, TrackPublishedEvent,
|
|
||||||
TrackSubscribedEvent,
|
|
||||||
};
|
|
||||||
use crate::proto;
|
|
||||||
use crate::proto::participant_info;
|
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
use tracing::{debug, error, instrument, trace_span, Level};
|
use tokio::sync::mpsc;
|
||||||
|
|
||||||
use crate::rtc_engine::{EngineError, EngineEvent, EngineEvents, EngineResult, RTCEngine};
|
|
||||||
use crate::signal_client::SignalOptions;
|
|
||||||
|
|
||||||
pub use crate::rtc_engine::SimulateScenario;
|
pub use crate::rtc_engine::SimulateScenario;
|
||||||
|
|
||||||
@@ -29,6 +17,10 @@ pub mod publication;
|
|||||||
pub mod room_session;
|
pub mod room_session;
|
||||||
pub mod track;
|
pub mod track;
|
||||||
|
|
||||||
|
pub type RoomEvents = mpsc::UnboundedReceiver<RoomEvent>;
|
||||||
|
pub type RoomEmitter = mpsc::UnboundedSender<RoomEvent>;
|
||||||
|
pub type RoomResult<T> = Result<T, RoomError>;
|
||||||
|
|
||||||
#[derive(Error, Debug)]
|
#[derive(Error, Debug)]
|
||||||
pub enum RoomError {
|
pub enum RoomError {
|
||||||
#[error("engine : {0}")]
|
#[error("engine : {0}")]
|
||||||
@@ -37,34 +29,54 @@ pub enum RoomError {
|
|||||||
Internal(String),
|
Internal(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
pub type RoomResult<T> = Result<T, RoomError>;
|
#[derive(Error, Debug, Clone)]
|
||||||
|
pub enum TrackError {
|
||||||
|
#[error("could not find published track with sid: {0}")]
|
||||||
|
TrackNotFound(String),
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Default)]
|
#[derive(Clone, Debug)]
|
||||||
|
pub enum RoomEvent {
|
||||||
|
ParticipantConnected(Arc<RemoteParticipant>),
|
||||||
|
ParticipantDisconnected(Arc<RemoteParticipant>),
|
||||||
|
TrackSubscribed {
|
||||||
|
track: RemoteTrackHandle,
|
||||||
|
publication: RemoteTrackPublication,
|
||||||
|
participant: Arc<RemoteParticipant>,
|
||||||
|
},
|
||||||
|
TrackPublished {
|
||||||
|
publication: RemoteTrackPublication,
|
||||||
|
participant: Arc<RemoteParticipant>,
|
||||||
|
},
|
||||||
|
TrackSubscriptionFailed {
|
||||||
|
error: TrackError,
|
||||||
|
sid: TrackSid,
|
||||||
|
participant: Arc<RemoteParticipant>,
|
||||||
|
},
|
||||||
|
ConnectionStateChanged(ConnectionState),
|
||||||
|
Connected,
|
||||||
|
Disconnected,
|
||||||
|
Reconnecting,
|
||||||
|
Reconnected,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
pub struct Room {
|
pub struct Room {
|
||||||
internal: Option<RoomInternal>,
|
handle: SessionHandle,
|
||||||
events: Arc<RoomEvents>, // Keep the same RoomEvents across sessions
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Room {
|
impl Room {
|
||||||
#[instrument(level = Level::DEBUG)]
|
pub async fn connect(url: &str, token: &str) -> RoomResult<(Self, RoomEvents)> {
|
||||||
pub async fn connect(&mut self, url: &str, token: &str) -> RoomResult<()> {
|
let (emitter, events) = mpsc::unbounded_channel();
|
||||||
let internal = RoomInternal::connect(self.events.clone(), url, token).await?;
|
let handle = SessionHandle::connect(emitter, url, token).await?;
|
||||||
self.internal = Some(internal);
|
Ok((Self { handle }, events))
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[instrument(level = Level::DEBUG)]
|
pub async fn close(self) {
|
||||||
pub async fn close(&mut self) {
|
self.handle.close().await;
|
||||||
if let Some(internal) = self.internal.take() {
|
|
||||||
internal.close().await;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn events(&self) -> Arc<RoomEvents> {
|
pub fn session(&self) -> RoomSession {
|
||||||
self.events.clone()
|
self.handle.session()
|
||||||
}
|
|
||||||
|
|
||||||
pub fn session(&self) -> Option<RoomSession> {
|
|
||||||
self.internal.as_ref().map(RoomInternal::session)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
use std::sync::Weak;
|
|
||||||
|
|
||||||
use crate::proto::{data_packet, DataPacket, UserPacket};
|
use crate::proto::{data_packet, DataPacket, UserPacket};
|
||||||
use crate::room::participant::{
|
use crate::room::participant::{
|
||||||
impl_participant_trait, ParticipantInternalTrait, ParticipantShared,
|
impl_participant_trait, ParticipantInternalTrait, ParticipantShared, ParticipantTrait,
|
||||||
};
|
};
|
||||||
use crate::room::RoomError;
|
use crate::room::{RoomError, RoomEmitter};
|
||||||
use crate::rtc_engine::RTCEngine;
|
use crate::rtc_engine::RTCEngine;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@@ -20,9 +18,10 @@ impl LocalParticipant {
|
|||||||
identity: ParticipantIdentity,
|
identity: ParticipantIdentity,
|
||||||
name: String,
|
name: String,
|
||||||
metadata: String,
|
metadata: String,
|
||||||
|
room_emitter: RoomEmitter,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
shared: ParticipantShared::new(sid, identity, name, metadata),
|
shared: ParticipantShared::new(sid, identity, name, metadata, room_emitter),
|
||||||
rtc_engine,
|
rtc_engine,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -35,7 +34,7 @@ impl LocalParticipant {
|
|||||||
let data = DataPacket {
|
let data = DataPacket {
|
||||||
kind: kind as i32,
|
kind: kind as i32,
|
||||||
value: Some(data_packet::Value::User(UserPacket {
|
value: Some(data_packet::Value::User(UserPacket {
|
||||||
participant_sid: "".to_string(), /*self.sid().to_owned()*/
|
participant_sid: self.sid().to_string(),
|
||||||
payload: data.to_vec(),
|
payload: data.to_vec(),
|
||||||
destination_sids: vec![],
|
destination_sids: vec![],
|
||||||
})),
|
})),
|
||||||
@@ -49,10 +48,6 @@ impl LocalParticipant {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ParticipantInternalTrait for LocalParticipant {
|
impl ParticipantInternalTrait for LocalParticipant {
|
||||||
fn internal_events(&self) -> Arc<ParticipantEvents> {
|
|
||||||
self.shared.internal_events.clone()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn update_info(&self, info: ParticipantInfo) {
|
fn update_info(&self, info: ParticipantInfo) {
|
||||||
self.shared.update_info(info);
|
self.shared.update_info(info);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
use crate::events::ParticipantEvents;
|
|
||||||
use crate::proto::ParticipantInfo;
|
use crate::proto::ParticipantInfo;
|
||||||
use crate::room::id::{ParticipantIdentity, ParticipantSid, TrackSid};
|
use crate::room::id::{ParticipantIdentity, ParticipantSid, TrackSid};
|
||||||
use crate::room::participant::local_participant::LocalParticipant;
|
use crate::room::participant::local_participant::LocalParticipant;
|
||||||
@@ -14,13 +13,12 @@ pub mod remote_participant;
|
|||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub(super) struct ParticipantShared {
|
pub(super) struct ParticipantShared {
|
||||||
pub(super) events: Arc<ParticipantEvents>,
|
|
||||||
pub(super) internal_events: Arc<ParticipantEvents>,
|
|
||||||
pub(super) sid: Mutex<ParticipantSid>,
|
pub(super) sid: Mutex<ParticipantSid>,
|
||||||
pub(super) identity: Mutex<ParticipantIdentity>,
|
pub(super) identity: Mutex<ParticipantIdentity>,
|
||||||
pub(super) name: Mutex<String>,
|
pub(super) name: Mutex<String>,
|
||||||
pub(super) metadata: Mutex<String>,
|
pub(super) metadata: Mutex<String>,
|
||||||
pub(super) tracks: RwLock<HashMap<TrackSid, TrackPublication>>,
|
pub(super) tracks: RwLock<HashMap<TrackSid, TrackPublication>>,
|
||||||
|
pub(super) room_emitter: RoomEmitter,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ParticipantShared {
|
impl ParticipantShared {
|
||||||
@@ -29,15 +27,15 @@ impl ParticipantShared {
|
|||||||
identity: ParticipantIdentity,
|
identity: ParticipantIdentity,
|
||||||
name: String,
|
name: String,
|
||||||
metadata: String,
|
metadata: String,
|
||||||
|
room_emitter: RoomEmitter,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
events: Default::default(),
|
|
||||||
internal_events: Default::default(),
|
|
||||||
sid: Mutex::new(sid),
|
sid: Mutex::new(sid),
|
||||||
identity: Mutex::new(identity),
|
identity: Mutex::new(identity),
|
||||||
name: Mutex::new(name),
|
name: Mutex::new(name),
|
||||||
metadata: Mutex::new(metadata),
|
metadata: Mutex::new(metadata),
|
||||||
tracks: Default::default(),
|
tracks: Default::default(),
|
||||||
|
room_emitter
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,12 +52,10 @@ impl ParticipantShared {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) trait ParticipantInternalTrait {
|
pub(crate) trait ParticipantInternalTrait {
|
||||||
fn internal_events(&self) -> Arc<ParticipantEvents>;
|
|
||||||
fn update_info(&self, info: ParticipantInfo);
|
fn update_info(&self, info: ParticipantInfo);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait ParticipantTrait {
|
pub trait ParticipantTrait {
|
||||||
fn events(&self) -> Arc<ParticipantEvents>;
|
|
||||||
fn sid(&self) -> ParticipantSid;
|
fn sid(&self) -> ParticipantSid;
|
||||||
fn identity(&self) -> ParticipantIdentity;
|
fn identity(&self) -> ParticipantIdentity;
|
||||||
fn name(&self) -> String;
|
fn name(&self) -> String;
|
||||||
@@ -75,7 +71,6 @@ pub enum ParticipantHandle {
|
|||||||
impl ParticipantInternalTrait for ParticipantHandle {
|
impl ParticipantInternalTrait for ParticipantHandle {
|
||||||
enum_dispatch!(
|
enum_dispatch!(
|
||||||
[Local, Remote]
|
[Local, Remote]
|
||||||
fnc!(internal_events, &Self, [], Arc<ParticipantEvents>);
|
|
||||||
fnc!(update_info, &Self, [info: ParticipantInfo], ());
|
fnc!(update_info, &Self, [info: ParticipantInfo], ());
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -83,7 +78,6 @@ impl ParticipantInternalTrait for ParticipantHandle {
|
|||||||
impl ParticipantTrait for ParticipantHandle {
|
impl ParticipantTrait for ParticipantHandle {
|
||||||
enum_dispatch!(
|
enum_dispatch!(
|
||||||
[Local, Remote]
|
[Local, Remote]
|
||||||
fnc!(events, &Self, [], Arc<ParticipantEvents>);
|
|
||||||
fnc!(sid, &Self, [], ParticipantSid);
|
fnc!(sid, &Self, [], ParticipantSid);
|
||||||
fnc!(identity, &Self, [], ParticipantIdentity);
|
fnc!(identity, &Self, [], ParticipantIdentity);
|
||||||
fnc!(name, &Self, [], String);
|
fnc!(name, &Self, [], String);
|
||||||
@@ -93,16 +87,11 @@ impl ParticipantTrait for ParticipantHandle {
|
|||||||
|
|
||||||
macro_rules! impl_participant_trait {
|
macro_rules! impl_participant_trait {
|
||||||
($x:ty) => {
|
($x:ty) => {
|
||||||
use crate::events::ParticipantEvents;
|
|
||||||
use crate::proto::ParticipantInfo;
|
use crate::proto::ParticipantInfo;
|
||||||
use crate::room::id::{ParticipantIdentity, ParticipantSid};
|
use crate::room::id::{ParticipantIdentity, ParticipantSid};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
impl crate::room::participant::ParticipantTrait for $x {
|
impl crate::room::participant::ParticipantTrait for $x {
|
||||||
fn events(&self) -> Arc<ParticipantEvents> {
|
|
||||||
self.shared.events.clone()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn sid(&self) -> ParticipantSid {
|
fn sid(&self) -> ParticipantSid {
|
||||||
self.shared.sid.lock().clone()
|
self.shared.sid.lock().clone()
|
||||||
}
|
}
|
||||||
@@ -123,3 +112,5 @@ macro_rules! impl_participant_trait {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(super) use impl_participant_trait;
|
pub(super) use impl_participant_trait;
|
||||||
|
|
||||||
|
use super::RoomEmitter;
|
||||||
|
|||||||
@@ -1,6 +1,3 @@
|
|||||||
use crate::events::{
|
|
||||||
TrackError, TrackPublishedEvent, TrackSubscribedEvent, TrackSubscriptionFailedEvent,
|
|
||||||
};
|
|
||||||
use crate::proto::TrackInfo;
|
use crate::proto::TrackInfo;
|
||||||
use crate::room::id::TrackSid;
|
use crate::room::id::TrackSid;
|
||||||
use crate::room::participant::{
|
use crate::room::participant::{
|
||||||
@@ -14,6 +11,7 @@ use crate::room::track::remote_audio_track::RemoteAudioTrack;
|
|||||||
use crate::room::track::remote_track::RemoteTrackHandle;
|
use crate::room::track::remote_track::RemoteTrackHandle;
|
||||||
use crate::room::track::remote_video_track::RemoteVideoTrack;
|
use crate::room::track::remote_video_track::RemoteVideoTrack;
|
||||||
use crate::room::track::{TrackKind, TrackTrait};
|
use crate::room::track::{TrackKind, TrackTrait};
|
||||||
|
use crate::room::{RoomEmitter, RoomEvent, TrackError};
|
||||||
use livekit_webrtc::media_stream::MediaStreamTrackHandle;
|
use livekit_webrtc::media_stream::MediaStreamTrackHandle;
|
||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
@@ -35,9 +33,10 @@ impl RemoteParticipant {
|
|||||||
identity: ParticipantIdentity,
|
identity: ParticipantIdentity,
|
||||||
name: String,
|
name: String,
|
||||||
metadata: String,
|
metadata: String,
|
||||||
|
room_emitter: RoomEmitter,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
shared: ParticipantShared::new(sid, identity, name, metadata),
|
shared: ParticipantShared::new(sid, identity, name, metadata, room_emitter),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -109,55 +108,21 @@ impl RemoteParticipant {
|
|||||||
.add_track_publication(TrackPublication::Remote(remote_publication.clone()));
|
.add_track_publication(TrackPublication::Remote(remote_publication.clone()));
|
||||||
track.start();
|
track.start();
|
||||||
|
|
||||||
let event = TrackSubscribedEvent {
|
self.shared.room_emitter.send(RoomEvent::TrackSubscribed {
|
||||||
room_session,
|
track: track,
|
||||||
track,
|
|
||||||
publication: remote_publication,
|
publication: remote_publication,
|
||||||
participant: self.clone(),
|
participant: self.clone(),
|
||||||
};
|
});
|
||||||
|
|
||||||
if let Some(cb) = self
|
|
||||||
.shared
|
|
||||||
.internal_events
|
|
||||||
.on_track_subscribed
|
|
||||||
.lock()
|
|
||||||
.as_mut()
|
|
||||||
{
|
|
||||||
cb(event.clone()).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(cb) = self.shared.events.on_track_subscribed.lock().as_mut() {
|
|
||||||
cb(event).await;
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
error!("could not find published track with sid: {:?}", sid);
|
error!("could not find published track with sid: {:?}", sid);
|
||||||
|
|
||||||
let event = TrackSubscriptionFailedEvent {
|
self.shared
|
||||||
room_session,
|
.room_emitter
|
||||||
sid: sid.clone(),
|
.send(RoomEvent::TrackSubscriptionFailed {
|
||||||
error: TrackError::TrackNotFound(sid.clone().to_string()),
|
sid: sid.clone(),
|
||||||
participant: self.clone(),
|
error: TrackError::TrackNotFound(sid.clone().to_string()),
|
||||||
};
|
participant: self.clone(),
|
||||||
|
});
|
||||||
if let Some(cb) = self
|
|
||||||
.shared
|
|
||||||
.internal_events
|
|
||||||
.on_track_subscription_failed
|
|
||||||
.lock()
|
|
||||||
.as_mut()
|
|
||||||
{
|
|
||||||
cb(event.clone()).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(cb) = self
|
|
||||||
.shared
|
|
||||||
.events
|
|
||||||
.on_track_subscription_failed
|
|
||||||
.lock()
|
|
||||||
.as_mut()
|
|
||||||
{
|
|
||||||
cb(event).await;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -178,25 +143,10 @@ impl RemoteParticipant {
|
|||||||
.add_track_publication(TrackPublication::Remote(publication.clone()));
|
.add_track_publication(TrackPublication::Remote(publication.clone()));
|
||||||
|
|
||||||
// This is a new track, fire publish events
|
// This is a new track, fire publish events
|
||||||
let event = TrackPublishedEvent {
|
self.shared.room_emitter.send(RoomEvent::TrackPublished {
|
||||||
room_session: room_session.clone(),
|
|
||||||
participant: self.clone(),
|
|
||||||
publication: publication.clone(),
|
publication: publication.clone(),
|
||||||
};
|
participant: self.clone(),
|
||||||
|
});
|
||||||
if let Some(cb) = self
|
|
||||||
.shared
|
|
||||||
.internal_events
|
|
||||||
.on_track_published
|
|
||||||
.lock()
|
|
||||||
.as_mut()
|
|
||||||
{
|
|
||||||
cb(event.clone()).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(cb) = self.shared.events.on_track_published.lock().as_mut() {
|
|
||||||
cb(event).await;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
valid_tracks.insert(track.sid.into());
|
valid_tracks.insert(track.sid.into());
|
||||||
@@ -205,10 +155,6 @@ impl RemoteParticipant {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ParticipantInternalTrait for RemoteParticipant {
|
impl ParticipantInternalTrait for RemoteParticipant {
|
||||||
fn internal_events(&self) -> Arc<ParticipantEvents> {
|
|
||||||
self.shared.internal_events.clone()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn update_info(&self, info: ParticipantInfo) {
|
fn update_info(&self, info: ParticipantInfo) {
|
||||||
self.shared.update_info(info)
|
self.shared.update_info(info)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,26 +1,22 @@
|
|||||||
|
use super::id::{ParticipantIdentity, ParticipantSid};
|
||||||
|
use super::participant::local_participant::LocalParticipant;
|
||||||
|
use super::participant::remote_participant::RemoteParticipant;
|
||||||
|
use super::participant::{ParticipantInternalTrait, ParticipantTrait};
|
||||||
|
use super::{RoomEmitter, RoomError, RoomEvent, RoomResult, SimulateScenario};
|
||||||
|
use crate::proto::{self, participant_info};
|
||||||
|
use crate::rtc_engine::{EngineEvent, EngineEvents, EngineResult, RTCEngine};
|
||||||
|
use crate::signal_client::SignalOptions;
|
||||||
use parking_lot::{Mutex, RwLock};
|
use parking_lot::{Mutex, RwLock};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::sync::atomic::{AtomicU8, Ordering};
|
use std::sync::atomic::{AtomicU8, Ordering};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use tokio::sync::oneshot;
|
use tokio::sync::oneshot;
|
||||||
use tokio::task::JoinHandle;
|
use tokio::task::JoinHandle;
|
||||||
|
|
||||||
use crate::events::{ParticipantConnectedEvent, ParticipantDisconnectedEvent, RoomEvents};
|
|
||||||
use crate::proto::{self, participant_info};
|
|
||||||
use crate::rtc_engine::{EngineEvent, EngineEvents, EngineResult, RTCEngine};
|
|
||||||
use crate::signal_client::SignalOptions;
|
|
||||||
|
|
||||||
use super::id::{ParticipantIdentity, ParticipantSid};
|
|
||||||
use super::participant::local_participant::LocalParticipant;
|
|
||||||
use super::participant::remote_participant::RemoteParticipant;
|
|
||||||
use super::participant::{ParticipantInternalTrait, ParticipantTrait};
|
|
||||||
use super::{RoomError, RoomResult, SimulateScenario};
|
|
||||||
use tracing::{error, instrument, Level};
|
use tracing::{error, instrument, Level};
|
||||||
|
|
||||||
#[derive(Debug, Clone, Eq, PartialEq)]
|
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
|
||||||
pub enum ConnectionState {
|
pub enum ConnectionState {
|
||||||
Disconnected,
|
Disconnected,
|
||||||
Connecting,
|
|
||||||
Connected,
|
Connected,
|
||||||
Reconnecting,
|
Reconnecting,
|
||||||
}
|
}
|
||||||
@@ -31,14 +27,14 @@ impl TryFrom<u8> for ConnectionState {
|
|||||||
fn try_from(value: u8) -> Result<Self, Self::Error> {
|
fn try_from(value: u8) -> Result<Self, Self::Error> {
|
||||||
match value {
|
match value {
|
||||||
0 => Ok(ConnectionState::Disconnected),
|
0 => Ok(ConnectionState::Disconnected),
|
||||||
1 => Ok(ConnectionState::Connecting),
|
1 => Ok(ConnectionState::Connected),
|
||||||
2 => Ok(ConnectionState::Connected),
|
2 => Ok(ConnectionState::Reconnecting),
|
||||||
3 => Ok(ConnectionState::Reconnecting),
|
|
||||||
_ => Err("invalid ConnectionState"),
|
_ => Err("invalid ConnectionState"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Internal representation of a RoomSession
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
struct SessionInner {
|
struct SessionInner {
|
||||||
state: AtomicU8, // ConnectionState
|
state: AtomicU8, // ConnectionState
|
||||||
@@ -47,7 +43,14 @@ struct SessionInner {
|
|||||||
participants: RwLock<HashMap<ParticipantSid, Arc<RemoteParticipant>>>,
|
participants: RwLock<HashMap<ParticipantSid, Arc<RemoteParticipant>>>,
|
||||||
rtc_engine: Arc<RTCEngine>,
|
rtc_engine: Arc<RTCEngine>,
|
||||||
local_participant: Arc<LocalParticipant>,
|
local_participant: Arc<LocalParticipant>,
|
||||||
room_events: Arc<RoomEvents>,
|
room_emitter: RoomEmitter,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub(crate) struct SessionHandle {
|
||||||
|
session: RoomSession,
|
||||||
|
session_task: JoinHandle<()>,
|
||||||
|
close_emitter: oneshot::Sender<()>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RoomSession represents a connection to a room.
|
/// RoomSession represents a connection to a room.
|
||||||
@@ -57,16 +60,8 @@ pub struct RoomSession {
|
|||||||
inner: Arc<SessionInner>,
|
inner: Arc<SessionInner>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Responsible for creating and closing the room session.
|
impl SessionHandle {
|
||||||
#[derive(Debug)]
|
pub async fn connect(room_emitter: RoomEmitter, url: &str, token: &str) -> RoomResult<Self> {
|
||||||
pub struct RoomInternal {
|
|
||||||
inner: Arc<SessionInner>,
|
|
||||||
session_task: JoinHandle<()>,
|
|
||||||
close_emitter: oneshot::Sender<()>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RoomInternal {
|
|
||||||
pub async fn connect(room_events: Arc<RoomEvents>, url: &str, token: &str) -> RoomResult<Self> {
|
|
||||||
let (rtc_engine, engine_events) = RTCEngine::new();
|
let (rtc_engine, engine_events) = RTCEngine::new();
|
||||||
let rtc_engine = Arc::new(rtc_engine);
|
let rtc_engine = Arc::new(rtc_engine);
|
||||||
rtc_engine
|
rtc_engine
|
||||||
@@ -81,16 +76,17 @@ impl RoomInternal {
|
|||||||
pi.identity.into(),
|
pi.identity.into(),
|
||||||
pi.name,
|
pi.name,
|
||||||
pi.metadata,
|
pi.metadata,
|
||||||
|
room_emitter.clone(),
|
||||||
));
|
));
|
||||||
let room_info = join_response.room.unwrap();
|
let room_info = join_response.room.unwrap();
|
||||||
let inner = Arc::new(SessionInner {
|
let inner = Arc::new(SessionInner {
|
||||||
state: AtomicU8::new(ConnectionState::Connecting as u8),
|
state: AtomicU8::new(ConnectionState::Disconnected as u8),
|
||||||
sid: Mutex::new(room_info.sid),
|
sid: Mutex::new(room_info.sid),
|
||||||
name: Mutex::new(room_info.name),
|
name: Mutex::new(room_info.name),
|
||||||
participants: Default::default(),
|
participants: Default::default(),
|
||||||
rtc_engine,
|
rtc_engine,
|
||||||
local_participant,
|
local_participant,
|
||||||
room_events,
|
room_emitter,
|
||||||
});
|
});
|
||||||
|
|
||||||
for pi in join_response.other_participants {
|
for pi in join_response.other_participants {
|
||||||
@@ -107,8 +103,12 @@ impl RoomInternal {
|
|||||||
let (close_emitter, close_receiver) = oneshot::channel();
|
let (close_emitter, close_receiver) = oneshot::channel();
|
||||||
let session_task = tokio::spawn(inner.clone().room_task(engine_events, close_receiver));
|
let session_task = tokio::spawn(inner.clone().room_task(engine_events, close_receiver));
|
||||||
|
|
||||||
|
inner
|
||||||
|
.update_connection_state(ConnectionState::Connected)
|
||||||
|
.await;
|
||||||
|
|
||||||
let session = Self {
|
let session = Self {
|
||||||
inner,
|
session: RoomSession::from(inner),
|
||||||
session_task,
|
session_task,
|
||||||
close_emitter,
|
close_emitter,
|
||||||
};
|
};
|
||||||
@@ -116,17 +116,13 @@ impl RoomInternal {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn close(self) {
|
pub async fn close(self) {
|
||||||
self.inner.close();
|
self.session.inner.close().await;
|
||||||
let _ = self.close_emitter.send(());
|
let _ = self.close_emitter.send(());
|
||||||
self.session_task.await;
|
let _ = self.session_task.await;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn session(&self) -> RoomSession {
|
pub fn session(&self) -> RoomSession {
|
||||||
RoomSession::from(self.inner.clone())
|
self.session.clone()
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn simulate_scenario(&self, scenario: SimulateScenario) -> EngineResult<()> {
|
|
||||||
self.inner.rtc_engine.simulate_scenario(scenario).await
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -161,6 +157,7 @@ impl RoomSession {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl SessionInner {
|
impl SessionInner {
|
||||||
|
#[instrument(level = Level::DEBUG)]
|
||||||
async fn room_task(
|
async fn room_task(
|
||||||
self: Arc<Self>,
|
self: Arc<Self>,
|
||||||
mut engine_events: EngineEvents,
|
mut engine_events: EngineEvents,
|
||||||
@@ -168,7 +165,7 @@ impl SessionInner {
|
|||||||
) {
|
) {
|
||||||
loop {
|
loop {
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
res = engine_events.recv() => {
|
res = engine_events.recv() => {
|
||||||
if let Some(event) = res {
|
if let Some(event) = res {
|
||||||
if let Err(err) = self.on_engine_event(event).await {
|
if let Err(err) = self.on_engine_event(event).await {
|
||||||
error!("failed to handle engine event: {:?}", err);
|
error!("failed to handle engine event: {:?}", err);
|
||||||
@@ -240,6 +237,7 @@ impl SessionInner {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[instrument(level = Level::DEBUG)]
|
||||||
async fn close(&self) {
|
async fn close(&self) {
|
||||||
self.rtc_engine.close().await;
|
self.rtc_engine.close().await;
|
||||||
}
|
}
|
||||||
@@ -248,6 +246,21 @@ impl SessionInner {
|
|||||||
self.participants.read().get(sid).cloned()
|
self.participants.read().get(sid).cloned()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Change the connection state and emit an event
|
||||||
|
/// Does nothing if the state is already the same
|
||||||
|
#[instrument(level = Level::DEBUG)]
|
||||||
|
async fn update_connection_state(self: &Arc<Self>, state: ConnectionState) {
|
||||||
|
let old_state = self.state.load(Ordering::Acquire);
|
||||||
|
if old_state == state as u8 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.state.store(state as u8, Ordering::Release);
|
||||||
|
let _ = self
|
||||||
|
.room_emitter
|
||||||
|
.send(RoomEvent::ConnectionStateChanged(state));
|
||||||
|
}
|
||||||
|
|
||||||
/// Update the participants inside a Room.
|
/// Update the participants inside a Room.
|
||||||
/// It'll create, update or remove a participant
|
/// It'll create, update or remove a participant
|
||||||
/// It also update the participant tracks.
|
/// It also update the participant tracks.
|
||||||
@@ -280,13 +293,10 @@ impl SessionInner {
|
|||||||
let pi = pi.clone();
|
let pi = pi.clone();
|
||||||
self.create_participant(pi.sid.into(), pi.identity.into(), pi.name, pi.metadata)
|
self.create_participant(pi.sid.into(), pi.identity.into(), pi.name, pi.metadata)
|
||||||
};
|
};
|
||||||
let mut handler = self.room_events.on_participant_connected.lock();
|
|
||||||
if let Some(cb) = handler.as_mut() {
|
let _ = self
|
||||||
cb(ParticipantConnectedEvent {
|
.room_emitter
|
||||||
room_session: RoomSession::from(self.clone()),
|
.send(RoomEvent::ParticipantConnected(remote_participant.clone()));
|
||||||
participant: remote_participant.clone(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
remote_participant.update_info(pi.clone());
|
remote_participant.update_info(pi.clone());
|
||||||
remote_participant
|
remote_participant
|
||||||
@@ -296,21 +306,20 @@ impl SessionInner {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A participant has disconnected
|
||||||
|
/// Cleanup the participant and emit an event
|
||||||
#[instrument(level = Level::DEBUG)]
|
#[instrument(level = Level::DEBUG)]
|
||||||
fn handle_participant_disconnect(self: &Arc<Self>, remote_participant: Arc<RemoteParticipant>) {
|
fn handle_participant_disconnect(self: &Arc<Self>, remote_participant: Arc<RemoteParticipant>) {
|
||||||
self.participants.write().remove(&remote_participant.sid());
|
self.participants.write().remove(&remote_participant.sid());
|
||||||
|
|
||||||
// TODO(theomonnom): Unpublish all tracks
|
// TODO(theomonnom): Unpublish all tracks
|
||||||
|
let _ = self.room_emitter.send(RoomEvent::ParticipantDisconnected(
|
||||||
let mut handler = self.room_events.on_participant_disconnected.lock();
|
remote_participant.clone(),
|
||||||
if let Some(cb) = handler.as_mut() {
|
));
|
||||||
cb(ParticipantDisconnectedEvent {
|
|
||||||
room_session: RoomSession::from(self.clone()),
|
|
||||||
participant: remote_participant.clone(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Create a new participant
|
||||||
|
/// Also add it to the participants list
|
||||||
fn create_participant(
|
fn create_participant(
|
||||||
self: &Arc<Self>,
|
self: &Arc<Self>,
|
||||||
sid: ParticipantSid,
|
sid: ParticipantSid,
|
||||||
@@ -323,46 +332,9 @@ impl SessionInner {
|
|||||||
identity,
|
identity,
|
||||||
name,
|
name,
|
||||||
metadata,
|
metadata,
|
||||||
|
self.room_emitter.clone(),
|
||||||
));
|
));
|
||||||
|
|
||||||
macro_rules! forward_event {
|
|
||||||
($type:ident, when_connected) => {
|
|
||||||
p.internal_events().$type({
|
|
||||||
let room_internal = self.clone();
|
|
||||||
move |event| {
|
|
||||||
let room_internal = room_internal.clone();
|
|
||||||
async move {
|
|
||||||
if room_internal.state.load(Ordering::SeqCst)
|
|
||||||
== ConnectionState::Connected as u8
|
|
||||||
{
|
|
||||||
if let Some(cb) = room_internal.room_events.$type.lock().as_mut() {
|
|
||||||
cb(event).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
};
|
|
||||||
($type:ident) => {
|
|
||||||
p.internal_events().$type({
|
|
||||||
let room_internal = self.clone();
|
|
||||||
move |event| {
|
|
||||||
let room_internal = room_internal.clone();
|
|
||||||
async move {
|
|
||||||
if let Some(cb) = room_internal.room_events.$type.lock().as_mut() {
|
|
||||||
cb(event).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Forward participantevents to room events
|
|
||||||
forward_event!(on_track_published, when_connected);
|
|
||||||
forward_event!(on_track_subscribed);
|
|
||||||
forward_event!(on_track_subscription_failed);
|
|
||||||
|
|
||||||
self.participants.write().insert(sid, p.clone());
|
self.participants.write().insert(sid, p.clone());
|
||||||
p
|
p
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user