finally using RoomSession & Merry Christmas 🎄

This commit is contained in:
Théo Monnom
2022-12-26 00:15:29 +01:00
parent ba770f7c87
commit f7a746f0f6
5 changed files with 159 additions and 154 deletions
+7 -7
View File
@@ -1,8 +1,8 @@
use crate::room::id::TrackSid; use crate::room::id::TrackSid;
use crate::room::participant::remote_participant::RemoteParticipant; use crate::room::participant::remote_participant::RemoteParticipant;
use crate::room::publication::RemoteTrackPublication; use crate::room::publication::RemoteTrackPublication;
use crate::room::room_session::{ConnectionState, RoomSession};
use crate::room::track::remote_track::RemoteTrackHandle; use crate::room::track::remote_track::RemoteTrackHandle;
use crate::room::{ConnectionState, RoomHandle};
use futures::future::Future; use futures::future::Future;
use futures_util::future::BoxFuture; use futures_util::future::BoxFuture;
use parking_lot::Mutex; use parking_lot::Mutex;
@@ -32,19 +32,19 @@ pub enum TrackError {
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct ParticipantConnectedEvent { pub struct ParticipantConnectedEvent {
pub room_handle: RoomHandle, pub room_session: RoomSession,
pub participant: Arc<RemoteParticipant>, pub participant: Arc<RemoteParticipant>,
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct ParticipantDisconnectedEvent { pub struct ParticipantDisconnectedEvent {
pub room_handle: RoomHandle, pub room_session: RoomSession,
pub participant: Arc<RemoteParticipant>, pub participant: Arc<RemoteParticipant>,
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct TrackSubscribedEvent { pub struct TrackSubscribedEvent {
pub room_handle: RoomHandle, pub room_session: RoomSession,
pub track: RemoteTrackHandle, pub track: RemoteTrackHandle,
pub publication: RemoteTrackPublication, pub publication: RemoteTrackPublication,
pub participant: Arc<RemoteParticipant>, pub participant: Arc<RemoteParticipant>,
@@ -52,14 +52,14 @@ pub struct TrackSubscribedEvent {
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct TrackPublishedEvent { pub struct TrackPublishedEvent {
pub room_handle: RoomHandle, pub room_session: RoomSession,
pub publication: RemoteTrackPublication, pub publication: RemoteTrackPublication,
pub participant: Arc<RemoteParticipant>, pub participant: Arc<RemoteParticipant>,
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct TrackSubscriptionFailedEvent { pub struct TrackSubscriptionFailedEvent {
pub room_handle: RoomHandle, pub room_session: RoomSession,
pub error: TrackError, pub error: TrackError,
pub sid: TrackSid, pub sid: TrackSid,
pub participant: Arc<RemoteParticipant>, pub participant: Arc<RemoteParticipant>,
@@ -67,7 +67,7 @@ pub struct TrackSubscriptionFailedEvent {
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct ConnectionStateChangedEvent { pub struct ConnectionStateChangedEvent {
pub room_handle: RoomHandle, pub room_session: RoomSession,
pub state: ConnectionState, pub state: ConnectionState,
} }
+14 -106
View File
@@ -4,11 +4,11 @@ use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::Arc; use std::sync::Arc;
use self::id::{ParticipantIdentity, ParticipantSid}; use self::id::{ParticipantIdentity, ParticipantSid};
use self::internal::{RoomInternal, RoomSession};
use self::participant::local_participant::LocalParticipant; use self::participant::local_participant::LocalParticipant;
use self::participant::remote_participant::RemoteParticipant; use self::participant::remote_participant::RemoteParticipant;
use self::participant::ParticipantInternalTrait; use self::participant::ParticipantInternalTrait;
use self::participant::ParticipantTrait; use self::participant::ParticipantTrait;
use self::room_session::{RoomInternal, RoomSession};
use crate::events::{ use crate::events::{
ParticipantConnectedEvent, ParticipantDisconnectedEvent, RoomEvents, TrackPublishedEvent, ParticipantConnectedEvent, ParticipantDisconnectedEvent, RoomEvents, TrackPublishedEvent,
TrackSubscribedEvent, TrackSubscribedEvent,
@@ -23,10 +23,10 @@ use crate::signal_client::SignalOptions;
pub use crate::rtc_engine::SimulateScenario; pub use crate::rtc_engine::SimulateScenario;
mod room_session;
pub mod id; pub mod id;
pub mod participant; pub mod participant;
pub mod publication; pub mod publication;
pub mod room_session;
pub mod track; pub mod track;
#[derive(Error, Debug)] #[derive(Error, Debug)]
@@ -39,124 +39,32 @@ pub enum RoomError {
pub type RoomResult<T> = Result<T, RoomError>; pub type RoomResult<T> = Result<T, RoomError>;
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum ConnectionState {
Disconnected,
Connecting,
Connected,
Reconnecting,
}
#[derive(Clone, Debug)]
pub struct RoomSession {
internal: Arc<RoomInternal>,
}
impl RoomSession {
pub fn sid(&self) -> String {
self.session.sid.lock().clone()
}
pub fn name(&self) -> String {
self.internal.name.lock().clone()
}
pub fn local_participant(&self) -> Arc<LocalParticipant> {
self.internal.local_participant.clone()
}
pub async fn simulate_scenario(&self, scenario: SimulateScenario) -> EngineResult<()> {
self.internal.rtc_engine.simulate_scenario(scenario).await
}
}
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct Room { pub struct Room {
session: Option<Arc<RoomSession>>, internal: Option<RoomInternal>,
events: Arc<RoomEvents>, // Keep the same RoomEvents across sessions events: Arc<RoomEvents>, // Keep the same RoomEvents across sessions
} }
impl Room { impl Room {
#[instrument(level = Level::DEBUG)] #[instrument(level = Level::DEBUG)]
pub async fn connect(&self, url: &str, token: &str) -> RoomResult<()> { pub async fn connect(&mut self, url: &str, token: &str) -> RoomResult<()> {
let room_session = Arc::new(RoomSession::connect(self.events.clone(), url, token).await?); let internal = RoomInternal::connect(self.events.clone(), url, token).await?;
self.session = Some(room_session.clone()); self.internal = Some(internal);
Ok(()) Ok(())
} }
pub async fn close(&self) {} #[instrument(level = Level::DEBUG)]
pub async fn close(&mut self) {
if let Some(internal) = self.internal.take() {
internal.close().await;
}
}
pub fn events(&self) -> Arc<RoomEvents> { pub fn events(&self) -> Arc<RoomEvents> {
self.events.clone() self.events.clone()
} }
pub fn session(&self) -> Option<> { pub fn session(&self) -> Option<RoomSession> {
self.internal.as_ref().map(|internal| RoomHandle { self.internal.as_ref().map(RoomInternal::session)
internal: internal.clone(),
})
}
}
#[derive(Debug)]
pub struct RoomInternal {
inner: Arc<RoomInner>,
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 = Arc::new(rtc_engine);
rtc_engine
.connect(url, token, SignalOptions::default())
.await?;
let join_response = rtc_engine.join_response().unwrap();
let pi = join_response.participant.unwrap().clone();
let local_participant = Arc::new(LocalParticipant::new(
rtc_engine.clone(),
pi.sid.into(),
pi.identity.into(),
pi.name,
pi.metadata,
));
let room_info = join_response.room.unwrap();
let inner = Arc::new(SessionInner {
state: AtomicU8::new(ConnectionState::Connecting as u8),
sid: Mutex::new(room_info.sid),
name: Mutex::new(room_info.name),
participants: Default::default(),
rtc_engine,
local_participant,
room_events,
});
for pi in join_response.other_participants {
let participant = {
let pi = pi.clone();
inner.create_participant(pi.sid.into(), pi.identity.into(), pi.name, pi.metadata)
};
participant.update_info(pi.clone());
participant
.update_tracks(RoomHandle::from(inner.clone()), pi.tracks)
.await;
}
let (close_emitter, close_receiver) = oneshot::channel();
let session_task = tokio::spawn(inner.room_task(engine_events, close_receiver));
let session = Self {
inner,
session_task,
close_emitter,
};
Ok(session)
}
pub async fn close(self) {
self.inner.close();
let _ = self.close_emitter.send(());
self.session_task.await;
} }
} }
@@ -4,7 +4,7 @@ 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,
}; };
use crate::room::{RoomError, RoomInner}; use crate::room::RoomError;
use crate::rtc_engine::RTCEngine; use crate::rtc_engine::RTCEngine;
#[derive(Debug)] #[derive(Debug)]
@@ -9,11 +9,11 @@ use crate::room::participant::{
use crate::room::publication::{ use crate::room::publication::{
RemoteTrackPublication, TrackPublication, TrackPublicationInternalTrait, TrackPublicationTrait, RemoteTrackPublication, TrackPublication, TrackPublicationInternalTrait, TrackPublicationTrait,
}; };
use crate::room::room_session::RoomSession;
use crate::room::track::remote_audio_track::RemoteAudioTrack; 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::{RoomHandle, RoomInner};
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;
@@ -51,10 +51,10 @@ impl RemoteParticipant {
}) })
} }
#[instrument(level = Level::DEBUG, skip(room_handle))] #[instrument(level = Level::DEBUG, skip(room_session))]
pub(crate) async fn add_subscribed_media_track( pub(crate) async fn add_subscribed_media_track(
self: Arc<Self>, self: Arc<Self>,
room_handle: RoomHandle, room_session: RoomSession,
sid: TrackSid, sid: TrackSid,
media_track: MediaStreamTrackHandle, media_track: MediaStreamTrackHandle,
) { ) {
@@ -110,7 +110,7 @@ impl RemoteParticipant {
track.start(); track.start();
let event = TrackSubscribedEvent { let event = TrackSubscribedEvent {
room_handle, room_session,
track, track,
publication: remote_publication, publication: remote_publication,
participant: self.clone(), participant: self.clone(),
@@ -133,7 +133,7 @@ impl RemoteParticipant {
error!("could not find published track with sid: {:?}", sid); error!("could not find published track with sid: {:?}", sid);
let event = TrackSubscriptionFailedEvent { let event = TrackSubscriptionFailedEvent {
room_handle, room_session,
sid: sid.clone(), sid: sid.clone(),
error: TrackError::TrackNotFound(sid.clone().to_string()), error: TrackError::TrackNotFound(sid.clone().to_string()),
participant: self.clone(), participant: self.clone(),
@@ -161,10 +161,10 @@ impl RemoteParticipant {
} }
} }
#[instrument(level = Level::DEBUG, skip(room_handle))] #[instrument(level = Level::DEBUG, skip(room_session))]
pub(crate) async fn update_tracks( pub(crate) async fn update_tracks(
self: Arc<Self>, self: Arc<Self>,
room_handle: RoomHandle, room_session: RoomSession,
tracks: Vec<TrackInfo>, tracks: Vec<TrackInfo>,
) { ) {
let mut valid_tracks = HashSet::<TrackSid>::new(); let mut valid_tracks = HashSet::<TrackSid>::new();
@@ -179,7 +179,7 @@ impl RemoteParticipant {
// This is a new track, fire publish events // This is a new track, fire publish events
let event = TrackPublishedEvent { let event = TrackPublishedEvent {
room_handle: room_handle.clone(), room_session: room_session.clone(),
participant: self.clone(), participant: self.clone(),
publication: publication.clone(), publication: publication.clone(),
}; };
+129 -32
View File
@@ -7,7 +7,6 @@ use tokio::task::JoinHandle;
use crate::events::{ParticipantConnectedEvent, ParticipantDisconnectedEvent, RoomEvents}; use crate::events::{ParticipantConnectedEvent, ParticipantDisconnectedEvent, RoomEvents};
use crate::proto::{self, participant_info}; use crate::proto::{self, participant_info};
use crate::room::ConnectionState;
use crate::rtc_engine::{EngineEvent, EngineEvents, EngineResult, RTCEngine}; use crate::rtc_engine::{EngineEvent, EngineEvents, EngineResult, RTCEngine};
use crate::signal_client::SignalOptions; use crate::signal_client::SignalOptions;
@@ -18,51 +17,149 @@ use super::participant::{ParticipantInternalTrait, ParticipantTrait};
use super::{RoomError, RoomResult, SimulateScenario}; use super::{RoomError, RoomResult, SimulateScenario};
use tracing::{error, instrument, Level}; use tracing::{error, instrument, Level};
#[derive(Debug)] #[derive(Debug, Clone, Eq, PartialEq)]
pub struct SessionInner { pub enum ConnectionState {
pub state: AtomicU8, // ConnectionState Disconnected,
pub sid: Mutex<String>, Connecting,
pub name: Mutex<String>, Connected,
pub participants: RwLock<HashMap<ParticipantSid, Arc<RemoteParticipant>>>, Reconnecting,
pub rtc_engine: Arc<RTCEngine>,
pub local_participant: Arc<LocalParticipant>,
pub room_events: Arc<RoomEvents>,
} }
#[derive(Clone, Debug)] impl TryFrom<u8> for ConnectionState {
type Error = &'static str;
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0 => Ok(ConnectionState::Disconnected),
1 => Ok(ConnectionState::Connecting),
2 => Ok(ConnectionState::Connected),
3 => Ok(ConnectionState::Reconnecting),
_ => Err("invalid ConnectionState"),
}
}
}
#[derive(Debug)]
struct SessionInner {
state: AtomicU8, // ConnectionState
sid: Mutex<String>,
name: Mutex<String>,
participants: RwLock<HashMap<ParticipantSid, Arc<RemoteParticipant>>>,
rtc_engine: Arc<RTCEngine>,
local_participant: Arc<LocalParticipant>,
room_events: Arc<RoomEvents>,
}
/// RoomSession represents a connection to a room.
/// It can be cloned and shared across threads.
#[derive(Debug, Clone)]
pub struct RoomSession { pub struct RoomSession {
inner: Arc<SessionInner>, inner: Arc<SessionInner>,
} }
impl RoomSession { /// Responsible for creating and closing the room session.
pub fn sid(&self) -> String { #[derive(Debug)]
self.session.sid.lock().clone() 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 = Arc::new(rtc_engine);
rtc_engine
.connect(url, token, SignalOptions::default())
.await?;
let join_response = rtc_engine.join_response().unwrap();
let pi = join_response.participant.unwrap().clone();
let local_participant = Arc::new(LocalParticipant::new(
rtc_engine.clone(),
pi.sid.into(),
pi.identity.into(),
pi.name,
pi.metadata,
));
let room_info = join_response.room.unwrap();
let inner = Arc::new(SessionInner {
state: AtomicU8::new(ConnectionState::Connecting as u8),
sid: Mutex::new(room_info.sid),
name: Mutex::new(room_info.name),
participants: Default::default(),
rtc_engine,
local_participant,
room_events,
});
for pi in join_response.other_participants {
let participant = {
let pi = pi.clone();
inner.create_participant(pi.sid.into(), pi.identity.into(), pi.name, pi.metadata)
};
participant.update_info(pi.clone());
participant
.update_tracks(RoomSession::from(inner.clone()), pi.tracks)
.await;
}
let (close_emitter, close_receiver) = oneshot::channel();
let session_task = tokio::spawn(inner.clone().room_task(engine_events, close_receiver));
let session = Self {
inner,
session_task,
close_emitter,
};
Ok(session)
} }
pub fn name(&self) -> String { pub async fn close(self) {
self.internal.name.lock().clone() self.inner.close();
let _ = self.close_emitter.send(());
self.session_task.await;
} }
pub fn local_participant(&self) -> Arc<LocalParticipant> { pub fn session(&self) -> RoomSession {
self.internal.local_participant.clone() RoomSession::from(self.inner.clone())
} }
pub async fn simulate_scenario(&self, scenario: SimulateScenario) -> EngineResult<()> { pub async fn simulate_scenario(&self, scenario: SimulateScenario) -> EngineResult<()> {
self.internal.rtc_engine.simulate_scenario(scenario).await self.inner.rtc_engine.simulate_scenario(scenario).await
} }
} }
impl RoomSession { impl RoomSession {
fn from(inner: Arc<SessionInner>) -> Self {
Self { inner }
}
pub(crate) async fn close(&self) -> RoomResult<()> { pub fn sid(&self) -> String {
self.internal.rtc_engine.close().await?; self.inner.sid.lock().clone()
self.internal.room_events.close(); }
Ok(())
} pub fn name(&self) -> String {
self.inner.name.lock().clone()
}
pub fn local_participant(&self) -> Arc<LocalParticipant> {
self.inner.local_participant.clone()
}
pub fn connection_state(&self) -> ConnectionState {
self.inner.state.load(Ordering::Acquire).try_into().unwrap()
}
pub fn participants(&self) -> &RwLock<HashMap<ParticipantSid, Arc<RemoteParticipant>>> {
&self.inner.participants
}
pub async fn simulate_scenario(&self, scenario: SimulateScenario) -> EngineResult<()> {
self.inner.rtc_engine.simulate_scenario(scenario).await
}
} }
// Connect me to a database
impl SessionInner { impl SessionInner {
async fn room_task( async fn room_task(
self: Arc<Self>, self: Arc<Self>,
@@ -110,13 +207,13 @@ impl SessionInner {
if let Some(remote_participant) = remote_participant { if let Some(remote_participant) = remote_participant {
tokio::spawn({ tokio::spawn({
let room_internal = self.clone(); let session_inner = self.clone();
{ {
let track_sid = track_sid.to_owned().into(); let track_sid = track_sid.to_owned().into();
async move { async move {
remote_participant remote_participant
.add_subscribed_media_track( .add_subscribed_media_track(
RoomHandle::from(room_internal), RoomSession::from(session_inner),
track_sid, track_sid,
track, track,
) )
@@ -174,7 +271,7 @@ impl SessionInner {
// Participant is already connected, update the it // Participant is already connected, update the it
remote_participant.update_info(pi.clone()); remote_participant.update_info(pi.clone());
remote_participant remote_participant
.update_tracks(RoomHandle::from(self.clone()), pi.tracks) .update_tracks(RoomSession::from(self.clone()), pi.tracks)
.await; .await;
} }
} else { } else {
@@ -186,14 +283,14 @@ impl SessionInner {
let mut handler = self.room_events.on_participant_connected.lock(); let mut handler = self.room_events.on_participant_connected.lock();
if let Some(cb) = handler.as_mut() { if let Some(cb) = handler.as_mut() {
cb(ParticipantConnectedEvent { cb(ParticipantConnectedEvent {
room_handle: RoomHandle::from(self.clone()), room_session: RoomSession::from(self.clone()),
participant: remote_participant.clone(), participant: remote_participant.clone(),
}); });
} }
remote_participant.update_info(pi.clone()); remote_participant.update_info(pi.clone());
remote_participant remote_participant
.update_tracks(RoomHandle::from(self.clone()), pi.tracks) .update_tracks(RoomSession::from(self.clone()), pi.tracks)
.await; .await;
} }
} }
@@ -208,7 +305,7 @@ impl SessionInner {
let mut handler = self.room_events.on_participant_disconnected.lock(); let mut handler = self.room_events.on_participant_disconnected.lock();
if let Some(cb) = handler.as_mut() { if let Some(cb) = handler.as_mut() {
cb(ParticipantDisconnectedEvent { cb(ParticipantDisconnectedEvent {
room_handle: RoomHandle::from(self.clone()), room_session: RoomSession::from(self.clone()),
participant: remote_participant.clone(), participant: remote_participant.clone(),
}); });
} }