提交 afd1c95f authored 作者: Nazar Mokrynskyi's avatar Nazar Mokrynskyi

Add inline documentation for both client-side and server-side code of `echo` Rust example

上级 d5672c22
...@@ -114,15 +114,19 @@ async function init() ...@@ -114,15 +114,19 @@ async function init()
switch (decodedMessage.action) switch (decodedMessage.action)
{ {
case 'Init': { case 'Init': {
// It is expected that server will send initialization message right after
// WebSocket connection is established
await device.load({ await device.load({
routerRtpCapabilities : decodedMessage.routerRtpCapabilities routerRtpCapabilities : decodedMessage.routerRtpCapabilities
}); });
// Send client-side initialization message back right away
send({ send({
action : 'Init', action : 'Init',
rtpCapabilities : device.rtpCapabilities rtpCapabilities : device.rtpCapabilities
}); });
// Producer transport is needed to send audio and video to SFU
producerTransport = device.createSendTransport( producerTransport = device.createSendTransport(
decodedMessage.producerTransportOptions decodedMessage.producerTransportOptions
); );
...@@ -130,10 +134,13 @@ async function init() ...@@ -130,10 +134,13 @@ async function init()
producerTransport producerTransport
.on('connect', ({ dtlsParameters }, success) => .on('connect', ({ dtlsParameters }, success) =>
{ {
// Send request to establish producer transport connection
send({ send({
action : 'ConnectProducerTransport', action : 'ConnectProducerTransport',
dtlsParameters dtlsParameters
}); });
// And wait for confirmation, but, obviously, no error handling,
// which you should definitely have in real-world applications
waitingForResponse.set('ConnectedProducerTransport', () => waitingForResponse.set('ConnectedProducerTransport', () =>
{ {
success(); success();
...@@ -142,17 +149,24 @@ async function init() ...@@ -142,17 +149,24 @@ async function init()
}) })
.on('produce', ({ kind, rtpParameters }, success) => .on('produce', ({ kind, rtpParameters }, success) =>
{ {
// Once connection is established, send request to produce
// audio or video track
send({ send({
action : 'Produce', action : 'Produce',
kind, kind,
rtpParameters rtpParameters
}); });
// And wait for confirmation, but, obviously, no error handling,
// which you should definitely have in real-world applications
waitingForResponse.set('Produced', ({ id }: {id: string}) => waitingForResponse.set('Produced', ({ id }: {id: string}) =>
{ {
success({ id }); success({ id });
}); });
}); });
// Request microphone and camera access, in real-world apps you may want
// to do this separately so that audio-only and video-only cases are
// handled nicely instead of failing completely
const mediaStream = await navigator.mediaDevices.getUserMedia({ const mediaStream = await navigator.mediaDevices.getUserMedia({
audio : true, audio : true,
video : { video : {
...@@ -172,6 +186,7 @@ async function init() ...@@ -172,6 +186,7 @@ async function init()
const producers = []; const producers = [];
// And create producers for all tracks that were previously requested
for (const track of mediaStream.getTracks()) for (const track of mediaStream.getTracks())
{ {
const producer = await producerTransport.produce({ track }); const producer = await producerTransport.produce({ track });
...@@ -180,6 +195,8 @@ async function init() ...@@ -180,6 +195,8 @@ async function init()
console.log(`${track.kind} producer created:`, producer); console.log(`${track.kind} producer created:`, producer);
} }
// Producer transport is now needed to receive previously produced
// tracks back
consumerTransport = device.createRecvTransport( consumerTransport = device.createRecvTransport(
decodedMessage.consumerTransportOptions decodedMessage.consumerTransportOptions
); );
...@@ -187,10 +204,13 @@ async function init() ...@@ -187,10 +204,13 @@ async function init()
consumerTransport consumerTransport
.on('connect', ({ dtlsParameters }, success) => .on('connect', ({ dtlsParameters }, success) =>
{ {
// Send request to establish consumer transport connection
send({ send({
action : 'ConnectConsumerTransport', action : 'ConnectConsumerTransport',
dtlsParameters dtlsParameters
}); });
// And wait for confirmation, but, obviously, no error handling,
// which you should definitely have in real-world applications
waitingForResponse.set('ConnectedConsumerTransport', () => waitingForResponse.set('ConnectedConsumerTransport', () =>
{ {
success(); success();
...@@ -198,22 +218,32 @@ async function init() ...@@ -198,22 +218,32 @@ async function init()
}); });
}); });
// For simplicity of this example producers were stored in an array
// and are now all consumed one at a time
for (const producer of producers) for (const producer of producers)
{ {
await new Promise((resolve) => await new Promise((resolve) =>
{ {
// Send request to consume producer
send({ send({
action : 'Consume', action : 'Consume',
producerId : producer.id producerId : producer.id
}); });
// And wait for confirmation, but, obviously, no error handling,
// which you should definitely have in real-world applications
waitingForResponse.set('Consumed', async (consumerOptions: ConsumerOptions) => waitingForResponse.set('Consumed', async (consumerOptions: ConsumerOptions) =>
{ {
// Once confirmation is received, corresponding consumer
// can be created client-side
const consumer = await (consumerTransport as Transport).consume( const consumer = await (consumerTransport as Transport).consume(
consumerOptions consumerOptions
); );
console.log(`${consumer.kind} producer created:`, consumer); console.log(`${consumer.kind} consumer created:`, consumer);
// Consumer needs to be resumed after being created in
// paused state (see official documentation about why:
// https://mediasoup.org/documentation/v3/mediasoup/api/#transport-consume)
send({ send({
action : 'ConsumerResume', action : 'ConsumerResume',
id : consumer.id id : consumer.id
...@@ -237,6 +267,8 @@ async function init() ...@@ -237,6 +267,8 @@ async function init()
break; break;
} }
default: { default: {
// All messages other than initialization go here and are assumed
// to be notifications that correspond to previously sent requests
const callback = waitingForResponse.get(decodedMessage.action); const callback = waitingForResponse.get(decodedMessage.action);
if (callback) if (callback)
......
...@@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize}; ...@@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize};
use std::collections::HashMap; use std::collections::HashMap;
use std::num::{NonZeroU32, NonZeroU8}; use std::num::{NonZeroU32, NonZeroU8};
/// List of codecs that SFU will accept from clients
fn media_codecs() -> Vec<RtpCodecCapability> { fn media_codecs() -> Vec<RtpCodecCapability> {
vec![ vec![
RtpCodecCapability::Audio { RtpCodecCapability::Audio {
...@@ -33,6 +34,8 @@ fn media_codecs() -> Vec<RtpCodecCapability> { ...@@ -33,6 +34,8 @@ fn media_codecs() -> Vec<RtpCodecCapability> {
] ]
} }
/// Data structure containing all the necessary information about transport options required from
/// the server to establish transport connection on the client
#[derive(Serialize)] #[derive(Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct TransportOptions { struct TransportOptions {
...@@ -42,22 +45,31 @@ struct TransportOptions { ...@@ -42,22 +45,31 @@ struct TransportOptions {
ice_parameters: IceParameters, ice_parameters: IceParameters,
} }
/// Server messages sent to the client
#[derive(Serialize, Message)] #[derive(Serialize, Message)]
#[serde(tag = "action")] #[serde(tag = "action")]
#[rtype(result = "()")] #[rtype(result = "()")]
enum ServerMessage { enum ServerMessage {
/// Initialization message with consumer/producer transport options and Router's RTP
/// capabilities necessary to establish WebRTC transport connection client-side
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
Init { Init {
consumer_transport_options: TransportOptions, consumer_transport_options: TransportOptions,
producer_transport_options: TransportOptions, producer_transport_options: TransportOptions,
router_rtp_capabilities: RtpCapabilitiesFinalized, router_rtp_capabilities: RtpCapabilitiesFinalized,
}, },
/// Notification that producer transport was connected successfully (in case of error connection
/// is just dropped, in real-world application you probably want to handle it better)
ConnectedProducerTransport, ConnectedProducerTransport,
/// Notification that producer was created on the server, in this simple example client will try
/// to consume it right away, hence `echo` example
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
Produced { Produced { id: ProducerId },
id: ProducerId, /// Notification that consumer transport was connected successfully (in case of error connection
}, /// is just dropped, in real-world application you probably want to handle it better)
ConnectedConsumerTransport, ConnectedConsumerTransport,
/// Notification that consumer was successfully created server-side, client can resume the
/// consumer after this
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
Consumed { Consumed {
id: ConsumerId, id: ConsumerId,
...@@ -67,49 +79,72 @@ enum ServerMessage { ...@@ -67,49 +79,72 @@ enum ServerMessage {
}, },
} }
/// Client messages sent to the server
#[derive(Deserialize, Message)] #[derive(Deserialize, Message)]
#[serde(tag = "action")] #[serde(tag = "action")]
#[rtype(result = "()")] #[rtype(result = "()")]
enum ClientMessage { enum ClientMessage {
/// Client-side initialization with its RTP capabilities, in this simple case we expect those to
/// match server Router's RTP capabilities
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
Init { rtp_capabilities: RtpCapabilities }, Init { rtp_capabilities: RtpCapabilities },
/// Request to connect producer transport with client-side DTLS parameters
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
ConnectProducerTransport { dtls_parameters: DtlsParameters }, ConnectProducerTransport { dtls_parameters: DtlsParameters },
/// Request to produce a new audio or video track with specified RTP parameters
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
Produce { Produce {
kind: MediaKind, kind: MediaKind,
rtp_parameters: RtpParameters, rtp_parameters: RtpParameters,
}, },
/// Request to connect consumer transport with client-side DTLS parameters
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
ConnectConsumerTransport { dtls_parameters: DtlsParameters }, ConnectConsumerTransport { dtls_parameters: DtlsParameters },
/// Request to consume specified producer
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
Consume { producer_id: ProducerId }, Consume { producer_id: ProducerId },
/// Request to resume consumer that was previously created
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
ConsumerResume { id: ConsumerId }, ConsumerResume { id: ConsumerId },
} }
/// Internal actor messages for convenience
#[derive(Message)] #[derive(Message)]
#[rtype(result = "()")] #[rtype(result = "()")]
enum InternalMessage { enum InternalMessage {
/// Save producer in connection-specific hashmap to prevent it from being destroyed
SaveProducer(Producer), SaveProducer(Producer),
/// Save consumer in connection-specific hashmap to prevent it from being destroyed
SaveConsumer(Consumer), SaveConsumer(Consumer),
/// Stop/close the WebSocket connection
Stop, Stop,
} }
/// Consumer/producer transports pair for the client
struct Transports { struct Transports {
consumer: WebRtcTransport, consumer: WebRtcTransport,
producer: WebRtcTransport, producer: WebRtcTransport,
} }
struct EchoServer { /// Actor that will represent WebSocket connection from the client, it will handle inbound and
/// outbound WebSocket messages in JSON.
///
/// See https://actix.rs/docs/websockets/ for official `actix-web` documentation.
struct EchoConnection {
/// RTP capabilities received from the client
client_rtp_capabilities: Option<RtpCapabilities>, client_rtp_capabilities: Option<RtpCapabilities>,
/// Consumers associated with this client, preventing them from being destroyed
consumers: HashMap<ConsumerId, Consumer>, consumers: HashMap<ConsumerId, Consumer>,
/// Producers associated with this client, preventing them from being destroyed
producers: Vec<Producer>, producers: Vec<Producer>,
/// Producers associated with this client, useful to get its RTP capabilities later
router: Router, router: Router,
/// Consumer and producer transports associated with this client
transports: Transports, transports: Transports,
} }
impl EchoServer { impl EchoConnection {
/// Create a new instance representing WebSocket connection
async fn new(worker_manager: &WorkerManager) -> Result<Self, String> { async fn new(worker_manager: &WorkerManager) -> Result<Self, String> {
let worker = worker_manager let worker = worker_manager
.create_worker(WorkerSettings::default()) .create_worker(WorkerSettings::default())
...@@ -120,6 +155,9 @@ impl EchoServer { ...@@ -120,6 +155,9 @@ impl EchoServer {
.await .await
.map_err(|error| format!("Failed to create router: {}", error))?; .map_err(|error| format!("Failed to create router: {}", error))?;
// We know that for echo example we'll need 2 transports, so we can create both right away.
// This may not be the case for real-world applications or you may create this at a
// different time and/or in different order.
let transport_options = let transport_options =
WebRtcTransportOptions::new(TransportListenIps::new(TransportListenIp { WebRtcTransportOptions::new(TransportListenIps::new(TransportListenIp {
ip: "127.0.0.1".parse().unwrap(), ip: "127.0.0.1".parse().unwrap(),
...@@ -148,12 +186,15 @@ impl EchoServer { ...@@ -148,12 +186,15 @@ impl EchoServer {
} }
} }
impl Actor for EchoServer { impl Actor for EchoConnection {
type Context = ws::WebsocketContext<Self>; type Context = ws::WebsocketContext<Self>;
fn started(&mut self, ctx: &mut Self::Context) { fn started(&mut self, ctx: &mut Self::Context) {
println!("WebSocket connection created"); println!("WebSocket connection created");
// We know that both consumer and producer transports will be used, so we sent server
// information about both in an initialization message alongside with router capabilities
// to the client right after WebSocket connection is established
let server_init_message = ServerMessage::Init { let server_init_message = ServerMessage::Init {
consumer_transport_options: TransportOptions { consumer_transport_options: TransportOptions {
id: self.transports.consumer.id(), id: self.transports.consumer.id(),
...@@ -170,7 +211,7 @@ impl Actor for EchoServer { ...@@ -170,7 +211,7 @@ impl Actor for EchoServer {
router_rtp_capabilities: self.router.rtp_capabilities().clone(), router_rtp_capabilities: self.router.rtp_capabilities().clone(),
}; };
ctx.text(serde_json::to_string(&server_init_message).unwrap()); ctx.address().do_send(server_init_message);
} }
fn stopped(&mut self, _ctx: &mut Self::Context) { fn stopped(&mut self, _ctx: &mut Self::Context) {
...@@ -178,8 +219,11 @@ impl Actor for EchoServer { ...@@ -178,8 +219,11 @@ impl Actor for EchoServer {
} }
} }
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for EchoServer { impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for EchoConnection {
fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) { fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) {
// Here we handle incoming WebSocket messages, intentionally not handling continuation
// messages since we know all messages will fit into a single frame, but in real-world apps
// you need to handle continuation frames too (`ws::Message::Continuation`)
match msg { match msg {
Ok(ws::Message::Ping(msg)) => { Ok(ws::Message::Ping(msg)) => {
ctx.pong(&msg); ctx.pong(&msg);
...@@ -187,6 +231,9 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for EchoServer { ...@@ -187,6 +231,9 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for EchoServer {
Ok(ws::Message::Pong(_)) => {} Ok(ws::Message::Pong(_)) => {}
Ok(ws::Message::Text(text)) => match serde_json::from_str::<ClientMessage>(&text) { Ok(ws::Message::Text(text)) => match serde_json::from_str::<ClientMessage>(&text) {
Ok(message) => { Ok(message) => {
// Parse JSON into an enum and just send it back to the actor to be processed
// by another handler below, it is much more convenient to just parse it in one
// place and have typed data structure everywhere else
ctx.address().do_send(message); ctx.address().do_send(message);
} }
Err(error) => { Err(error) => {
...@@ -205,17 +252,22 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for EchoServer { ...@@ -205,17 +252,22 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for EchoServer {
} }
} }
impl Handler<ClientMessage> for EchoServer { impl Handler<ClientMessage> for EchoConnection {
type Result = (); type Result = ();
fn handle(&mut self, message: ClientMessage, ctx: &mut Self::Context) { fn handle(&mut self, message: ClientMessage, ctx: &mut Self::Context) {
match message { match message {
ClientMessage::Init { rtp_capabilities } => { ClientMessage::Init { rtp_capabilities } => {
// We need to know client's RTP capabilities, those are sent using initialization
// message and are stored in connection struct for future use
self.client_rtp_capabilities.replace(rtp_capabilities); self.client_rtp_capabilities.replace(rtp_capabilities);
} }
ClientMessage::ConnectProducerTransport { dtls_parameters } => { ClientMessage::ConnectProducerTransport { dtls_parameters } => {
let address = ctx.address(); let address = ctx.address();
let transport = self.transports.producer.clone(); let transport = self.transports.producer.clone();
// Establish connection for producer transport using DTLS parameters received
// from the client, but doing so in a background task since this handler is
// synchronous
actix::spawn(async move { actix::spawn(async move {
match transport match transport
.connect(WebRtcTransportRemoteParameters { dtls_parameters }) .connect(WebRtcTransportRemoteParameters { dtls_parameters })
...@@ -238,6 +290,8 @@ impl Handler<ClientMessage> for EchoServer { ...@@ -238,6 +290,8 @@ impl Handler<ClientMessage> for EchoServer {
} => { } => {
let address = ctx.address(); let address = ctx.address();
let transport = self.transports.producer.clone(); let transport = self.transports.producer.clone();
// Use producer transport to create a new producer on the server with given RTP
// parameters
actix::spawn(async move { actix::spawn(async move {
match transport match transport
.produce(ProducerOptions::new(kind, rtp_parameters)) .produce(ProducerOptions::new(kind, rtp_parameters))
...@@ -246,6 +300,8 @@ impl Handler<ClientMessage> for EchoServer { ...@@ -246,6 +300,8 @@ impl Handler<ClientMessage> for EchoServer {
Ok(producer) => { Ok(producer) => {
let id = producer.id(); let id = producer.id();
address.do_send(ServerMessage::Produced { id }); address.do_send(ServerMessage::Produced { id });
// Producer is stored in a hashmap since if we don't do it, it will get
// destroyed as soon as its instance goes out out scope
address.do_send(InternalMessage::SaveProducer(producer)); address.do_send(InternalMessage::SaveProducer(producer));
println!("{:?} producer created: {}", kind, id); println!("{:?} producer created: {}", kind, id);
} }
...@@ -259,6 +315,7 @@ impl Handler<ClientMessage> for EchoServer { ...@@ -259,6 +315,7 @@ impl Handler<ClientMessage> for EchoServer {
ClientMessage::ConnectConsumerTransport { dtls_parameters } => { ClientMessage::ConnectConsumerTransport { dtls_parameters } => {
let address = ctx.address(); let address = ctx.address();
let transport = self.transports.consumer.clone(); let transport = self.transports.consumer.clone();
// The same as producer transport, but for consumer transport
actix::spawn(async move { actix::spawn(async move {
match transport match transport
.connect(WebRtcTransportRemoteParameters { dtls_parameters }) .connect(WebRtcTransportRemoteParameters { dtls_parameters })
...@@ -285,6 +342,8 @@ impl Handler<ClientMessage> for EchoServer { ...@@ -285,6 +342,8 @@ impl Handler<ClientMessage> for EchoServer {
return; return;
} }
}; };
// Create consumer for given producer ID, while first making sure that RTP
// capabilities were sent by the client prior to that
actix::spawn(async move { actix::spawn(async move {
let mut options = ConsumerOptions::new(producer_id, rtp_capabilities); let mut options = ConsumerOptions::new(producer_id, rtp_capabilities);
options.paused = true; options.paused = true;
...@@ -300,6 +359,8 @@ impl Handler<ClientMessage> for EchoServer { ...@@ -300,6 +359,8 @@ impl Handler<ClientMessage> for EchoServer {
kind, kind,
rtp_parameters, rtp_parameters,
}); });
// Consumer is stored in a hashmap since if we don't do it, it will get
// destroyed as soon as its instance goes out out scope
address.do_send(InternalMessage::SaveConsumer(consumer)); address.do_send(InternalMessage::SaveConsumer(consumer));
println!("{:?} consumer created: {}", kind, id); println!("{:?} consumer created: {}", kind, id);
} }
...@@ -337,7 +398,9 @@ impl Handler<ClientMessage> for EchoServer { ...@@ -337,7 +398,9 @@ impl Handler<ClientMessage> for EchoServer {
} }
} }
impl Handler<ServerMessage> for EchoServer { /// Simple handler that will transform typed server messages into JSON and send them over to the
/// client over WebSocket connection
impl Handler<ServerMessage> for EchoConnection {
type Result = (); type Result = ();
fn handle(&mut self, message: ServerMessage, ctx: &mut Self::Context) { fn handle(&mut self, message: ServerMessage, ctx: &mut Self::Context) {
...@@ -345,7 +408,10 @@ impl Handler<ServerMessage> for EchoServer { ...@@ -345,7 +408,10 @@ impl Handler<ServerMessage> for EchoServer {
} }
} }
impl Handler<InternalMessage> for EchoServer { /// Convenience handler for internal messages, these actions require mutable access to the
/// connection struct and having such message handler makes it easy to use from background tasks
/// where otherwise Mutex would have to be used instead
impl Handler<InternalMessage> for EchoConnection {
type Result = (); type Result = ();
fn handle(&mut self, message: InternalMessage, ctx: &mut Self::Context) { fn handle(&mut self, message: InternalMessage, ctx: &mut Self::Context) {
...@@ -364,12 +430,15 @@ impl Handler<InternalMessage> for EchoServer { ...@@ -364,12 +430,15 @@ impl Handler<InternalMessage> for EchoServer {
} }
} }
/// Function that receives HTTP request on WebSocket route and upgrades it to WebSocket connection.
///
/// See https://actix.rs/docs/websockets/ for official `actix-web` documentation.
async fn ws_index( async fn ws_index(
request: HttpRequest, request: HttpRequest,
worker_manager: Data<WorkerManager>, worker_manager: Data<WorkerManager>,
stream: Payload, stream: Payload,
) -> Result<HttpResponse, Error> { ) -> Result<HttpResponse, Error> {
match EchoServer::new(&worker_manager).await { match EchoConnection::new(&worker_manager).await {
Ok(echo_server) => ws::start(echo_server, &request, stream), Ok(echo_server) => ws::start(echo_server, &request, stream),
Err(error) => { Err(error) => {
eprintln!("{}", error); eprintln!("{}", error);
...@@ -383,12 +452,15 @@ async fn ws_index( ...@@ -383,12 +452,15 @@ async fn ws_index(
async fn main() -> std::io::Result<()> { async fn main() -> std::io::Result<()> {
env_logger::init(); env_logger::init();
// We will reuse the same worker manager across all connections, this is more than enough for
// this use case
let worker_manager = Data::new(WorkerManager::new()); let worker_manager = Data::new(WorkerManager::new());
HttpServer::new(move || { HttpServer::new(move || {
App::new() App::new()
.app_data(worker_manager.clone()) .app_data(worker_manager.clone())
.route("/ws", web::get().to(ws_index)) .route("/ws", web::get().to(ws_index))
}) })
// 2 threads is plenty for this example, default is to have as many threads as CPU cores
.workers(2) .workers(2)
.bind("127.0.0.1:3000")? .bind("127.0.0.1:3000")?
.run() .run()
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论